目标是计算出一个长数字中最常见的数字.例如,213523432455555555将返回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
错误.会爱一些帮助!
这样做,使用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)]
你正在使用错误的地图功能.
returnvalue[analysisnumber[i]] = list(map(i,analysisnumber))
映射的第一个值(来自文档)是函数): map(function, iterable, ...)
你提供了一个int(i).