Python: Advanced Objects

Slides:



Advertisements
Similar presentations
Introduction to Trees Chapter 6 Objectives
Advertisements

CS 206 Introduction to Computer Science II 03 / 27 / 2009 Instructor: Michael Eckmann.
Abstract Data Types and Subprograms
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
Data Structures Using C++
CS 206 Introduction to Computer Science II 11 / 11 / Veterans Day Instructor: Michael Eckmann.
Department of Computer Science University of Maryland, College Park
Binary Trees Terminology A graph G = is a collection of nodes and edges. An edge (v 1,v 2 ) is a pair of vertices that are directly connected. A path,
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
CS 206 Introduction to Computer Science II 11 / 05 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 03 / 25 / 2009 Instructor: Michael Eckmann.
1 Introduction to Graphs Graph definition / applications Graph terminology –Undirected graphs –Directed graphs –Networks Implementing graphs Reading: L&C.
CS 206 Introduction to Computer Science II 11 / 09 / 2009 Instructor: Michael Eckmann.
Fall 2007CS 2251 Graphs Chapter 12. Fall 2007CS 2252 Chapter Objectives To become familiar with graph terminology and the different types of graphs To.
CS 307 Fundamentals of Computer Science 1 Data Structures Review Session 2 Ramakrishna, PhD student. Grading Assistant for this course.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
CS 206 Introduction to Computer Science II 03 / 30 / 2009 Instructor: Michael Eckmann.
Marc Smith and Jim Ten Eyck
Binary Search Trees Section Trees Trees are efficient Many algorithms can be performed on trees in O(log n) time. Searching for elements.
Binary Trees Chapter 6.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
Trees & Graphs Nell Dale & John Lewis (adaptation by Michael Goldwasser and Erin Chambers)
COSC2007 Data Structures II
Chapter 9 – Graphs A graph G=(V,E) – vertices and edges
Computer Science 112 Fundamentals of Programming II Introduction to Graphs.
 What is a graph? What is a graph?  Directed vs. undirected graphs Directed vs. undirected graphs  Trees vs graphs Trees vs graphs  Terminology: Degree.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Binary Trees. Binary Tree Finite (possibly empty) collection of elements A nonempty binary tree has a root element The remaining elements (if any) are.
Preview  Graph  Tree Binary Tree Binary Search Tree Binary Search Tree Property Binary Search Tree functions  In-order walk  Pre-order walk  Post-order.
CISC 235: Topic 9 Introduction to Graphs. CISC 235 Topic 92 Outline Graph Definition Terminology Representations Traversals.
Trees : Part 1 Section 4.1 (1) Theory and Terminology (2) Preorder, Postorder and Levelorder Traversals.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 19 Binary Search Trees.
Chapter 12 Abstract Data Type. Understand the concept of an abstract data type (ADT). Understand the concept of a linear list as well as its operations.
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 13: Graphs Data Abstraction & Problem Solving with C++
Trees, Binary Search Trees, Balanced Trees, Graphs Graph Fundamentals Telerik Algo Academy
1 Directed Graphs Chapter 8. 2 Objectives You will be able to: Say what a directed graph is. Describe two ways to represent a directed graph: Adjacency.
1 Trees What is a Tree? Tree terminology Why trees? What is a general tree? Implementing trees Binary trees Binary tree implementation Application of Binary.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
Data Structures and Algorithm Analysis Graph Algorithms Lecturer: Jing Liu Homepage:
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
Chapter 11. Chapter Summary  Introduction to trees (11.1)  Application of trees (11.2)  Tree traversal (11.3)  Spanning trees (11.4)
(c) University of Washington20-1 CSC 143 Java Trees.
1 GRAPHS – Definitions A graph G = (V, E) consists of –a set of vertices, V, and –a set of edges, E, where each edge is a pair (v,w) s.t. v,w  V Vertices.
What is a Tree? Formally, we define a tree T as a set of nodes storing elements such that the nodes have a parent-child relationship, that satisfies the.
TREES From root to leaf. Trees  A tree is a non-linear collection  The elements are in a hierarchical arrangement  The elements are not accessible.
CSE 373 Data Structures Lecture 7
Chapter 12 Abstract Data Type.
Trees Chapter 15.
CC 215 Data Structures Trees
Chapter 5 : Trees.
CSE 373 Data Structures Lecture 7
i206: Lecture 13: Recursion, continued Trees
Revised based on textbook author’s notes.
CS201: Data Structures and Discrete Mathematics I
CS202 - Fundamental Structures of Computer Science II
CS120 Graphs.
Trees CSE 373 Data Structures.
Graphs Chapter 13.
Graphs Chapter 11 Objectives Upon completion you will be able to:
Week nine-ten: Trees Trees.
CSC 143 Java Trees.
Graphs Chapter 7 Visit for more Learning Resources.
Graph Algorithms DS.GR.1 Chapter 9 Overview Representation
Trees CSE 373 Data Structures.
Trees CSE 373 Data Structures.
Heaps Chapter 6 Section 6.9.
Cs212: Data Structures Lecture 7: Tree_Part1
Presentation transcript:

