[Tutor] lottery problem (Was Re: (no subject))

Adam Jensen hanzer at riseup.net
Fri Dec 19 02:27:03 CET 2014


On Fri, 19 Dec 2014 00:55:49 +0000
Alan Gauld <alan.gauld at btinternet.com> wrote:

> You could have used a list instead of all the
> individual variables
> 
> line[0] = ...
> line[1] = ...
> 
> But then you could get clever and use a loop:
> 
> while lines != 0:
>     start = 1
>     period = 7
>     for lineNum in range(7):
>         line[lineNum] = random(start,period)
>         start += period
>         period += period
>     print (*line)
>     lines -=1
> 

A list comprehension might be fun. https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions

For example:

>>> [random.randint(x,x+6) for x in range(1,50,7)]
[4, 9, 15, 27, 33, 36, 49]

And to build the 'lines' list (although, this is getting rather ugly):

>>> lines = [[random.randint(x,x+6) for x in range(1,50,7)] for i in range(7)]
>>> lines
[[2, 13, 18, 27, 35, 37, 47], [1, 11, 21, 24, 34, 37, 49], [7, 12, 16, 24, 29, 36, 44], [4, 9, 16, 22, 32, 37, 46], [2, 13, 20, 22, 29, 40, 46], [7, 14, 19, 26, 35, 42, 43], [4, 12, 16, 22, 34, 40, 46]]

It might also be a good idea to execute random.seed() before calling randint() - https://docs.python.org/3.4/library/random.html#random.seed


More information about the Tutor mailing list