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 = "".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((strings[0][:i] for i,(p,*r) in enumerate(zip(*strings))
if any(p!=c for c in r)),strings[0])
print(common) # ap
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))))
3条答案
按热度按时间bt1cpqcv1#
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:
To get common characters at the same positions:
To get the longest common prefix (without libraries):
q9yhzks02#
就像这样:
退货:
假设您需要对所有常用字符进行排序。
t9eec4r03#