on writing a while loop for rolling two dice

Chris Angelico rosuav at gmail.com
Mon Aug 30 09:50:27 EDT 2021


On Mon, Aug 30, 2021 at 11:13 PM David Raymond <David.Raymond at tomtom.com> wrote:
>
> > def how_many_times():
> >   x, y = 0, 1
> >   c = 0
> >   while x != y:
> >     c = c + 1
> >     x, y = roll()
> >   return c, (x, y)
>
> Since I haven't seen it used in answers yet, here's another option using our new walrus operator
>
> def how_many_times():
>     roll_count = 1
>     while (rolls := roll())[0] != rolls[1]:
>         roll_count += 1
>     return (roll_count, rolls)
>

Since we're creating solutions that use features in completely
unnecessary ways, here's a version that uses collections.Counter:

def how_many_times():
    return next((count, rolls) for count, rolls in
enumerate(iter(roll, None)) if len(Counter(rolls)) == 1)

Do I get bonus points for it being a one-liner that doesn't fit in
eighty characters?

ChrisA


More information about the Python-list mailing list