Need Help for the Python Code :
Define and test these two Python functions. You must use recursion to define them: you are not allowed to use loops or local variables. Both these functions are short: if you find yourself writing many pages of code, then you do not understand the assignment.
most(P, S)
Here P is a function of one argument that returns either True or False, and S is a list. The function most calls P on each element of S. It must return True if P returns True more often than it returns False. It must return False otherwise. Here are some examples of how most must work, where the symbol '?' means returns,and where the function odd tests if a number is odd.
most(odd, [])
|
?
|
False
|
most(odd, [0])
|
?
|
False
|
most(odd, [1])
|
?
|
True
|
most(odd, [1, 2])
|
?
|
False
|
most(odd, [1, 2, 3])
|
?
|
True
|
These are only examples! Your function most must work correctly for any P, and any S whose elements are compatible with P.
sigma(F, B, E)
Here F is a function of one argument that returns a number, B is a number, and E is a number. The function sigma must call F on all numbers from B to E and returns the sum of those calls. If B > E then sigma must return 0. Here are some examples of how sigma must work, where the function sqr returns the square of its argument.
sigma(sqr, 0, 0)
|
?
|
0
|
sigma(sqr, 1, 0)
|
?
|
0
|
sigma(sqr, 0, 4)
|
?
|
30
|
sigma(sqr, 1, 1)
|
?
|
1
|
sigma(sqr, 2, 100)
|
?
|
338349
|
These are only examples! Your function sigma must work correctly for any F, B, and E.
Hint: you may write additional functions that are called by more and sigma to help them do their jobs. However, these ''helper'' functions must also be recursive.
test.py
# The comments show what each call must print.
# ODD. Assume N is an integer. Test if N is odd.
def odd(N):
return N % 2 != 0
print(most(odd, [])) # False
print(most(odd, [0])) # False
print(most(odd, [1])) # True
print(most(odd, [1, 2])) # False
print(most(odd, [1, 2, 3])) # True
# SQR. Assume N is a number. Return N times N.
def sqr(N):
return N * N
print(sigma(sqr, 0, 0)) # 0
print(sigma(sqr, 1, 0)) # 0
print(sigma(sqr, 0, 4)) # 30
print(sigma(sqr, 1, 1)) # 1
print(sigma(sqr, 2, 100)) # 338349