Skip to content

Instantly share code, notes, and snippets.

@ellisandrews
ellisandrews / exponential.py
Last active August 20, 2020 04:08
Exponential time complexity
def nth_fibonacci_term(n: int) -> int:
"""Recursively finds the nth term in the Fibonacci sequence. Assumes positive n."""
# Base case -- The first two numbers of the sequence are {0, 1}
if n <= 2:
return n - 1
return nth_fibonacci_term(n - 1) + nth_fibonacci_term(n - 2)
@ellisandrews
ellisandrews / polynomial.py
Last active August 20, 2020 04:09
Polynomial time complexity
from typing import Any, List, Set
def find_duplicates(list_: List[Any]) -> Set[Any]:
"""Find all duplicate items in a list."""
# Initialize a set to hold the duplicate items
duplicates = set()
# Check each item in the list against every other item in the list
@ellisandrews
ellisandrews / linear.py
Last active August 20, 2020 04:09
Linear time complexity
from typing import Any, List
def linear_search(list_: List[Any], target_value: Any) -> int:
"""
Perform a linear search of an input list for a target value.
Return the index of the target value in the list, or -1 if not found.
"""
# Iterate over each item in the list, checking whether it is the target value
for index, item in enumerate(list_):
@ellisandrews
ellisandrews / binary_search.py
Last active August 20, 2020 04:10
Log n time complexity
from typing import Any, List
def binary_search(list_: List[int], target_value: int) -> int:
"""
Perform a binary search of a sorted input list for a target value.
Return the index of the target value in the list, or -1 if not found.
"""
# Initialize left and right indexes for start of search
left = 0
@ellisandrews
ellisandrews / constant.py
Last active August 20, 2020 04:11
Constant time complexity
from typing import Any, Dict, List
# Example 1
def list_lookup(list_: List[Any], index: int) -> Any:
"""Lookup a value in a list by index."""
return list_[index]
# Example 2