The Most Frequent
题目:
Input: a list of strings.
Output: a string.
Example:
most_frequent([
'a', 'b', 'c',
'a', 'b',
'a'
]) == 'a'
most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi'
结果:
def most_frequent(data: list) -> str:
"""
determines the most frequently occurring string in the sequence.
"""
# your code here
return max(data, key=lambda a: data.count(a))
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
print('Example:')
print(most_frequent([
'a', 'b', 'c',
'a', 'b',
'a'
]))
assert most_frequent([
'a', 'b', 'c',
'a', 'b',
'a'
]) == 'a'
assert most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi'
print('Done')
max用法
- max(1,2,3,4) 返回4
- 如果max只输入一个参数 那那个参数一定是可迭代对象
- 下面将data(可迭代对象) 的值依次赋给a 然后根据lambda定义的函数算出应返回给max的值
- 当存在多个相同的最大值时,返回的是最先出现的那个最大值。
-
>>> max(1,2,'3') #数值和字符串不能取最大值 Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> max(1,2,'3') TypeError: unorderable types: str() > int() >>> max(1,2,'3',key = int) # 指定key为转换函数后,可以取最大值 >>> max((1,2),[1,1]) #元组和列表不能取最大值 Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> max((1,2),[1,1]) TypeError: unorderable types: list() > tuple() >>> max((1,2),[1,1],key = lambda x : x[1]) #指定key为返回序列索引1位置的元素后,可以取最大值 (1, 2)

浙公网安备 33010602011771号