dimanche 12 juillet 2020

How to write short code of finding random integer based probability in python

from random import *

dice_roll = int(input("dice throwing count?: "))
even_num_cnt = 0

for i in range(dice_roll):
    num = randint(1,6)
    if num % 2 == 0:
        even_num_cnt += 1

print(even_num_cnt / dice_roll)

This is the code of finding the probability of even_num_cnt by dice_roll Is there a simpler code (like a one-line code) using other functions in Python 3? I tried lambdas

from random import *

v = []
even_num_cnt = 0
dice_roll = int(input())

for i in range(dice_roll):
    v.append(randint(1,6))
    x = lambda dice_roll: dice_roll % 2 == 0
    if(x):
        even_num_cnt +=1

print(even_num_cnt / dice_roll)

like this but it seems like I am not knowing how lambdas work properly.

If there is anything to edit the question, please let me know. ~Thanks




Aucun commentaire:

Enregistrer un commentaire