...

# Random Numbers

MindTheGap
12-09-2007, 10:42 PM
I want to generate 4 random numbers that are all different from eachother.

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()

For some reason the numbers aren't always different from eachother. Any help to fix this?

Psycho-Joe
12-13-2007, 01:09 AM
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.

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()

However, IF is just my preference.
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).

Kakao
12-13-2007, 01:17 PM
A generic version:

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