编写一个函数recursiveLongestString(lst),该函数将字符串列表作为输入
并返回列表中最长的字符串。您可以假设该列表至少包含一个
元素,不会出现平局。此函数必须以有意义的方式使用递归
方法使用循环或内置max函数的解决方案将不会获得分数。
例如,recursiveLongestString(["a", "bb", "ccc"])
返回"ccc"
,并且
recursiveLongestString(["hi", "its", "fantastic", "here"])
返回
"fantastic"
这是我目前的代码:
def recursiveLongestString(lst):
if(len(lst)==1):
return(lst[0])
else:
smaller= recursiveLongestString(lst[1:])
if len(lst[0])<len(lst[1]):
return smaller
else:
return lst[0] + smaller
我知道这是错误的,但似乎找不到解决办法。请帮忙
为了有意义地使用,您可以将列表一分为二,并递归列表的左子集和右子集,以确定两个最长的字符串,然后比较这两个字符串以获得最终结果:
这样做的好处是,当您的列表有近1000个项目时,不会达到递归深度限制。此外,它不会创建列表内容的任何副本
通过使用默认参数沿递归调用向下传输最长字符串,可以使还原方法更加紧凑:
你很接近。在if/else中,您应该只返回单个字符串,因为这是您希望
recursive_longest
最终返回的字符串。试试这个:对您的奖励:您可能还想在开头添加一个额外的if语句,以决定在提供的列表为空时您可以做什么
这里有一个更有效的版本,因为
lst[1:]
需要线性时间和空间,因此整个过程需要二次时间和空间。这只需要线性时间和空间:相关问题 更多 >
编程相关推荐