Compare dictionary key with an integer

Asked

Viewed 110 times

2

My teacher gave a problem to be solved by the class.

Given a sentence, we want to know which letter appears the most, always working with lowercase letter, that is, disregarding the distinction between uppercase and lowercase letters.

I coded the following solution, in python:

def letra_q_mais_aparece(frase):
alfabeto = {"a":0, "b":0, "c":0, "d":0, 'e':0, 'f':0, 'g':0, 'h':0, 'i':0, 'j':0, 'k':0, 'l':0, 'm':0, 'n':0, 'o':0,'p':0,'q':0,'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0}
new_frase = frase.lower()
count = 0
mais_repete = ''
for letra in new_frase:
    if letra in alfabeto:
        alfabeto[letra] += 1

for letra in alfabeto:
    if alfabeto.keys() > count:
        count += letra.keys()
        mais_repete += letra
return mais_repete
a = input()
print(letra_q_mais_aparece(a))

The problem happens in the second. I wanted to compare each dictionary key with the counter variable, to then locate the most repeating letter, but gives an error that says that:

if alphabet.Keys() > Count: Typeerror: '>' not supported between instances of 'dict_keys' and 'int'

How can I make this code work?

2 answers

2


I was able to find the solution. I used the get command to get the values associated with the letters.

def letra_q_mais_aparece(frase):
alfabeto = {"a":0, "b":0, "c":0, "d":0, 'e':0, 'f':0, 'g':0, 'h':0, 'i':0, 'j':0, 'k':0, 'l':0, 'm':0, 'n':0, 'o':0,'p':0,'q':0,'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0}
new_frase = frase.lower()
count = 0
mais_repete = ''
for letra in new_frase:
    if letra in alfabeto:
        alfabeto[letra] += 1

for letra in alfabeto:
    if alfabeto.get(letra) > count:
        count = alfabeto.get(letra)
        mais_repete = letra
return mais_repete
a = input()
print(letra_q_mais_aparece(a))

2

I imagine the exercise is for educational purposes, but it is worth pointing out that the Counter, of the standard library collections, is a good tool for this case:

from collections import Counter

frase = 'A rápida raposa marrom pula sobre o cão preguiçoso.'

contador = Counter(frase.lower())
print(contador)  # Counter({' ': 8, 'o': 7, 'a': 6, 'r': 6, 'p': 4, 's': 3, 'i': 2, 'm': 2 ...

# Remover caracteres que não são do alfabeto.
# Iteramos sobre uma cópia do Counter pra não ter problemas com a remoção de elementos durante iteração
for chave in contador.copy():
    # O `isalpha()` tem a vantagem de manter caracteres acentuados (ç, ã, etc)
    if not chave.isalpha():
        contador.pop(chave)

print(contador)  # Counter({'o': 7, 'a': 6, 'r': 6, 'p': 4, 's': 3, 'i' ...
# Elemento mais comum e sua contagem
print(contador.most_common(1))  # [('o', 7)]
  • Yes, it’s for teaching purposes, but thanks for the tip!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.