Last active
August 7, 2023 15:34
-
-
Save coffeewasmyidea/76ef61df77226d76f0ef7760b528d2e2 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python | |
def combinations(digits): | |
keys = { | |
"2": "abc", | |
"3": "def", | |
"4": "ghi", | |
"5": "jkl", | |
"6": "mno", | |
"7": "pqrs", | |
"8": "tuv", | |
"9": "wxyz", | |
} | |
def backtrack(combination, next_digits): | |
if len(next_digits) == 0: | |
result.append(combination) | |
else: | |
letters = keys[next_digits[0]] | |
for letter in letters: | |
backtrack(combination + letter, next_digits[1:]) | |
result = [] | |
if digits: | |
backtrack("", digits) | |
return result | |
print(combinations("23")) # ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf'] | |
print(combinations("")) # [] | |
print(combinations("2")) # ['a', 'b', 'c'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment