Skip to content

Commit 4075f17

Browse files
Adding commonprefix method using OrderedDict
1 parent fc42605 commit 4075f17

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

idioms.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,28 @@ def flatten(iterables):
158158
for j in flatten(i): yield j
159159
else:
160160
yield i
161-
161+
162+
def commonprefix(*instrings):
163+
""" Common prefix of input strings using OrderedDict
164+
165+
>>> commonprefix('Python','Pythonista')
166+
'Python'
167+
>>> commonprefix('Persia','Person','Perl','Perlite')
168+
'Per'
169+
>>> commonprefix('Batman', 'Battleship','Batista','Bat')
170+
'Bat'
171+
172+
"""
173+
174+
d = collections.OrderedDict()
175+
176+
for instring in instrings:
177+
for idx,char in enumerate(instring):
178+
# Make sure index is added into key
179+
d[(char, idx)] = d.get((char,idx), 0) + 1
180+
181+
# Return prefix of keys where value == length(instrings)
182+
return ''.join([k[0] for k in itertools.takewhile(lambda x: d[x] == len(instrings), d)])
162183

163184
if __name__ == "__main__":
164185
import doctest

0 commit comments

Comments
 (0)