How to count the most frequent letter in a line?

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 it was there that she lost me.

Here is the code calling 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() 
+5
source share
6 answers

I would use a dict to store the account. But first, I want to delete all spaces and other characters, and then az, I also want to consider the upper and lower case letters as one and the same.

When the dict is built with all my values, I use the max function. max takes iterability, so we pass the dict as a β€œlist” of tuples (key, val) . We need to tell max how to determine what we want to compare, because we give a lambda function that takes the second element ( val ) in the tuple in key-arg .

In turn, max will spit out the tuple with the highest val .

 class MyString: def __init__(self, myString): self.__myString = myString def countWord(self): count = len(self.__myString.split()) return count def findMostFrequentChar(self): counter = {} # Instead of performing various modifications on the string # one can instead filter all the undesired chars. # new_string = self.__myString.replace(' ', '').lower() new_string = list(filter(lambda x: 'a' >= x <= 'z', self.__myString.lower())) for char in new_string: if char in counter: counter[char] += 1 else: counter[char] = 1 key, value = max(counter.items(), key=lambda x:x[1]) return value, key 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() 
+1
source

The only hint she gave us was that we needed to make 2 lists. and it was there that she lost me.

This means that you cannot use collections.Counter , and perhaps not even dictionaries.

If we can assume that the letters are defined as the English alphabet, then one list is enough. In this case, you can create a list of 26 elements, all of which are initialized to 0. Then you can iterate over the characters of the string, and for each letter of the English alphabet, increase the counter of the n element in the list, where n is the index of the letter in the alphabet.

Create a list of 26 zeros:

 counts = [0] * 26 

Scroll the characters of the input string s :

 for c in s: 

Make sure the character is a letter:

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

Calculate the index by a letter in the alphabet and draw a counter:

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

Once you have the counters, 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')) .

+4
source

You can use sorted :

 class String: def __init__(self, s): self.s = s def findMostFrequentChar(self): return sorted([(a, self.s.count(a)) for a in self.s], key=lambda x:x[-1])[-1] 
+3
source

If you can use the Counter module from collections :

 from collections import Counter def findMostFrequentChar(self): d = Counter(self.__myString.replace(' ', '').lower()) return d.most_common()[0] 

If Counter out of the question:

 def findMostFrequentChar(self): d = {} for ch in self.__myString.replace(' ', '').lower(): if ch in d: d[ch] += 1 else: d[ch] = 1 most_frequent = max(d, key=d.get) return most_frequent, d[most_frequent] 

Introducing this as a whole:

 class MyString: def __init__(self, myString): self.__myString = myString def countWord(self): count = len(self.__myString.split()) return count def findMostFrequentChar(self): d = {} for ch in self.__myString.replace(' ', '').lower(): if ch in d: d[ch] += 1 else: d[ch] = 1 most_frequent = max(d, key=d.get) return most_frequent, d[most_frequent] 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.") letter, count = aString.findMostFrequentChar() print("The most frequent character is", letter, "which appeared", count, "times") main() 
+2
source

I will show you how to get the most frequent letter from a regular line using a dictionary without import. Your task is to customize your class accordingly.

I assume that if two or more letters have the highest frequency, either of these is a valid result.

 >>> s = 'aabacbcd' >>> counts = {} >>> for c in s: ... counts[c] = counts.get(c, 0) + 1 ... >>> counts {'a': 3, 'c': 2, 'b': 2, 'd': 1} >>> max(counts, key=counts.get) 'a' 
+1
source

The two-list part is annoying. However, one practical tool for counting iteration elements in Python is collections.Counter :

 from collections import Counter # ... def findMostFrequentChar(self): return Counter(self.__myString).most_common()[0][0] 
0
source

Source: https://habr.com/ru/post/1273299/


All Articles