Python code requiring some review

im currently learning python (at the very beginning) so i still have some doubts about the good mana codes and how should i proceed with it.

Today I created this code which should be random 01 to 60 (but works 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 am also in doubt how to make the code stop at "60".

+1


a source to share


4 answers


You realize that you can write the same code in 1 line, right? It's easy to use randint :

>>> [random.randint(1,60) for _ in range(6)]
[22, 29, 48, 18, 20, 22]

      



This will give you a list of 6 random numbers from 1 to 60. In your code, you create strings that have those numbers. However, if you intentionally create them as strings, you can do this:

>>> [str(random.randint(1,60)) for _ in range(6)]
['55', '54', '15', '46', '42', '37']

      

+4


a source


You can just use



random.randrange(1,60)

      

+2


a source


To get 6 unique random numbers ranging from 1 to 59:

sample = random.sample(xrange(1, 60), 6)
# -> [8, 34, 16, 28, 46, 39]

      

To get the lines:

['%02d' % i for i in sample]
# -> ['08', '34', '16', '28', '46', '39']

      

+1


a source


you don't really get the benefit of shuffling every cycle. Do this once before the loop.

choose not a word

0


a source







All Articles