Reputation: 71
I need to write a code where the code counts the number of letters that are similar in the input. However the output should be in the same order as the input. For example if "Hello World" is in the input the output should say H: 1 e: 1 l: 3 o: 2 : 1 W: 1 r: 1 d: 1
so far I have this
import collections
sentence = input ('Enter a sentence : ')
#using Counter to count all the letters
letter_counts = collections.Counter(sentence)
#using sort to arrange the words in order.
for letter, count in sorted(letter_counts.items()):
print(letter, ':', str(count))
Upvotes: 0
Views: 70
Reputation: 6575
>>> from collections import OrderedDict
>>> sentence = 'Hello World'
>>> count = OrderedDict((word, sentence.count(word)) for word in sentence)
>>> print count
OrderedDict([('H', 1), ('e', 1), ('l', 3), ('o', 2), (' ', 1), ('W', 1), ('r', 1), ('d', 1)])
Upvotes: 0
Reputation: 691
string = "Hello World"
for index, char in enumerate(string):
if char not in string[:index]:
print '{0}: {1}'.format(char, string.count(char))
Output:
H: 1
e: 1
l: 3
o: 2
: 1
W: 1
r: 1
d: 1
Upvotes: 1
Reputation: 238647
You can change your for loop into this one:
unique_letters = []
#using sort to arrange the words in order.
for letter in sentence:
if letter not in unique_letters and letter is not ' ':
print(letter + ': ' + str(letter_counts[letter]), end=' ')
unique_letters.append(letter)
The result is:
H: 1 e: 1 l: 3 o: 2 W: 1 r: 1 d: 1
In the code i iterate through the original sentence, and check if any letter has been already shown or not, using unique_letters
list.
Upvotes: 0