Extra Topic: Functions as Arguments
Note: extra topics are not in CS Academy, but are required
and can appear on any future
homework, writing session, quiz, or exam.
def andFunction(A, B): return A and B
def orFunction(A, B): return A or B
def xorFunction(A, B): return (A and not B) or (B and not A)
def equalsXor(f):
# assume f takes two booleans and returns a boolean
return (f(True, True) == False and
f(True, False) == True and
f(False, True) == True and
f(False, False) == False)
print(equalsXor(andFunction))
print(equalsXor(orFunction))
print(equalsXor(xorFunction))
# Another fine example!
def derivative(f, x):
h = 10**-7
return (f(x+h) - f(x))/h
def f(x):
return 4*x**2 - 2*x + 3 # f'(x) = 8x - 2
def g(x):
return 5*x**3 + 3*x # g'(x) = 15x**2 + 3
print(derivative(f, 5)) # f'(5) = 38
print(derivative(g, 2)) # g'(2) = 63