I'm trying to write a function that takes two user inputs: a word and a maximum length. The function reads from a text file (opened earlier in the program), looks at all the words that fit within the maximum length given, and returns a list of words from the file that contain all of the letters in the word that the user gave. Here's my code so far:
def comparison():
otherWord = input("Enter word: ")
otherWord = list(otherWord)
maxLength = input("What is the maximum length of the words you want: ")
listOfWords = []
for line in file:
line = line.rstrip()
letterCount = 0
if len(line) <= int(maxLength):
for letter in otherWord:
if letter in line:
letterCount += 1
if letterCount == len(otherLine):
listOfWords.append(line)
return listOfWords
This code works, but my problem is that it does not account for duplicate letters in the words read from the file. For example, if I enter "GREEN" as otherWord, then the function returns a list of words containing the letters G, R, E, and N. I would like it to return a list containing words that have 2 E's. I imagine I'll also have to do some tweaking with the letterCount part, as the duplicates would affect that, but I'm more concerned with recognizing duplicates for now. Any help would be much appreciated.
You could use a Counter for the otherWord, like this:
>>> from collections import Counter
>>> otherWord = 'GREEN'
>>> otherWord = Counter(otherWord)
>>> otherWord
Counter({'E': 2, 'R': 1, 'N': 1, 'G': 1})
And then your check could look like this:
if len(line) <= int(maxLength):
match = True
for l, c in counter.items():
if line.count(l) < c:
match = False
break
if match:
listOfWords.append(line)
You can also write this without a match variable using Python’s for..else construct:
if len(line) <= int(maxLength):
for l, c in counter.items():
if line.count(l) < c:
break
else:
listOfWords.append(line)
Edit: If you want to have an exact match on character count, check for equality instead, and further check if there are any extra characters (which is the case if the line length is different).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With