麻木中最常出现的数字

2024-06-14 04:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是计算出长数中最常见的数字。例如,2135232455555将返回5。你知道吗

print('Question 4')



def most_frequent(number):
    analysisnumber=map(int,str(number))
    returnvalue=[0,0,0,0,0,0,0,0,0,0]
highest = 0
total2=0
for i in range(0,len(str(number))):
    returnvalue[analysisnumber[i]] = list(map(i,analysisnumber))
for i in range(0,20):
    if i < 10:
        if returnvalue[i] > highest:
            highest = returnvalue[i]
    if i > 10:
        if returnvalue[i-10] == highest:
            total2+=highest
print("The most frequent number",end="")
if total2 > highest:
    print("s are: ")
    for i in range(0,10):
        if returnvalue[i] == highest:
            print(i)
else:
    print(" is ", end="")
    for i in range(0,10):
        if returnvalue[i] == highest:
            print(i)
            break
number=int(input("Enter the number intended for analysis:"))
most_frequent(number)

我明白了

TypeError: 'int' object is not callable

错误。我需要帮助!你知道吗


Tags: innumbermapmostforifrangeint
2条回答

您使用了错误的map函数。你知道吗

returnvalue[analysisnumber[i]] = list(map(i,analysisnumber))

映射的第一个值(来自文档)是function):map(function, iterable, ...)

你给它提供了一个int(i)。你知道吗

这样就可以了,使用Counter

>>> from collections import Counter
>>> i = 24325872039847324509823475
>>> c = Counter(str(i))
>>> c
Counter({'2': 5, '3': 4, '4': 4, '5': 3, '7': 3, '8': 3, '0': 2, '9': 2})
>>> max(c.items(), key= lambda (x,y): y)
('2', 5)

或者直接使用(感谢@tobias\k):

>>> c.most_common(1)
[('2', 5)]

相关问题 更多 >