0

I'm working on a lab (in Python 3) that requires me to find and print the character in a string that occurs most frequently. For example:

>>> print(maxCharCount('apple'))
['p']

The idea is to do this using a loop, but I'm confused about how to do this.

zondo
  • 18,070
  • 7
  • 35
  • 73
Kelsey
  • 11
  • 1
  • 2
  • `maxCharCount = lambda string: sorted(string, key=lambda s: string.count(s))[-1]` – zondo Mar 02 '16 at 01:29
  • Possible duplicate of [Finding the most frequent character in a string](http://stackoverflow.com/questions/4131123/finding-the-most-frequent-character-in-a-string) – idjaw Mar 02 '16 at 01:35

4 Answers4

4
def maxCharCount(ss):
    return max(ss, key=ss.count)
bddap
  • 371
  • 3
  • 6
1

Since you really want to use a for loop:

a = 'apple'
m = set(a)
max = 0
for i in m:
    if a.count(i) > max:
         max = a.count(i)

edit: I didnt read good, you actually want the letter not the number of times it appear so i edit this code into:

a = 'apple'
m = set(a)
max = 0
p = ''
for i in m:
        if a.count(i) > max:
             max = a.count(i)
             p = i
pipiripi
  • 11
  • 2
1
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('apple'))
ChrisFreeman
  • 4,143
  • 4
  • 17
  • 29
0
def count(char, string):
    c = 0
    for s in string:
        if char == s:
            c += 1
    return c

def max_char_count(string):
    biggest = string[0]
    for c in string:
        if count(c,string) > count(biggest,string):
            biggest = c
    return biggest
bddap
  • 371
  • 3
  • 6