[英]Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K
[英]given an array of strings words of length n, find the number of pairs of string that are similar
问:给定一个长度为 n 的字符串数组,找出相似的字符串对的数量
回答:
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)
您需要从字符串列表中找到所有值对的组合。 然后,对于每一对,对一组每个字符串进行排序并比较它们是否相等。 可能有更有效的方法:
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:
2
笔记:
在 integer 算法的上下文中,Python True 和 False 的有效值分别为 1 和 0
选择:
由于您只使用对,因此您可以使用双循环而不是依赖 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.