I am new to Python and trying to generate 5 numbers with 2 conditions:
I have managed to solve the first part:
import random
rand_even = random.sample(range(0, 100, 2), 3)
rand_odd = random.sample(range(1, 100, 2), 2)
rand_total = rand_even,rand_odd
print(rand_total)
Obviously this is not getting me anywhere For the second part i thought i could use something like:
rand_low = random.sample(range(0, 51), 3)
rand_high = random.sample(range(51,100), 2)
But obviously this is not the way as i am getting more than 5 numbers.
Any help would be appriciated. Thank you
The question is, as pointed out by others, whether we allow correlations between the numbers being high/low and even/odd. The following code does not introduce this correlation.
import random
n = 5
odd = 2
high = 2
odd_indices = random.sample(range(n), odd)
high_indices = random.sample(range(n), high)
out = random.sample(range(26),n)
for i in range(n):
out[i] *= 2
if i in odd_indices:
out[i] += 1
if i in high_indices:
out[i] += 50
Please note that this includes the number 100 as output option. Strictly speaking you did not include it, so one could introduce a shift if the 100 is hit:
if out[i]==100:
out[i] -= random.sample(range(1,25),1)[0]*2
This code is not optimized for performance.
edit
This code will have an irregularity, though, as in each possible output 2k
and 2k+1
never occur at the same time for any k
.
I tried working through this problem logically and it got pretty messy.
Heuristically, what about something like this:
def valid_list(l):
evens, odds = 0, 0
lows, highs = 0, 0
for elem in l:
if elem%2 == 0:
evens += 1
else:
odds += 1
if elem < 52:
lows += 1
else:
highs += 1
return evens <= 3 and odds <= 2 and lows <= 3 and highs <= 2
current_list = [random.randint(0, 100)]
while len(current_list) < 5:
if not valid_list(current_list):
current_list[-1] = random.randint(0, 100)
else:
current_list.append(random.randint(0, 100))
print(current_list)
You have a function that constantly checks whether the numbers you have so far are on track/valid, and then a while loop that will keep pegging said function with random numbers until there is a list of 5 numbers that pass valid_list
.
This is pretty much the epitome of randomness, haha
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With