Last active
August 7, 2023 15:34
-
-
Save coffeewasmyidea/c98b483f597cc66a7f55d7a891db39f1 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 | |
from collections import deque | |
def combinations(digits): | |
keys = { | |
"2": "abc", | |
"3": "def", | |
"4": "ghi", | |
"5": "jkl", | |
"6": "mno", | |
"7": "pqrs", | |
"8": "tuv", | |
"9": "wxyz", | |
} | |
queue = deque() | |
if digits: | |
queue.append("") | |
while queue and len(queue[0]) < len(digits): | |
current_combination = queue.popleft() | |
next_digit = digits[len(current_combination)] | |
letters = keys[next_digit] | |
for letter in letters: | |
queue.append(current_combination + letter) | |
return list(queue) | |
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