mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
reorganize dir
Signed-off-by: Mia Steinkirch <mia.steinkirch@gmail.com>
This commit is contained in:
parent
1b6f705e7c
commit
a8e71c50db
276 changed files with 23954 additions and 0 deletions
32
other_resources/interview_cake/math/recursive_per.py
Normal file
32
other_resources/interview_cake/math/recursive_per.py
Normal file
|
@ -0,0 +1,32 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Write a recursive function for generating all permutations of an input string. Return them as a set.
|
||||
"""
|
||||
|
||||
def get_permutations(string):
|
||||
|
||||
if len(string) < 2:
|
||||
return set([string])
|
||||
|
||||
all_chars_except_last = string[:-1]
|
||||
last_char = string[-1]
|
||||
|
||||
permutations_of_all_chars_except_last = get_permutations(all_chars_except_last)
|
||||
|
||||
permutations = set()
|
||||
for permutation_of_all_chars_except_last in permutations_of_all_chars_except_last:
|
||||
for position in range(len(all_chars_except_last) + 1):
|
||||
permutation = (
|
||||
permutation_of_all_chars_except_last[:position]
|
||||
+ last_char
|
||||
+ permutation_of_all_chars_except_last[position:]
|
||||
)
|
||||
permutations.add(permutation)
|
||||
|
||||
|
||||
return permutations
|
||||
|
||||
|
||||
str = "abcd"
|
||||
print get_permutations(str)
|
Loading…
Add table
Add a link
Reference in a new issue