#==================================================
# Lecture 19: Sorting
#--------------------------------------------------

import random
import time

#--------------------------------------------------
# Slide 4: You Try! — one plan for the three bags
# 1st weighing: is A lighter than B?  2nd: is B lighter than C?
# Two of the four answer patterns cannot tell two orders apart.

#--------------------------------------------------
# Slide 8: Finding a Repeat, Faster

def any_repeat(L):
    """Any list. Checks every pair: O(n^2). Lecture 18's mystery."""
    for i in range(len(L)):
        for j in range(i + 1, len(L)):
            if L[i] == L[j]:
                return True
    return False

def has_repeat(L):
    """L is sorted. Checks neighbours only: O(n)."""
    for i in range(len(L) - 1):
        if L[i] == L[i + 1]:
            return True
    return False

# print(any_repeat([21, 8, 44, 3, 8]))      # True
# print(has_repeat(sorted([21, 8, 44, 3, 8])))   # True
# print(has_repeat([3, 8, 8, 15, 21]))      # True

#--------------------------------------------------
# Slide 10: You Try! — sort it yourself, with min()

def my_sort(L):
    """Returns a new sorted list. L stays as it is."""
    rest = L[:]                 # a copy
    answer = []
    while len(rest) > 0:
        smallest = min(rest)    # min() hides a loop
        rest.remove(smallest)
        answer.append(smallest)
    return answer

# print(my_sort([5, 2, 8, 1, 4]))   # [1, 2, 4, 5, 8]

#--------------------------------------------------
# Slide 13: Swap Two Items in One Line

L = [5, 2, 8, 1, 4]
L[0], L[3] = L[3], L[0]
# print(L)     # [1, 2, 8, 5, 4]

#--------------------------------------------------
# Slide 14: Selection Sort in Python

def selection_sort(L):
    """Sorts L, smallest first."""
    n = len(L)
    for i in range(n - 1):
        smallest = i
        for j in range(i + 1, n):
            if L[j] < L[smallest]:
                smallest = j
        L[i], L[smallest] = L[smallest], L[i]

marks = [5, 2, 8, 1, 4]
selection_sort(marks)
# print(marks)   # [1, 2, 4, 5, 8]

#--------------------------------------------------
# Slide 15: You Try! — L after each pass

def selection_sort_trace(L):
    """Like selection_sort, but prints L after each pass."""
    n = len(L)
    for i in range(n - 1):
        smallest = i
        for j in range(i + 1, n):
            if L[j] < L[smallest]:
                smallest = j
        L[i], L[smallest] = L[smallest], L[i]
        print('after pass', i + 1, ':', L)

# selection_sort_trace([6, 3, 5, 1, 2])
# after pass 1 : [1, 3, 5, 6, 2]
# after pass 2 : [1, 2, 5, 6, 3]
# after pass 3 : [1, 2, 3, 6, 5]
# after pass 4 : [1, 2, 3, 5, 6]

#--------------------------------------------------
# Slide 17: Bug Hunt! — the friend's selection sort

def selection_sort_bug(L):
    n = len(L)
    for i in range(n - 1):
        smallest = 0             # BUG: must be smallest = i
        for j in range(i + 1, n):
            if L[j] < L[smallest]:
                smallest = j
        L[i], L[smallest] = L[smallest], L[i]

# marks = [5, 2, 8, 1, 4]
# selection_sort_bug(marks)
# print(marks)   # [8, 1, 2, 4, 5]

#--------------------------------------------------
# Slide 19: Which Numbers Are Prime? — Lab 05's way

def is_prime(n):
    """n >= 2. Tries every divisor from 2 to n - 1."""
    for d in range(2, n):
        if n % d == 0:
            return False
    return True

# print([k for k in range(2, 30) if is_prime(k)])
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

#--------------------------------------------------
# Slide 20: Listing the Primes: The Slow Way

def primes_up_to(n):
    """All primes up to n, testing every k with is_prime: slow."""
    primes = []
    for k in range(2, n + 1):
        if is_prime(k):
            primes.append(k)
    return primes

# print(primes_up_to(30))   # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

#--------------------------------------------------
# Slide 23: The Sieve in Python

def sieve(n):
    """List: True at k when k is prime."""
    is_prime = [True] * (n + 1)
    is_prime[0] = False
    is_prime[1] = False
    for p in range(2, n + 1):
        if is_prime[p]:
            for m in range(2 * p, n + 1, p):
                is_prime[m] = False
    return is_prime

# flags = sieve(10)
# print(flags[7], flags[9])                     # True False
# flags = sieve(50)
# print([k for k in range(51) if flags[k]])     # the 15 primes up to 50

#--------------------------------------------------
# Slides 20 and 22: the race — all primes up to n, two ways

def prime_race(n):
    """Finds the primes up to n with is_prime, then with sieve."""
    start = time.perf_counter()
    count = 0
    for k in range(2, n + 1):
        if is_prime(k):
            count += 1
    print('is_prime:', count, 'primes,', round(time.perf_counter() - start, 4), 'seconds')

    start = time.perf_counter()
    flags = sieve(n)
    print('sieve:   ', flags.count(True), 'primes,', round(time.perf_counter() - start, 4), 'seconds')

# prime_race(100000)    # is_prime: about 8.5 s, sieve: about 0.005 s (one laptop)
# prime_race(1000000)   # sieve: about 0.05 s; is_prime: about 12 minutes (82 times the divisions)

