[英]Add minimum and maximum number in list using Recursion: Python
I wrote a recursive function to find the summation of a list, here is my code: 我编写了一个递归函数来查找列表的总和,这是我的代码:
def rsum (eleList):
if len(eleList) == 1:
return eleList[0]
else:
return eleList[0] + rsum(eleList[1:])
However, right now I want to write a recursive function to find the summation of the max and min of a list, and I have no clue where I should start. 但是,现在我想编写一个递归函数来查找列表的最大值和最小值的总和,而且我不知道应该从哪里开始。 Could anyone give me some hint?
谁能给我一些提示吗?
If you want to write a recursive function, you have to figure out how to solve this problem based on having solved a smaller problem. 如果要编写一个递归函数,则必须在解决一个较小的问题的基础上弄清楚如何解决此问题。 You know that the sum of this list is the first element plus the sum of the rest of the list.
您知道此列表的总和是第一个元素加上列表其余部分的总和。 If you have a list:
如果您有清单:
[1,2,3,4,5]
and you know that the max of the last four elements is 5
and the first element is 1
, and you want to find the total maximum, how do you do that in a constant number of operations? 并且您知道最后四个元素的最大值是
5
,而第一个元素是1
,并且想要找到总最大值,您如何在恒定数量的操作中做到这一点?
I would search for maximum and minimum value in each iteration. 我将在每次迭代中搜索最大值和最小值。 And if that is the case, I will return the sum.
如果是这种情况,我将退还款项。
Something like: 就像是:
def rsum(eleList, ans, index):
if index == len(eleList) - 1:
if max(eleList) == eleList[index] or min(eleList) == eleList[index]:
return ans+eleList[index]
else:
return ans
else:
if max(eleList) == eleList[index] or min(eleList) == eleList[index]:
return ans + eleList[index] + rsum(eleList, ans, index + 1)
else:
return rsum(eleList, ans, index + 1)
print rsum([9, 2, 3, 4], 0, 0)
Output: 输出:
11 11
Might not be the smartest one or most pythonic but it gets things done. 可能不是最聪明的Python之一,但它可以完成工作。
For finding the sum of all the elements of the list use sum
function: 要查找列表中所有元素的总和,请使用
sum
函数:
temp = [1,2,3,4]
sum(temp)
#output = 10
If you want to find sum of min and max elements, get the list sorted and add first and last element: 如果要查找最小和最大元素的总和,请对列表进行排序并添加第一个和最后一个元素:
temp = [1,2,3,4]
sorted_list = sorted(temp)
total = sorted_list[0] + sorted_list[-1]
Avoid making your own functions whenever there is a possibility of built-in function being present. 只要有内置功能存在,就避免自己制作函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.