简体   繁体   English

递归函数在python上找到最大值

[英]recursive function find the max value on python

I am stuck my code.我被我的代码卡住了。 I want to find recursive max value.我想找到递归最大值。 here is my goal这是我的目标

1.If more than one element maximises the key, then the first one (the one that comes earliest in the array) must be returned. 1.如果有多个元素最大化键,则必须返回第一个(数组中最早出现的元素)。

2.The key parameter must be optional; 2.key参数必须是可选的; if not provided, the function must return the (first) largest element.如果未提供,则该函数必须返回(第一个)最大元素。 Think of a good default value for the key function!为键函数想一个好的默认值!

3.Do not use the built-in max or min functions (obviously). 3.不要使用内置的 max 或 min 函数(显然)。

here is my code!这是我的代码!

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.

I just cant get ritht output.我只是无法获得正确的输出。

even another code is甚至另一个代码是

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)

the feedback is Runtime error反馈是运行时错误

File "prog.python3", line 5, in recursive_max return max(seq[0], recursive_max(seq[1:], key), key=key)文件“prog.python3”,第 5 行,在 recursive_max 中 return max(seq[0], recursive_max(seq[1:], key), key=key)

how to improve it ?如何改进呢? any suggestions will be glad :)任何建议都会很高兴:)

Consider:考虑:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM