Reputation: 23
I'm trying to create a program where if you input a word, it will print out each letter of the word and how many times the letter appears in that word.
Eg; when I input "aaaarggh", the output should be "a 4 r 1 g 2 h 1".
def compressed (word):
count = 0
index = 0
while index < len(word):
letter = word[index]
for letter in word:
index = index + 1
count = count + 1
print(letter, count)
break
print("Enter a word:")
word = input()
compressed(word)
So far it just prints out each letter and position in the word. Any help appreciated, thank you!
(no using dict method)
Upvotes: 0
Views: 7850
Reputation: 13
def counter(word):
dic ={}
for i in [*word]:
counter = word.count(i)
d={i:counter}
dic.update(d)
return dic
counter("aaaarggh")
Upvotes: -1
Reputation: 2490
Counter
is concise. But here's an alternative using defaultdict
, which is a subclass of dict
.
from collections import defaultdict
test_input = "aaaarggh"
d = defaultdict(int)
for letter in test_input:
d[letter] += 1
https://docs.python.org/3.6/library/collections.html#defaultdict-examples
Upvotes: 0
Reputation: 467
try this, You can use counter it will return dict type
from collections import Counter
print(Counter("aaaarggh"))
Upvotes: 1
Reputation: 493
As others have suggested, you can do this easily with a dict
!
test_input = "aaaarggh"
def compressed (word):
letter_dict = {}
for letter in test_input:
if letter not in letter_dict:
letter_dict[letter] = 1
else:
letter_dict[letter] = letter_dict[letter]+1
return letter_dict
print(compressed(test_input))
Outputs:
{'a': 4, 'r': 1, 'g': 2, 'h': 1}
Upvotes: 0
Reputation: 4106
One way of implementing it using a dict
:
def compressed(word):
letters = dict()
for c in word:
letters[c] = letters.get(c, 0) + 1
for key, value in letters.items():
print(f'{value}{key}', end=' ')
Upvotes: 0
Reputation: 1039
Just type (for Python 2.7+):
import collections
dict(collections.Counter('aaaarggh'))
having:
{'a': 4, 'g': 2, 'h': 1, 'r': 1}
Upvotes: 2
Reputation: 8273
a="aaaarggh"
d={}
for char in set(a):
d[char]=a.count(char)
print(d)
output
{'a': 4, 'h': 1, 'r': 1, 'g': 2}
Upvotes: 1