使用递归查找序列中的最大项目 [英] finding the max item in a sequence using recursion
问题描述
im试图获取使用递归在序列中查找最大项目的函数,但我不断遇到错误,例如当我尝试 最大值(范围(100)):
im trying to get a function to find the max item in a sequence using recursion but I keep getting an error,like when i try Max(range(100)):
TypeError: unorderable types: int() > list()
我是编程新手,所以请多多关照.
Im a programming newbie btw so any help is much appreciated.
def Max(s)
if len(s) == 1:
return s[0]
else:
m = Max(s[1:])
if m > s:
return m
else:
return s[0]
推荐答案
您似乎忘记了放置索引:
You seem to forget to put the index:
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
是单个数字,因此无法与作为list
的s
进行比较.因此,您遇到了错误.
m
is a single number, therefore it cannot be compared with s
which is a list
. Thus you got your error.
旁注,请考虑使用三元运算[true_val if true_cond else false_val]
来简化表示法.另外,您不需要最后一个else
块,因为if
子句在离开该块之前具有确定的return
:
Side note, consider of using ternary operation [true_val if true_cond else false_val]
to simplify your notation. Also you do not need the last else
block since your if
clause has definite return
before leaving the block:
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
然后您的代码将变得更加简单.
Then your code will become a lot simpler.
这篇关于使用递归查找序列中的最大项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!