在字符串列表中查找常见字符



我想在不使用集合库的情况下,在给定的字符串列表中找到常见字符。有人能帮忙吗?

输入:

strings = ["apple", "app", "ape"]

输出:

result - ap

您的示例可能有三种解释:任何位置的公共字符、相同位置的公共字母或开头的公共字母(所有这些都会导致"ap"(:

要在任何位置获得常见字符,可以在所有字符串上使用一个集合交集:

strings = ["apple", "app", "ape"]
common = set.intersection(*map(set,strings))
print(common) # {'p', 'a'}

要在相同位置获得常见字符:

strings = ["apple", "app", "ape"]
common = "".join(p for p,*r in zip(*strings) if all(p==c for c in r))
print(common) # ap

要获得最长的公共前缀(无库(:

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)),min(strings,key=len))
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))))

退货:

ap

假设您需要对所有常见字符进行排序。

print({c for c in strings[0] if all(c in s for s in strings[1:])})

最新更新