Reputation: 1151
im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it.
Today I created this code that should random trought 01 to 60 (but is running from 01 to 69)
import random
dez = ['0', '1', '2', '3', '4', '5', '6']
uni = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
sort = []
while len(sort) <= 5:
random.shuffle(dez)
random.shuffle(uni)
w = random.choice(dez)
z = random.choice(uni)
chosen = str(w) + str(z)
if chosen != "00" and chosen not in sort:
sort.append(chosen)
print chosen
I'm also in doubt how to make the code stop at "60".
Upvotes: 1
Views: 222
Reputation: 414265
To get 6 unique random integers in the range from 1 to 59:
sample = random.sample(xrange(1, 60), 6)
# -> [8, 34, 16, 28, 46, 39]
To get strings:
['%02d' % i for i in sample]
# -> ['08', '34', '16', '28', '46', '39']
Upvotes: 1
Reputation: 488434
You do realize you can write the exact same code in 1 line, right? It is easy using randint:
>>> [random.randint(1,60) for _ in range(6)]
[22, 29, 48, 18, 20, 22]
This will give you a list of 6 random integers between 1 and 60. In your code you are creating strings that have these numbers. If you are deliberately creating them as strings, however, you then can do this:
>>> [str(random.randint(1,60)) for _ in range(6)]
['55', '54', '15', '46', '42', '37']
Upvotes: 4
Reputation: 38976
you will get no real benefit by shuffling on each loop. Do it once before the loop.
choosen isn't a word
Upvotes: 0