CS61A Lecture 11 Immutable Trees Jom Magrotker UC Berkeley EECS July 5, 2012.

Slides:



Advertisements
Similar presentations
CS61A Lecture 24 Infinite Sequences
Advertisements

CS61A Lecture 25 Delayed Sequences Jom Magrotker UC Berkeley EECS July 31, 2012.
CS 410 Applied Algorithms Applied Algorithms Lecture #7 Counting.
CS61A Lecture 8 Data Abstraction Tom Magrino and Jon Kotker UC Berkeley EECS June 28, 2012.
B+-Trees (PART 1) What is a B+ tree? Why B+ trees? Searching a B+ tree
CS61A Lecture 4 Higher Order Functions Tom Magrino and Jon Kotker UC Berkeley EECS June 21, 2012.
Indexes. Primary Indexes Dense Indexes Pointer to every record of a sequential file, (ordered by search key). Can make sense because records may be much.
Indexes. Primary Indexes Dense Indexes Pointer to every record of a sequential file, (ordered by search key). Can make sense because records may be much.
COMP 451/651 Indexes Chapter 1.
CSE332: Data Abstractions Lecture 9: B Trees Dan Grossman Spring 2010.
Data Structures and Algorithms1 B-Trees with Minimum=1 2-3 Trees.
Binary Search Introduction to Trees. Binary searching & introduction to trees 2 CMPS 12B, UC Santa Cruz Last time: recursion In the last lecture, we learned.
CS 206 Introduction to Computer Science II 12 / 03 / 2008 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 12 / 01 / 2008 Instructor: Michael Eckmann.
B + -Trees (Part 1) Lecture 20 COMP171 Fall 2006.
B + -Trees (Part 1). Motivation AVL tree with N nodes is an excellent data structure for searching, indexing, etc. –The Big-Oh analysis shows most operations.
Quiz: Box and Pointer fun! (cons (cons (cons ‘hey (cons ‘there nil)) nil) (cons ‘wow nil)) (list ‘boo (append (list ‘hoo ‘hoo) (cons ‘see ‘me)))
Primary Indexes Dense Indexes
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
Homework #3 Due Thursday, April 17 Problems: –Chapter 11: 11.6, –Chapter 12: 12.1, 12.2, 12.3, 12.4, 12.5, 12.7.
B + -Trees COMP171 Fall AVL Trees / Slide 2 Dictionary for Secondary storage * The AVL tree is an excellent dictionary structure when the entire.
Backtracking.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 20: Binary Trees.
CS61A Lecture 14 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 11, 2012.
CS61A Lecture 3 Higher Order Functions Jon Kotker and Tom Magrino UC Berkeley EECS June 20, 2012.
CS61A Lecture 21 Scheme Jom Magrotker UC Berkeley EECS July 24, 2012.
CS61A Lecture 16 Mutable Data Structures Jom Magrotker UC Berkeley EECS July 16, 2012.
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
CS61A Lecture 15 Object-Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
CS61A Lecture 22 Interpretation Jom Magrotker UC Berkeley EECS July 25, 2012.
CS61A Lecture 6 Recursion Tom Magrino and Jon Kotker UC Berkeley EECS June 26, 2012.
CS61A Lecture 13 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 10, 2012.
CS61A Lecture 30 MapReduce Jom Magrotker UC Berkeley EECS August 8, 2012 Slides developed from those of John DeNero, Paul Hilfinger, and Eric Tzeng.
COSC 2007 Data Structures II Chapter 15 External Methods.
TREES Lecture 12 CS2110 – Fall Announcements  Prelim #1 is tonight!  Olin 155  A-L  5:30  M-Z  5:30  A4 will be posted today  Mid-semester.
Discrete Structures Lecture 12: Trees Ji Yanyan United International College Thanks to Professor Michael Hvidsten.
CS61A Lecture 12 Immutable Trees Jom Magrotker UC Berkeley EECS July 9, 2012.
CS61A Lecture 23 Py Jom Magrotker UC Berkeley EECS July 26, 2012.
CSCI 4310 Lecture 6: Adversarial Tree Search. Book Winston Chapter 6.
Week 8 - Wednesday.  What did we talk about last time?  Level order traversal  BST delete  2-3 trees.
CS61A Lecture 27 Logic Programming Jom Magrotker UC Berkeley EECS August 2, 2012.
Indexes. Primary Indexes Dense Indexes Pointer to every record of a sequential file, (ordered by search key). Can make sense because records may be much.
CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class 
CS61A Lecture 20 Object-Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012.
CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012.
1 More Trees Trees, Red-Black Trees, B Trees.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
2014-T2 Lecture 27 School of Engineering and Computer Science, Victoria University of Wellington  Lindsay Groves, Marcus Frean, Peter Andreae, and Thomas.
Week 7 - Wednesday.  What did we talk about last time?  Recursive running time  Master Theorem  Symbol tables.
CS61A Lecture 10 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 3, 2012.
CS61A Lecture 29 Parallel Computing Jom Magrotker UC Berkeley EECS August 7, 2012.
DATA STRUCURES II CSC QUIZ 1. What is Data Structure ? 2. Mention the classifications of data structure giving example of each. 3. Briefly explain.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Binary Search Trees One of the tree applications in Chapter 10 is binary search trees. In Chapter 10, binary search trees are used to implement bags.
Recursive Objects (Part 4)
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
Chapter 10.1 Binary Search Trees
CMSC 341 Lecture 13 Leftist Heaps
Data Structures and Algorithms
Another problem to solve…
Balanced-Trees This presentation shows you the potential problem of unbalanced tree and show two way to fix it This lecture introduces heaps, which are.
Binary Search Trees One of the tree applications in Chapter 10 is binary search trees. In Chapter 10, binary search trees are used to implement bags.
Another problem to solve…
B-Trees This presentation shows you the potential problem of unbalanced tree and show one way to fix it This lecture introduces heaps, which are used.
Balanced-Trees This presentation shows you the potential problem of unbalanced tree and show two way to fix it This lecture introduces heaps, which are.
B-Trees This presentation shows you the potential problem of unbalanced tree and show one way to fix it This lecture introduces heaps, which are used.
Another problem to solve…
Instructor: Dr. Michael Geiger Spring 2019 Lecture 34: Exam 3 Preview
Data Structures Using C++ 2E
Presentation transcript:

