Issue
I want to find common chars in given list of strings without using collections library. Can someone help on this?
Input:
strings = ["apple", "app", "ape"]
Output:
result - ap
Solution
You example could have 3 interpretations: common char at any position, common chars at same position, or common chars at the beginning (all these would result in 'ap'):
To get common characters at any position, you can use a set intersection over all strings:
strings = ["apple", "app", "ape"]
common = set.intersection(*map(set,strings))
print(common) # {'p', 'a'}
To get common characters at the same positions:
strings = ["apple", "app", "ape"]
common = "".join(p for p,*r in zip(*strings) if all(p==c for c in r))
print(common) # ap
To get the longest common prefix (without libraries):
strings = ["apple", "app", "ape"]
common = next((i for i,(p,*r) in enumerate(zip(*strings))
if any(p!=c for c in r)),0)
print(strings[0][:common]) # ap
Answered By - Alain T.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.