'Hey guys. I am having problem on my code on python
I am having problem on how to code this one:
def letter_count(word):
ans = {}
word = ''.join(j for j in word if j.isalpha()).lower()
for j in word:
keys = ans.keys()
if j not in keys:
ans [j] = 1
else:
ans [j] += 1
return ans
print(letter_count(word = "Hello_world!"))
I keep getting this one
{'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}
But I want to make my output into
output = [
("d", 1),
("e", 1),
("h", 1),
("l", 3),
("o", 2),
("r", 1),
("w", 1)
]
Solution 1:[1]
Use return list(ans.items()) instead of return ans. This how to turn a dict into a list of tuples like you wanted.
With this change, the output is:
[('h', 1), ('e', 1), ('l', 3), ('o', 2), ('w', 1), ('r', 1), ('d', 1)]
Solution 2:[2]
Replace return ans with
[(k, v) for k, v in ans.items()]
Solution 3:[3]
This would be a good case for utilising defaultdict as follows:
from collections import defaultdict
def letter_count(word):
d = defaultdict(int)
for c in word.lower():
if c.isalpha():
d[c] += 1
return [(k, v) for k, v in d.items()]
print(letter_count(word = "Hello_world!"))
Output:
[('h', 1), ('e', 1), ('l', 3), ('o', 2), ('w', 1), ('r', 1), ('d', 1)]
Solution 4:[4]
Use set to remove the repeated elements from the data. It will be needed as a sequence of unique characters used to count. To avoid discrimination between upper and lower case characters I used the casefold method.
text = "Hello_worlDd!"
# get unique characters
chars = set(char for char in text.casefold() if char.isalpha())
# count the characters in the text
text_as_chars = tuple(text.casefold())
stats = [(char, text_as_chars.count(char)) for char in chars]
print(stats)
Output
[('l', 3), ('h', 1), ('o', 2), ('w', 1), ('e', 1), ('r', 1), ('d', 2)]
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 | Ukulele |
| Solution 2 | Oliver Mohr Bonometti |
| Solution 3 | Albert Winestein |
| Solution 4 | cards |
