Python 3.4 Problem. Recursive. I need help with this problem. Many students find
ID: 3818493 • Letter: P
Question
Python 3.4 Problem. Recursive. I need help with this problem.
Many students find it helpful when writing recursive functions to first write the function using iteration (loops). Doing so helps them to figure out the basic algorithm for solving the problem that can be transformed into a recursive solution. However, your final solutions MUST NOT not be iterative. Use of loops for a function will result in 0 points for that function. Write a recursive function sum_odds () that takes a non-empty list of integers as an argument and returns the sum of only the odd integers in the list. In class we explored a recursive function called rsum () that recursively computes the sum of a list of integers - use it as a model to get started. Your function must be recursive and must not use any loops.Explanation / Answer
code:
import os
import sys
import numpy as np
def sum_odds(li,summ,ind):
if ind<len(li):
if (li[ind]%2) !=0:
summ+=li[ind]
return sum_odds(li,summ,ind+1)
return summ
print sum_odds([1,2,3,4,5],0,0)
The output of above code is 9
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.