簡體   English   中英

在兩個列表中有效地查找字謎

[英]Efficiently finding anagrams in two lists

我有兩個名為“查詢”和“數據”的列表,它們都包含字符串。 我需要計算“數據”中有多少“查詢”中每個字符串的字謎。

例如以下兩個列表:

查詢= ['否','結果','哦','abc','脾氣']

數據= ['no','on','bca','oh','cba','repmet','serult','pemter','tluser','tlures','pterem','temrep' ]

output 將是一個字典,其中包含每個單詞的字謎計數:

{'no': 2, 'result': 3, 'oh': 1, 'abc': 2, 'temper': 4}

我有一個使用嵌套循環的初始蠻力解決方案,但想知道我應該如何 go 來優化它,因為當列表變大時它會很慢。

dict1 = {}
data.sort()
data.sort(key=len, reverse=False)    

for idx in range(len(query)):

    dict1[query[idx]] = 0
    x = sorted(query[idx])

    for idx2 in range(len(data)):
      if len(data[idx2]) > len(query[idx]):
        break

      if data[idx2] == query[idx]:
        dict1[query[idx]] += 1

      elif x == sorted(data[idx2]):
        dict1[query[idx]] += 1

您可以使用計數器object:

from collections import Counter
query = ['no', 'result', 'oh', 'abc', 'temper']
data = ['no', 'on', 'bca', 'oh', 'cba', 'repmet', 'serult', 'pemter', 'tluser', 'tlures', 'pterem', 'temrep']

counts = Counter(''.join(sorted(word)) for word in data)
anagram_counts = {k:counts[''.join(sorted(k))] for k in query}
print(anagram_counts) #prints {'no': 2, 'result': 3, 'oh': 1, 'abc': 2, 'temper': 4}

這具有線性復雜性,而您的嵌套循環方法具有二次復雜性。 即使不使用計數器 object,您也可以獲得線性復雜度:一次傳遞data以創建計數字典和隨后傳遞query ,使用在第一個循環中構造的字典來創建目標字典。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM