我想在不使用集合庫的情況下在給定的字串串列中找到常見字符。有人可以幫忙嗎?
輸入:
strings = ["apple", "app", "ape"]
輸出:
result - ap
uj5u.com熱心網友回復:
您的示例可能有 3 種解釋:任何位置的公共字符、同一位置的公共字符或開頭的公共字符(所有這些都會導致“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((i for i,(p,*r) in enumerate(zip(*strings))
if any(p!=c for c in r)),0)
print(strings[0][:common]) # ap
uj5u.com熱心網友回復:
像這樣:
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
假設您需要對所有常見字符進行排序。
uj5u.com熱心網友回復:
print({c for c in strings[0] if all(c in s for s in strings[1:])})
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/392869.html
