on writing a while loop for rolling two dice
Peter Otten
__peter__ at web.de
Sun Aug 29 04:06:47 EDT 2021
On 28/08/2021 14:00, Hope Rouselle wrote:
> def how_many_times():
> x, y = 0, 1
> c = 0
> while x != y:
> c = c + 1
> x, y = roll()
> return c, (x, y)
> --8<---------------cut here---------------end--------------->8---
>
> Why am I unhappy? I'm wish I could confine x, y to the while loop. The
> introduction of ``x, y = 0, 1'' must feel like a trick to a novice. How
> would you write this? Thank you!
I'd probably hide the while loop under the rug:
>>> import random
>>> def roll_die():
while True: yield random.randrange(1, 7)
Then:
>>> def hmt():
for c, (x, y) in enumerate(zip(roll_die(), roll_die()), 1):
if x == y:
return c, (x, y)
>>> hmt()
(1, (2, 2))
>>> hmt()
(4, (4, 4))
>>> hmt()
(1, (5, 5))
OK, maybe a bit complicated... but does it pay off if you want to
generalize?
>>> def roll_die(faces):
while True: yield random.randrange(1, 1 + faces)
>>> def hmt(faces, dies):
for c, d in enumerate(zip(*[roll_die(faces)]*dies), 1):
if len(set(d)) == 1: return c, d
>>> hmt(10, 1)
(1, (2,))
>>> hmt(10, 2)
(3, (10, 10))
>>> hmt(10, 3)
(250, (5, 5, 5))
>>> hmt(1, 10)
(1, (1, 1, 1, 1, 1, 1, 1, 1, 1, 1))
You decide :)
More information about the Python-list
mailing list