Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

python - How to count the most frequent letter in a string?

class MyString:
    def __init__(self, myString):
        self.__myString = myString

    def countWord(self):
         count = len(self.__myString.split())
         return count

    def findMostFrequentChar(self):
        # ?

I need to implement findMostFrequenctChar. The only hint she gave us was that we needed to make 2 lists. and this is where she lost me.

Here's the code that calls the function:

def main():
    aString = MyString("This is a super long long long string. Please help count me")
    print("There are", aString.countWord(), "words in the string.")

    count, letter = aString.findMostFrequentChar()
    print("The most frequent character is", letter, "which appeared", count, "times")

main()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only hint she gave us was that we needed to make 2 lists. and this is where she lost me.

That seems to imply that you cannot use collections.Counter, and probably not even dictionaries.

If we can assume that letters are defined as the English alphabet, then one list is enough. In that case, you could create a list of 26 items, all initialized to 0. Then you could iterate over the characters of the string, and for each letter of the English alphabet, increment the count of the n-th item in the list, where n is the index of the letter in the alphabet.

Create a list of 26 zeros:

counts = [0] * 26

Loop over the characters of the input string s:

for c in s:

Check that the character is a letter:

if 'a' <= c.lower() <= 'z'

Calculate the 0-based index of the letter in the alphabet and increment the count:

index = ord(c.lower()) - ord('a')
counts[index] += 1

Once you have the counts, you can find the index that has the maximum value (left for you as an exercise), and get the corresponding character with chr(index + ord('a')).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...