on writing a while loop for rolling two dice

Avi Gross avigross at verizon.net
Sat Aug 28 20:19:02 EDT 2021


And there is the ever popular recursive version you call with no while loop
in sight. And, oddly, no variable declared in your main body:

#---- CODE START ---
import random

def roll2():
    return random.randint(1,6), random.randint(1,6)

def roll_equal(counter):
    first, second = roll2()
    encountered = counter + 1
    if (first == second):
        return(encountered)
    else:
        return(roll_equal(encountered))

#--- CODE END ---

Since the result is usually a single digit of iterations, no biggie. Here is
some output:

>>> roll_equal(0)
6
>>> roll_equal(0)
7
>>> roll_equal(0)
1
>>> roll_equal(0)
7
>>> roll_equal(0)
6
>>> [ roll_equal(0) for n in range(10)]
[3, 4, 2, 5, 8, 1, 1, 2, 3, 9]
>>> [ roll_equal(0) for n in range(10)]
[3, 3, 7, 19, 7, 2, 1, 3, 8, 4]
>>> [ roll_equal(0) for n in range(10)]
[1, 3, 1, 13, 11, 4, 3, 5, 2, 4]

And the code can be a tad shorter, LOL!

But obviously then you have more overhead than an iterative solution or one
using a generator ...

-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On
Behalf Of Alan Gauld via Python-list
Sent: Saturday, August 28, 2021 6:52 PM
To: python-list at python.org
Subject: Re: on writing a while loop for rolling two dice

On 28/08/2021 21:50, Hope Rouselle wrote:

>>> roll_count = 0
>>> while True:
>>>     outcome = roll_two_dice()
>>>     roll_count += 1
>>>     if outcome[ 0 ]== outcome[ 1 ]: break return roll_count, 
>>> outcome[ 0 ]
>>
> 
> Wait, I'm surprised ``outcome'' is still a valid name at the 
> return-statement.  Wasn't it defined inside the while?

If that really bugs you just replace the break with the return.


>>>     if outcome[ 0 ]== outcome[ 1 ]:
>>>        return roll_count, outcome[ 0 ]

Now its all inside the loop.

But remember readable code is better than  cute code every time.
And personally I'd just declare the x,y up front. Easier to understand and
debug IMHO.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


-- 
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list