CS61A Lecture 11 Immutable Trees Jom Magrotker UC Berkeley EECS July 5, 2012

2 C OMPUTER S CIENCE IN THE N EWS

3 T ODAY Review: Immutable Dictionaries Deep Tuples Immutable Trees

4 R EVIEW : D ICTIONARIES Often we want to associate pieces of data with other pieces of data. “Ozzy” “Geezer” “Tony” “Dictionary” Keys Values

5 R EVIEW : I MMUTABLE D ICTIONARIES >>> phone_bk = make_idict((“Ozzy”, “ ”),... (“Tony”, “ ”),... (“Geezer”, “ ”)) >>> idict_select(phone_bk, “Ozzy”) “ ” >>> idict_select(phone_bk, “Geezer”) “ ” >>> idict_keys(phone_bk) (“Ozzy”, “Tony”, “Geezer”)

6 R EVIEW : H IGHER O RDER F UNCTIONS F OR S EQUENCES >>> nums = (1, 2, 3, 4, 5) >>> tuple(map(lambda x: x * x, nums)) (1, 4, 9, 16, 25) >>> tuple(map(lambda x: x + 1, nums)) (2, 3, 4, 5, 6) >>> tuple(filter(lambda x: x % 2 == 0, nums)) (2, 4) >>> tuple(filter(lambda x: x <= 3, nums)) (1, 2, 3) >>> from functools import reduce >>> reduce(lambda x, y: x * y, nums, 1) 120 >>> reduce(lambda x, y: x + y, nums, 0) 15

