[英]Python 2.7 Mode of list without using built-in functions
在 Python 2.7 上,我想创建一个函数来计算列表的模式而不使用任何内置函数(例如,不允许使用计数)
Try the following function, which does not use sum()
, count()
, or any built-in function apart from append
, to add to a list.尝试以下函数,该函数不使用sum()
、 count()
或除append
之外的任何内置函数来添加到列表。
def mode(lst):
sums = {}
for i in lst:
if i in sums:
sums[i]+=1
else:
sums[i] = 1
maxModes = [[-1, -1]]
for j in sums:
if sums[j] > maxModes[0][0]:
maxModes = [[sums[j], j]]
elif sums[j] == maxModes[0][0]:
maxModes.append([sums[j], j])
indices = 0
for k in maxModes:
indices+=1
if indices == 1:
return maxModes[0][1]
else:
thisSum = 0
for l in maxModes:
thisSum+=l[1]
return float(thisSum)/indices
>>> mode([1, 2, 3, 3, 4])
3
>>> mode([1, 2, 3, 3, 4, 4])
3.5
>>> mode([1, 2, 3, 3, 4, 4, 5, 5, 5])
5
>>> mode([1, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6])
5.5
>>> mode([1, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 9, 9, 9])
6.666666666666667
>>> mode([1, 2])
1.5
>>> mode([1])
1
>>> mode([])
-1
>>>
Taking an example of k = [1,2,3,5,3,1,6,3] as a sample list whose mode needs to be calculated以k = [1,2,3,5,3,1,6,3]为例,作为需要计算众数的样本列表
def quickSrt(lst):
if len(lst) < 2:
return lst
pivot = lst[0]
l = quickSrt([x for x in lst[1:] if x < pivot])
r = quickSrt([x for x in lst[1:] if x >= pivot])
return l + [pivot] + r
k = [1,2,3,5,3,1,6,3]
d = {}
for i in k:
if i in d:
d[i] += 1
else:
d[i] = 1
values = [value for key, value in d.items()]
val = quickSrt(values)
for x,y in d.items():
if y == val[-1]:
print(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.