#==================================================
# Lecture 18: Counting Steps, Big-O
#--------------------------------------------------
# The demos at the bottom (demo_stopwatch, demo_list_vs_dict,
# demo_common) use the time module only to measure. Their calls
# are commented out: uncomment one at a time in class.

import time

#--------------------------------------------------
# Slide 4: You Try! Read every page while you wait?

pages = 100_000_000_000      # 100 billion pages
per_second = 10_000_000      # one computer reads 10 million pages a second

# print(pages / per_second)              # 10000.0 seconds
# print(pages / per_second / 60 / 60)    # 2.77... hours: about 2 hours 47 minutes

#--------------------------------------------------
# Slide 10: Counting the Steps of total(L)

def total(L):           # runs
    s = 0               # 1
    for x in L:         # n
        s = s + x       # n
    return s            # 1

# Steps = 1 + n + n + 1 = 2n + 2
# print(total([4, 8, 15, 16, 23, 42]))   # 108

#--------------------------------------------------
# Slide 12: You Try! Count the runs of each line

def times_table(n):          # runs
    for i in range(n):       # n
        for j in range(n):   # n * n
            print(i * j)     # n * n

# Steps = n + n*n + n*n = 2n^2 + n
# times_table(3)    # 9 lines printed; 3 + 9 + 9 = 21 steps

#--------------------------------------------------
# Slide 13: You Try! The data doubled

def times_table_steps(n):
    return 2 * n * n + n

# print(times_table_steps(100))   # 20100
# print(times_table_steps(200))   # 80200: about 4 times more

#--------------------------------------------------
# Slide 21: Linear: O(n), linear search

def find(L, x):
    for item in L:
        if item == x:
            return True
    return False

# Best case (x is first): 3 steps. Worst case (x not in L): 2n + 1 steps.
# print(find([7, 3, 9], 7))    # True
# print(find([7, 3, 9], 5))    # False

#--------------------------------------------------
# Slide 22: Hidden Loops: each of these is n steps on a list of n items

L = [7, 3, 9, 3, 5]
# print(3 in L)        # True
# print(L.index(9))    # 2
# print(max(L), min(L), sum(L))
# L2 = L.copy()
# L.remove(3)          # removes the first 3 only

#--------------------------------------------------
# Slide 23: Constant: O(1), the same steps for any size

L = [7, 3, 9]
d = {'ali': 'A+', 'bilal': 'B'}
# print(L[0], len(L))
# L.append(5)
# print(d['ali'], 'ali' in d)
# d['zain'] = 'A'

#--------------------------------------------------
# Slide 28: Bisection Search on a Sorted List: O(log n)

def find_sorted(L, x):
    low = 0
    high = len(L) - 1
    while low <= high:
        mid = (low + high) // 2
        if L[mid] == x:
            return True
        elif L[mid] < x:
            low = mid + 1
        else:
            high = mid - 1
    return False

# nums = [3, 5, 8, 12, 15, 19, 23, 27, 31, 36, 40, 44, 51, 58, 63, 70]
# print(find_sorted(nums, 51))   # True
# print(find_sorted(nums, 50))   # False

#--------------------------------------------------
# Slide 29: You Try! How many looks? (halve n until 1 is left)

def halvings(n):
    count = 0
    while n > 1:
        n = n / 2
        count += 1
    return count

# print(halvings(1_000))              # 10
# print(halvings(1_000_000))          # 20
# print(halvings(1_000_000_000))      # 30
# print(halvings(100_000_000_000))    # 37

#--------------------------------------------------
# Slide 31: You Try! Read and explain: O(n^2)

def mystery(L):
    for i in range(len(L)):
        for j in range(i + 1, len(L)):
            if L[i] == L[j]:
                return True
    return False

# print(mystery([4, 1, 7, 1]))   # True: 1 is there twice
# print(mystery([4, 1, 7]))      # False: no duplicate

#--------------------------------------------------
# Slide 32: Exponential: try every PIN

def crack(pin, d):      # d = number of digits
    for guess in range(10 ** d):
        if guess == pin:
            return guess

# print(crack(4821, 4))   # at most 10,000 guesses

#--------------------------------------------------
# Slide 39: You Try! Find the slow line

def common(A, B):
    result = []
    for x in A:
        if x in B:          # hidden loop over B
            result.append(x)
    return result

# print(common(['ali', 'sana', 'zain'], ['zain', 'omar', 'ali']))   # ['ali', 'zain']

#--------------------------------------------------
# Slide 41: The Fix: Ask a Dictionary: O(n)

def common_fast(A, B):
    seen = {}
    for x in B:        # once
        seen[x] = True
    result = []
    for x in A:
        if x in seen:  # 1 step!
            result.append(x)
    return result

# print(common_fast(['ali', 'sana', 'zain'], ['zain', 'omar', 'ali']))   # ['ali', 'zain']

#--------------------------------------------------
# Slide 43: Build the Index

pages = {1: 'python keyerror fix',
         2: 'lahore weather today',
         3: 'python list index'}

def build_index(pages):
    index = {}
    for num, text in pages.items():
        for word in text.split():
            if word in index:
                index[word].append(num)
            else:
                index[word] = [num]
    return index

index = build_index(pages)
# index = {'python': [1, 3], 'keyerror': [1],
#   'fix': [1], 'lahore': [2], 'weather': [2],
#   'today': [2], 'list': [3], 'index': [3]}
# print(index['python'])     # [1, 3]
# print(index['keyerror'])   # [1]

#==================================================
# Live demos (the stopwatch only confirms what counting predicts)
#--------------------------------------------------
# Slide 8: Why Not Use a Stopwatch? Same code, different times

def demo_stopwatch():
    L = list(range(1_000_000))
    for run in range(3):
        start = time.perf_counter()
        total(L)
        print("run", run + 1, ":", round(time.perf_counter() - start, 3), "s")
    # The steps never change: 2n + 2 = 2,000,002

# demo_stopwatch()

#--------------------------------------------------
# Slide 26: You Try! List or dictionary?

def demo_list_vs_dict():
    n = 1_000_000
    L = list(range(n))
    d = {}
    for x in L:
        d[x] = True

    start = time.perf_counter()
    for k in range(1_000):
        -1 in L                 # not there: checks all n items
    print("x in L:", round(time.perf_counter() - start, 4), "s")

    start = time.perf_counter()
    for k in range(1_000):
        -1 in d                 # one step
    print("x in d:", round(time.perf_counter() - start, 6), "s")

# demo_list_vs_dict()

#--------------------------------------------------
# Slide 40: You Try! Predict, then run: data x2 -> time x4

def demo_common():
    for n in [10_000, 20_000, 40_000]:
        A = list(range(0, 2 * n, 2))      # n even numbers
        B = list(range(0, 3 * n, 3))      # n multiples of 3
        start = time.perf_counter()
        common(A, B)
        slow = time.perf_counter() - start
        start = time.perf_counter()
        common_fast(A, B)
        fast = time.perf_counter() - start
        print(n, "names:  common", round(slow, 2), "s   common_fast", round(fast, 4), "s")

# demo_common()
