python - 列表的最小值和最大值(不使用最小/最大函数)

标签 python algorithm minmax

我想知道是否有一种方法可以在不使用 Python 中的最小/最大函数的情况下找到列表的最小值和最大值。所以我用递归写了一个小代码。我的逻辑非常天真:我制作了两个堆栈(min_stackmax_stack),它们在每次递归调用期间跟踪最小值和最大值。我有两个问题:

  1. 有人可以帮我估计代码的复杂性吗?
  2. 有更好的方法吗?使用合并排序/快速排序并选取第一个和最后一个元素对列表进行排序是否会提供更好的性能?

这是我在 Python 中的尝试:

minimum = []
maximum = []

# Defining Stack Class
class Stack:
    def __init__(self) :
        self.items = []

    def push(self, item) :
        self.items.append(item)

    def pop(self) :
        return self.items.pop()

    def access(self, index):
        return self.items[index]

    def isEmpty(self) :
        return (self.items == [])

    def length(self):
        return len(self.items)

def minmax(input_list):
    # make two stacks, one for min and one for max
    min_stack = Stack()
    max_stack = Stack()
    # comparing the first two elements of the list and putting them in appropriate stack
    if input_list[0]<input_list[1]:
        min_stack.push(input_list[0])
        max_stack.push(input_list[1])
    else:
        max_stack.push(input_list[0])
        min_stack.push(input_list[1])

    # Pushing remaining elements of the list into appropriate stacks. 
    for i in range(2, len(input_list)):
        if input_list[i] < min_stack.access(-1):
            min_stack.push(input_list[i])
        else:
            max_stack.push(input_list[i])

    # to find minimum
    minlist = []
    while min_stack.length() > 0:
        minlist.append(min_stack.pop())

    # to find maximum
    maxlist = []
    while max_stack.length() > 0:
        maxlist.append(max_stack.pop())

    if len(minlist) > 1:
        minmax(minlist)
    else:
        minimum.append(minlist)


    if len(maxlist) > 1:
        minmax(maxlist)
    else:
        maximum.append(maxlist)

def main():
    input_list = [2, 0, 2, 7, 5, -1, -2]
    print 'Input List is: ', input_list
    minmax(input_list)

print 'Global Minimum is: ', minimum[0]
print 'Global Maximum is: ', maximum[len(maximum)-1]

if __name__ == "__main__":
    main()

最佳答案

对于中等大小的列表,sorted() 当然是可靠的、快速编写的和高性能的,因为它是内置的。对于大型列表,O(n) 算法会更快,例如:

def minmax1 (x):
    # this function fails if the list length is 0 
    minimum = maximum = x[0]
    for i in x[1:]:
        if i < minimum: 
            minimum = i 
        else: 
            if i > maximum: maximum = i
    return (minimum,maximum)

print(minmax1([9,8,7,6,5,4,3,2,1,11,12,13,14,15,16,17,18,19]))
print(minmax1([1]))
print(minmax1([2, 0, 2, 7, 5, -1, -2]))

...输出为:

(1, 19)
(1, 1)
(-2, 7)

我有兴趣检查这两个备选方案的性能。在我运行 Windows XP 和 Python 3.2.3 的 PC 上,我发现对于少于 500 个元素的列表,排序方法比上面定义的 minmax1() 函数更快,但是对于更长的列表,O (n) minmax1() 更快。我的计时测试代码如下:

def minmax_sort(x):
    x = sorted(x)
    return (x[0],x[-1])

import timeit

aa = list(range(0,100))
a = aa
while (1):
    stime = min(timeit.repeat('minmax_sort(a)', "from __main__ import minmax_sort,a",number=1000))
    mtime = min(timeit.repeat('minmax1(a)', "from __main__ import minmax,a",number=1000))
    if (stime > mtime):
        break
    else:
        a = a + aa
print(len(a))

关于python - 列表的最小值和最大值(不使用最小/最大函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15148491/

相关文章:

javascript - 加载其他函数时,最小-最大过滤器不起作用

matlab - 错误类型为 'min'的输入参数的未定义函数或方法 'struct'

python - 为什么 hasattr 在使用 @property 方法的类和实例上表现不同?

python - 是否有任何受监督的聚类算法或将先验知识应用于聚类的方法?

android - 以一定间隔发送大量推送通知

c++ - 函数定义中与 '&'运算符相关的疑问!

python - 如何使用 fabric 2 运行本地命令?

python - 有哪些策略可确保在所有区域设置中正确处理所有区域设置感知操作?

c# - 在算法竞赛中不使用 BigInteger 库处理大整数

c++ - C++ 中的 "minmax.h"是什么?