Skip to content

Instantly share code, notes, and snippets.

@coffeewasmyidea
Last active August 7, 2023 15:34
Show Gist options
  • Save coffeewasmyidea/76ef61df77226d76f0ef7760b528d2e2 to your computer and use it in GitHub Desktop.
Save coffeewasmyidea/76ef61df77226d76f0ef7760b528d2e2 to your computer and use it in GitHub Desktop.
#!/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