重要说明:我无法在min()
函数中使用max()
和minmax
内置函数。
以下是我的代码中发现的错误:
expression « minmax([-1000, -999]) » doesn't have expected value
expected value : (-1000, -999)
actual value : (-1000, -1000)
这是我的代码:
def minmax(liste):
if len(liste)==1:
return (liste[0],liste[0])
elif len(liste)==0:
return(None,None)
else:
min=liste[0]
for i in liste:
if i<min:
min=i
max=liste[0]
for k in liste:
if k>=max:
max=k
return(min,max)
答案 0 :(得分:1)
更改您的上一行代码:
for k in liste:
if k>=max:
max=k
return(min,max)
分为:
for k in liste:
if k>=max:
max=k
return(min,max)
因为return
语句在for
循环中,所以它总是返回第一个元素。您需要将return
语句放在外面以允许循环完成。
答案 1 :(得分:0)
参加本次派对的时间太晚了,但我不能不给这个问题一个更好的答案。上面的代码是非Python的,因此我想我应该做些什么来完善它(同时保持原始签名和行为),同时还要进行一些细微的优化:
def minmax(arr):
"""
Given some array, returns a tuple containing the first occurrences of the minimum and maximum values.
Args:
arr (list of T): The list to search through
Returns:
A 2-tuple containing:
lo (T): The minimum object in the array
hi (T): The maximum object in the array
"""
if not arr: # This returns early if the array is None or []
return (None, None)
lo, hi = arr[0], arr[0] # Don't use min/max, shadowing built-ins is bad form
for val in arr:
if val < lo:
lo = val
elif val > hi:
hi = val
return (lo, hi)