Python中的递归函数查找最大值

2024-04-25 18:14:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码被卡住了。我想找到递归的最大值。 这是我的目标

1.如果多个元素使键最大化,则必须返回第一个元素(数组中最早出现的元素)。在

2.key参数必须是可选的;如果没有提供,函数必须返回(第一个)最大的元素。为键函数考虑一个好的默认值!在

3.不要使用内置的max或min函数(显然)。在

这是我的密码!在

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.

我就是不能得到正确的输出。在

甚至另一个代码也是

^{pr2}$

反馈是运行时错误

“文件”Python3“,第5行,递归的最大值 返回max(seq[0],recursive_max(seq[1:],key),key=key)

如何改进? 任何建议都会很高兴:)


Tags: key函数代码answernameself元素return
1条回答
网友
1楼 · 发布于 2024-04-25 18:14:37

考虑:

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]

相关问题 更多 >