简体   繁体   English

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

[英]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.

相关问题 在没有内置函数的情况下查找列表的模式 - Finding the mode of a list without built-in functions 在不使用python内置函数的情况下计算或添加列表元素 - Count or add list elements without using python built-in functions 在不使用内置函数的情况下反转列表 - Reverse a list without using built-in functions 如何在不使用控制台的内置函数的情况下在Python中的整数列表中查找最小值和最大值 - How to find minimum and maximum among a list of integers in Python without using built-in functions from console 在不使用内置函数的情况下在python中递归合并两个字符串 - Merging two strings recursively in python without using built-in functions 不使用内置函数返回第n个最低数字-Python - Returning nth lowest number without using built-in functions - Python 在不使用内置 python 函数的情况下替换字符串中的短语? - Replacing phrases in string without using built-in python functions? 在不使用内置 function 的情况下随机播放 python 列表 - Shuffle a python list without using the built-in function 不使用内置功能对字典排序 - sort a dictionary without using built-in functions 我需要在 python 2.7 中不使用内置 CSV 解析器读取 CSV 文件 - I need to read a CSV file without using built-in CSV parser in python 2.7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM