-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Lecture "Recursion", exercise 1 #24
Comments
def test_exponentiation(base_number, exponent, expected):
result = exponentiation(base_number, exponent)
if expected == result:
return True
else:
return expected, result
def exponentiation(base_number, exponent):
if exponent == 0:
return 1
else:
# Recursive call that reads as x^n = x * x^(n-1) = x * x * x^(n-2) until n reaches 0:
# x^n = x n times * x^0 = x n times * 1
result = base_number * exponentiation(base_number, exponent-1)
return result
print(test_exponentiation(3,4,81))
print(test_exponentiation(17,1,17))
print(test_exponentiation(2,0,1))
print(test_exponentiation(-5,2,25)) # With negatives, result is positive if exponent is even
print(test_exponentiation(-5,3,-125)) # Result is negative if exponent is odd |
|
# test function
def test_exponentiation(base_number, exponent, expected):
result = exponentiation(base_number, exponent)
if result == expected:
return True
else:
return False
# function
def exponentiation(base_number, exponent):
if exponent == 0:
return 1
else:
return base_number * exponentiation(base_number, exponent-1)
# three tests run
print(test_exponentiation(3, 4, 81)) # True
print(test_exponentiation(17, 1, 17)) # True
print(test_exponentiation(2, 0, 1)) # basic case |
|
|
|
|
|
|
|
def test_esp(base_number, exponent , expected):
result = esp(base_number, exponent)
if result == expected:
return True
else:
return False
def esp(base_number, exponent):
if exponent == 0:
return 1
elif exponent == 1:
return base_number
else:
return base_number * esp(base_number, exponent - 1)
print(test_esp(3,4,81))
print(test_esp(17,1,17))
print(test_esp(2,0,1)) |
|
|
Thank you for all your takes. Just a few comments:
|
|
def test_exponentiation(base_number, exponent, expected):
result = exponentiation(base_number, exponent)
if result == expected:
return True
else:
return False
def exponentiation(base_number, exponent):
if exponent == 0:
return 1
else:
return base_number * exponentiation(base_number, exponent - 1)
print(test_exponentiation(3, 4, 81))
print(test_exponentiation(17, 1, 17))
print(test_exponentiation(2, 0, 1)) |
Define a recursive function
def exponentiation(base_number, exponent)
for implementing the exponentiation operation. Test (by implementing the related test case) it on the following inputs: 34, 171, and 20.The text was updated successfully, but these errors were encountered: