Alex Bass
Alex Bass

Reputation: 73

Use a dictionary to calculate most common letter

I am trying to write a function that will take in a string and use a dictionary to calculate and return the most common letter in that string. I believe that my code is close to working; however, I get a "cant assign to function call" error on line 5.

Here is my code so far:

def mostCommon(myString):
    charCount = []
    for c in myString.lower():
        if c in charCount:
            charCount(c) += 1
        else:
            charCount(c) = 1
    myVal = 0
    myKey = 0
    for key, value in charCount.lower():
        if value > myVal:
           myVal = value
           myKey = key
        return charCount

Upvotes: 0

Views: 762

Answers (4)

sslloo
sslloo

Reputation: 521

here after a few things that can help.

  1. The correct syntax to declare a dictionary is charCount = {}

  2. you cannot create an item with charCount(c), you better do charcount[c] = 'c'

To add element to a dictionnary: Add new keys to a dictionary?

Upvotes: 0

Oak Bot
Oak Bot

Reputation: 1

I think you intended charCount to be a dict not a list. Here is a simple solution using the max function:

def mostCommon2(myString):
    charCount = {}
    for c in myString.lower():
        if c in charCount:
            charCount[c] += 1
        else:
            charCount[c] = 1
    return max(charCount, key=charCount.get)

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60974

Here's your function with the errors corrected.

def mostCommon(myString):
    charCount = {}
    for c in myString.lower():
        if c in charCount:
            charCount[c] += 1
        else:
            charCount[c] = 1
    myVal = 0
    myKey = 0
    for key, value in charCount.items():
        if value > myVal:
           myVal = value
           myKey = key
    return myKey

Here's a much simpler way of doing it

from collections import Counter

def mostCommon(myString):
    return Counter(myString).most_common(1)[0][0]

Upvotes: 2

SuperStew
SuperStew

Reputation: 3054

Well you defined charCount as a list, and then tried to call it like a function. If you want charCount to just be a number, just set it to 0 before your for loop.

Or to use a dict

charCount = {}
for c in myString.lower():
    if c in charCount:
        charCount[c] += 1

Upvotes: 0

Related Questions