Skip to content

Instantly share code, notes, and snippets.

@gabrii
Last active Mar 21, 2017
Embed
What would you like to do?
Pseudo random number & series generator, consistent across python 2.x and 3.x based on SHA

HELLO WORLD

import hashlib
seed_value = 1
i = 0
def from_bytes (data):
if isinstance(data, str):
data = bytearray(data)
num = 0
for offset, byte in enumerate(data):
num += byte << (offset * 8)
return num
def seed(s):
global seed_value, i
i = 0
if type(s) == int:
s = str(s)
seed_value = from_bytes(bytearray(s, 'UTF-8'))
def randint(a, b):
'''Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b Generate random number between a <= N <= b '''
global i, seed_value
k = str(seed_value+i).encode('utf-8')
k = hashlib.sha224(k).hexdigest()
k = int(k, 16)
i+=1
b+=1
delta = b - a
o = k % delta
return int(a + o)
def serie(*s):
'''Example of a series:
serie(
(1, (0, 1)),
(2, (2, 4)),
)
Returns an array of 2 elements:
First element is randomly chosen from [0, 1] with repetition.
The next 3 elements are randomly chosen from [2,3,4] with repetition.
Possible outputs:
[0, 2, 2]
[1, 4, 4]
[0, 3, 4]
...
'''
o = []
for part in s:
for element in range(part[0]):
o.append(randint(*part[1]))
return o
def choice(options):
return options[randint(0, len(options)-1)]
def verify():
seed(124)
assert(seed_value == 3420721)
d = {0:0, 1:0, 2:0, 3:0}
for j in range(1000):
d[randint(0,3)]+=1
if d[0] != 237:
raise Exception("Consistency error! "+str(d[0])+' != 237')
if __name__ == '__main__':
verify()
11
# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD# HELLO WORLD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment