-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.py
45 lines (42 loc) · 1 KB
/
util.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
#!/bin/python
# greatest common divisor (Czech: nsd)
# Euclidean algorith (Czech: EAPD)
def nsd(x):
assert isinstance(x, list)
assert len(x) >= 2
a,b = x[:2]
if a < b:
a,b = b,a
assert b <= a
assert b > 0
while (b > 0):
a, b = b, a % b
if len(x) == 2:
return a
else:
return nsd([a] + x[2:])
# least common multiple (Czech: nsn)
# gcd * lcm = a * b (Czech: nsd * nsn = a * b)
#
def nsn(x):
assert isinstance(x, list)
if (len(x) == 1):
return x[0]
assert len(x) >= 2
a = x[0] * x[1] // nsd(x[:2])
if len(x) == 2:
return a
else:
return nsn([a] + x[2:])
# check if two sequences are equivalent
#
# equivalent means that they are the same up to a rotation
#
def are_equal(x, y):
if (len(x) != len(y)):
return False
for i in range(len(x)):
# the first check is redundant, but might speed things up...
if x[i] == y[0] and x[i:] + x[:i] == y:
return True
return False