7 P RACTICE : H IGHER O RDER F UNCTIONS F OR S EQUENCES What are the outputs for each of the following lines of Python? >>> from operator import add >>> tuple(map(lambda x: reduce(add, x), ((2, 3), (5, 6), (8, 9)))) ????? >>> tuple(map(lambda x: x – 1, filter(lambda x: x % 2 == 0, map(lambda x: x + 1, range(10))))) ?????

8 P RACTICE : H IGHER O RDER F UNCTIONS F OR S EQUENCES What are the outputs for each of the following lines of Python? >>> from operator import add >>> tuple(map(lambda x: reduce(add, x), ((2, 3), (5, 6), (8, 9)))) (5, 11, 17) >>> tuple(map(lambda x: x – 1, filter(lambda x: x % 2 == 0, map(lambda x: x + 1, range(10))))) (1, 3, 5, 7, 9)

9 A NNOUNCEMENTS Homework 5 is due July 6. Project 2 is due July 13. Project 1 contest is on! – How to submit: Submit a file pig.py with your final_strategy to proj1-contest. – Deadline: Friday, July 6 at 11:59pm. – Prize: One of 3 copies of Feynman and 1 extra credit point. – Metric: We will simulate your strategy against everyone else’s, and tally your win rate. Draws count as losses.

10 A NNOUNCEMENTS : M IDTERM 1 Midterm 1 is on July 9. – Where? 2050 VLSB. – When? 7PM to 9PM. – How much? Material covered until July 4. Closed book and closed electronic devices. One 8.5” x 11” ‘cheat sheet’ allowed. Group portion is 15 minutes long. Post-midterm potluck on Wednesday, July 11.

11 H IERARCHICAL D ATA Often we find that information is nicely organized into hierarchies. Example: Writing! Book Chapter Paragraph Sentence Word

12 H IERARCHICAL D ATA : D EEP T UPLES We already had a way of representing something like this. >>> p = ((“Cat”, “is”, “fat.”), (“Cat”, “is”, “coming.”), (“Watch”, “Out!”)) “Cat” “is” “fat.” “is” “coming.” “Watch” “out!” p

13 O PERATING ON D EEP T UPLES So we already have a simple way of organizing data into hierarchies using “deep tuples.” How do we manipulate deep tuples? – Not that different from working with regular tuples. – Use tree recursion!

14 E XAMPLE : O PERATING ON D EEP T UPLES Let’s say I want to write a function, evens_count, that counts the number of even numbers found in a deep tuple containing numbers (or tuples). >>> woah_deep = ((1, 2), 3, ((4, 5), 6)) >>> evens_count(woah_deep) 3

15 # Recursive def evens_count(t): if len(t) == 0: return 0 if t[0] % 2 == 0: return 1 + evens_count(t[1:]) return 0 + evens_count(t[1:]) E XAMPLE : O PERATING ON D EEP T UPLES How we would have solved this if we were handed a simple tuple of numbers? # Iterative def evens_count(t): total = 0 for num in t: if num % 2 == 0: total += 1 return total Now extend this to handle deep tuples!

16 # Recursive def evens_count(t): if len(t) == 0: return 0 if is_tuple(t[0]): return evens_count(t[0]) + evens_count(t[1:]) if t[0] % 2 == 0: return 1 + evens_count(t[1:]) return 0 + evens_count(t[1:]) E XAMPLE : O PERATING ON D EEP T UPLES First check if the first item in the sequence is also a tuple. If so, use tree recursion and count the evens in both the first item and the rest of t. def is_tuple(x): return type(x) is tuple

17 P RACTICE : O PERATING ON D EEP T UPLES Write the procedure deep_filter, which takes a predicate and a deep tuple and returns a new deep tuple with only the items for which predicate returns True. >>> woah_deep = ((1, 2), 3, ((4, 5), 6)) >>> deep_filter(lambda x: x % 2 == 0, woah_deep) ((2,), ((4,), 6)) >>> deep_filter(lambda x: x >= 2 and x <= 3, woah_deep) ((2,), 3, ((),))

18 P RACTICE : O PERATING ON D EEP T UPLES Write the procedure deep_filter, which takes a predicate and a deep tuple and returns a new deep tuple with only the items for which predicate returns True. def deep_filter(pred, dt): if len(dt) == 0: return dt if is_tuple(dt[0]): return (deep_filter(pred, dt[0]),) +\ deep_filter(pred, dt[1:]) if pred(dt[0]): return (dt[0],) + deep_filter(pred, dt[1:]) return deep_filter(pred, dt[1:])

19 B REAK

20 H IERARCHICAL D ATA : T REES Often, deep tuples aren’t quite expressive enough for our purposes. Sometimes we want values in the middle too! fib(4) fib(3) fib(2) fib(1) fib(0) fib(2) fib(1) fib(0) fib(1)

21 H IERARCHICAL D ATA : T REES A tree data structure traditionally has 2 parts: 1.A datum – The data stored in the top point of the tree. 2.Some children – Any trees that appear below this tree. “Datum”... “Children”...

22 H IERARCHICAL D ATA : T REES B B C C A A Nodes Branches A is a parent to B and C B and C are children of A

23 H IERARCHICAL D ATA : T REES fib(4) fib(3) fib(2) fib(1) fib(0) fib(2) fib(1) fib(0) fib(1) Root Leaves

24 IT REES >>> fir = make_tree(1, (make_tree(2), make_tree(3, (make_tree(4), make_tree(5))), make_tree(6, (make_tree(7),))))

25 IT REES >>> itree_datum(fir) 1 >>> for child in itree_children(fir): print(itree_datum(child))

26 IT REES def make_itree(datum, children=()): return (datum, children) def itree_datum(t): return t[0] def itree_children(t): return t[1] Constructor Selectors

27 E XAMPLE : O PERATING ON IT REES Suppose I want to write the function itree_prod, which takes an ITree of numbers and returns the product of all the numbers in the ITree. >>> t = make_itree(1, (make_itree(2), make_itree(3), make_itree(4))) >>> itree_prod(t) 24 Look! I got it right this time!

28 E XAMPLE : O PERATING ON IT REES Idea: split the problem into 2 different parts: handling a single tree and handling a group of trees (a forest). def itree_prod(t): return itree_datum(t) * forest_prod(itree_children(t)) def forest_prod(f): if len(f) == 0: return 1 return itree_prod(f[0]) * forest_prod(f[1:]) This is called mutual recursion because it involves two functions recursively calling each other!

29 P RACTICE : O PERATING ON IT REES Write the function max_path_sum, which takes an ITree of positive numbers and returns the largest sum you can get adding all the numbers along a path from the root to a leaf

30 P RACTICE : O PERATING ON IT REES Write the function max_path_sum, which takes an ITree of positive numbers and returns the largest sum you can get adding all the numbers along a path from the root to a leaf. def max_path_sum(t): ?????? def max_forest_sum(f): if len(f) == 0: return 0 ??????

31 P RACTICE : O PERATING ON IT REES Write the function max_path_sum, which takes an ITree of positive numbers and returns the largest sum you can get adding all the numbers along a path from the root to a leaf. def max_path_sum(t): max_child_sum = max_forest_sum(itree_children(t)) return itree_datum(t) + max_child_sum def max_forest_sum(f): if len(f) == 0: return 0 return max(max_path_sum(f[0]), max_forest_sum(f[1:]))

32 C ONCLUSION Organizing data into hierarchies is very useful and very common in Computer Science We can think of nested tuples as a simple form of a tree structure that only has leaves. ITrees are useful for representing general tree- structures. Preview: binary search trees!