-2

I got a list of points for each letter:

SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
                    (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]

And in file I have to find word with the highest score

I have a problem, because I don't know how to examine new line. I tried this, but its never ending loop:

max = 0
help = 0
file = open("dictionary.txt", "r")
for line in file:
    for l in line:
        while(l != '\n'):
            help += LETTER_SCORES.get(l)
            if(help > max):
                max = help
            else:
                continue
    help = 0

print(max)

Does anybody know what Im doing wrong?

[Edit] Mapping for dictionary:

LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
                    for letter in letters.split()}
martineau
  • 119,623
  • 25
  • 170
  • 301
Frendom
  • 508
  • 6
  • 24
  • `while(l != '\n'):` is an infinite loop because `l` never changes inside the body of the `while` loop. – mkrieger1 Nov 08 '18 at 18:31
  • Your structure is the wrong way round. For the scale of this problem, use a dictionary that maps letters as _keys_ to their points as _values_. – roganjosh Nov 08 '18 at 18:31

2 Answers2

1

The while loop is causing your error.

Say the first line began with the letter 'a', then the condition l != '\n' will be true and won't change during the iterations of the while loop, so you get stuck there.

You don't need the while loop altogether.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
1

Try using generator comprehensions for a cleaner and clearer answer:

words = ['foo', 'bar', 'baz']  # this simulates the words in your file

max(sum(LETTER_SCORES[c.upper()] for c in word) for word in words)  # returns 14 for 'baz'

You can read your file as follows:

with open("dictionary.txt") as f:
    words = list(f)
Alex
  • 18,484
  • 8
  • 60
  • 80