How to get the sum of a list of numbers with recursion?
You don't need to loop. Recursion will do that for you.
def getSum(piece):
if len(piece)==0:
return 0
else:
return piece[0] + getSum(piece[1:])
print getSum([1, 3, 4, 2, 5])
Python: sum of List (recursive function) with starting point p
Define a function that normally computes the sum recursively.
To compute sum of a subsequence of a list, use list slicing.
def recsum(num_list):
if len(num_list) == 0:
return 0
return num_list[0] + recsum(num_list[1:])
a = [1,2,3,4,5]
recsum(a)
>>> 15
# It means 1+2+3+4+5
recsum(a[1:])
>>> 14
# It means 2+3+4+5
recsum(a[2:4])
>>> 7
# It means 3+4
Sum of the numbers in a list starting from the given index, RECURSIVELY
You could just check if the index is negative and, if it is, convert it to the corresponding positive one:
def recsumlisti(index, alist):
if index < 0:
index = index + len(alist)
if len(alist) == 0:
return 0
elif index >= len(alist):
return 0
else:
return alist[index] + recsumlisti(index + 1, alist)
The rest of the code is the same.
This way the output of recsumListi(-1, [1,2,3,4]) is 4 as expected
Summing the elements of a list recursively
I think what you were aiming for was to write a recursive sum
function that continuously splits the list into smaller chunks. So basically what you need to do is compute the index of the midpoint, then use list slicing to pass the first sublist and second sublist recursively back into the function, until hitting your base case(s) of 0
or 1
elements remaining.
def add(values):
if len(values) == 0:
return 0
elif len(values) == 1:
return values[0]
mid = len(values)//2
return add(values[:mid]) + add(values[mid:])
>>> add([1,2,3,4,5])
15
Sum integers from a list of lists
Recursion means you have to use a function.
tab = [7, 5, [3, 6, [2]], 7, [1, [2, 3, [4]], 9, 2], 4]
def int_sum(tbl):
s = 0
for e in tbl:
if isinstance(e, int):
s += e
else:
# this is the trick!
s += int_sum(e)
return s
print(int_sum(tab))
Find combination of numbers from list that add up to a sum in Haskell
You can modify the body of the function of canSum
to create howSum'
. For False
you can return an empty list []
, for True
you return a list that contains one list (solution): the empty list; so:
howSum' :: (Num a, Ord a) => a -> [a] -> [[a]]
howSum' target nums
| target > 0 = # …
| target < 0 = []
| otherwise = [[]]
For target > 0
we thus need to find candidate values. We thus will enumerate over the list, and thus make a recursive call. In case that returns a hit, we need to prepend that value to all the results of that call. We can use concatMap :: Foldable f => (a -> [b]) -> f a -> [b]
to concatenate the results. This will thus look like:
howSum' :: (Num a, Ord a) => a -> [a] -> [[a]]
howSum' target nums
| target > 0 = concatMap (\x -> … (howSum' (target-x) nums)) nums
| target < 0 = []
| otherwise = [[]]
where you still need to fill in the …
part.
howSum'
will thus list all possible ways to construct a result. You can use howSum'
as a helper function to produce a single solution in case there is such solution.
This solution allows to use the same value in nums
multiple times. It will also produce the same solution multiple times but in a different order, so [3, 5]
and [5, 3]
will both be solutions for 8
. I leave it as an exercise to improve this further.
Recursion algorithm for the sum of all elements in a list in java
You need to add one parameters to your method: index
, to keep track of your current position in the array:
public int sumOfElements(int[] elements, int index) {
if (index >= elements.length)
return 0;
return elements[index] + sumOfElements(elements, index + 1);
}
Recursion - summing a nested list
You are exiting on the first iteration of the for loop. As i
equals 1
, then you type check it, then you +=
total
and immediately return. You should return after you have exited the for loop.
def sumL(ls):
total = 0
for i in ls:
if isinstance(i, list):
total += sumL(i)
else:
total += i
return total
Note* don't use input
as an argument, as it is the name of a function
Related Topics
How to Check All Versions of Python Installed on Osx and Centos
Receiving Integers from the User Until They Enter 0
How to Get Max Output from a While Loop
Saving the Output of a Python Program
How to Remove All Characters Before a Specific Character in Python
Export Pandas Dataframe into a Pdf File Using Python
How to Run External Executable Using Python
How to Make a Roll the Dice Command With My Discord Bot
Spark Equivalent of If Then Else
How to Continue a Loop After Catching Exception in Try ... Except
Pandas: Subtracting Two Date Columns and the Result Being an Integer
Adding a Data File in Pyinstaller Using the Onefile Option
Python Xlsxwriter Set Border Around Multiple Cells
How to Split Image into Multiple Pieces in Python
Filenotfounderror: [Errno 2] No Such File or Directory