递归函数查找python上的最大值
我的代码卡住了。我想找到递归的最大值。 这是我的目标 1.如果多个元素使密钥最大化,则必须返回第一个元素(数组中最早出现的元素) 2.关键参数必须是可选的;如果未提供,函数必须返回(第一个)最大的元素。为键函数想出一个好的默认值 3.不要使用内置的max或min功能(显然) 这是我的密码递归函数查找python上的最大值,python,recursion,Python,Recursion,我的代码卡住了。我想找到递归的最大值。 这是我的目标 1.如果多个元素使密钥最大化,则必须返回第一个元素(数组中最早出现的元素) 2.关键参数必须是可选的;如果未提供,函数必须返回(第一个)最大的元素。为键函数想出一个好的默认值 3.不要使用内置的max或min功能(显然) 这是我的密码 def recursive_max(seq, key): if len(seq) == 1: return seq[0] else: key = recursiv
def recursive_max(seq, key):
if len(seq) == 1:
return seq[0]
else:
key = recursive_max(seq[1:])
if key > seq[0]:
return key
else:
return seq[0]
print(recursive_max(range(-5, 5 + 1))) #answer is 5
print(recursive_max(range(-5, 5 + 1), lambda x: x * x)) #answer is -5
class PoliticalDivision:
def __init__(self, name, area):
self.name = name
self.area = area
divisions = [
PoliticalDivision("Brazil", 8.5),
PoliticalDivision("China", 9.5),
PoliticalDivision("New Zealand", 0.27),
PoliticalDivision("Russia", 17),
PoliticalDivision("UK", 0.24),
PoliticalDivision("US", 9.5),
]
print(recursive_max(divisions, lambda division: division.area).name) #answer is Russia.
我就是不能得到正确的输出
甚至还有另一个代码是
def recursive_max(seq, key=lambda x: x):
if len(seq) == 1:
return seq[0]
else:
return max(seq[0], recursive_max(seq[1:], key), key=key)
反馈为运行时错误
文件“prog.python3”,第5行,递归_max
return max(seq[0],recursive_max(seq[1:],key),key=key)
如何改进?
任何建议都会很高兴:)考虑:
def recursive_max(seq, key=None):
# if key isn't given, call it again with key being returning the value itself
if not key: return recursive_max(seq, lambda a: a)
# error checking: can't get max of empty sequence
if not seq: raise ValueError("max of empty seq")
# base case: seq of 1, the max is the first element
if len(seq) == 1: return seq[0]
# get the max of the rest of the list
sub_max = recursive_max(seq[1:], key)
# if that's bigger than 1st element, return that, else return 1st element
return sub_max if key(sub_max) > key(seq[0]) else seq[0]
你所拥有的有什么问题吗?第一个建议是说出你的困境。你似乎不明白
键
参数的作用。实际上,您忽略了传递的函数,并将键重新绑定到递归调用的结果。您是否了解键
如何与内置的max
功能配合使用?我建议给key
一个默认值lambda x:x
。你认为lambda x:x*x>seq[0]
应该返回什么?