Python: Advanced Objects

Data Structure Python has some basic data types built-in  list  tuple  complex  dictionary  etc.. Which of these would you use to represents an  Organizational chart?  A book outline?  An XML file?  A folder system? CEO Marketing Director Manufacturing Director Quality Control Director

Trees A tree is a collection of elements  The elements are in a non-linear, hierarchical arrangement  The elements are not accessible by position Mirrors common real-world objects  A book : chapters – sections – paragraphs – sentences – words.  Org charts  Folder systems 3

Terminology Trees are formed from nodes and edges.  Nodes are also known as vertices  Edges are also known as branches An edge establishes a relationship between nodes  This is a parent-child relationship  Given nodes A and B, the edge {A, B} means that A is the parent of B.  A node can have at most one parent.  The children are ordered from left to right. Each tree has one root node. The root node is the only node that has no parent. 4

Definitions Trees can be defined recursively (inductively)  A single node is a tree. It is the root of the tree.  If N is a node and T 1, T 2, …, T k are trees with root nodes N 1, N 2, …, N k, then so is the tree having N as the root and adding edges {N, N 1 }, {N, N 2 }, …, {N, N k }.  Trees are usually drawn “upside” down. Root at the top. 5

Binary Search Tree A binary search tree is a binary tree with the following property  Each node is associated with a value or key  For each node in the tree, the nodes key is greater than or equal to all keys in the left subtree and is less than or equal to all keys in the right subtree. 6

Binary Search Tree Operations A binary search tree is a collection that supports efficient operations such as:  searching!  inserting  removing  finding the minimum  finding the maximum 7

Min and Max Give a binary search tree node T (that has left, right and value attributes), describe an algorithm for finding the minimum value in T Describe an algorithm for finding the maximum key in a binary search tree. algorithm getMin(T): if T is empty then return None else if T has a left child then getMin(T.left) else return T.value algorithm getMin(T): if T is empty then return None else if T has a left child then getMin(T.left) else return T.value algorithm getMax(T): if T is empty then return None else if T has a right child then getMax(T.right) else return T.value algorithm getMax(T): if T is empty then return None else if T has a right child then getMax(T.right) else return T.value

Insertion Give a binary search tree node T, describe an algorithm for inserting into T # This returns the tree that results from inserting V into T algorithm insert(T, V): if T is empty then return a new node (V, None, None) else if V < T.value then T.left = insert(T.left, V) else T.right = insert(T.right, V) return T # This returns the tree that results from inserting V into T algorithm insert(T, V): if T is empty then return a new node (V, None, None) else if V < T.value then T.left = insert(T.left, V) else T.right = insert(T.right, V) return T

