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