Python 自定义最小值函数不返回负输入,只返回零?如何修复我的代码?
我的任务是创建一个函数,从列表中返回最小值,而不使用min函数。当我运行以下代码时,它返回0而不是-1。我不太清楚为什么。注:1。fancy_min只返回给定的两个参数之间的较小数字。2.如果列表为空或参数为None,则我希望返回NonePython 自定义最小值函数不返回负输入,只返回零?如何修复我的代码?,python,Python,我的任务是创建一个函数,从列表中返回最小值,而不使用min函数。当我运行以下代码时,它返回0而不是-1。我不太清楚为什么。注:1。fancy_min只返回给定的两个参数之间的较小数字。2.如果列表为空或参数为None,则我希望返回None def minimum_of(numbers): mini = 99999999 if numbers == []: return None elif numbers is None: return None for i in
def minimum_of(numbers):
mini = 99999999
if numbers == []:
return None
elif numbers is None:
return None
for i in range(len(numbers)-1):
m = fancy_min(numbers[i], numbers[i+1])
if m<mini:
return m
print(minimum_of([-1,3,None,2,1,]))
def fancy_min(a, b):
while a is None:
return b
while b is None:
return a
if a > b:
return b
elif b > a:
return a
您的代码返回最后两个数字的最小值。试试这个:
def fancy_min(a, b):
if a is None:
return b
if b is None:
return a
if a > b:
return b
elif b > a:
return a
def minimum_of(numbers):
mini = 99999999
if numbers == []:
return None
elif None in numbers:
return None
for i in range(len(numbers)):
mini = fancy_min(numbers[i], mini)
return mini
实际上,您不需要两个函数来实现这一点,并且可以使用内置函数更简洁地处理None list item约束 如果您想深入了解上面的链接,也可以通过这种方式获得最小值,尽管这忽略了参数本身为None或不包含None值的情况:
def new_min(l=None):
if not l:
return None
m = None
for n in filter(lambda x: x is not None, l):
if (m is None) or (n < m):
m = n
return m
new_min([-1,3,None,2,1,])
> -1
new_min([None, None]) is None
> True
new_min(None) is None
> True
new_min() is None
> True
reduce(
lambda a, b: a if (a < b) else b,
filter(lambda x: x is not None, l)
) or None