0

This prog takes in an input from the user such as "aeoritre" and outputs any word that can be made from these letters. The dictionary.txt file contains the wordlist.

My question is how do I output just the longest word that the string matches to instead of printing all of them? also if words are tied for longest, output only one of them. Thanks in advance!

from collections import Counter

words = []


def isAnAnagram(word, user):
    word_counter = Counter(word)
    input_counter = Counter(user)
    return all(count <= input_counter[key] for key, count in word_counter.items())

def getAnagrams(user):
    lister = [word for word in words if len(word) <= len(user) ]
    for item in lister:
        if isAnAnagram(item, user):
            yield item


with open('Dictionary.txt', 'r') as f:
    allwords = f.readlines()
f.close()

for x in allwords:
    x = x.rstrip()
    words.append(x)
inp = 1


while inp != "99":
    inp = input("enter word:")
    result = getAnagrams(inp)
    print(list(result))
    print(len(list(result)))

2 Answers 2

1

A simple way would be to sort the resulting list by length in descending (reversed) order and print the first element:

result = list(getAnagrams(inp))
result.sort(key=lambda x: len(x), reverse=True)
print(result[0])
Sign up to request clarification or add additional context in comments.

Comments

0

Create a dictionary with key (word) and values(len(word), then sort the dictionary and take the last value of the sort result.

import operator
resultDict = {i: len(i) for i in list(result)}
sortedresult = sorted(resultDict.items(), key=operator.itemgetter(1))
print sortedresult[-1][0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.