Python 2.7列表模式,不使用内置函数

时间:2016-03-22 01:36:09

标签: python

在Python 2.7上我想创建一个函数来计算列表的模式而不使用任何内置函数(例如,不允许使用Count)

2 个答案:

答案 0 :(得分:1)

尝试以下功能,该功能不会使用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
>>> 

答案 1 :(得分:0)

以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)