Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 3 of 3
Thread: Random Numbers

12092007, 09:42 PM #1
 Join Date
 Jul 2007
 Posts
 67
 Thanks
 0
 Thanked 0 Times in 0 Posts
Random Numbers
I want to generate 4 random numbers that are all different from eachother.
Code:import random def oblio(): a = 0 b = 0 c = 0 d = 0 while ( a == b & a == c & a == d & b == c & b == d & c == d): a = random.randint(1,9) b = random.randint(1,9) c = random.randint(1,9) d = random.randint(1,9) print a,b,c,d oblio()

12132007, 12:09 AM #2
 Join Date
 Dec 2007
 Location
 Florida
 Posts
 1
 Thanks
 0
 Thanked 0 Times in 0 Posts
Sometimes it's about how you structure things.
IF is a powerful tool, although a little verbose.
I'm going to try to wing it from memory, so this MIGHT not work.
Code:import random def oblio(): if a==b or a==c or a==d or b==c or b==d or c==d: a = random.randint(1,9) b = random.randint(1,9) c = random.randint(1,9) d = random.randint(1,9) print a,b,c,d oblio()
I believe that your problem is that you used &(and) instead of OR.
If you look at my program, it looks the same as yours, except I used IF and OR.
If you replaced the & in between your equations with an OR, your problem is solved.
OR is the key here. If you use and, then if all of the numbers are equal, your condition is satisfied. However, is one of the groups are unequal, the whole condition fails.
OR, on the other hand, evaluates each equation seperately, and if any of the groups of two are equal, then your condition is satisfied, and you get to re roll your numbers until they are all unequal. Then the condition fails and your program continues.
Not the most efficient way, but it works.
If all that confused you, just remember to use OR instead of &(and).
It will solve your problem.

12132007, 12:17 PM #3
 Join Date
 Mar 2006
 Location
 Brasília, Brazil
 Posts
 153
 Thanks
 0
 Thanked 0 Times in 0 Posts
A generic version:
Code:import random list_size = 4 range_top = 9 assert list_size <= range_top and list_size > 0 and range_top > 0 r = list() i = 0 while i < list_size: r.append(random.randint(1, range_top)) j = 0 while j < i: if r[i] == r[j]: r[i] = random.randint(1, range_top) j = 0 continue j += 1 i += 1 print r
Last edited by Kakao; 12132007 at 12:23 PM.