on writing a while loop for rolling two dice
Hope Rouselle
hrouselle at jevedi.com
Thu Sep 2 10:43:57 EDT 2021
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?
More information about the Python-list
mailing list