#--------------------------------------------------
# Slide 25: Counting the Crossings

def crossings(n):
    """How many times sieve(n) sets a flag to False."""
    is_prime = [True] * (n + 1)
    count = 0
    for p in range(2, n + 1):
        if is_prime[p]:
            for m in range(2 * p, n + 1, p):
                is_prime[m] = False
                count += 1
    return count

# for n in [30, 1000, 10000, 1000000]:
#     print(n, crossings(n))    # 30 33, 1000 1958, 10000 23071, 1000000 2775210

#--------------------------------------------------
# Slides 26-27: Pretty Average Primes (CCC 2019, Senior #2)
# Input: T, then T lines with one N each.  Output: A B, primes with A + B = 2N.

def pretty_average_primes():
    flags = sieve(2000000)
    T = int(input())
    for t in range(T):
        N = int(input())
        for A in range(2, N + 1):
            B = 2 * N - A
            if flags[A] and flags[B]:
                print(A, B)
                break

# pretty_average_primes()
# type 3, then 8, 4, 21   ->   3 13 / 3 5 / 5 37
# Slide 28: N = 12 gives 5 19, N = 15 gives 7 23

#--------------------------------------------------
# Slide 27: the race — 1,000 questions, is_prime or the sieve

def average_race(questions):
    """Answers the same random N with is_prime, then with the sieve."""
    numbers = [random.randint(4, 1000000) for k in range(questions)]

    start = time.perf_counter()
    for N in numbers:
        for A in range(2, N + 1):
            if is_prime(A) and is_prime(2 * N - A):
                break
    print('is_prime:', round(time.perf_counter() - start, 4), 'seconds')

    start = time.perf_counter()
    flags = sieve(2000000)
    for N in numbers:
        for A in range(2, N + 1):
            if flags[A] and flags[2 * N - A]:
                break
    print('sieve:   ', round(time.perf_counter() - start, 4), 'seconds')

# average_race(1000)    # is_prime: about 18 s, sieve: about 0.1 s (one laptop)

#--------------------------------------------------
# Slide 34: The Rule for n Items — 2**k >= n!

def fewest_comparisons(n):
    """The fewest comparisons that can always sort n different items."""
    orders = 1
    for k in range(2, n + 1):
        orders *= k               # n! orders
    k = 0
    while 2 ** k < orders:        # 2**k answer patterns
        k += 1
    return k

# for n in [3, 4, 5, 10, 1000]:
#     print(n, fewest_comparisons(n))   # 3 3, 4 5, 5 7, 10 22, 1000 8530

#--------------------------------------------------
# Slide 38: You Try! — the race (predict, then run it)

def race(n):
    """Sorts the same n random numbers two ways and prints the times."""
    numbers = [random.randint(1, 1000000) for k in range(n)]

    L = numbers[:]
    start = time.perf_counter()
    selection_sort(L)
    print('selection_sort:', round(time.perf_counter() - start, 4), 'seconds')

    start = time.perf_counter()
    sorted(numbers)
    print('sorted:        ', round(time.perf_counter() - start, 4), 'seconds')

# race(20000)

#--------------------------------------------------
# Slide 43: Counting Sort in Python

def counting_sort(marks, top):
    """marks: whole numbers, 0 to top."""
    counts = [0] * (top + 1)
    for m in marks:
        counts[m] += 1
    result = []
    for value in range(top + 1):
        for k in range(counts[value]):
            result.append(value)
    return result

# print(counting_sort([7, 3, 10, 7, 0, 3, 7, 9], 10))
# [0, 3, 3, 7, 7, 7, 9, 10]

#--------------------------------------------------
# Slide 45: Bug Hunt! — dice rolls

# rolls = [3, 6, 1, 3, 5]
# counts = [0] * 6               # BUG: no counter for a 6; use [0] * 7
# for r in rolls:
#     counts[r] += 1             # IndexError: list index out of range
# result = []
# for value in range(len(counts)):
#     for k in range(counts[value]):
#         result.append(value)
# print(result)

#--------------------------------------------------
# Slide 48: sorted() and .sort()

L = [5, 2, 8, 1]
M = sorted(L)                  # M is [1, 2, 5, 8]; L is not changed
L.sort()                       # L is [1, 2, 5, 8]; returns None
# print(sorted(L, reverse=True))   # [8, 5, 2, 1]
# print(sorted(['bilal', 'Ali', 'zara', 'Hamza']))
# ['Ali', 'Hamza', 'bilal', 'zara']

#--------------------------------------------------
# Slide 49: Sort by Something Else: key=

cities = ['Karachi', 'Hub', 'Multan', 'Swat']
# print(sorted(cities, key=len))   # ['Hub', 'Swat', 'Multan', 'Karachi']

results = [('Ali', 72), ('Sana', 91), ('Omar', 65)]
merit = sorted(results, key=lambda r: r[1], reverse=True)
# print(merit)   # [('Sana', 91), ('Ali', 72), ('Omar', 65)]

#--------------------------------------------------
# Slide 50: You Try! — predict

# print(sorted([3, 1, 2], reverse=True))           # [3, 2, 1]
# print(sorted(['pear', 'Fig', 'apple']))          # ['Fig', 'apple', 'pear']
# print(sorted(['ccc', 'a', 'bb'], key=len))       # ['a', 'bb', 'ccc']
# L = [3, 1, 2]
# x = L.sort()
# print(x, L)                                      # None [1, 2, 3]
