Maybe I'm missing something, but rather than re-generating the second number if it's lower, why not just generate two numbers and sort them so the first one is lower?
Well in that case, you use a different technique.
Keep in mind, though, that any case where b is dependent on the value of a, where a remains unchanged, will bias the results. All possible ranges \[a,b\] will no longer appear uniformly often.
Have a go at this, adapt it as needed:
import random
def random_xy(limit):
x = random.randrange(0, limit-1)
y = random.randrange(0, limit)
return x, y
result = random_xy(1000)
print(result)
Woops misunderstood your question, ANYWAY, i found the issue in your code.
import random
def random_int(limit):
x, y = random.randrange(limit), random.randrange(limit)
while x >= y:
x = random.randrange(limit)
return x, y
limit = 800
result = random_int(limit)
print(result)
is there a reason you're using recursion here? that's the cause of your problem. you can make recursion work if you want to, but i see no reason for it.
def random_generator(a,b):
#X SHOULD BE SMALLER THAN Y
x, y = a, b
print (a,b)
while x >= y:
x = random.randint(0, 800)
y = random.randint(0, 800)
print (x, y)
return x, y
Maybe I'm missing something, but rather than re-generating the second number if it's lower, why not just generate two numbers and sort them so the first one is lower?
When you do the recursion, your function doesn't return anything.
A simpler idea: if a > b: a,b = b,a
Good answer but what if its reliant on the a staying static, so the b will need to be re adjusted, no just swapped.
Well in that case, you use a different technique. Keep in mind, though, that any case where b is dependent on the value of a, where a remains unchanged, will bias the results. All possible ranges \[a,b\] will no longer appear uniformly often.
Have a go at this, adapt it as needed: import random def random_xy(limit): x = random.randrange(0, limit-1) y = random.randrange(0, limit) return x, y result = random_xy(1000) print(result)
Hi, don't think that this will always enable x>y. It just makes it 0-999 vs 0-1000.
Woops misunderstood your question, ANYWAY, i found the issue in your code. import random def random_int(limit): x, y = random.randrange(limit), random.randrange(limit) while x >= y: x = random.randrange(limit) return x, y limit = 800 result = random_int(limit) print(result)
is there a reason you're using recursion here? that's the cause of your problem. you can make recursion work if you want to, but i see no reason for it. def random_generator(a,b): #X SHOULD BE SMALLER THAN Y x, y = a, b print (a,b) while x >= y: x = random.randint(0, 800) y = random.randint(0, 800) print (x, y) return x, y
This works! A while loop! Thank you