【问题标题】:finding the max item in a sequence using recursion使用递归查找序列中的最大项目
【发布时间】:2016-03-09 13:53:26
【问题描述】:

我试图获得一个函数来使用递归在序列中查找最大项目,但我不断收到错误,就像我尝试时一样 最大(范围(100)):

TypeError: unorderable types: int() > list()

顺便说一句,我是一名编程新手,因此非常感谢任何帮助。

def Max(s)
    if len(s) == 1:
        return s[0]
    else:
        m = Max(s[1:])
        if m > s:
            return m
        else:
            return s[0]

【问题讨论】:

  • m2s[1,2,3] 时,if m > s: 应该计算什么?
  • 在 m = Max... 之后输入一个 print 来告诉你 m 和 s 是什么然后你就会明白为什么 m>s 有错误
  • 谢谢!我现在明白了

标签: python recursion max


【解决方案1】:

你好像忘记放索引了:

def Max(s):
    if len(s) == 1:
        return s[0]
    else:
        m = Max(s[1:])
        if m > s[0]: #put index 0 here
            return m
        else:
            return s[0]

m 是单个数字,因此不能与s 比较,后者是list。因此,您得到了错误。

旁注,考虑使用三元运算[true_val if true_cond else false_val] 来简化您的符号。此外,您不需要最后一个 else 块,因为您的 if 子句在离开块之前具有明确的 return

def Max(s):
    if len(s) == 1:
        return s[0]
    m = Max(s[1:])
    return m if m > s[0] else s[0] #put index 0 here

那么你的代码会变得简单很多。

【讨论】:

  • @DecafOyster208 考虑使用ternary operation 并删除最后一个else 语句。这也将简化您的代码..
【解决方案2】:

此变体将通过在每个递归级别将问题分成两半并递归求解两半来减少堆栈大小。这允许您评估包含数千个元素的列表,其中将问题大小减少一的方法会导致堆栈溢出。

def Max(lst):
    l = len(lst)
    if l > 1:
        mid = l / 2
        m1 = Max(lst[:mid])     # find max of first half of the list
        m2 = Max(lst[mid:])     # find max of second half of the list
        # max of the list is the larger of these two values
        return m1 if m1 > m2 else m2
    return lst[0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2021-11-11
    相关资源
    最近更新 更多