I have an exercise to find the most common letter in a string, excluding punctuation symbols, digits and whitespaces and the result should be in lowercase "A"== "a".
What I have:
import string
def most_common_letter(text: str):
s = string.ascii_lowercase
text = text.lower()
counter = {}
for i in text:
if i in s:
counter[i] = 1
for k,v in counter.items():
if k == i:
v = 1
return counter
But in result my dictionary doesn't count. Where is mistake?
CodePudding user response:
You're never incrementing the counts in counter
. You just set the count to 1
whenever the character is in s
. The loop that increments v
has no effect on the dictionary.
You can use defaultdict(int)
to create a dictionary that automatically initializes elements to 0
the first time you access them.
After filling in the dictionary, you can get the maximum count, and then find all the letters with that count.
import string
from collections import default dict
def most_common_letter(text: str):
s = string.ascii_lowercase
text = text.lower()
counter = defaultdict(int)
for i in text:
if i in s:
counter[i] = 1
highest = max(counter.values())
return [k for k, v in counter.items() if v == highest]
CodePudding user response:
First lowercase string
s = "Ascsdfavsdfsdassdf!@5DFA7&".lower()
Next, keep only alphabetic characters
s_alpha = filter(lambda x:x.isalpha(), s)
finally, use Counter
to count repeated characters and keep the most common ones.
from collections import Counter
most_char = Counter(s_alpha).most_common(1)
print(most_char)
# output: [('s', 6)]
Note: most_char[0][0]
printed char
you can read all lines in a function and run it
def most_common_letter(text: str) -> str:
text_lowercase: str = text.lower()
text_alpha: str = filter(lambda x:x.isalpha(), text_lowercase)
most_char: List[tuple] = Counter(text_alpha).most_common(1)
return most_char[0][0]