xzzuf/utils.py

46 lines
963 B
Python
Raw Normal View History

2023-10-27 10:13:05 +00:00
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