In [88]:
# Pattern

def pattern(n: int) -> int:
    """Return term n of the given pattern"""
    if n % 2 == 0:
        return -(n*2)**2
    else:
        return (n*2)**2
    
print("term 1:", pattern(1))
print("term 2:", pattern(2))
print("term 3:", pattern(3))
print("term 4:", pattern(4))
term 1: 4
term 2: -16
term 3: 36
term 4: -64
In [89]:
# booleans

def bools(x: float) -> bool:
    """Return True of x is between 5 and 10 inclusive
    or larger than 15. Otherwise return False"""
    if x >= 5 and x <= 10:
        return True
    elif x > 15:
        return True
    else:
        return False

# def bools(x: float) -> bool:
#     return (x >= 5 and x <= 10) or x > 15

assert bools(8) == True, "Inside range"
assert bools(16) == True, "Above 15"
assert bools(3) == False, "Neither"
In [82]:
# Quadratic 

import math

def num_roots(a: float, b: float, c: float) -> int:
    """Return the number of roots a quadratic function has 
    in the form of f(x) = ax^2 + bx + c"""
    discriminant = b**2 - (4*a*c)
    if discriminant > 0:
        return(2)
    elif discriminant == 0:
        return(1)
    else:
        return(0)
    
def quadratic(a: float, b: float, c: float) -> float:
    """Return the root using addition of a quadratic in the form 
    f(x) = ax^2 + bx + c if it has real roots, otherwise return 0"""
    number_roots = num_roots(a, b, c)
    if number_roots == 0:
        return 0
    else:
        return (-b + math.sqrt(b**2 - (4*a*c))) / (2*a)

assert num_roots(1,4,4) == 1, "num_roots perfect square"
assert num_roots(1,2,3) == 0, "num_roots imaginary"
assert num_roots(1,-8,12) == 2, "num_roots real"

assert abs(quadratic(1,4,4) + 2.0) < 0.0001, "quadratic perfect square"
assert quadratic(1,2,3) == 0, "quadratic imaginary"
assert abs(quadratic(1,-8,12) - 6.0) < 0.0001, "quadratic real"
In [ ]: