How to extract max value from txt?

3963 views python
-1

I am coding my small scrabble game. What I have to do, is to print the highest score (only one) from a txt file.

This is my code:

letter_score = {'a' : 1, 'e' : 1, 'o' : 1,
        'i' : 1, 'n' : 1, 'r' : 1,
        'l' : 1, 't' : 1, 'l' : 1,
        's' : 1, 'n' : 1, 'd' : 2,
        'u' : 2,
        'g' : 2, 'b' : 3, 'c' : 3,
        'm' : 3, 'p' : 3, 'f' : 4,
        'h' : 4, 'v' : 4, 'w' : 4,
        'y' : 4, 'k' : 5, 'j' : 8,
        'x' : 8, 'q' : 10, 'z' : 10
}


max_word, max_score = '', 0
with open('dictionary.txt') as file:
for line in file:
words = line.split()
for word in words:
    word_value = 0
    if word.isalpha():
        for letter in word:
            word_value += letter_score[letter]

        if word_value > max_score:
            max_word = word
            max_score = word_value
        print(max_score)

But this is printing all values from a dictionary txt file. I just want it to print one, highest value from a txt file. Anyone can help?

answered question

If max_score eventually goes to the value you are wanting. Then unindent print(max_score). It also appears you are missing an indentation after with open('dictionary.txt') as file:

2 Answers

0

You can make a dict of all difirence values then choose the biggist one in that dict

posted this
0

Your print statement is in the wrong place. Where you have it currently makes the value print every single time it reads a line.

with open('dictionary.txt') as file:
    for line in file:
        words = line.split()
        for word in words:
            word_value = 0
            if word.isalpha():
                for letter in word:
                    word_value += letter_score[letter]

            if word_value > max_score:
                max_word = word
                max_score = word_value
    print(max_score)
    print(max_word)

posted this

Have an answer?

JD

Please login first before posting an answer.