Maximum Occurrence Letter - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Maximum Occurrence Letter (/thread-6544.html) |
Maximum Occurrence Letter - GalaxyCR - Nov-27-2017 Hey Guys, So I have an assignment regarding finding the most letters used in a word. For some reason I can't seem to make it work as the output that I get is based on First Letter. The def function for max_char_count I got from stack overflow if I'm not mistaken. Any help will be appreciated.This is my Code. global str1 def main(): str1 = input("Enter Your Message: ") print ("The Lenght of Your Message is:", len(str1),) print (max_char_count(str1)) def max_char_count(str1): max_char = '' max_count = 0 for char in (str1): count = str1.count(char) if count > max_count: max_count = count max_char = char return max_char main()This is my output. Original Def function. I just add the .upper() def max_char_count(string): max_char = '' max_count = 0 for char in set(string): count = string.count(char) if count > max_count: max_count = count max_char = char return max_char print(max_char_count('eeFAGAAJeEff'.upper()))The Output:
Nah Nevermind Got it. The return is a space ahead. I don't know how to delete this thread.
RE: Maximum Occurrence Letter - DeaD_EyE - Nov-27-2017 In your first function return max_char has the wrong indention. It's one level too deep. It returns inside the loop and you get only the count of the first letter.To count something, you should look for collections.Counter. import collections text = 'This is a test. Hello World. Foo Bar Baz...' c = collections.Counter(text) print('Most common') print(c.most_common(3)) RE: Maximum Occurrence Letter - nilamo - Nov-27-2017 Using collections is probably cheating, but using a dict might be fine:>>> def max_char(string): ... chars = {string.count(ch): ch for ch in string} ... most_used = max(chars.keys()) ... return chars[most_used] ... >>> max_char("foo bar") 'o' >>> max_char("spam eggs") 's' >>> max_char("on a bright sunny day in august") ' 'The important part, is that you actually understand how it works, whichever one you turn in. |