简体   繁体   中英

Make Dictionary of Strings with Common Characters

I'm stuck on a homework problem and am utterly stumped with no ideas left. I have tried different variations of code for the last 7 hours to no avail. The homework question is as follows:

Write a function named shareALetter that takes one parameter, wordList -- a list of words. Create and return a dictionary in which each word in wordList is a key and the corresponding value is a list of all the words in wordList that share at least one letter with that word. There should be no duplicate words in any value in the dictionary.

For example, the following is correct output:

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']}

Below is the code that has come the closest to solving the problem:

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))

I know this is terrible, sloppy, and inefficient with probably over a dozen issues, but I can't figure out how to fix any of the problems here. Any help would be appreciated.

When you need to create this kind of algorithm, it's helpful to imagine how you would approach the situation with just pen and paper. If I were you, I'd actually write out a few words and complete the exercise manually. As you do so, note how you are working through the problem, and see if you can translate that series of actions into code.

Here's a bit of a nudge to keep you going:

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))

确保添加正确的变量,这是我的问题!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM