0

I am looking to write a program that lets a user enter a string and then shows the character that appears the most often in their inputted string. I originally wrote a program that counted the number of times a specific letter appeared (the letter T), but was looking to convert that. It may take a whole new code, though.

My former program is here:

# This program counts the number of times
# the letter T (uppercase or lowercase)
# appears in a string.

def main():
    # Create a variable to use to hold the count.
    # The variable must start with 0.
    count = 0

    # Get a string from the user.
    my_string = input('Enter a sentence: ')

    # Count the Ts.
    for ch in my_string:
        if ch == 'T' or ch  == 't':
            count += 1

    # Print the result.
    print('The letter T appears', count, 'times.')

# Call the main function.
main()

Similar to this code, but I am not familiar with a lot of what is used there. I am thinking the version of Python I use is older, but I may not be correct.

Community
  • 1
  • 1
user2901098
  • 11
  • 1
  • 3
  • 5

2 Answers2

7

You could use collections.Counter from Py's std lib.
Take a look here.

Also, a small example:

>>> from collections import Counter
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

EDIT

One liner!

count = [(i, string.count(i)) for i in set(string)]

Or if you want to write your own function (that's interesting!) you could start with something like this:

string = "abracadabra"

def Counter(string):
    count = {}
    for each in string:
        if each in count:
            count[each] += 1
        else:
            count[each] =  1
    return count # Or 'return [(k, v) for k, v in count]'

Counter(string)
out: {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}
JadedTuna
  • 1,783
  • 2
  • 18
  • 32
1
>>> s = 'abracadabra'
>>> max([(i, s.count(i)) for i in set(s.lower)], key=lambda x: x[1])
('a', 5)

This will not show ties though. This will:

>>> s = 'abracadabrarrr'
>>> lcounts = sorted([(i, s.count(i)) for i in set(s)], key=lambda x: x[1])
>>> count = max(lcounts, key=lambda x: x[1])[1]
>>> filter(lambda x: x[1] == count, lcounts)
[('a', 5), ('r', 5)]
dansalmo
  • 11,506
  • 5
  • 58
  • 53