我想写一个递归函数,以便在列表中找到最大整数。我知道如何为整数列表编写func。任何人都可以给我一些这方面的提示吗?我 我想这样做没有最大功能。 ex。 a = [1,[2,3],4,[[2],1]] find_max(a) - > 4列表python的递归最大函数
2
A
回答
0
如果数据类型是列表,则可以遍历列表并调用MAX()
函数:
l = [[54,65,464,656,5],[568,49,7,8,4,3,3515],[312,64,598,46]]
def MAX(l):
mx = None
for item in l:
if isinstance(item, list):
tmp = MAX(item)
else:
tmp = item
if mx < tmp:
mx = tmp
return mx
1
我决定用纯递归,没有循环来解决这个。下面,似乎这样的伎俩对我来说:
def find_max(a_list):
l = len(a_list)
if l > 1: # if there are multiple elements...
l /= 2 # find the midpoint
m1 = find_max(a_list[:l]) # find the max in the first half
m2 = find_max(a_list[l:]) # find the max in the second half
if m1 > m2: # pick between them
return m1
else:
return m2
elif l < 1: # deal with empty lists
return None
else: # we're down to one element...
if isinstance(a_list[0], list): # ...but it may be a list
return find_max(a_list[0]) # if so, find its max
else:
return a_list[0] # otherwise, a single element is trivially the max of its subset
注意通过在一半分裂子问题,而不是由1减少,这应实现对堆栈大名单甚至溢出是稳健的。
现在修改为处理空列表。
相关问题
- 1. Python的递归函数错误:“最大递归深度超过”
- 2. 递归python函数产生anagrams列表
- 3. 递归Python函数在列表中查找最小数字
- 4. 列表的递归函数
- 5. Python:最大递归深度
- 6. 递归函数和列表
- 7. 递归列表函数
- 8. Java或python中的范围的递归最大函数
- 9. 递归函数Python
- 10. 递归函数python
- 11. Python列表递归
- 12. Python递归函数不递归
- 13. Python函数组合(最大递归深度错误,范围?)
- 14. Python 3:获取列表__repr__时超出最大递归深度
- 15. Python的递归和列表
- 16. Python的最大递归,约sys.setrecursionlimit问题()
- 17. Python中递归的最大级别
- 18. Python中的递归函数在列表中添加奇数值
- 19. 递归函数的空列表
- 20. 大量函数递归 - C++
- 21. 长度最长共同序列Python递归函数
- 22. sml列表参数函数递归
- 23. 增加最大递归深度表值函数
- 24. 了解递归函数python
- 25. Python递归函数输入
- 26. python递归函数深度
- 27. 递归函数帮助(Python)
- 28. 测试递归Python函数
- 29. Python龟:递归函数
- 30. 列表项存在时的Python列表最大值函数
但是这不是一个很好的问题,但请指定一些样本,以更好地解决您的问题 – Arman