There is a list with words (wordListReal). Every letter in the alphabet has an assigned value (see code).
Now the question is how to obtain the value of all the letter values added together per word, then divided by the number of letters in that word.
I tried this, but strangely enough it returns only lots of 0, 1 and 2, which is incorrect:
frequencyPointList = []
points1 = 0
toDivideBy = 1
for word1 in wordListReal:
points1 = (int(points1) // int(toDivideBy))
frequencyPointList.append(points1)
points1 = 0
toDivideBy = len(word1)
for letter1 in word1:
if letter1 in {"e" , "a" , "r" , "i" , "o"}:
points1 = 1
if letter1 in {"t" , "n" , "s" , "l" , "c"}:
points1 = 2
if letter1 in {"u" , "d" , "p" , "m" , "h"}:
points1 = 3
if letter1 in {"g" , "b" , "f" , "y" , "w"}:
points1 = 4
if letter1 in {"k" , "v" , "x" , "z" , "j" , "q"}:
points1 = 5
print(frequencyPointList)
Eventually the results need to be in a list, not in a dictionary.
Many thanks in advance!
CodePudding user response:
Couple of things that seem odd to me:
- the logic for checking each letter seems incorrect, it can be done a lot easier.
- use
elifinstead ofifas this will speed up the process. A letter can only match one time. - This calls for a method...
def get_points_for_word(word: str) -> float:
total_points = 0
for letter in word:
if letter in "eario":
total_points = 1
elif letter in "tnslc":
total_points = 2
elif letter in "udpmh":
total_points = 3
elif letter in "gbfyw":
total_points = 4
elif letter in "xvxzjq":
total_points = 5
print(total_points)
return total_points / len(word)
print(get_points_for_word("thisisnotaword"))
CodePudding user response:
You just need to keep track of your variables:
points1should always be0at the begining of your loop- You accumulate the points in the variable inside the
letter1loop - After the loop in the previous step, you calculate the average points per word (i.e. redefine
points1) - Add the previous value to your list
- Keep going
This means:
for word1 in wordListReal:
points1 = 0
for letter1 in word1:
# if ...
# points1 = ...
toDivideBy = len(word1)
points1 = (int(points1) // int(toDivideBy))
frequencyPointList.append(points1)
At the moment, your code does not reflect this logic, instead it is forcing the first value to always be the same and misses the value of the last word.
Some tips to improve your code further:
- Use
if/elif(andelseif necessary) to avoid calculating conditions multiple times when you don't need. For example, you have multipleifstatements and all of them will be calculated on each iteration. Usingif/elifthe calculation will stop the first time that condition isTrue. - Use
printto check how your code is progressing, for example: print the current word and in the inner loop print the letter and currentpoints1total to confirm that the total matches your expectations. You could also print the value offrequencyPointListat the end of each iteration in your outer loop.
