Python 3.x 嗨,我是python新手,想知道如何在搜索算法中找到最大值?
您好,我目前正在学习离散结构和算法课程,并且第一次必须使用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
使用为列表提供的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)
当您为列表中的最大数量编写代码时,首先要考虑基本情况,这将是
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