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
CodePudding user response:
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
CodePudding user response:
Like this:
strings = ["apple", "app", "ape"]
char_sets = [{*s} for s in strings]
result_set = char_sets[0]
for char_set in char_sets[1:]:
result_set.intersection_update(char_set)
print(''.join(sorted(list(result_set))))
Returns:
ap
Assumed you need all common characters sorted.
CodePudding user response:
print({c for c in strings[0] if all(c in s for s in strings[1:])})