[英]given an array of strings words of length n, find the number of pairs of string that are similar
Q: given an array of strings words of length n, find the number of pairs of string that are similar问:给定一个长度为 n 的字符串数组,找出相似的字符串对的数量
Answer:回答:
ls = ['aba','abaca','baab','cba']
ls2=[]
p=""
for str in ls:
print(str)
for char in str:
if char not in p:
p=p+char
sort_char = sorted(p)
p=''.join(sort_char)
ls2.append(p)
p=""
print(ls2)
cnt = 0
for i in range(0,len(ls)):
for j in range(i+1,len(ls)):
if ls2[i]==ls2[j]:
cnt+=1
print(cnt)
You'll need to find all combinations of pairs of values from the list of strings.您需要从字符串列表中找到所有值对的组合。 Then, for each pair, sort a set of each string and compare them for equality.
然后,对于每一对,对一组每个字符串进行排序并比较它们是否相等。 There may be more efficient ways:
可能有更有效的方法:
from itertools import combinations
ls = ['aba','abaca','baab','cba']
lsx = [set(e) for e in ls]
count = 0
for a, b in combinations(lsx, 2):
count += a == b
print(count)
Output: Output:
2
Note:笔记:
In the context of integer arithmetic, Python True and False have effective values of 1 and 0 respectively在 integer 算法的上下文中,Python True 和 False 的有效值分别为 1 和 0
Alternative:选择:
As you're only working with pairs you could use a double loop rather than rely on itertools as follows:由于您只使用对,因此您可以使用双循环而不是依赖 itertools,如下所示:
ls = ['aba','abaca','baab','cba']
lsx = [set(e) for e in ls]
count = 0
for i, a in enumerate(lsx):
for b in lsx[i+1:]:
count += a == b
print(count)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.