簡體   English   中英

使具有共同字符的字符串字典

[英]Make Dictionary of Strings with Common Characters

我陷入了家庭作業問題,完全陷入困境,沒有任何想法。 在過去的7個小時里,我嘗試了各種代碼變化,但無濟於事。 作業問題如下:

編寫一個名為shareALetter的函數,該函數帶有一個參數wordList-單詞列表。 創建並返回一個字典,其中wordList中的每個單詞都是一個鍵,而對應的值是wordList中與該單詞共享至少一個字母的所有單詞的列表。 字典中的任何值都不應有重復的單詞。

例如,以下是正確的輸出:

print(shareALetter(horton))
{'I': ['I'],
 'say': ['say', 'what', 'mean', 'and'], 
 'what': ['say', 'what', 'mean', 'and'], 
 'mean': ['say', 'what', 'mean', 'and'], 
 'and': ['say', 'what', 'mean', 'and']}

以下是最接近解決問題的代碼:

def shareALetter(wordList):
    shareCount = {}
    words=[]
    string=''
    for word in wordList:
        if word not in words:
            words.append(word)
        if word not in string:
            string += word
        if word not in shareCount:
            shareCount[word] = ''
    for key in shareCount:
        sharedWords = []
        for word in words:
            for letter in string:
                if letter in word and word not in sharedWords:
                    sharedWords.append(word)
                if word not in shareCount:
                    shareCount[word]=sharedWords

    return(shareCount)
print(shareALetter(test1))

我知道這很糟糕,草率而且效率低下,可能有十幾個問題,但是我不知道如何解決這里的任何問題。 任何幫助,將不勝感激。

當您需要創建這種算法時,想象一下如何用筆和紙來處理這種情況會很有幫助。 如果我是你,我實際上會寫下幾句話,然后手動完成練習。 在執行此操作時,請注意如何解決問題,並查看是否可以將一系列操作轉換為代碼。

為了讓您繼續前進,這里有一些提示:

def share_a_letter(word_list):
  character_matches = {}
  for word_one in word_list:
    character_matches[word_one] = set()
    for word_two in word_list:
      for character in word_two:
        # TODO:
        # check if the character is in word_one
        # if so, do something special
  return character_matches

words = ['hello', 'wopper', 'cat', 'pickle']
print(share_a_letter(words))

確保添加正確的變量,這是我的問題!

暫無
暫無

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

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