Search code examples
pythonprintingcountletter

Python: Print the common letter from user input


Is there a better way the write this code. While there are no errors it seems that its printing all the letters I typed sorted into a list.

I want to print the common letters in a string, even if more than one.

Here is what I Have

mystr = input("Enter a string:")
s = list(mystr) 
letter_counter = {}
for word in mystr:
    if word in letter_counter:
         letter_counter[word] += 1
    else:
         letter_counter[word] = 1

 user_letter = sorted(letter_counter, key = letter_counter.get, reverse = True)

 number_1 = user_letter[:2]
 print(number_1)  

The only way I can print the correct letters is by setting a limit on

number_1 = user_letter[:2]

For example if I enter the following:

mystr = input("Thomas Jones")

in the code the printed output would be

print(number_1)       
[o], [s]

Which is right but if the limit was set to from 2 to 3

number_1 = user_letter[:3]

It will print [o] [s] [a] there is only one a it shouldn't be there. I want it so that any amount the of words the user inputs it will show the correct repeated letter without the limiter.

I'm liberality stuck I have no idea how to correct this


Solution

  • from collections import Counter
    [letter for letter,count in Counter("Thomas Jones").items() if count > 1]