forked from MakeContributions/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore(Python): add find all permutations (MakeContributions#831)
* added find_all_permutations * added test case for find_all_permutations * updated README with find all permutations * Added desc and time complexity of find_all_permutations * PR comment spelling correction
- Loading branch information
1 parent
033fbe1
commit e1bbc8b
Showing
2 changed files
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
""" | ||
Find all the permutations of a given string | ||
Sample input: 'ABC' | ||
Expected output: ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] | ||
Description: The algorithm is recursive. In each recursion, each element of the string (left) is removed and added to the beginning (head). This process is repeated until left is empty. | ||
Time complexity: (n!) | ||
""" | ||
|
||
def permutation(head, left, permutations): | ||
if len(left) == 0: | ||
permutations.append(head) | ||
else: | ||
for i in range(len(left)): | ||
permutation(head+left[i], left[:i]+left[i+1:], permutations) | ||
|
||
def find_all_permutations(string): | ||
permutations = [] | ||
permutation('', string, permutations) | ||
return permutations | ||
|
||
if __name__ == "__main__": | ||
input = 'ABC' | ||
output = find_all_permutations(input) | ||
|
||
expected = ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] | ||
assert len(output) == len(expected), f"Expected 6 permutations, got: {len(expected)}" | ||
for perm in expected: | ||
assert perm in output, f"Expected permutation {perm} to be in output, missing" |