From e1bbc8b3020e607cd13c8fc5f2194c95a3c5995e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Mart=C3=ADnez?= <44838230+amartinez1224@users.noreply.github.com> Date: Tue, 6 Sep 2022 14:15:28 -0400 Subject: [PATCH] chore(Python): add find all permutations (#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 --- algorithms/Python/README.md | 1 + .../Python/strings/find_all_permutations.py | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 algorithms/Python/strings/find_all_permutations.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index b7c82fd7..9bcc929b 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -63,6 +63,7 @@ - [Unique Character](strings/unique_character.py) - [Add String](strings/add_string.py) - [Rabin Karp algorithm](strings/rabin-karp-algorithm.py) +- [Find all permutations](strings/find_all_permutations.py) ## Dynamic Programming - [Print Fibonacci Series Up To N-th Term](dynamic_programming/fibonacci_series.py) diff --git a/algorithms/Python/strings/find_all_permutations.py b/algorithms/Python/strings/find_all_permutations.py new file mode 100644 index 00000000..cffb75d7 --- /dev/null +++ b/algorithms/Python/strings/find_all_permutations.py @@ -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"