# sumation
# WHILE LOOP
def sum_odd(n: int) -> int:
"""Sum up all odd number between 0 and n inclusive"""
total = 0
while n > 0:
if n % 2 == 1:
total += n
n -= 1
return total
# FOR LOOP with range
def sum_odd(n: int) -> int:
total = 0
for i in range(1, n+1):
if i % 2 == 1:
total += i
return total
# FOR LOOP with range and count by 2
def sum_odd(n: int) -> int:
total = 0
for i in range(1, n+1, 2):
total += i
return total
assert sum_odd(5) == 9, "5"
assert sum_odd(0) == 0, "0"
assert sum_odd(10) == 1+3+5+7+9, "15"
# callables
import typing
def do_math(x: float, y: float, operator: typing.Callable) -> int:
"""Return the integer result of an operator that combines x and y in some
mathematical way"""
math = operator(x,y)
return int(math)
assert do_math(3.0, 5.0, max) == 5, "max"
assert do_math(9.0, 0.5, pow) == 3, "powers"
# Taylor series
import math
def exponent(x: int) -> float:
"""Return the exponential taylor series approximation
of e to the power of x"""
e = 0
count = 0
while x**count / math.factorial(count) >= 0.001:
e += x**count / math.factorial(count)
count += 1
return e
assert abs(exponent(3) - math.e**3) < 0.001
assert abs(exponent(5) - math.e**5) < 0.001
assert abs(exponent(1) - math.e) < 0.001