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?
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
Might not be the smartest one or most pythonic but it gets things done.
For finding the sum of all the elements of the list use sum
function:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.