Skip to content

Commit 9be8b79

Browse files
committed
Added doctests
1 parent a71618f commit 9be8b79

File tree

1 file changed

+50
-62
lines changed

1 file changed

+50
-62
lines changed

backtracking/all_permutations.py

Lines changed: 50 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,88 +1,76 @@
11
"""
2-
In this problem, we want to determine all possible permutations
3-
of the given sequence. We use backtracking to solve this problem.
2+
Backtracking: generate all permutations of a sequence.
43
5-
Time complexity: O(n! * n),
6-
where n denotes the length of the given sequence.
4+
Time complexity: O(n! * n), where n is length of sequence.
75
"""
86

97
from __future__ import annotations
8+
from typing import List, Union
109

10+
Element = Union[int, str]
1111

12-
def generate_all_permutations(sequence: list[int | str]) -> None:
13-
create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
12+
13+
def generate_all_permutations(sequence: List[Element]) -> List[List[Element]]:
14+
"""
15+
Generate and return all permutations of the given sequence.
16+
17+
:param sequence: The input sequence.
18+
:return: A list of permutations (each permutation is a list).
19+
20+
Example 1 (integers):
21+
>>> generate_all_permutations([1, 2, 3])
22+
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
23+
24+
Example 2 (strings):
25+
>>> generate_all_permutations(["A", "B", "C"])
26+
[['A', 'B', 'C'], ['A', 'C', 'B'], ['B', 'A', 'C'], ['B', 'C', 'A'], ['C', 'A', 'B'], ['C', 'B', 'A']]
27+
28+
Example 3 (single element):
29+
>>> generate_all_permutations([1])
30+
[[1]]
31+
32+
Example 4 (empty sequence):
33+
>>> generate_all_permutations([])
34+
[[]]
35+
"""
36+
result: List[List[Element]] = []
37+
index_used = [False] * len(sequence)
38+
create_state_space_tree(sequence, [], 0, index_used, result)
39+
return result
1440

1541

1642
def create_state_space_tree(
17-
sequence: list[int | str],
18-
current_sequence: list[int | str],
43+
sequence: List[Element],
44+
current_sequence: List[Element],
1945
index: int,
20-
index_used: list[int],
46+
index_used: List[bool],
47+
result: List[List[Element]],
2148
) -> None:
2249
"""
23-
Creates a state space tree to iterate through each branch using DFS.
24-
We know that each state has exactly len(sequence) - index children.
25-
It terminates when it reaches the end of the given sequence.
26-
27-
:param sequence: The input sequence for which permutations are generated.
28-
:param current_sequence: The current permutation being built.
29-
:param index: The current index in the sequence.
30-
:param index_used: list to track which elements are used in permutation.
31-
32-
Example 1:
33-
>>> sequence = [1, 2, 3]
34-
>>> current_sequence = []
35-
>>> index_used = [False, False, False]
36-
>>> create_state_space_tree(sequence, current_sequence, 0, index_used)
37-
[1, 2, 3]
38-
[1, 3, 2]
39-
[2, 1, 3]
40-
[2, 3, 1]
41-
[3, 1, 2]
42-
[3, 2, 1]
43-
44-
Example 2:
45-
>>> sequence = ["A", "B", "C"]
46-
>>> current_sequence = []
47-
>>> index_used = [False, False, False]
48-
>>> create_state_space_tree(sequence, current_sequence, 0, index_used)
49-
['A', 'B', 'C']
50-
['A', 'C', 'B']
51-
['B', 'A', 'C']
52-
['B', 'C', 'A']
53-
['C', 'A', 'B']
54-
['C', 'B', 'A']
55-
56-
Example 3:
57-
>>> sequence = [1]
58-
>>> current_sequence = []
59-
>>> index_used = [False]
60-
>>> create_state_space_tree(sequence, current_sequence, 0, index_used)
61-
[1]
62-
"""
50+
Backtracking helper that appends permutations into result.
6351
52+
Example:
53+
>>> res = []
54+
>>> create_state_space_tree([1, 2], [], 0, [False, False], res)
55+
>>> res
56+
[[1, 2], [2, 1]]
57+
"""
6458
if index == len(sequence):
65-
print(current_sequence)
59+
# append a shallow copy
60+
result.append(current_sequence[:])
6661
return
6762

6863
for i in range(len(sequence)):
6964
if not index_used[i]:
7065
current_sequence.append(sequence[i])
7166
index_used[i] = True
72-
create_state_space_tree(sequence, current_sequence, index + 1, index_used)
67+
create_state_space_tree(sequence, current_sequence, index + 1, index_used, result)
7368
current_sequence.pop()
7469
index_used[i] = False
7570

7671

77-
"""
78-
remove the comment to take an input from the user
79-
80-
print("Enter the elements")
81-
sequence = list(map(int, input().split()))
82-
"""
83-
84-
sequence: list[int | str] = [3, 1, 2, 4]
85-
generate_all_permutations(sequence)
72+
if __name__ == "__main__":
73+
# example usage; kept under __main__ so it doesn't run on import/tests
74+
print(generate_all_permutations([3, 1, 2, 4]))
75+
print(generate_all_permutations(["A", "B", "C"]))
8676

87-
sequence_2: list[int | str] = ["A", "B", "C"]
88-
generate_all_permutations(sequence_2)

0 commit comments

Comments
 (0)