嗨,我是 python 的新手,想知道如何在我的搜索算法中找到最大值



嗨,我目前正在学习离散结构和算法课程,并且必须第一次使用 python,所以我在让我的函数找到列表中的最大值时遇到了一点麻烦,你能看看我的代码吗,因为我也试图转换为伪代码:


def max_search(numbers):
    numbers = [1, 5, 9, 3, 4, 6]
    max = numbers = [0]
    for i in range(1, len(numbers)):
        if numbers[i] > max:
            max = numbers[i]
    max_search(numbers)
    print(max)

使用为 list 提供的 max 方法

max(numbers)

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

  1. 最大值可以是预定义的常量,如果列表为空,则为 -1
  2. 最大值是列表中的第一个元素(如果列表只有一个元素(。
之后,如果列表

较长,则将列表的第一个元素指定为最大值,然后遍历列表,如果发现大于最大值的数字,则更新最大值。

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参数,并且您正在递归地调用具有相同参数的相同函数,这将导致堆栈溢出

我做了一些更改

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)

最新更新