Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 嗨,我是python新手,想知道如何在搜索算法中找到最大值?_Python 3.x - Fatal编程技术网

Python 3.x 嗨,我是python新手,想知道如何在搜索算法中找到最大值?

Python 3.x 嗨,我是python新手,想知道如何在搜索算法中找到最大值?,python-3.x,Python 3.x,您好,我目前正在学习离散结构和算法课程,并且第一次必须使用python,因此我在获取函数“查找列表中的最大值”时遇到了一些困难。您能看看我的代码吗?因为我正在尝试转换为伪代码: 使用为列表提供的max方法 max(numbers) 我做了一些改变 def max_search(numbers): max = -1 # if numbers contains all positive number for i in range(len(numbers)): i

您好,我目前正在学习离散结构和算法课程,并且第一次必须使用python,因此我在获取函数“查找列表中的最大值”时遇到了一些困难。您能看看我的代码吗?因为我正在尝试转换为伪代码:


使用为列表提供的max方法

max(numbers)

我做了一些改变

def max_search(numbers):

    max = -1 # if numbers contains all positive number

    for i in range(len(numbers)):
        if numbers[i] > max:
            max = numbers[i]

max = max_search([1, 5, 9, 3, 4, 6])
print(max)

当您为列表中的最大数量编写代码时,首先要考虑基本情况,这将是

  • 最大值可以是预定义的常量,如果列表为空,则为-1
  • 如果列表只有一个元素,则Maximum是列表中的第一个元素
  • 之后,如果列表较长,则将列表的第一个元素指定为最大值,然后遍历列表,如果找到大于最大值的数字,则更新最大值

    def max_search(numbers):
    
        #Maximum of an empty list is undefined, I defined it as -1
        if len(numbers) == 0:
            return -1
        #Maximum of a list with one element is the element itself
        if len(numbers) == 1:
            return numbers[0]
    
        max = numbers[0]
        #Iterate through the list and update maximum on the fly
        for num in numbers:
            if num >= max:
                max = num
    
        return max
    
    在您的例子中,您正在使用函数
    [1,5,9,3,4,6]
    中的另一个列表覆盖
    numbers
    参数,并且使用相同的参数递归调用相同的函数,这将导致堆栈溢出

    您可以直接使用“max”函数是由python提供的,还是您想编写自己的单独函数?因此,将max_search(numbers)替换为max(numbers)
    def max_search(numbers):
    
        #Maximum of an empty list is undefined, I defined it as -1
        if len(numbers) == 0:
            return -1
        #Maximum of a list with one element is the element itself
        if len(numbers) == 1:
            return numbers[0]
    
        max = numbers[0]
        #Iterate through the list and update maximum on the fly
        for num in numbers:
            if num >= max:
                max = num
    
        return max