46 lines
963 B
Python
46 lines
963 B
Python
|
import random
|
||
|
import time
|
||
|
|
||
|
|
||
|
def rndstr(length):
|
||
|
return ''.join(random.choice('0123456789abcdef') for i in range(length))
|
||
|
|
||
|
|
||
|
def choice(arr):
|
||
|
return random.choice(arr)
|
||
|
|
||
|
|
||
|
def rndunicode():
|
||
|
return chr(random.randint(0, 0x10FFFF))
|
||
|
|
||
|
|
||
|
def choice_percent(elements):
|
||
|
# elements is a dict of {percent: action}
|
||
|
# like following:
|
||
|
# elements = {
|
||
|
# 10: lambda: 'a',
|
||
|
# 20: lambda: 'b',
|
||
|
# 30: lambda: 'c',
|
||
|
# 40: lambda: 'd',
|
||
|
# }
|
||
|
# that means we have 10% chance to get 'a', 20% chance to get 'b', etc.
|
||
|
|
||
|
# get total percent
|
||
|
total_percent = 0
|
||
|
for percent in elements:
|
||
|
total_percent += percent
|
||
|
|
||
|
# get random number
|
||
|
random.seed(int(time.time() * 1000))
|
||
|
rnd = random.randint(0, total_percent)
|
||
|
|
||
|
# get action
|
||
|
for percent in elements:
|
||
|
if rnd < percent:
|
||
|
return elements[percent]
|
||
|
else:
|
||
|
rnd -= percent
|
||
|
|
||
|
# should not reach here
|
||
|
return None
|