Searching Give a binary search tree node T, describe an algorithm for finding a value # returns true if T contains V and false otherwise algorithm contains(T, V): if T is empty then return False else if T.value = V then return True else if V < T.value then return contains(T.left, V) else return contains(T.right, V) # returns true if T contains V and false otherwise algorithm contains(T, V): if T is empty then return False else if T.value = V then return True else if V < T.value then return contains(T.left, V) else return contains(T.right, V)

Search Tree as List We will eventually construct a binary search tree class. But for now, consider representing a binary search tree as a list.  The empty tree is the empty list  A non-empty tree is a list of length 3:  [VALUE LEFT-TREE RIGHT-TREE]  Write functions named  insert  min  max  size  contains

Nodes Can also write a tree class that uses "nodes"  Explicitly represent a node object  Each node has three attributes  A left node  A right node  A value  The empty node is different:  Has no value  Has no left  Has no right  Use two difference classes for nodes  NonEmptyNode  EmptyNode

Node Class In addition to attributes each node should support some operations  insert  remove  size  contains  height These methods should be supported even for EmptyNodes. A BinarySearch tree is then an object with one attribute:  The root node

Empty Node class EmptyNode: def __init__(self): pass def insert(self, value): return SearchTree.NonEmptyNode(value) def size(self): return 0 def height(self): return -1 def remove(self, value): return self def isEmpty(self): return True def min(self): return None def max(self): return None class EmptyNode: def __init__(self): pass def insert(self, value): return SearchTree.NonEmptyNode(value) def size(self): return 0 def height(self): return -1 def remove(self, value): return self def isEmpty(self): return True def min(self): return None def max(self): return None class NonEmptyNode: def __init__(self, value): self.left = SearchTree.EmptyNode() self.right = SearchTree.EmptyNode() self.value = value def insert(self, value): ??? def size(self): ??? def height(self): ??? def remove(self, value): ??? def isEmpty(self): ??? def min(self): ??? def max(self): ??? class NonEmptyNode: def __init__(self, value): self.left = SearchTree.EmptyNode() self.right = SearchTree.EmptyNode() self.value = value def insert(self, value): ??? def size(self): ??? def height(self): ??? def remove(self, value): ??? def isEmpty(self): ??? def min(self): ??? def max(self): ???

Search Tree What would the search tree class look like?  How many attributes?  How many methods? class SearchTree: def __init__(self): self.root = EmptyNode() def size(self): ??? etc… class SearchTree: def __init__(self): self.root = EmptyNode() def size(self): ??? etc…

A graph G is a pair of sets (V, E)  Let V be a set of vertices. A vertex is some object.  Let E be a set of edges. A single edge is a pair of vertices. An edge establishes a connection between two vertices.  A graph is undirected if the edge is unordered  A graph is directed if the edge is ordered. Consider the following graph:  V = {1,2,3,4,5,6}  E = {{1,2}, {1,5}, {2,3}, {2,5}, {3, 4}, {4, 5}, {4, 6}} Vertex a is adjacent to vertex b iff {a,b} is in E. If {u,v} is a directed edge  u is the predecessor to v  v is the successor to u  The in-degree of a vertex is the number of its successors  The out-degree of a vertex is the number of its predecessors Graphs

A weighted graph is a graph (directed or undirected) where each edge is associated with a weight. A weight is a numeric value. Consider the following graph:  V = {1,2,3,4,5,6}  E = {{1,2}:12, {1,5}:18, {2,3}:1, {2,5}:3, {3, 4}:-5, {4, 5}:6, {4, 6}:9} Graph Properties

Define G Is [F, E, C, D] a path?  length?  weight? Example

Associate every node with an airport and every edge with a flight and every weight with a time/distance. This is a reasonable model of an airline. Associate every node with a router and every edge with a connection and every weight with a time. This is a reasonable model of a computer network. Associate every node with a course in the CS-major and a directed edge as a pre-requisite. This is a reasonable model of a college curriculum. You could even weight the edges with the credit hours. Applications

