on writing a while loop for rolling two dice

Chris Angelico rosuav at gmail.com
Thu Sep 2 15:08:56 EDT 2021


On Fri, Sep 3, 2021 at 4:51 AM Hope Rouselle <hrouselle at jevedi.com> wrote:
>
> Chris Angelico <rosuav at gmail.com> writes:
>
> > 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?
>
> Lol.  You do not.  In fact, this should be syntax error :-D --- as I
> guess it would be if it were a lambda expression?

It got split across lines when I posted it, but if I did this in a
program, I'd make it a single long line. That said, though - Python
doesn't mind if you mess up the indentation inside a parenthesized
expression. Even broken like this, it WILL work. It just looks even
uglier than it does with proper indentation :)

BTW, this sort of thing is great as an anti-plagiarism check. If a
student ever turns in an abomination like this, you can be extremely
confident that it was copied from some programming site/list.
Especially since I've used the two-arg version of iter() in there -
that's quite a rarity.

Hmmmmm.

My mind is straying to evil things.

The two-arg iter can do SO much more than I'm using it for here.

By carefully designing the second argument, we could make something
that is equal to anything whose two elements are equal, which would
then terminate the loop. This... could be a lot worse than it seems.

I'll leave it as an exercise for the reader to figure out how to
capture the matching elements for return.

ChrisA


More information about the Python-list mailing list