46.0k views
4 votes
Write a program that contains the recursive functions below (please note for all the functions, you must use recursion and not loops or built in Python functions): a. def power (x,y) : This function should recursively compute the power of a number (x represents the number and y represents the power to which its being raised assume y will always be a positive integer) e.g.,

i. print(power(2,3))#2³=8
ii. print(power(−2,3))#−2³=−8
iii. print(power(1,5))#1⁵=1

b. def cat_ears(n): If every cat has 2 ears, this function should recursively compute the total number of ears based off the number of cats (n represents the total number of cats) e.g.,
i. print(cat_ears (0))#0−0 cats have 0 ears in total
ii. print(cat_ears(1)) \#2-1 cat has 2 ears in total
iii. print(cat_ears(2)) \# 4-2 cats have 4 ears in total

c. def alien_ears(n): We have aliens standing in a line, numbered 1,2,… The odd aliens (1,3,…) have 3 ears. The even aliens (2,4,…) have 2 ears. This function should return the total number of alien ears (n represents the total number of aliens) e.g.,
i. print(alien_ears(1)) \#3-(alien 1 has 3 ears)
ii. print(alien_ears(2)) \# 4 -(alien 1 has 3 ears, alien 2 has 2 ears)

User Toribio
by
8.1k points

1 Answer

2 votes

Final answer:

To solve the given problem, we will define three recursive functions in Python: power, cat_ears, and alien_ears. The power function calculates the power of a number, the cat_ears function calculates the total number of ears based on the number of cats, and the alien_ears function calculates the total number of alien ears based on the position of the aliens.

Step-by-step explanation:

To solve the given problem, we will define three recursive functions in Python: power, cat_ears, and alien_ears.

The power function calculates the power of a number by recursively multiplying the base number by itself until the exponent becomes 0. If the exponent is negative, we need to take the reciprocal of the base number. Here's the implementation:

def power(x, y):
if y == 0:
return 1
if y < 0:
return 1 / power(x, -y)
return x * power(x, y - 1)

The cat_ears function calculates the total number of ears based on the number of cats. Since each cat has 2 ears, we can recursively compute the total by adding 2 for each cat until there are no more cats left. Here's the implementation:

def cat_ears(n):
if n == 0:
return 0
return 2 + cat_ears(n - 1)

The alien_ears function calculates the total number of ears based on the position of the aliens. The odd aliens have 3 ears and the even aliens have 2 ears. We can use recursion to compute the total by adding the appropriate number of ears based on the alien's position. Here's the implementation:

def alien_ears(n):
if n == 0:
return 0
if n % 2 == 1:
return 3 + alien_ears(n - 1)
return 2 + alien_ears(n - 1)

User Duoc Tran
by
8.2k points