In Python, Write a recursive function named productOfOdds that accepts a tuple c
ID: 3763806 • Letter: I
Question
In Python,
Write a recursive function named productOfOdds that accepts a tuple containing integer values and returns the product of the odd-valued elements in the tuple. You may assume the tuple has at least one odd-valued element.
The product of the odd-valued elements may be calculated as follows:
If the tuple has a single element and it is odd, return the value of that element; otherwise return 1
Otherwise, if the first element of the tuple is odd, return the product of that element and the result of finding the product of hte odd elements of the rest of the tuple. If the first element is not odd, simply return the result of of finding the product of the odd elements of the rest of the tuple.
Explanation / Answer
#! /usr/bin/python
def productOfOdds(list):
if len(list) == 0:
return 1;
else:
if list[0]%2 != 0 :
return list[0]* productOfOdds(list[1:]);
else:
return productOfOdds(list[1:]);
list = [5,2,3,4,5];
x = productOfOdds(list);
print x;
If you have any further queries, just revert here.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.