'The most common letter in a string (Python)
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?
Solution 1:[1]
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]
Solution 2:[2]
Try this:
from string import ascii_lowercase
def most_common_letter(text: str):
counter = {}
for letter in text.lower():
if letter not in counter:
counter[letter] = 0
if letter in ascii_lowercase:
counter[letter] += 1
return max(counter, key=counter.get)
This solution increments the value after making sure that the key exists in the dictionary, and then returns the key with the max value.
Solution 3:[3]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Barmar |
Solution 2 | |
Solution 3 |