What is the built-in .count in python?

I solved problems on checkio.com, and one of the questions: "Write a function to find the letter that occurs with the maximum number of times in a given string"

The top solution was:

import string

def checkio(text):
    """
    We iterate through latin alphabet and count each letter in the text.
    Then 'max' selects the most frequent letter.
    For the case when we have several equal letter,
    'max' selects the first from they.
    """
    text = text.lower()
    return max(string.ascii_lowercase, key=text.count)

I did not understand what text.count is when it is used as a key in the max function.

Edit: Sorry for not specifying. I know what the program does, as well as the str.count () function. I want to know what text.count is. If .count is a method, shouldn't curly braces follow it?

+4
source share
3 answers

key=text.count - , , , , , .

, e, , , .

import string

def checkio(text):
    """
    We iterate through latin alphabet and count each letter in the text.
    Then 'max' selects the most frequent letter.
    For the case when we have several equal letter,
    'max' selects the first from they.
    """
    text = text.lower()
    return max(string.ascii_lowercase, key=text.count)

print checkio('hello my name is heinst')
+4

max() , , .

, max(string.ascii_lowercase, key=text.count) :

max_character, max_count = None, -1
for character in string.ascii_lowercase:
    if text.count(character) > max_count:
        max_character = character
return max_character

str.count() text, character.

/; Python, collections.Counter() type:

max_character = Counter(text.lower()).most_common(1)[0][0]

Counter() O (N) N, , O (K) , K - . , O (N) .

max() O (MN), M - string.ascii_lowercase.

+2

Use the Counter function from the collections module.

>>> import collections
>>> word = "supercalafragalistic"
>>> c = collections.Counter(word)
>>> c.most_common()
[('a', 4), ('c', 2), ('i', 2), ('l', 2), ('s', 2), ('r', 2), ('e', 1), ('g', 1), ('f', 1), ('p', 1), ('u', 1), ('t', 1)]
>>> c.most_common()[0]
('a', 4)
0
source

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


All Articles