简体   繁体   English

给定一个长度为 n 的字符串数组,找出相似的字符串对的数量

[英]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.

相关问题 给定一个由 N 个整数组成的数组和一个整数 K,找出该数组中总和等于 K 的元素对的数量 - 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 使用python在for循环中的字符串中找到相似的单词 - Find similar words in strings in a for loop with python 查找长字符串中给定单词之前的 \\n 个数 - Find the number of \n before a given word in a long string 查找数组中分隔对的数量 - find the number of separated pairs in array 给定 2 个字符串 str 和 word,您必须找出从该给定字符串中可以创建多少个单词 - Given 2 Strings str and word, you have to find how many words can you make from that given string 在Python中查找给定长度的所有单词 - Find all words with a given length in Python 如何在单词/事物词典中找到前 N 个相似词? - How to Find Top N Similar Words in a Dictionary of Words / Things? 在给定字符列表的情况下生成字符串的所有可能性,但只需要长度不超过 n 的字符串 - Generating all possibilities of a string given a list of chars but want only the strings up to n length 如何在 python 中找到大于给定长度数的单词? - How can i find words which are greater than given number of length in python? 查找由 0 到 n 个单词分隔的两个字符串的最有效的正则表达式是什么? - What is the most efficient regular expression to find two strings separated by 0 to n number of words?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM