Skip to content

Commit e866f42

Browse files
committed
Day 12: Fix nits, add runtime analysis and follow up link to Python permutations
1 parent a5a72cc commit e866f42

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

day22/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,23 @@ the permutations, like this:
4343
[3, 2, 1]
4444
```
4545

46+
This solution is `O((spots for the first elem to go in) * (num perms of the remaining list))`
47+
where `(num perms of the remaining list)` is equal to
48+
`(spots for the first elem to go in) * (num perms of the remaining list)` recursively.
49+
So the runtime is `O(n!)`.
50+
4651
## Code
4752

4853
[Python](permutations.py)
4954

5055
## Follow up
5156

57+
This procedure has already been implemented in Python's built-in library:
58+
59+
```python
60+
from itertools import permutations
61+
62+
permutations([1, 2, 3])
63+
```
64+
65+
https://docs.python.org/2/library/itertools.html#itertools.permutations

day22/permutations.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
def permutations(arr):
22
allPermutations = list()
33

4-
if len(arr) <= 1:
5-
return [arr]
4+
if len(arr) < 1:
5+
return [[]]
66
else:
77
for i in xrange(len(arr)):
88
for permutation in permutations(arr[1:]):
9-
# when i is 0, arr[0:1] is at the beginning of this list
109
allPermutations.append(permutation[:i] + arr[0:1] + permutation[i:])
1110

12-
return sorted(allPermutations)
11+
return allPermutations
1312

1413
def main():
1514
assert permutations([1]) == [[1]]
1615
assert permutations([1,2]) == [[1, 2], [2, 1]]
17-
assert permutations([1,2,3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
16+
assert permutations([1,2,3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 1, 2], [2, 3, 1], [3, 2, 1]]
1817

1918
if __name__ == "__main__":
2019
main()

0 commit comments

Comments
 (0)