On 8/28/2021 8:00 AM, Hope Rouselle wrote:
How should I write this? I'd like to roll two six-sided dice until I
get the same number on both. I'd like to get the number of times I
tried. Here's a primitive I'm using:
--8<---------------cut here---------------start------------->8---
x, y = roll()
x
6
y
6 # lucky
x, y = roll()
x
4
y
1 # unlucky
--8<---------------cut here---------------end--------------->8---
Here's my solution:
--8<---------------cut here---------------start------------->8---
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!
Something like (untested)
c = 0
while True:
c += 1
x, y = roll()
if x == y:
return c, (x,y)
or even better to me, as it will not loop forever if you mess up the
condition
for i in range(1, 1000000):
x, y = roll()
if x == y:
return i, (x,y)
# return "The universe ends as the essentially impossible happened"
--
Terry Jan Reedy
--
https://mail.python.org/mailman/listinfo/python-list