Python: Adding Positive Values In A List
Solution 1:
You never actually create a value to add to. You are adding one value to a list per in iteration.
Just in iterate through the list and add them manually:
def sam(n):
value =0for x in n:
if x > 0:
value += x
return value
Or you could do it in one line:
defsam(n):
returnsum(x for x in n if x > 0)
For better practice you should choose better variables. More meaningful variables are easier to remember and makes your code more readable:
So n
could be num_list
(or number_list
).
Rather than iterate with x you could use number
. This tells you that number contains a single letter.
Solution 2:
You should do an addition in the recursive call, and you need to identify the base factors (the conditions that terminate the recursive call) in recursion.
You can try out this:
defsum(n):
if(len(n) > 0):
if(x > 0):
return x + sum(n[(x+1):])
else:
returnsum(n[(x+1):])
else:
return0
Here the recursive call x + sum(n[(x+1):])
is made at the end, so it is also known as tail recursion.
And, each time when you are making the recursive call, you need to pass the rest of the list as the argument (this is done by slicing the list). sum(n[(x+1):])
Or, if you want just a simple way of doing this without using recursion, you could just use an iterative method instead. In order to make this more simple to understand, you need to have an extra variable in order to keep track of the sum.
So, your code would look like this:
def sum(n):
s =0for x in n:
if(x > 0):
s += x
return s
Post a Comment for "Python: Adding Positive Values In A List"