如何编写返回数组中最小元素的递归函数? [英] How do I write a recursive function that return the minimum element in an array?
问题描述
编写一个递归函数,返回数组中的最小元素,其中 C 是数组,s 是大小.这是我的代码.
write a recursive function that return the minimum element in an array where C is the array and s is the size. this is my code.
c = [2,5,6,4,3]
def min (c, s):
smallest = c[0]
if c[s] < smallest:
smallest = c[s]
else:
return min
print min (c,s)
错误:s 未定义.
推荐答案
首先,我会谨慎使用 min
作为函数名.Min 是一个内置的python,因此使用您自己的函数名称可能会导致您的代码中出现不需要的结果.
First of all, I'd caution the use of min
as a function name.
Min is a python built in so use as your own function name may cause unwanted results in your code.
如果我正确理解了代码和您的问题,那么与列表中的最小整数相比,您似乎试图获得列表长度的最小值.
If I'm understanding the code and your question correctly, it seems as if you are trying to get the minimum of the list length compared to the minimum integer in the list.
c = [2,5,6,4,3]
'''The function takes the name of the array as the parameter. In this case c'''
def minimum(array):
'''This function compares the length of array to the smallest integer in the array'''
length = 0
for i in c:
length += 1
'''In this case length is 5'''
smallest = min(c)
'''smallest is 2 in this case'''
print min(smallest,length)
但是,如果您只想获得数组的最小值,请执行以下操作:
However if all you want is to get the minimum value of an array, just do:
def minval(array):
print min(array)
这篇关于如何编写返回数组中最小元素的递归函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!