Skip to content

Commit 54e93de

Browse files
committed
[Feature] Added combinations of phone numbers. Minified permutation code.
1 parent a383ec1 commit 54e93de

File tree

4 files changed

+47
-3
lines changed

4 files changed

+47
-3
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,6 @@ Different algorithmic programs. Grouped by general topic.
6060
#### String Based Algorithms
6161
* [Fizz Buzz](algorithms/string/fizz_buzz.py)
6262
* [Permutations](algorithms/string/permutations.py)
63-
* [Combinations](algorithms/string/combinations.py)
63+
* [Combinations](algorithms/string/combinations.py)
64+
* [Letters in Word](algorithms/string/combinations.py)
65+
* [Letters from Phone](algorithms/string/combinations.py)

algorithms/string/combinations.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,39 @@ def combinations_of_word(string: str):
1010
output.append(string[i:j+1])
1111

1212
return output
13+
14+
def combinations_of_phone_input(string: str):
15+
"""
16+
Find all permutations of phone numbers in an input of numbers.
17+
18+
While not a 'combination' of numbers in the mathematical sense
19+
this is known more lexically as a combination. But does not
20+
contain all combinations possible. Only combinations that are
21+
full length using all input numbers in the string.
22+
23+
"""
24+
phone_mapper = {
25+
'1' : [],
26+
'2' : ['a','b','c'],
27+
'3' : ['d','e','f'],
28+
'4' : ['g','h','i'],
29+
'5' : ['j','k','l'],
30+
'6' : ['m','n','o'],
31+
'7' : ['p','q','r','s'],
32+
'8' : ['t','u','v'],
33+
'9' : ['w','x','y','z'],
34+
}
35+
36+
outputs = [letter for letter in phone_mapper[string[0]]]
37+
38+
for i in range(1,len(string)):
39+
temp = []
40+
for output in outputs:
41+
temp = temp + [output + letter for letter in phone_mapper[string[i]]]
42+
outputs = temp
43+
44+
return outputs
45+
46+
47+
48+

algorithms/string/permutations.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ def permute(current, remaining):
88
permute.list.append(current)
99
return
1010
for i in range(0,len(remaining)):
11-
remaining_minus = remaining[0:i] + remaining[i+1:]
12-
permute(current + remaining[i], remaining_minus)
11+
permute(current + remaining[i], remaining[:i] + remaining[i+1:])
1312

1413
permute.list = []
1514
permute('', list(string))

tests/test_combinations_phone.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import unittest
2+
from algorithms.string.combinations import combinations_of_phone_input
3+
4+
class TestCombinationsPhone(unittest.TestCase):
5+
6+
def test_phone_combo_simple(self):
7+
self.assertEqual(['da', 'db', 'dc', 'ea', 'eb', 'ec', 'fa', 'fb', 'fc'], combinations_of_phone_input('32'))

0 commit comments

Comments
 (0)