1

I have created a function to find the longest word in a text file and finding the longest word(s) in a text file that can be made from 9 letters. I'm new to python and I'm creating a game similar to countdown.

I've created a function to find the longest word in the text file. What I want now is to create python code to find the longest word(s) that can be formed from the 9 letters.

Each letter can only be used once. So from 'qugteroda', I should get rag outed, outraged, out dare, out read, outrage,readout. I'm using python 2.2

    def Words():
           qfile=open('dict.txt','r')
           longg=''
           for line in qfile:
           if len(line)>len(longg):
             longg=line
           return longg
Mal C
  • 23
  • 1
  • 2
  • 4
  • 2
    Why are you using Python 2.2? Are you sure it's 2.2? – Blender May 03 '13 at 18:59
  • 2
    You can write a permutation algorithm, but, Python has no concept of which permutations will be a valid English word. – adchilds May 03 '13 at 19:01
  • @adchilds. thats why i am using the file dict.txt which is a dictionary – Mal C May 03 '13 at 19:03
  • Do you have a dictionary or a list of valid english words to compare to? – Bhavish Agarwal May 03 '13 at 19:04
  • @MalC, so the longest possible word and the longest possible word(s) from the previous longest possible word are all in the same file (dict.txt)? – adchilds May 03 '13 at 19:05
  • Your Python is 10 years old now, please update to 2.7.4 (should go painless) – Kos May 03 '13 at 19:09
  • Please clarify this question; the title appears to contradict the actual question content. I suggested an edit, but it was considered too major to accept; feel free to use it as a suggestion for how to improve this question, though. http://stackoverflow.com/review/suggested-edits/2046682 – Kyle Strand May 04 '13 at 07:22
  • possible duplicate of [Length of longest word in a list](http://stackoverflow.com/questions/14637696/length-of-longest-word-in-a-list) – n0p Sep 01 '14 at 09:56

7 Answers7

2

I would do something like this:

from collections import Counter

def find_words(valid_letters):
    valid_letters = Counter(valid_letters)

    with open('dict.txt', 'r') as handle:
        for word in handle:
            letters = Counter(word.strip())

            if valid_letters >= letters:
                yield word

longest_word = max(find_words('qugteroda'), key=len)

The gist of it is that you count what letters are in your word. Something like this:

>>> count_letters('test')
{'t': 2, 'e': 1, 's': 1}

And then check to see if every one of those letters is in your valid letters dict (making sure that the counts are also equal to or smaller than the allowed counts).

Then, you just find the longest word.

To find the longest combination of words, make a recursive function that builds chains of words that fit within your letter constraints.

Blender
  • 289,723
  • 53
  • 439
  • 496
1

Use itertools to get the permutation:

list(itertools.permutations("qugteroda")

and for every element in the list, check if that word exists in the dictionary file.

You can check Trie for fast lookup in the dctionary.

Bhavish Agarwal
  • 663
  • 7
  • 13
0

1/ create a sorted string from the letters :

qugteroda ->  adegoqrtu
the_letters = 'adegoqrtu'

2/ Create a list from all the words in your word file, the list should have words with largest length at beginning, and smaller ones in the end, this will fasten your search for N largest words.

eg. international, ragouted,facebook,outraged, outdare, outread, outrage,readout

This list of words will not contain the words as is, but contain the sorted representation of the words. Store this search_dict in cache or file for further use.

eg. search_dict = ['aaeiilnnnortt' , 'adegortu' ,'abcefkoo','adegortu']

3/ To find N largest words, just loop through search_dict, and keep adding words which are a subset of the characters in the_letters string. You can exit the loop once N words have been found.

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
  • This is somewhat clever, but unfortunately even despite sorting there's no guarantee that the dictionary words will be substrings of `the_letters`. Consider the case where the dictionary contains the single string `ac` and the letters are `abc`. `ac` is valid, but this algorithm will reject it. – Kyle Strand May 03 '13 at 20:29
  • @KyleStrand Thanks for picking up that big bug, added a correction that instead of substring,it should be a subset of the characters of the_letters. Rest of the method remains the same. – DhruvPathak May 04 '13 at 07:10
0

I would do something like this:

def longest_word(filename):
with open(filename, 'r') as infile:
          words = infile.read().split()
print(words)    #  return list ['What', 'is', 'Python', 'language?', 'Python', ……..]
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('test.txt'))
yogesh kumar
  • 327
  • 1
  • 4
  • 15
0
with open('text.txt') as file:
    data=file.read().split()
    max=len(max(data,key=len ))
    print(max)
    res=[word for word in data if len(word)==max]
    print(res)
0
file = open("C:/Users/Dell/Desktop/Demo.TXT", mode="r", encoding="utf8")
file = file.read().split()
lenght = 0
Longest_word = ""
for word in file:
    if len(word) > lenght:
        lenght = len(word)
        Longest_word = word

print(Longest_word, lenght)
  • I am trying to get 5 longest word from a text file but i only get one longest word . Anyone can tellme what am i doing wrong – raja Osama Sep 30 '22 at 12:49
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 04 '22 at 17:16
-2

I know this question is a year old now but, try this:

'''Write a function find_longest_word() that takes a list of words and returns the length of the longest one.'''

a = ['mamao', 'abacate', 'pera', 'goiaba', 'uva', 'abacaxi', 'laranja', 'maca']


def find_longest_word(a):

    d = []
    for c in a:
        d.append(len(c))
        e = max(d)  #Try "min" :D
    for b in a:
        if len(b) == e:
            print "Length is %i for %s" %(len(b), b)
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331