This formating is really tricky

Peter Otten __peter__ at web.de
Wed Aug 27 03:16:43 EDT 2014


Seymore4Head wrote:

> On Mon, 25 Aug 2014 18:22:35 -0400, Terry Reedy <tjreedy at udel.edu>
> wrote:
> 
>>On 8/25/2014 4:14 PM, Seymore4Head wrote:
>>> import random
>>> sets=3
>>> for x in range(0, sets):
>>>      pb2=random.choice([1-53])
>>
>>You want random.randint(1, 53)
>>...
>>>      alist = sorted([pb1, pb2, pb3, pb4, pb5])
>>>      print ("Your numbers: {} Powerball: {}".format(alist, pb6))
>>>
>>> I am trying this example.  The program works, but the numbers don't
>>> line up if the number of digits are different sizes.
>>> http://openbookproject.net/pybiblio/practice/wilson/powerball.php
>>
>>To get them to line up, you have to format each one to the same width.
>>
>>> Suggestion please?
>>> BTW the exercise instructions say to use the choice function.
>>
>>import random
>>sets=3
>>
>>def ran53():
>>     return random.randint(1, 53)
>>
>>f1 = '{:2d}'
>>bform = "Your numbers: [{0}, {0}, {0}, {0}, {0}]".format(f1)
>>pform = " Powerball: {0}".format(f1)
>>
>>for x in range(0, sets):
>>     balls = sorted(ran53() for i in range(5))
>>     print(bform.format(*balls), pform.format(ran53()))
>>
> I modified your code to only use lotto numbers that don't repeat.  I
> am sure there is a more elegant way to this too.
> 
> import random
> sets=10
> print ("How many sets of numbers? ",sets)
> 
> f1 = '{:2d}'
> bform = "Your numbers: [{0}, {0}, {0}, {0}, {0}]".format(f1)
> pform = " Powerball: {0}".format(f1)
> 
> for x in range(0, sets):
>      balls = sorted(random.randint(1, 53) for i in range(5))
>      if balls[0]!= balls[1] and balls[1]!= balls[2] and balls[2]!=
> balls[3] and balls[3]!= balls[4]:

A simpler test would be

       if len(set(balls)) == 5:

>           print(bform.format(*balls), pform.format(random.randint(1,
> 42)))
>      sets=sets-1

It's not just elegance, the code is incorrect as it can print less than 10 
sets.

Replace the for loop with a while loop, and only decrease sets when you 
print a valid draw.





More information about the Python-list mailing list