on writing a while loop for rolling two dice
lucas
lucas at bourneuf.net
Thu Sep 2 18:25:23 EDT 2021
>> 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)
>
I would go even further, saying there is no need to «roll dices»:
def how_many_times():
nb_times = random.choice([n for n in range(50) for _ in
range(round(10000*(1/6)*(5/6)**(n-1)))])
return nb_times, (random.randint(1, 6),) * 2
If i had more time on my hands, i would do something with bissect to get
nb_times with more precision, as i have (mis)calculated that the
probability of having nb_times = N is N = (1/6) * (5/6) ** (N-1)
Something like this may work:
nb_times = [random.random() < (1/6) * (5/6) ** (N-1) for N in
range(1, 50)].index(True)+1
More information about the Python-list
mailing list