forked from prakashcc/HashPay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
55 lines (45 loc) · 1.18 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# -*- coding: utf-8 -*-
from collections import deque
from pysodium import randombytes
def toposort(nodes, parents):
seen = {}
def visit(u):
if u in seen:
if seen[u] == 0:
raise ValueError('not a DAG')
elif u in nodes:
seen[u] = 0
for v in parents(u):
yield visit(v)
seen[u] = 1
yield u
for u in nodes:
yield visit(u)
def bfs(s, succ):
s = tuple(s)
seen = set(s)
q = deque(s)
while q:
u = q.popleft()
yield u
for v in succ(u):
if not v in seen:
seen.add(v)
q.append(v)
def dfs(s, succ):
seen = set()
q = [s]
while q:
u = q.pop()
yield u
seen.add(u)
for v in succ(u):
if v not in seen:
q.append(v)
def randrange(n):
a = (n.bit_length() + 7) // 8 # number of bytes to store n
b = 8 * a - n.bit_length() # number of shifts to have good bit number
r = int.from_bytes(randombytes(a), byteorder='big') >> b
while r >= n:
r = int.from_bytes(randombytes(a), byteorder='big') >> b
return r