Linking Up

Jed Rembold

April 26, 2021

Announcements

  • Adventure Game Project due next Sunday night
  • Nothing formal planned for sections this week. Contact your section leader if you want to meet them during the normal time for questions.
  • Final Format
    • A change of pace from how the midterm was done
    • Will have a checklist of learning objectives from the 2nd half of the semester
    • You will be responsible for writing 1-2 programs that meet a certain number of those objectives
      • Programs will also need to accomplish something meaningful. Which is entirely up to you, but they can’t exist soley to meet objectives.
    • Guidelines and objectives will be posted on Friday evening, and you’ll have until the date of your final to have your programs submitted
  • Polling: rembold-class.ddns.net

Review Question

Three of the below expressions are valid; one is not. Which one would return an error?

  1. {'A': {'B': (1,2)}, 'C': 3}
  2. {1, 2, (3,4), 5 }
  3. [{'Alpha': 1, 'Omega': 26}, {2, 3, 4, 5}]
  4. {['A', 'B']: {1, 2}}

The Beacons of Gondor

For answer Gandalf cried aloud to his horse. “On Shadowfax! We must hasten. Time is short. See! The beacons of Gondor are alight, calling for aid. War is kindled. See, there is the fire on Amon Dìn, and flame on Eilach; and there they go speeding west: Nardol, Erelas, Min-Rimmon, Calenhad, and the Halifirien on the borders of Rohan.”

J.R.R. Tolkien, The Return of the King, 1955

  • Rohan alerted to danger by a succession of signal fires moving from mountain top to mountain top
  • Mimics the idea of message passing in a linked list

Linking Objects

  • Since Python stores objects as references, it is possible to represent relationships among objects by linking them in various ways
  • Simplest example of a linked structure is a linked list
    • Each object in a sequence contains a reference to the one that follows it, similar to a sequential treasure hunt image/svg+xml clue clue clue clue None
  • Python marks the end of the linked list with a pointer to None
    • In diagrams, the None value is commonly shown as just a diagonal line across the box

Lighting the Fires

class SignalTower:

    def __init__(self, name, link=None):
        self.name = name
        self.link = link

    def __str__(self):
        s = self.name
        if self.link is not None:
            return f"{s} -> {str(self.link)}"
        return s

    def get_name(self):
        return self.name

    def signal(self):
        print(f"Lighting {self.name}!")
        if self.link is not None:
            self.link.signal()

    @staticmethod
    def create_chain(names):
        towers = None
        for name in reversed(names):
            towers = SignalTower(name, towers)
        return towers


if __name__ == '__main__':
    names = [
            'Minas Tirith', 'Amon Din', 'Eilenach', 'Nardol', 
            'Erelas', 'Min-Rimmon', 'Calenhad', 'Halifierien', 
            'Rohan'
            ]
    towers = SignalTower.create_chain(names)
    print(towers)
    towers.signal()

Comparisons

  • Arrays
    • Can access any element by index in \(\mathcal{O}(1)\) time
    • Generally static in length, though Python will readjust length on the fly if needed
    • Adding, inserting, or removing new elements is expensive, as all other elements need to be moved
  • Linked Lists
    • Must move through the whole list to get an element by index, taking \(\mathcal{O}(N)\) time
    • Entirely flexible in length
    • Adding, inserting, or removing is very easy

Beacons of Gondor Tree

image/svg+xml Ethring Calembel MinasTirith Edoras Amon Din Eilenach Nardol Erelas Min-Rimmon Calenhad Halifirien Dunharrow Aldburg Amon Din Eilenach Nardol Erelas Min-Rimmon Calenhad Halifirien Dunharrow Aldburg

Trees

  • A tree is a collection of objects called nodes
    • Begins at a single root node and connects to other nodes in branching, non-cyclical, patterns
  • Trees appear in many familiar contexts:
    • Family trees
    • Evolutionary trees
    • Object-oriented hierarchies in programming languages like Python

image/svg+xml

Family Trees

  • Family trees are common examples of a tree structure
  • Useful for defining terminology
    • William I is the root of the tree
    • Adela is a child of William I and the parent of Stephen
    • Robert, William II, Adela, and Henry and siblings
    • Henry II is a descendant of William I, Henry I, and Matilda
    • William I is an ancestor of everyone else in this tree

Binary Search Trees

  • Trees can be used to implement dictionaries using a structure called a binary search trees (or BST)
  • Each node in a BST has exactly two subtrees:
    • A left subtree that contains all nodes before the current node
    • A right subtree that contains all the nodes that come after it
  • The classic example of a binary search tree uses the names of the seven dwarves:

Balance Your Trees

  • Ideally, a binary search tree would look similar to our last picture
  • If you placed a different dwarf at the root, then the tree would end up unbalanced
    • If you placed Bashful at the root, the entire left subtree would be empty!
  • Balancing BST’s is important for effectively and quickly finding the desired values
  • If you go on to take CS 343 (Analysis of Algorithms), you will learn several strategies for maintaining balanced binary search trees
// reveal.js plugins