# Why doesn't this algorithm work correctly?

Given this algorithm why is the result ‘hareinnt’ and not ‘hareent’? at position number 4 of the for loop, which calculates the number of occurrences at the given position, the ‘i’ and ‘e’ both appear twice. Why is the ‘i’ added in the ‘newdict’ dictionary and not the ‘e’?

words = ['house ', 'garden ', 'kitchen ', 'balloon ', 'home ', 'park ', 'affair ', 'kite ', 'hello ', ‘portrait’, 'angel ', 'surfing ']

``````def freq(words):
pos = 0
lst = []
ris = ''
dictionary = {}
newdict = {}
for el in words:
conteggio = len(el)
while pos < conteggio:
for el in words:
for x in el[pos]:
lst.append(x)
print(lst)
for el in lst:
if el.isalpha():
dictionary[el] = dictionary.get(el, 0) + 1
for y in dictionary.items():
newdict[y[1]] = y[0]
print(newdict, end = '')
MAX = max(newdict.keys())
print(MAX)
ris += newdict.get(MAX)
MAX = 0
dictionary = {}
newdict = {}
lst = []
pos += 1
return ris
``````

Calculations performed by the for loop
[‘h’, ‘g’, ‘k’, ‘b’, ‘h’, ‘p’, ‘a’, ‘k’, ‘h’, ‘p’, ‘a’, ‘s’]
{3: ‘h’, 1: ‘s’, 2: ‘a’}3
[‘o’, ‘a’, ‘i’, ‘a’, ‘o’, ‘a’, ‘f’, ‘i’, ‘e’, ‘o’, ‘n’, ‘u’]
{3: ‘a’, 2: ‘i’, 1: ‘u’}3
[‘u’, ‘r’, ‘t’, ‘l’, ‘m’, ‘r’, ‘f’, ‘t’, ‘l’, ‘r’, ‘g’, ‘r’]
{1: ‘g’, 4: ‘r’, 2: ‘l’}4
[‘s’, ‘d’, ‘c’, ‘l’, ‘e’, ‘k’, ‘a’, ‘e’, ‘l’, ‘t’, ‘e’, ‘f’]
{1: ‘f’, 2: ‘l’, 3: ‘e’}3
[‘e’, ‘e’, ‘h’, ‘o’, ’ ', ’ ', ‘i’, ’ ‘, ‘o’, ‘r’, ‘l’, ‘i’] <---- Here the letters ‘i’ and ‘e’ both appear twice however the dictionary inserts the ‘i’ as the value of key 2 in the variable ‘newdict’. Why don’t you insert the ‘e’?
{2: ‘i’, 1: ‘l’}2
[’ ', ‘n’, ‘e’, ‘o’, ’ ', ’ ', ‘r’, ’ ', ’ ', ‘a’, ’ ‘, ‘n’]
{2: ‘n’, 1: ‘a’}2
[’ ', ’ ', ‘n’, ‘n’, ’ ', ’ ', ’ ', ’ ', ’ ', ‘i’, ’ ‘, ‘g’]
{2: ‘n’, 1: ‘g’}2
[’ ', ’ ', ’ ', ’ ', ’ ', ’ ', ’ ', ’ ', ’ ', ‘t’, ’ ', ’ ']
{1: ‘t’}1

I’ve haven’t looked closely at the code, but:

``````    for el in words:
conteggio = len(el)
``````

looks wrong to me. It’s getting the length of all the words, but `conteggio` will only ever be the length of the last one.

yes it is true, however since all the words in the list have a length of 8 characters each, some words lengthened with spaces, I preferred to give the variable ‘count’ the value of the length of the characters.

Please move the first triple ``` above the first line. The words in `words`, as displayed, are not all 8 chars. But they must be padded with spaces to the output printed. Perhaps `words` not being formatted as code is the problem, or else spaces disappeared somehow otherwise.

To understand your code, you should have printed `dictionary`. To answer your question about ‘e’ and ‘i’, should should have printed each `y` pair when pos is 3. `if pos == 3: print(y, end = '')`. In particular, `newdict(2) = 'e'` followed by `newdict(2) = 'i'` results in the latter being true. I believe ‘e’ was inserted and then replaced with ‘i’.