-
Notifications
You must be signed in to change notification settings - Fork 34
/
combinatorics.py
48 lines (32 loc) · 932 Bytes
/
combinatorics.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
""" Various combinatorics functions. """
__author__ = "Caleb Madriagl"
__date__ = "2015-02-20"
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def permutations(lst):
result = []
def permute(current, rest):
if rest == []:
result.append(current)
return
for r in rest:
permute(current + (r,), [i for i in rest if i != r])
permute((), lst)
return result
def subsets(lst):
result = []
def _subsets(current, rest):
if rest == []:
result.append(current)
return
(first, *rest) = rest
_subsets(current + (first,), rest)
_subsets(current, rest)
_subsets((), lst)
return result
if __name__ == "__main__":
print("Permutations of ['a','b','c']:", permutations(['a','b','c']))
print("Subsets of ['a','b','c']:", subsets(['a','b','c']))