Programming for Engineers in Python. Inheritance
|
|
- Eugenia Carter
- 5 years ago
- Views:
Transcription
1 Programming for Engineers in Python Inheritance 1
2 Plan Background and motivation Examples: TwoWheeler isinstance Binary tree Beverages 2
3 Inheritance Inheritance is commonly used to reflect is-a relationship between classes: B is a subtype of A. Class B inherits from class A Class A is said to be a base class Class B is said to be a derived class 3 Is a B A
4 Motivation Extract common attributes and methods to avoid code duplication and to better manage the code Class Car Number of wheels Current speed Color Engine Number of airbags and more Class Bus Number of wheels Current speed Color Engine Ride cost and more 4
5 Method Extract common attributes and methods to avoid code duplication and to better manage the code Implement convenient and suitable hierarchy: Is a Is a 5
6 Method 1. Determine a base/parent class 2. Extend it attributes and methods in child classes. Example: car, bus Common property: vehicle (has color, speed, engine, wheels ) Manage vehicle as a separate class 6 In OOD books: Child extends Parent
7 Method 1. Determine a base/parent class 2. Extend it attributes and methods in child classes. Is a Vehicle Car Bus Is a 7
8 Basic example 8 Class: Vehicle Number of wheels Speed Color Engine and more Example: Checking speed limit is done in one place -Vehicle class code. Class Car - has all Vehicle attributes - and additionally: Number of airbags and more Class Bus - has all Vehicle attributes - and additionally: Number of passengers and more
9 Example 1 - TwoWheeler class TwoWheeler: '''Vehicles that run on two wheels''' def init (self, d1, d2): # The wheel diameters, not necessarily equal self.diam1 = d1 self.diam2 = d2 def repr (self): # Default implementation return '('+str(self.diam1)+')('+str(self.diam2)+')' >>> t = TwoWheeler(30, 10) >>> print t (30)(10) 9
10 TwoWheeler Cont. class Bicycle(TwoWheeler): Is a Bicycle TwoWheeler def init (self, d1=0, d2=0, electric=false): self.diam1 TwoWheeler. init (self, = d1 d1, d2) self.diam2 = d2 self.electric = electric Same as parent >>> b = Bicycle(30, 10, False) >>> print b (30)(10) >>> print b.electrtic False Extend object s attributes 10
11 TwoWheeler Cont. class Bicycle(TwoWheeler): def init (self, d1=0, d2=0, electric=false): TwoWheeler. init (self, d1, d2) self.electric = electric def repr (self): if self.electric: prefix = 'Electric' else: prefix = 'Non-electric Invoke parent s constructor Extend parent s attributes prefix += ' bicycle ' str_parent_data = TwoWheeler. repr (self) return prefix + str_parent_data >>> b = Bicycle(30, 10, False) >>> print b Non-electric bicycle - (30)(10) Invoke parent s method 11
12 Manipulating inheritance class Bicycle(TwoWheeler): def init (self, d1, d2, electric = False): self.diam1 = d1 self.diam2 = d2 self.electric = electric >>> b = Bicycle(30, 10, False) >>> print b Traceback (most recent call last):... AttributeError: 'Bicycle' object has no attribute 'diam2' Question: Do we crash if we invoke parent s init in Bicycle s constructor? No, we don t. We don t influence attribute creation. 12
13 class Bicycle(TwoWheeler): pass def init (self, d1, d2, electric = False): self.diam1 = d1 self.diam2 = d2 self.electric = electric >>> b = Bicycle(30, 10, False) Traceback (most recent call last):... TypeError: init () takes at most 3 arguments (4 given) Why? 13 Python s flow: Does Bicycle class have init? - No. Go to parent class s init with 4 args: self, 30, 10, False
14 One parent class can be inherited several times TwoWheeler Bicycle Motorcycle Segway and so on 14
15 One class can inherit several parents. TwoWheeler Engine Motorcycle Not in syllabus 15
16 TwoWheeler Cont. class Motorcycle(TwoWheeler): def init (self, d1, d2, fuel_type): TwoWheeler. init (self, d1, d2) self.fuel_type = fuel_type self.curr_speed = 0 def repr (self): return 'Motorcycle - ' + TwoWheeler. repr (self) +\ '\nfuel: ' + self.fuel_type +\ \ncurrent speed: ' + str(self.curr_speed) 16 def get_speed(self): >>> m = Motorcycle(30, 10, 'Diesel') return >>> print self.curr_speed m Motorcycle - (30)(10) def set_speed(self, Fuel: Diesel new_speed): self.curr_speed Current speed: 0= new_speed Extend parent s methods
17 The class hierarchy - TwoWheeler Bicycle Motorcycle 17
18 isinstance & issubclass 18 >>> m = Motorcycle(20, 20, 'Diesel') >>> b = Bicycle(30, 10, False) >>> isinstance(m, Motorcycle) True >>> isinstance(m, TwoWheeler) True >>> isinstance(b, TwoWheeler) True >>> isinstance(b, Motorcycle) False >>> issubclass(motorcycle, TwoWheeler) True >>> issubclass(motorcycle, Bicycle) False >>> issubclass(twowheeler, Bicycle) False
19 Iterating through a list of objects b = Bicycle(30, 10, False) m = Motorcycle(20, 20, '95') list_of_objects = [b,m] for curr_object in list_of_objects: if isinstance(curr_object, TwoWheeler): print 'It is a TwoWheeler object' if isinstance(curr_object, Motorcycle): curr_object.set_speed(50) print curr_object We get two positive answers for m object 19 It is a TwoWheeler object Not-electric bicycle - (30, 10) It is a TwoWheeler object Fuel: 95, Current speed: 50, (20, 20)
20 Iterating through a list of objects >>> b = Bicycle(30, 10, False) >>> m = Motorcycle(20, 20, '95') >>> list_of_objects = [b,m] >>> \ for obj in list_of_objects: if issubclass(obj. class, TwoWheeler): print 'This is a TwoWheeler object' if isinstance(obj,bicycle): print 'Yes' if hasattr(obj, 'set_speed'): obj.set_speed(50) print obj 20 This is a TwoWheeler object Yes Non-electric bicycle - (30)(10) This is a TwoWheeler object Motorcycle - (20)(20) Fuel: 95 Current speed: 50
21 Binary tree example a Root b c d e f Every node has 0-2 children Leaf g 21 What is the depth? 4
22 Binary tree; v1 Cont. class BinTreeNode: def init (self, data, left = None, right = None): self.data = data self.left = left self.right = right def set_left(self, left): self.left = left def set_right(self, right): self.right = right 22
23 Binary tree; v1 Cont. >>> d = BinTreeNode('d') >>> e = BinTreeNode('e') >>> f = BinTreeNode('f') >>> g = BinTreeNode('g') >>> b = BinTreeNode('b') >>> c = BinTreeNode('c') >>> b.set_left(d) >>> c.set_left(e) >>> c.set_right(f) >>> f.set_right(g) >>> a = BinTreeNode('a', b, c) a b c d e f g 23
24 Computing depth; v1 class BinTreeNode: def get_depth(self): if not self.left and not self.right: # self is a leaf. Stop recursion. return 1 d_left = 0 d_right = 0 if self.left: d_left = self.left.get_depth() if self.right: d_right = self.right.get_depth() return 1 + max(d_left, d_right) 24
25 Computing depth; v1 Cont. 25 >>> d = BinTreeNode('d') >>> e = BinTreeNode('e') >>> f = BinTreeNode('f') >>> g = BinTreeNode('g') >>> b = BinTreeNode('b') >>> c = BinTreeNode('c') >>> b.set_left(d) >>> c.set_left(e) >>> c.set_right(f) >>> f.set_right(g) >>> a = BinTreeNode('a', b, c) >>> print a.get_depth() 4 a b c d e f g
26 Full binary tree. Revisited BinTreeNode Object with 1-2 children BinTreeLeaf Object without children 26
27 BinTreeLeaf class BinTreeLeaf(BinTreeNode): def init (self, data): BinTreeNode. init (self, data) def get_depth(self): # This is a leaf. No children to check return 1 27
28 Computing depth; v2 class BinTreeNode:... def get_depth(self): d_left = 0 d_right = 0 if self.left: d_left = self.left.get_depth() if self.right: d_right = self.right.get_depth() return 1 + max(d_left, d_right) 28
29 Computing depth; v2 Cont. >>> d = BinTreeLeaf('d') >>> e = BinTreeLeaf('e') >>> f = BinTreeLeaf('f') >>> b = BinTreeNode('b', left = d) >>> c = BinTreeNode('c', e, f) >>> a = BinTreeNode('a', b, c) >>> print a.get_depth() 3 b a c d e f 29
30 Binary tree; v2 Cont. >>> a = BinTreeLeaf('a') >>> b = BinTreeLeaf('b') >>> a.set_left(b) >>> We created a leaf WITH a child.. Bug! We shall guarantee data consistency, i.e., that a leaf doesn t have children and set_left, set_right methods can not be invoked! 30
31 BinTreeLeaf class BinTreeLeaf(BinTreeNode): def init (self, data): # Perform the initialization BinTreeNode. init (self, data) # Delete unnecessary attributes and methods delattr(self, 'left') delattr(self, 'right') self.set_left = None self.set_right = None... 31
32 Complete binary tree, Ver. 3. >>> a = BinTreeLeaf('a') >>> b = BinTreeLeaf('b') >>> print isinstance(a, BinTreeLeaf) True >>> print hasattr(a, 'left') False >>> a.set_left(b) Traceback (most recent call last):... a.set_left(b) TypeError: 'NoneType' object is not callable 32
33 Complete binary tree, Ver. 4. A more neat solution: Create a class with as much in common as possible, and then inherit from it, without deleting methods / attributes BinTreeObject Only data BinTreeNode Add right son Add left son BinTreeLeaf 33
34 Beverages Our goal is to create Beverages objects Requirements: Handle several kinds of beverages - soda drinks, dairy drinks, alcohol drinks. 34
35 Soda Dairy Beer name ml (volume) price calories Methods: repr raise_price add_water name ml (volume) price calories Organic / Not Methods: repr raise_price add_water add_cal name ml (volume) price calories alcohol Methods: repr raise_price add_water 35
36 Soda Dairy Beer name ml (volume) price calories name ml (volume) price calories Organic / Not name ml (volume) price calories alcohol These three classes have lots in common Methods: repr raise_price add_water Methods: repr raise_price add_water add_cal Methods: repr raise_price add_water We can (and should) avoid code duplication 36
37 Soda Dairy Beer name ml (volume) price calories name ml (volume) price calories Organic / Not name ml (volume) price calories alcohol But, there are also some differences Methods: repr raise_price add_water Methods: repr raise_price add_water add_cal Methods: repr raise_price add_water 37 Changes the calories per 100ml (dilute) Changes the alcohol percentage
38 >>> a = Beer('Tuineken',500,7,44,5.5) >>> a Tuineken 500ml >>> a 7$ Milk 44cal per 100ml 250ml 5.5% alcohol 2$ 39cal per 100ml Non-Organic >>> a =Dairy( Milk',250,2,39,False) Soda Dairy Beer repr >>> a =Soda('Cola',330,3.5,41) >>> a Cola 330ml 3.5$ 41cal per 100ml 38 name ml (volume) price calories name ml (volume) price calories Organic / Not name ml (volume) price calories alcohol
39 Let s define a general class, Beverage, with as much in common as possible And now, inherit! Beverage name ml (volume) price calories Methods: repr raise_price add_water Name, ml, price & calories Changes the calories per 100ml (dilute) 39 Soda Methods: Dairy isorganic Methods: update repr Add add_cal Beer alcohol Methods: update repr update add_water
40 class Beverage: def init (self, name, ml, price, cal): self.name = name self.ml = ml self.price = price self.cal = cal Beverage name ml (volume) price calories Methods: repr raise_price add_water def repr (self): res = self.name + '\n' + str(self.ml) + 'ml\n' + str(self.price) + '$\n' + str(self.cal) + 'cal per 100ml' return res def raise_price(self, dprice): self.price += dprice 40 def add_water(self, amount): new_ml = self.ml + amount self.cal *= self.ml/new_ml self.ml += amount #update calories per 100ml
41 Soda Methods: Beverage name ml (volume) price calories Methods: repr raise_price add_water class Soda(Beverage): pass 41
42 class Dairy(Beverage): isorganic Dairy Methods: update repr Add add_cal Beverage name ml (volume) price calories Methods: repr raise_price add_water def init (self, name, ml, price, cal, isorganic): Beverage. init (self, name, ml, price, cal) self.isorganic = 'Organic' if isorganic else 'Non-Organic def repr (self): res = Beverage. repr (self) res += '\n' + self.isorganic return res def add_cal(self,calories): self.cal += calories 42
43 class Beer(Beverage): alcohol Beer Methods: update repr update add_water Beverage name ml (volume) price calories Methods: repr raise_price add_water def init (self, name, ml, price, cal, alc): Beverage. init (self, name, ml, price, cal) self.alc = alc def repr (self): res = Beverage. repr (self) res += '\n' + str(self.alc) + '% alcohol' return res 43 def add_water(self,amount): new_ml = self.ml + amount self.cal *= self.ml/new_ml self.alc *= self.ml/new_ml self.ml += amount #update calories per 100ml #update alcohol level
Trees. Tree Structure Binary Tree Tree Traversals
Trees Tree Structure Binary Tree Tree Traversals The Tree Structure Consists of nodes and edges that organize data in a hierarchical fashion. nodes store the data elements. edges connect the nodes. The
More informationOutline. An Application: A Binary Search Tree. 1 Chapter 7: Trees. favicon. CSI33 Data Structures
Outline Chapter 7: Trees 1 Chapter 7: Trees Approaching BST Making a decision We discussed the trade-offs between linked and array-based implementations of sequences (back in Section 4.7). Linked lists
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College October 19, 2016 Outline Outline 1 Chapter 7: Trees Outline Chapter 7: Trees 1 Chapter 7: Trees Uses Of Trees Chapter 7: Trees
More informationBinary Search Tree. Revised based on textbook author s notes.
Binary Search Tree Revised based on textbook author s notes. Search Trees The tree structure can be used for searching. Each node contains a search key as part of its data or payload. Nodes are organized
More informationTREES AND ORDERS OF GROWTH 7
TREES AND ORDERS OF GROWTH 7 COMPUTER SCIENCE 61A October 17, 2013 1 Trees In computer science, trees are recursive data structures that are widely used in various settings. This is a diagram of a simple
More informationCSC148H Week 8. Sadia Sharmin. July 12, /29
CSC148H Week 8 Sadia Sharmin July 12, 2017 1/29 Motivating Trees I A data structure is a way of organizing data I Stacks, queues, and lists are all linear structures I They are linear in the sense that
More informationLast week. Last week. Last week. Today. Binary Trees. CSC148 Intro. to Computer Science. Lecture 8: Binary Trees, BST
CSC1 Intro. to Computer Science Lecture : Binary Trees, BST Last week Tracing recursive programs Amir H. Chinaei, Summer 01 Office Hours: R 10-1 BA ahchinaei@cs.toronto.edu http://www.cs.toronto.edu/~ahchinaei/
More informationSTREAMS, ITERATORS, AND BINARY TREES 10
STREAMS, ITERATORS, AND BINARY TREES 10 COMPUTER SCIENCE 61A April 10, 2017 1 Streams A stream is a lazily-evaluated linked list. A stream s elements (except for the first element) are only computed when
More informationClass definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes
Class definition F21SC Industrial Programming: Python Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2014/15 Class definition uses familiar
More informationF21SC Industrial Programming: Python: Classes and Exceptions
F21SC Industrial Programming: Python: Classes and Exceptions Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2017/18 0 No proprietary software
More informationDo not turn this page until you have received the signal to start. In the meantime, please read the instructions below carefully.
CSC A48 Winter 2014 CSCA48 Final Exam 23 April 2014 Duration: Aids Allowed: 150 minutes None Student Number: UTORid: Last (Family) Name(s): First (Given) Name(s): Do not turn this page until you have received
More informationCSC148 Week 6. Larry Zhang
CSC148 Week 6 Larry Zhang 1 Announcements Test 1 coverage: trees (topic of today and Wednesday) are not covered Assignment 1 slides posted on the course website. 2 Data Structures 3 Data Structures A data
More informationStacks, Queues and Hierarchical Collections
Programming III Stacks, Queues and Hierarchical Collections 2501ICT Nathan Contents Linked Data Structures Revisited Stacks Queues Trees Binary Trees Generic Trees Implementations 2 Copyright 2002- by
More informationIn addition to the correct answer, you MUST show all your work in order to receive full credit.
In addition to the correct answer, you MUST show all your work in order to receive full credit. Questions Mark: Question1) Multiple Choice Questions /10 Question 2) Binary Trees /15 Question 3) Linked
More informationn 1 i = n + i = n + f(n 1)
2 Binary Search Trees Lab Objective: A tree is a linked list where each node in the list may refer to more than one other node. This structural flexibility makes trees more useful and efficient than regular
More informationStacks, Queues and Hierarchical Collections. 2501ICT Logan
Stacks, Queues and Hierarchical Collections 2501ICT Logan Contents Linked Data Structures Revisited Stacks Queues Trees Binary Trees Generic Trees Implementations 2 Queues and Stacks Queues and Stacks
More information1 A node in a tree. Trees. Datatypes ISC
Datatypes ISC-5315 1 1 A node in a tree /*C*/ typedef struct _node { struct _node *left; struct _node *right; struct _node *parent; float value; node; # # Python example class Node: Node class: this is
More informationLecture 16: Binary Search Trees
Extended Introduction to Computer Science CS1001.py Lecture 16: Binary Search Trees Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants: Michal Kleinbort, Amir Gilad School of Computer Science
More informationObject Model Comparisons
Object Model Comparisons 1 Languages are designed, just like programs Someone decides what the language is for Someone decides what features it's going to have Can't really understand a language until
More informationpublic Twix() { calories = 285; ingredients = "chocolate, sugar, cookie, caramel"; }
Additional inheritance example As another example of inheritance, perhaps we would like to build an application about candy. For starters, let s say we want to do something with Twix bars and something
More informationBinary Trees
Binary Trees 4-7-2005 Opening Discussion What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment? What is a Tree? You are all familiar with what
More informationStructure and Interpretation of Computer Programs
CS 61A Structure and Interpretation of Computer Programs Fall 2011 Midterm Exam 2 INSTRUCTIONS You have 2 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,
More informationData Structures CSCI C343, Fall 2014
Data Structures CSCI C343, This exam has 10 questions, for a total of 100 points. 1. 8 points For each of the nodes 35, 52, 63, and, list the successor and predecessors of the node (if they exist). 52
More informationBinary Tree Application Expression Tree. Revised based on textbook author s notes.
Binary Tree Application Expression Tree Revised based on textbook author s notes. Expression Trees A binary tree in which the operators are stored in the interior nodes and the operands are sored in the
More informationTrees. Make Money Fast! Bank Robbery. Ponzi Scheme. Stock Fraud Goodrich, Tamassia, Goldwasser Trees
Part 4: Trees Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery 2013 Goodrich, Tamassia, Goldwasser Trees 2 Example: Family Tree 2013 Goodrich, Tamassia, Goldwasser Trees 3 Example: Unix File
More informationLecture #21: Search Trees, Sets. Last modified: Tue Mar 18 18:15: CS61A: Lecture #21 1
Lecture #21: Search Trees, Sets Last modified: Tue Mar 18 18:15:49 2014 CS61A: Lecture #21 1 General Tree Class (From Last Lecture) class Tree: """A Tree consists of a label and a sequence of 0 or more
More informationProgramming for Engineers in Python
Programming for Engineers in Python Lecture 5: Object Oriented Programming Autumn 2011-12 1 Lecture 4 Highlights Tuples, Dictionaries Sorting Lists Modular programming Data analysis: text categorization
More informationOBJECT ORIENTED PROGRAMMING 6
OBJECT ORIENTED PROGRAMMING 6 COMPUTER SCIENCE 61A October 8, 2012 1 Overview Last week you were introduced to the programming paradigm known as Object Oriented Programming. If you ve programmed in a language
More informationBinary search trees. We can define a node in a search tree using a Python class definition as follows: class SearchTree:
Binary search trees An important use of binary trees is to store values that we may want to look up later. For instance, a binary search tree could be used to store a dictionary of words. A binary search
More informationOverview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017
Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable
More informationPyTrie Documentation. Release 0.3. George Sakkis
PyTrie Documentation Release 0.3 George Sakkis Jun 05, 2017 Contents 1 Usage 3 2 Reference documentation 5 2.1 Classes.................................................. 5 2.2 Trie methods...............................................
More information1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19
1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object
More informationPython Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8
Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,
More informationObject-Oriented Python
Object-Oriented Python Everything is an object. Every object has a value. a type. an identity. a namespace. CS105 Python def initstudent(student, eid): global A class is like a namespace. CS105 Python
More informationFriend Functions, Inheritance
Friend Functions, Inheritance Friend Function Private data member of a class can not be accessed by an object of another class Similarly protected data member function of a class can not be accessed by
More informationSEQUENCES AND TREES 4
SEQUENCES AND TREES 4 COMPUTER SCIENCE 61A February 19, 2015 1 List Comprehension A list comprehension is a compact way to create a list whose elements are the results of applying a fixed expression to
More informationpygtrie Release Jul 03, 2017
pygtrie Release Jul 03, 2017 Contents 1 Features 3 2 Installation 5 3 Upgrading from 0.9.x 7 4 Trie classes 9 5 PrefixSet class 19 6 Version History 21 Python Module Index 23 i ii Implementation of a
More informationOBJECT ORIENTED PROGRAMMING 7
OBJECT ORIENTED PROGRAMMING 7 COMPUTER SCIENCE 61A July 10, 2012 1 Overview This week you were introduced to the programming paradigm known as Object Oriented Programming. If you ve programmed in a language
More informationDo not turn this page until you have received the signal to start.
CSCA48 Winter 2017 Term Test #2 Duration 80 minutes Aids allowed: none Last Name: Student Number: Markus Login: First Name: Question 0. [1 mark] Carefully read and follow all instructions on this page,
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College November 13, 2017 Outline Outline 1 C++ Supplement.1: Trees Outline C++ Supplement.1: Trees 1 C++ Supplement.1: Trees Uses
More informationOBJECT ORIENTED PROGRAMMING 7
OBJECT ORIENTED PROGRAMMING 7 COMPUTER SCIENCE 61A July 10, 2012 1 Overview This week you were introduced to the programming paradigm known as Object Oriented Programming. If you ve programmed in a language
More informationData Structures (list, dictionary, tuples, sets, strings)
Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access
More informationWhat We ll Be Seeing Today
1 INTRO2CS Tirgul 8 What We ll Be Seeing Today 2 Introduction to Object-Oriented Programming (OOP). Using Objects Special methods What is OOP? 3 So far our programs were made of different variables and
More informationObjects and Classes. Chapter 8
200 Chapter 8 Objects and Classes The style of programming we have seen so far is called procedural programming. This was the first programming paradigm, developed in the 1950 s and 1960 s alongside the
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Binary search tree (part I) Version of March 24, 2013 Abstract These lecture notes are meant
More informationScientific Programming. Trees
Scientific Programming Trees Alberto Montresor Università di Trento 2018/11/30 This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. Table of contents 1 Introduction
More informationAn AVL tree with N nodes is an excellent data. The Big-Oh analysis shows that most operations finish within O(log N) time
B + -TREES MOTIVATION An AVL tree with N nodes is an excellent data structure for searching, indexing, etc. The Big-Oh analysis shows that most operations finish within O(log N) time The theoretical conclusion
More informationTree Structures. A hierarchical data structure whose point of entry is the root node
Binary Trees 1 Tree Structures A tree is A hierarchical data structure whose point of entry is the root node This structure can be partitioned into disjoint subsets These subsets are themselves trees and
More informationTREES AND ORDERS OF GROWTH 7
TREES AND ORDERS OF GROWTH 7 COMPUTER SCIENCE 61A March 12, 2015 1 Trees in OOP 1.1 Our Implementation Previously, we have seen trees defined as an abstract data type using lists. Let s look at another
More informationShort Python function/method descriptions:
Last Name First Name Student#. Short Python function/method descriptions: builtins : len(x) -> integer Return the length of the list, tuple, dict, or string x. max(l) -> value Return the largest value
More informationStructure and Interpretation of Computer Programs
CS 61A Summer 2015 Structure and Interpretation of Computer Programs Final INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Binary search tree (part I) Version of March 24, 2013 Abstract These lecture notes are meant
More informationInheritance and Polymorphism
Inheritance and Polymorphism The concept of inheritance is a common feature of an object-oriented programming language. Inheritance allows a programmer to define a general class, and then later define
More informationCHAPTER 9 INHERITANCE. 9.1 Introduction
CHAPTER 9 INHERITANCE 9.1 Introduction Inheritance is the most powerful feature of an object oriented programming language. It is a process of creating new classes called derived classes, from the existing
More informationStructure and Interpretation of Computer Programs
CS 61A Fall 2016 Structure and Interpretation of Computer Programs Final INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except
More informationInheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L
Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive
More informationLecture 19: Subclasses & Inheritance (Chapter 18)
http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 19: Subclasses & Inheritance (Chapter 18) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner,
More informationCS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.
CS 61A, Fall, 2002, Midterm #2, L. Rowe 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams. a) d) 3 1 2 3 1 2 e) b) 3 c) 1 2 3 1 2 1 2 For each of the following Scheme
More informationCSI33 Data Structures
Department of Mathematics and Computer Science Bronx Community College Section 13.3: Outline 1 Section 13.3: Section 13.3: Improving The Worst-Case Performance for BSTs The Worst Case Scenario In the worst
More informationINHERITANCE AND EXTENDING CLASSES
INHERITANCE AND EXTENDING CLASSES Java programmers often take advantage of a feature of object-oriented programming called inheritance, which allows programmers to make one class an extension of another
More informationExtended Introduction to Computer Science CS1001.py
Extended Introduction to Computer Science CS1001.py Lecture 15: Data Structures; Linked Lists Binary trees Instructors: Benny Chor, Amir Rubinstein Teaching Assistants: Michal Kleinbort, Yael Baran School
More informationLecture 18. Classes and Types
Lecture 18 Classes and Types Announcements for Today Reading Today: See reading online Tuesday: See reading online Prelim, Nov 6 th 7:30-9:30 Material up to next class Review posted next week Recursion
More informationStructure and Interpretation of Computer Programs
CS 61A Fall 2012 Structure and Interpretation of Computer Programs Midterm 2 Solutions INSTRUCTIONS You have 2 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed
More informationLecture #14: OOP. Last modified: Mon Feb 27 15:56: CS61A: Lecture #14 1
Lecture #14: OOP Last modified: Mon Feb 27 15:56:12 2017 CS61A: Lecture #14 1 Some Useful Annotations: @staticmethod We saw annotations earlier, as examples of higher-order functions. For classes, Python
More informationChapter 20: Binary Trees
Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other
More informationdjango-crucrudile Documentation
django-crucrudile Documentation Release 0.9.1 Hugo Geoffroy (pstch) July 27, 2014 Contents 1 Installation 1 1.1 From Python package index....................................... 1 1.2 From source...............................................
More informationIntegers and variables
CHAPTER 1 Integers and variables The main concepts in this chapter are abstract syntax trees: Inside the compiler, we represent programs with a data-structure called an abstract syntax tree, which is abbreviated
More informationB-Trees. CS321 Spring 2014 Steve Cutchin
B-Trees CS321 Spring 2014 Steve Cutchin Topics for Today HW #2 Once Over B Trees Questions PA #3 Expression Trees Balance Factor AVL Heights Data Structure Animations Graphs 2 B-Tree Motivation When data
More informationCALCULATOR Calculator COMPUTER SCIENCE 61A. July 24, 2014
CALCULATOR 10 COMPUTER SCIENCE 61A July 24, 2014 Remember homework 6? Let s take a second look at the Calculator language, a subset of a language we ll be learning later called Scheme. In today s discussion,
More informationrpaths Documentation Release 0.13 Remi Rampin
rpaths Documentation Release 0.13 Remi Rampin Aug 02, 2018 Contents 1 Introduction 1 2 Classes 3 2.1 Abstract classes............................................. 3 2.2 Concrete class Path............................................
More informationProject 6 Due 11:59:59pm Thu, Dec 10, 2015
Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Updates None yet. Introduction In this project, you will add a static type checking system to the Rube programming language. Recall the formal syntax for Rube
More informationBefore we start looking at how we build abstract data types in Python, let's define some import terms and look at some real-world examples.
Exception Handling Python Built-in Exceptions Abstract Data Types You can use a Python tuple to combine two simple values into a compound value. In this case, we use a 2-element tuple whose first element
More informationLecture 21. Programming with Subclasses
Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 9 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops
More information/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17
01.433/33 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/2/1.1 Introduction In this lecture we ll talk about a useful abstraction, priority queues, which are
More informationIntegers and variables
CHAPTER 1 Integers and variables The main concepts in this chapter are abstract syntax trees: Inside the compiler we represent programs with a data-structure called an abstract syntax tree (AST). recursive
More informationIN101: Algorithmic techniques Vladimir-Alexandru Paun ENSTA ParisTech
IN101: Algorithmic techniques Vladimir-Alexandru Paun ENSTA ParisTech License CC BY-NC-SA 2.0 http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ Outline Previously on IN101 Python s anatomy Functions,
More information! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge
Trees & Heaps Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Fall 2018 Jill Seaman!1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every
More informationLecture 21. Programming with Subclasses
Lecture 21 Programming with Subclasses Announcements for This Lecture Assignments Prelim 2 A4 is now graded Mean: 90.4 Median: 93 Std Dev: 10.6 Mean: 9 hrs Median: 8 hrs Std Dev: 4.1 hrs A5 is also graded
More informationrpaths Documentation Release 0.2 Remi Rampin
rpaths Documentation Release 0.2 Remi Rampin June 09, 2014 Contents 1 Introduction 1 2 Classes 3 2.1 Abstract classes............................................. 3 2.2 Concrete class Path............................................
More informationMotivation Computer Information Systems Storage Retrieval Updates. Binary Search Trees. OrderedStructures. Binary Search Tree
Binary Search Trees CMPUT 115 - Lecture Department of Computing Science University of Alberta Revised 21-Mar-05 In this lecture we study an important data structure: Binary Search Tree (BST) Motivation
More informationSearch. The Nearest Neighbor Problem
3 Nearest Neighbor Search Lab Objective: The nearest neighbor problem is an optimization problem that arises in applications such as computer vision, pattern recognition, internet marketing, and data compression.
More informationChapter 10 INHERITANCE 11/7/16 1
Chapter 10 INHERITANCE 11/7/16 1 Chapter Goals To learn about inheritance To implement subclasses that inherit and override superclass methods To understand the concept of polymorphism In this chapter,
More informationStructure and Interpretation of Computer Programs
CS 6A Fall 206 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,
More informationLecture 21. Programming with Subclasses
Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 10 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops
More informationCIS192 Python Programming
CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1
More informationCS 11 python track: lecture 3. n Today: Useful coding idioms
CS 11 python track: lecture 3 Today: Useful coding idioms Useful coding idioms "Idiom" Standard ways of accomplishing a common task Using standard idioms won't make your code more correct, but more concise
More information1. Which of the following circuits can be used to store one bit of data? A) Encoder B) OR gate C) Flip Flop D) Decoder
MCA Lateral 1. Which of the following circuits can be used to store one bit of data? A) Encoder B) OR gate C) Flip Flop D) Decoder 2. What would be the output of the following C program? main ( ){ int
More informationCSC/MAT-220: Lab 6. Due: 11/26/2018
CSC/MAT-220: Lab 6 Due: 11/26/2018 In Lab 2 we discussed value and type bindings. Recall, value bindings bind a value to a variable and are intended to be static for the life of a program. Type bindings
More informationCS102 Binary Search Trees
CS102 Binary Search Trees Prof Tejada 1 To speed up insertion, removal and search, modify the idea of a Binary Tree to create a Binary Search Tree (BST) Binary Search Trees Binary Search Trees have one
More informationFriday, 11 April 14. Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014
Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014 Intermission Rant about the history of this talk and why this topic matters. Python decorator syntax @function_wrapper def
More informationMarch 20/2003 Jayakanth Srinivasan,
Definition : A simple graph G = (V, E) consists of V, a nonempty set of vertices, and E, a set of unordered pairs of distinct elements of V called edges. Definition : In a multigraph G = (V, E) two or
More informationvoid insert( Type const & ) void push_front( Type const & )
6.1 Binary Search Trees A binary search tree is a data structure that can be used for storing sorted data. We will begin by discussing an Abstract Sorted List or Sorted List ADT and then proceed to describe
More informationCSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false.
Name: Class: Date: CSCI-401 Examlet #5 True/False Indicate whether the sentence or statement is true or false. 1. The root node of the standard binary tree can be drawn anywhere in the tree diagram. 2.
More informationAbstract Data Types Chapter 1
Abstract Data Types Chapter 1 Part Two Bags A bag is a basic container like a shopping bag that can be used to store collections. There are several variations: simple bag grab bag counting bag 2 Bag ADT
More informationA programming language requires two major definitions A simple one pass compiler
A programming language requires two major definitions A simple one pass compiler [Syntax: what the language looks like A context-free grammar written in BNF (Backus-Naur Form) usually suffices. [Semantics:
More informationStructure and Interpretation of Computer Programs
CS 61A Fall 2012 Structure and Interpretation of Computer Programs Alternate Midterm 2 Solutions INSTRUCTIONS You have 2 hours to complete the exam. The exam is closed book, closed notes, closed computer,
More informationLecture 20. Subclasses & Inheritance
Lecture 20 Subclasses & Inheritance Announcements for Today Reading Today: Chapter 18 Online reading for Thursday Prelim, Nov 9 th 7:30-9:00 Material up to Thursday Review posted on Thursday Recursion
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2016 Outline Outline 1 Chapter 7: Trees Outline Chapter 7: Trees 1 Chapter 7: Trees The Binary Search Property
More informationStructure and Interpretation of Computer Programs
CS 61A Summer 015 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,
More informationFigure 1: A complete binary tree.
The Binary Heap A binary heap is a data structure that implements the abstract data type priority queue. That is, a binary heap stores a set of elements with a total order (that means that every two elements
More information