Skip to content

Commit 178e62b

Browse files
committed
Added some combinatorics.
1 parent f90d912 commit 178e62b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

combinatorics.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
""" Various combinatorics functions. """
2+
3+
__author__ = "Caleb Madriagl"
4+
__date__ = "2015-02-20"
5+
6+
7+
def factorial(n):
8+
if n == 0:
9+
return 1
10+
else:
11+
return n * factorial(n-1)
12+
13+
14+
def permutations(lst):
15+
result = []
16+
17+
def permute(current, rest):
18+
if rest == []:
19+
result.append(current)
20+
return
21+
for r in rest:
22+
permute(current + (r,), [i for i in rest if i != r])
23+
24+
permute((), lst)
25+
return result
26+
27+
28+
def subsets(lst):
29+
result = []
30+
31+
def _subsets(current, rest):
32+
if rest == []:
33+
result.append(current)
34+
return
35+
36+
(first, *rest) = rest
37+
_subsets(current + (first,), rest)
38+
_subsets(current, rest)
39+
40+
_subsets((), lst)
41+
return result
42+
43+
if __name__ == "__main__":
44+
print("Permutations of ['a','b','c']:", permutations(['a','b','c']))
45+
print("Subsets of ['a','b','c']:", subsets(['a','b','c']))
46+

0 commit comments

Comments
 (0)