【发布时间】:2010-07-08 11:37:31
【问题描述】:
简单的问题:
percentage_chance = 0.36
if some_function(percentage_chance):
# action here has 36% chance to execute
pass
如何写some_function,或涉及percentage_chance的表达式来解决这个问题?
【问题讨论】:
简单的问题:
percentage_chance = 0.36
if some_function(percentage_chance):
# action here has 36% chance to execute
pass
如何写some_function,或涉及percentage_chance的表达式来解决这个问题?
【问题讨论】:
你可以使用random.random:
import random
if random.random() < percentage_chance:
print('aaa')
【讨论】:
import random
if random.randint(0,100) < 36:
do_stuff()
【讨论】:
randrange函数。
randrange 会改变行为。
只是为了让它更明确、更易读:
def probably(chance):
return random.random() < chance
if probably(35 / 100):
do_the_thing()
【讨论】:
此代码返回 1, 36% 的时间
import random
import math
chance = 0.36
math.floor( random.uniform(0, 1/(1-chance)) )
【讨论】: