lists dictionaries and trees oh my
play

Lists, Dictionaries, and Trees Oh My! Tyler Moore CSE 3353, SMU, - PDF document

Notes Lists, Dictionaries, and Trees Oh My! Tyler Moore CSE 3353, SMU, Dallas, TX February 12, 2013 Portions of these slides have been adapted from the slides written by Prof. Steven Skiena at SUNY Stony Brook, author of Algorithm Design


  1. Notes Lists, Dictionaries, and Trees – Oh My! Tyler Moore CSE 3353, SMU, Dallas, TX February 12, 2013 Portions of these slides have been adapted from the slides written by Prof. Steven Skiena at SUNY Stony Brook, author of Algorithm Design Manual. For more information see http://www.cs.sunysb.edu/~skiena/ Implementing Linked Lists in Python Notes You would never actually want to use linked lists in Python Built-in lists are much more efficient Nonetheless, implementing linked lists serves as a nice introduction to OOP in Python Code at http://lyle.smu.edu/~tylerm/courses/cse3353/ code/linked_list.py Compare to the C code in ADM pp. 68–70. Which do you prefer? 2 / 28 Implementing Linked Lists in Python Notes 1 class Node : def i n i t ( s e l f , item=None , next=None ) : 2 s e l f . item = item 3 s e l f . next = next 4 def s t r ( s e l f ) : 5 return s t r ( s e l f . item ) 6 7 8 L i n k e d L i s t : 9 class def i n i t ( s e l f ) : 10 s e l f . length = 0 11 s e l f . head = None 12 1 #code f o r Node and L i n k e d L i s t in l i n k e d l i s t . py l i n k e d l i s t 2 import 3 l i l = l i n k e d l i s t . L i n k e d L i s t () 3 / 28 Inserting a Node Notes i n s e r t l i s t ( s e l f , item ) : def 1 node = Node ( item ) 2 node . next = s e l f . head 3 s e l f . head = node 4 s e l f . length = s e l f . length + 1 5 1 l i l . i n s e r t n o d e ( ‘ ‘ a ’ ’ ) 4 / 28

  2. Searching the list Notes s e a r c h l i s t ( s e l f , item ) : def 1 node = s e l f . head 2 while node : 3 i f node . item==item : return node 4 node = node . next 5 return None 6 1 l i l . search ( ‘ ‘ b ’ ’ ) 5 / 28 Deleting from the list Notes def p r e d e c e s s o r l i s t ( s e l f , item ) : 1 node = s e l f . head 2 while node . next : 3 i f node . next . item==item : return node 4 node = node . next 5 return None 6 7 def d e l e t e l i s t ( s e l f , item ) : 8 p = s e l f . s e a r c h l i s t ( item ) 9 i f p : 10 pred = s e l f . p r e d e c e s s o r l i s t ( item ) 11 i f pred i s None : #i f p i s the head , then there w i l l be no p r e d e c e s s o r 12 s e l f . head = p . next 13 else : #otherwise point p r e d e c e s s o r to item ’ s next element 14 pred . next = p . next 15 6 / 28 Representing the list as a string Notes def s t r ( s e l f ) : 1 node = s e l f . head 2 l l s t r = ” [ ” 3 while node : 4 l l s t r += ” %s ”%node . item 5 node = node . next 6 l l s t r+= ” ] ” 7 return l l s t r 8 7 / 28 Cost of operations in linked lists Notes What does node insertion cost in the worst case? What does node search cost in the worst case? What does node deletion cost in the worst case? 8 / 28

  3. Stacks and Queues Notes Sometimes, the order in which we retrieve data is independent of its content, being only a function of when it arrived. A stack supports last-in, first-out operations: push and pop. A queue supports first-in, first-out operations: enqueue and dequeue. Lines in banks are based on queues, while food in my refrigerator is treated as a stack. 9 / 28 Python lists can be treated like stacks Notes Push: l.append() Pop: l.pop() What’s missing from list’s built-in methods to make queues possible? List’s methods are ‘append’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ’sort’ enqueue(): dequeue(): 10 / 28 Dictionary Notes Perhaps the most important class of data structures maintain a set of items, indexed by keys. Search ( S , k ) A query that, given a set S and a key value k , returns a pointer x to an element in S such that key [ x ] = k , or nil if no such element belongs to S . Insert ( S , x ) A modifying operation that augments the set S with the element x . Delete ( S , x ) Given a pointer x to an element in the set S ,remove x from S . Observe we are given a pointer to an element x , not a key value. Min ( S ) , Max ( S ) Returns the element of the totally ordered set S which has the smallest (largest) key. Next ( S , x ) , Previous ( S , x ) Given an element x whose key is from a totally ordered set S , returns the next largest (smallest) element in S , or NIL if x is the maximum (minimum) element. There are a variety of implementations of these dictionary operations, each of which yield different time bounds for various operations. 11 / 28 Different Ways to Implement Dictionaries Notes Array-based Sets: Unsorted Arrays Operation Implementation Efficiency Search ( S , k ) sequential search Insert ( S , x ) place in first empty spot Delete ( S , x ) copy nth item to the xth spot Min ( S ) , Max ( S ) sequential search Successor ( S , x ) , Pred ( S , x ) sequential search Array-based Sets: Sorted Arrays Operation Implementation Efficiency Search ( S , k ) binary search Insert ( S , x ) search, then move to make space Delete ( S , x ) move to fill up the hole Min ( S ) , Max ( S ) first or last element Successor ( S , x ) , Pred ( S , x ) add or subtract 1 from pointer 12 / 28

  4. How could you implement a dictionary in Python with an Notes unsorted array? 1 class Item : i n i t ( s e l f , key , v a l ) : def 2 s e l f . key = key 3 s e l f . v a l = v a l 4 def s t r ( s e l f ) : 5 s e l f . key+” , ”+s e l f . v a l return 6 7 D i c t i o n a r y : 8 class def i n i t ( s e l f ) : 9 s e l f . array =[] 10 13 / 28 Working with a Dictionary object Notes >>> import dlist >>> d = dlist.Dictionary() >>> d.Insert("smu","mustangs") >>> d.Insert("texas","longhorns") >>> d.Insert("memphis","tigers") >>> d.Insert("tulsa","golden hurricane") >>> print d {smu: mustangs, texas: longhorns, memphis: tigers, tulsa: golden hurricane, } >>> print d.Search("tulsa") tulsa, golden hurricane >>> print d.Delete("texas","longhorns") >>> print d {smu: mustangs, memphis: tigers, tulsa: golden hurricane, } 14 / 28 Inserting an element Notes Insert ( S , x ) A modifying operation that augments the set S with the element x Item : 1 class def i n i t ( s e l f , key , v a l ) : 2 s e l f . key = key 3 s e l f . v a l = v a l 4 s t r ( s e l f ) : def 5 return s e l f . key+” , ”+s e l f . v a l 6 7 8 class D i c t i o n a r y : i n i t ( s e l f ) : def 9 s e l f . array =[] 10 15 / 28 Search for an element Notes Search ( S , k ) A query that, given a set S and a key value k , returns a pointer x to an element in S such that key [ x ] = k , or nil if no such element belongs to S . Code: http://lyle.smu.edu/~tylerm/courses/cse3353/code/dlist.txt 16 / 28

  5. Binary Search Trees Notes Binary search trees provide a data structure which efficiently supports all six dictionary operations. A binary tree is a rooted tree where each node contains at most two children. Each child can be identified as either a left or right child. 17 / 28 Binary Search Trees Notes A binary search tree labels each node x in a binary tree such that all nodes in the left subtree of x have keys < x and all nodes in the right subtree of x have keys > x . The search tree labeling enables us to find where any key is. 18 / 28 Searching in a Binary Tree Notes def s e a r c h t r e e ( node , item ) : node None : KeyError i f i s r a i s e i f node . item == item : return node item < node . item : e l i f return s e a r c h t r e e ( node . l e f t , item ) else : return s e a r c h t r e e ( node . right , item ) The algorithm works because both the left and right subtrees of a binary search tree are binary search trees recursive structure, recursive algorithm. This takes time proportional to the height of the tree, O(h) 19 / 28 Finding the Maximum and Minimum Notes Where are the maximum and minimum elements in a binary search tree? Finding the max or min takes time proportional to the height of the tree, O ( h ). 20 / 28

  6. Finding a predecessor: internal node Notes If X has two children, its predecessor is the maximum value in its left subtree and its successor the minimum value in its right subtree. 21 / 28 Finding a predecessor: leaf node Notes If it does not have a left child, a nodes predecessor is its first left ancestor. The proof of correctness comes from looking at the in-order traversal of the tree. 22 / 28 Tree Insertion Notes Do a binary search to find where it should be, then replace the termination None with the new item. Insertion takes time proportional to the height of the tree, O(h). 23 / 28 Deleting from a tree Notes Deletion is trickier than insertion, because the node to die may not be a leaf, and thus effect other nodes. There are three cases: Where the node is a leaf: just NIL out the parent’s child pointer. 1 Where a node has one child: the doomed node can just be cut out. 2 Relabel the node as its successor (which has at most one child when z 3 has two children!) and delete the successor! 24 / 28

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend