In: Computer Science
All functions are written in python
Write a function cube_evens_lc(values) that takes as input a list of numbers called values, and that uses a list comprehension to create and return a list containing the cubes of the even numbers in values (i.e., the even numbers raised to the third power). For example:
>>> cube_evens_lc([2, 5, 6, 4, 1]) result: [8, 216, 64]
This version of the function may not use recursion.
Write a function cube_evens_rec(values) that takes as input a list of numbers called values, and that uses recursion to create and return a list containing the cubes of the even numbers in values. In other words, this function will do the same thing as the previous function, but it must use recursion instead of a list comprehension. For example:
>>> cube_evens_rec([2, 5, 6, 4, 1]) result: [8, 216, 64]
This version of the function may not use a list comprehension.
Source Code:
Output:
Code in text format (See above images of code for indentation):
#import math module
import math
#function using list comprehension
def cube_evens_lc(values):
result=[pow(x,3) for x in values if x%2==0]
return result
#list declaration
rec_res=[]
#function using recursion
def cube_evens_rec(values):
s=len(values)
if(s==0):
return [0]
else:
#check for even
if values[0]%2==0:
#add to list
rec_res.append(pow(values[0],3))
#recursive call
cube_evens_rec(values[1:])
else:
cube_evens_rec(values[1:])
#return result list
return rec_res
#list declaration
values=[]
#read size from user
s=int(input("Enter the size of the list: "))
print("Enter elements of list:")
#read numbers into list
for i in range(s):
n=int(input())
values.append(n)
#function call
result=cube_evens_lc(values)
#print list
print("Using list comprehension")
print("result: ",result)
#function call
result1=cube_evens_rec(values)
#print list
print("Using recusrsion")
print("result: ",result1)