import random
# The function you wanted
def run_trials(p):
'''only accepts int or float in range [0.0, 1.0]'''
# Count trials
num_trials = 1
while True:
r = random.random()
if r <= p:
print "This took", num_trials, "trial(s) to get a success."
break
else:
num_trials += 1
#Input
while True:
p = input("Please enter a probability: ")
if isinstance(p, float) or isinstance(p, int):
if 0 <= p <= 1:
break
run_trials(p) # pass it to the function
您可以使用
random()
模块中的random
来生成范围为[0,1]的浮点值。然后您可以将该值与用户输入的概率进行比较。如果随机值小于用户给定的概率,您就成功了。你知道吗一旦你明白了这一点,你所需要的就是一个简单的while循环,它会一直生成数字,直到你成功为止。你知道吗
下面是一个函数的示例,它可以执行您想要的操作:
相关问题 更多 >
编程相关推荐