Break and explain function codes . ......................................................................................
def checkio(text):
return (lambda x: max(x, key=x.count))(sorted([i for i in text.lower() if i.isalpha()]))
Can someone break this into normal form pls?
What are these parentheses mean (........ )(.........)?
I already know the output of this program just that I don't know how this works.
Thank You.
CodePudding user response:
With the (...)(...)
you define and immediately call a lambda
and pass it the sorted
list as the parameter x
. The first (...)
is for operator precedence (call the lambda
, not the result of max
), the second (...)
is regular function call syntax. It's clearer if you move the lambda to a separate line:
def checkio(text):
f = lambda x: max(x, key=x.count)
return f(sorted([i for i in text.lower() if i.isalpha()]))
It's even more clearer, if you drop the lambda and instead just define the list as x
and call max
directly. Also, no need to sort the list.
def checkio(text):
x = [i for i in text.lower() if i.isalpha()]
return max(x, key=x.count)
This is still pretty inefficient, though, as the repeated calls to count
make it O(n²). Better use collections.Counter
to count all at once, then get the most_common
element.
from collections import Counter
def checkio(text):
return Counter(i for i in text.lower() if i.isalpha()).most_common(1)[0][0]
CodePudding user response:
well this function is giving the alphabet character having maximum occuerance.
so insort this function is like this
def checkio(text):
if len(text) == 0:
return None
def get_alphabets(text):
return [char for char in text.lower() if char.isapha()]
def get_most_frequent(array):
result = {}
for char in array:
if char not in result:
result[char] = 0
result[char] = 1
max_occu = max(result.values)
max_occurernce_char = [ char for char, value in result.items() if value == max_occu]
returm max_occuerence_char
clean_alphabets_in_lower = get_alphabets(text)
max_occuernce_chars = get_most_frequent(clean_alphabets_in_lower)
return max_occuernce_chars