Bob*_*Bob -2 python python-3.x
我想在给定的字符串列表中查找常见字符而不使用集合库。有人可以帮忙吗?
输入:
strings = ["apple", "app", "ape"]
Run Code Online (Sandbox Code Playgroud)
输出:
result - ap
Run Code Online (Sandbox Code Playgroud)
您的示例可以有 3 种解释:任意位置的公共字符、同一位置的公共字符或开头的公共字符(所有这些都会导致“ap”):
要获取任意位置的公共字符,可以对所有字符串使用集合交集:
strings = ["apple", "app", "ape"]
common = set.intersection(*map(set,strings))
print(common) # {'p', 'a'}
Run Code Online (Sandbox Code Playgroud)
要获得相同位置的共同字符:
strings = ["apple", "app", "ape"]
common = "".join(p for p,*r in zip(*strings) if all(p==c for c in r))
print(common) # ap
Run Code Online (Sandbox Code Playgroud)
要获得最长的公共前缀(没有库):
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4319 次 |
最近记录: |