Created
March 30, 2015 21:42
-
-
Save rohit-jamuar/0addac31cd02265ca4f8 to your computer and use it in GitHub Desktop.
Find all combinations / permutations of a string
This file contains hidden or 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
| def combine(s): | |
| if len(s) <= 1: | |
| return {'', s} | |
| last_char = s[-1] | |
| result = combine(s[:-1]) | |
| intermediate = {i for i in result} | |
| for item in result: | |
| intermediate.add(item + last_char) | |
| return list(intermediate) | |
| def permute(s): | |
| if len(s) <= 1: | |
| return {s} | |
| last_char = s[-1] | |
| result = set() | |
| for item in permute(s[:-1]): | |
| for index in range(len(item) + 1): | |
| result.add(item[:index] + last_char + item[index:]) | |
| return list(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment