001

76 阅读1分钟

Algorithm

  • Procedure mapping each input to a single output(deterministic)
  • Binary relation from problem inputs to correct outputs

Correctness

  • For small inputs, can use case analysis
  • For arbitrary large inputs, algorithm must be recursive or loop
  • Must use induction(why recursion is a key concept)

Efficiency

  • how fast
    • Could measure time, but want performance to be machine independent(different machine , different performance)
    • Count number of fixed-time operations algorithm takes to return
    • depend on the size of input (larger input suggests longer time)
    • Sometimes no efficient algorithm exits for a problem
  • Asymptotic Notation:
    • ignore constant factors and low order terms

Data Structure :

def: a way to store non-constant data

  • A collection of operations is called interface
    • Sequence
    • Set
  • Data structures may implement the same interface with different performance

Problem:

Find if a pair of students have same birthdays.

Code:

class StaticArray:
    def __init__(self, n):
        self.data = [None] * n

    def get_at(self, i):
        if not (0 <= i <= len(self.data)): raise IndexError
        return self.data[i]

    def set_at(self, i, x):
        if not (0 <= i <= len(self.data)): raise IndexError
        self.data[i] = x


def birthday_match(students):
    n = len(students)
    record = StaticArray(n)
    for k in range(n):
        (name1, bird1) = students[k]
        for i in range(k):
            (name2, bird2) = record.get_at(i)
            if bird1 == bird2:
                return (name1, name2)
        record.set_at(k, (name1, bird1))
    return None

Time analysis:

O(n2)O(n^2)