April 23rd, 2004, 11:15 AM

Pyhton Loop
Hi
I am new to python infact programming. I am trying to write a programme which will pick 6 random numbers between 1 to 50 but no duplicate numbers and not using append function.
Here is something i wrote
import sys
import random
array=[]
#array=[55,65,1,89,10,54,1,258,2]
for i in range(5):
# storing Random numbers to an array
temp= random.randrange(1,50)
array+=[temp]
#print array
# random number(149) Validation (pick 6 different numbers) i #am stuck here
if temp == array[i]:
temp =random.randrange(1,50)
array+=[temp]
#Bubble sort(Ascending order)
for y in range(len(array)1,0,1):
for x in range(y):
if array[x]> array[x+1]:
array[x],array[x+1]=array[x+1],array[x]
# Displaying Random numbers in order (working)
for v in array:
print v,
Can someone help
Thanks
Luckyboy
April 23rd, 2004, 11:22 AM

Originally Posted by luckyboy
Hi
I am new to python infact programming. I am trying to write a programme which will pick 6 random numbers between 1 to 50 but no duplicate numbers and not using append function.
Here is something i wrote
import sys
import random
array=[]
#array=[55,65,1,89,10,54,1,258,2]
for i in range(5):
# storing Random numbers to an array
temp= random.randrange(1,50)
array+=[temp]
#print array
# random number(149) Validation (pick 6 different numbers) i #am stuck here
if temp == array[i]:
temp =random.randrange(1,50)
array+=[temp]
#Bubble sort(Ascending order)
for y in range(len(array)1,0,1):
for x in range(y):
if array[x]> array[x+1]:
array[x],array[x+1]=array[x+1],array[x]
# Displaying Random numbers in order (working)
for v in array:
print v,
Can someone help
Thanks
Luckyboy
April 23rd, 2004, 02:50 PM

Here's how I would do it, though I don't understand the restriction on not using .append()..
Code:
import random
picked_numbers = []
for i in range(6):
newnum = random.randrange(1,50)
while newnum in picked_numbers:
newnum = random.randrange(1,50)
picked_numbers += [newnum]
for num in picked_numbers:
print num,
Normally instead of
Code:
picked_numbers += [newnum]
you'd just do
Code:
picked_numbers.append(newnum)
as it's more efficient.
April 23rd, 2004, 06:38 PM

Python loop
Hi it's working
Thank you strike
April 23rd, 2004, 07:39 PM

This problem is discussed at length in the book 'Programming Pearls' by Jon Bentley, which I recommend that anyone who is serious about programming should read.
Here is an alternative way. Create a list with the numbers 150 in it, shuffle it, and gets the first six elements
Code:
>>> import random
>>> numbers = range(1, 51)
>>> random.shuffle(numbers)
>>> numbers[:6]
[48, 16, 4, 40, 35, 9]
This is fine for a small list of 50, but if you wanted a random number from the set of 1..1,000,000,000, then it would create an array with a billion elements, and throw away a billion minus six of them. In that case I would go to the book I mentioned and use an alternative algorithm.
Dave  The Developers' Coach