Erwy Lionel
Erwy Lionel

Reputation: 71

how to sort it in order of the input

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

Answers (3)

Mauro Baraldi
Mauro Baraldi

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

sumit-sampang-rai
sumit-sampang-rai

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

Marcin
Marcin

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

Related Questions