-4

Python 3 - write a program that lets the user enter a string and displays the character that appears most frequently in the string.

This is my attempt so far, I know it needs a lot of work:

def main():
    count = 0

    my_string = input('Enter a sentence: ')

for ch in my_string:
    if ch == 'A' or ch == 'a':
        count+=1

print('The most popular character appears ', count, 'times.')

main()
Frank
  • 1
  • 1
  • 6
    This is a pretty easy thing to accomplish with a dictionary (in fact, there's a special dict subclass `collections.Counter` which makes this almost trivial) -- Have you learned about dictionaries yet? – mgilson Sep 10 '14 at 23:44
  • 4
    Search for "python letter frequency", there are a few posts about this already with a few different solutions. –  Sep 10 '14 at 23:45
  • Use a [dictionary](https://docs.python.org/2/tutorial/datastructures.html) (or similar) to maintain a *different* count for *each* character. Also, indentation matters. – user2864740 Sep 10 '14 at 23:47

1 Answers1

-1

Please find the code below:

import collections
def main():
    d = collections.defaultdict(int)
    my_string = input('Enter a sentence: ')
    for c in my_string.strip().lower():
        d[c] += 1
    val=dict(d).values()
    print('The most popular character appears ', sorted(val,reverse=True)[0], 'times.')

main()
Rijo Pius
  • 1
  • 1