Representation There are two basic ways to represent a graph G = (V,E) 1. Adjacency matrix: Form a 2D graph of VxV in size called A. Each vertex is labeled with an integer 0 to (V-1)  If G is not weighted: A[i][j] is true if edge (i,j) is in E and false otherwise  If G is weighted: A[i][j] is the weight of edge (i,j). If there is no edge (i,j) then A[i][j] is set to some sentinel value (perhaps 0 or negative infinity or positive infinity or null depending on the specific needs of the application). 2. Adjacency list: For each vertex we form a list of vertices to which it is adjacent.  These lists can be contained within the vertex itself  These lists can be stored in an array and accessed by vertex number  If ordered, the list for a vertex contains only the outgoing vertices.

Example

Structure Consider writing a graph class such that  A vertex is known by a label  A vertex keeps a list of direct neighbors  Can perform operations such as  addVertex  removeVertex  getVertices  addEdge  removeEdge

Vertex A vertex is an object that has what attributes?  a list of adjacent vertices  a label An edge is not a "thing" in an adjacency list representation What operations does a vertex support?  getLabel  getSuccessors  addSuccessor

Vertex class Vertex: def __init__(self, label): self.label = label self.successors= set() def getLabel(self): return self.label def getSuccessors(self): return self.successors def addSuccessor(self, v): self.successors.add(v) class Vertex: def __init__(self, label): self.label = label self.successors= set() def getLabel(self): return self.label def getSuccessors(self): return self.successors def addSuccessor(self, v): self.successors.add(v)

Graph class Graph: def __init__(self): self.vertices = dict() def addVertex(self, label): self.vertices[label] = self.Vertex(label) def getVertex(self, label): return self.vertices.get(label) def containsVertex(self, label): return label in self.vertices def addEdge(self, label1, label2): self.getVertex(label1).addSuccessor(self.getVertex(label2)) class Graph: def __init__(self): self.vertices = dict() def addVertex(self, label): self.vertices[label] = self.Vertex(label) def getVertex(self, label): return self.vertices.get(label) def containsVertex(self, label): return label in self.vertices def addEdge(self, label1, label2): self.getVertex(label1).addSuccessor(self.getVertex(label2))

Consider iterating (or visiting) every vertex in a connected graph. There are various strategies that can be generalized as: Depth first search uses a stack (LIFO) rather than a set Breadth first search uses a queue (FIFO) rather than a set Traversal algorithm traverse(Graph G, Vertex S): Let UNVISITED be a an empty set of vertices UNVISITED.add(S) while size of UNIVISITED > 0: V = UNVISITED.remove() visit v for each edge (v, w) in G: if W has not been visited then UNVISITED.add(W) algorithm traverse(Graph G, Vertex S): Let UNVISITED be a an empty set of vertices UNVISITED.add(S) while size of UNIVISITED > 0: V = UNVISITED.remove() visit v for each edge (v, w) in G: if W has not been visited then UNVISITED.add(W)

Consider a directed acyclic graph such that ever node is a course in the CS major and each edge represents a pre-requisite structure. Determine in which order courses could be taken to complete the major. A topological sort of a directed acyclic graph G is an ordering of the vertices such that if there is a path from v[i] to v[j] then vertex v[i] occurs before v[j] in the ordering. Topological sort

Give a topological sort of this graph Give an algorithm to topologically sort a graph G. Topological sort List algorithm(Graph G): Let Q be an empty list Let L be an empty list for each V in G: if(inDegree(V) == 0): Q.addLast(V) while(!q.isEmpty()): V = q.removeFirst() L.addLast(V) for each W adjacent to V: inDegree(W)— if inDegree(W) == 0: Q.addLast(W) if L.size() != |V|: threw new Exception("Cycle found") return L; List algorithm(Graph G): Let Q be an empty list Let L be an empty list for each V in G: if(inDegree(V) == 0): Q.addLast(V) while(!q.isEmpty()): V = q.removeFirst() L.addLast(V) for each W adjacent to V: inDegree(W)— if inDegree(W) == 0: Q.addLast(W) if L.size() != |V|: threw new Exception("Cycle found") return L;