The document discusses object-oriented programming in Python. It defines key OOP concepts like classes, objects, and methods. It provides examples of defining classes and methods in Python. It also covers inheritance, polymorphism, and data abstraction in OOP. Database programming in Python is also discussed, including connecting to databases and performing CRUD operations using the Python DB API.
Inheritance and Polymorphism in Python. Inheritance is a mechanism which allows us to create a new class – known as child class – that is based upon an existing class – the parent class, by adding new attributes and methods on top of the existing class.
A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class.
An object is created using the constructor of the class. This object will then be called the instance of the class.
در این جلسه به بررسی بحث برنامه نویسی شی گرا و کلاس ها در پایتون پرداختیم
PySec101 Fall 2013 J7E1 By Mohammad Reza Kamalifard
Talk About:
Object oriented programming and Classes in Python
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Subclasses of an abstract class in Python are not required to implement abstract methods of the parent class.
Inheritance and Polymorphism in Python. Inheritance is a mechanism which allows us to create a new class – known as child class – that is based upon an existing class – the parent class, by adding new attributes and methods on top of the existing class.
A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class.
An object is created using the constructor of the class. This object will then be called the instance of the class.
در این جلسه به بررسی بحث برنامه نویسی شی گرا و کلاس ها در پایتون پرداختیم
PySec101 Fall 2013 J7E1 By Mohammad Reza Kamalifard
Talk About:
Object oriented programming and Classes in Python
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Subclasses of an abstract class in Python are not required to implement abstract methods of the parent class.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Arrays in Java” will talk about one of the pillars of Java fundamentals i.e Arrays. It will also take you through the various types of arrays in Java and how they are used to achieve various functionalities. Through this tutorial, you will learn the following topics:
1. Arrays in Java
2. Types of Arrays
3. Working with Arrays
4. Sorting in Arrays
5. Searching in Arrays
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
A high level introduction to R statistical programming language that was presented at the Chicago Data Visualization Group's Graphing in R and ggplot2 workshop on October 8, 2012.
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
Admit it: You have used a String to model email values, even though most strings aren’t valid emails (don’t worry, we all have!). Imprecise data models are easy, but they crash applications and corrupt external systems. On the other hand, precise data models take time and generate boilerplate.
So-called newtype libraries have stepped up to the challenge, making it easier to model data precisely using runtime validation. However, newtype libraries aren’t able to validate constants at compile-time, and they don’t generally work with Scala 3.
Enter ZIO Prelude Smart Types, which make it simple to model data types precisely, without any boilerplate, runtime overhead, or compile-time overhead. ZIO Prelude Smart Types work at compile-time and runtime, and they have a uniform API across Scala 2 & 3.
Join ZIO Prelude contributor Jorge Vásquez as he teaches you how to be smart, and constrain your types to free your brain!
Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer.
My talk at Bangalore Java Users Group. It was meant developers who want to get them started on Scala. This talk objectives was to get started on creating a project in Scala, write some code using collections and test it using ScalaTest.
Exploring type level programming in ScalaJorge Vásquez
In this introduction to type-level programming in Scala, we are going to discuss how we can leverage the full power of the type system to verify domain properties of an application at compile-time, instead of doing runtime verifications at the value-level
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Arrays in Java” will talk about one of the pillars of Java fundamentals i.e Arrays. It will also take you through the various types of arrays in Java and how they are used to achieve various functionalities. Through this tutorial, you will learn the following topics:
1. Arrays in Java
2. Types of Arrays
3. Working with Arrays
4. Sorting in Arrays
5. Searching in Arrays
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
A high level introduction to R statistical programming language that was presented at the Chicago Data Visualization Group's Graphing in R and ggplot2 workshop on October 8, 2012.
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
Admit it: You have used a String to model email values, even though most strings aren’t valid emails (don’t worry, we all have!). Imprecise data models are easy, but they crash applications and corrupt external systems. On the other hand, precise data models take time and generate boilerplate.
So-called newtype libraries have stepped up to the challenge, making it easier to model data precisely using runtime validation. However, newtype libraries aren’t able to validate constants at compile-time, and they don’t generally work with Scala 3.
Enter ZIO Prelude Smart Types, which make it simple to model data types precisely, without any boilerplate, runtime overhead, or compile-time overhead. ZIO Prelude Smart Types work at compile-time and runtime, and they have a uniform API across Scala 2 & 3.
Join ZIO Prelude contributor Jorge Vásquez as he teaches you how to be smart, and constrain your types to free your brain!
Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer.
My talk at Bangalore Java Users Group. It was meant developers who want to get them started on Scala. This talk objectives was to get started on creating a project in Scala, write some code using collections and test it using ScalaTest.
Exploring type level programming in ScalaJorge Vásquez
In this introduction to type-level programming in Scala, we are going to discuss how we can leverage the full power of the type system to verify domain properties of an application at compile-time, instead of doing runtime verifications at the value-level
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
2. UNIT – VI Contents
Object-Orientation
Data in Python, Data Structures in Python, Defining
Classes
The Python Database Interface.
Database Interfaces, The Underlying Interface Model,
Some Database Modules, A Simple Database-Driven Web,
SQL/Python Communication.
3. Unit VI outcomes
From the VI unit Student can
Implement user defined type class.
Design oops concepts like inheritance.
Understand, learn Python interface with databases.
Connect with database and can write solution as a python
program and executes.
4. Object Oriented Programming in Python
Class: A user-defined prototype for an object that defines
a set of attributes that characterize any object of the class.
The attributes are data members (class variables and
instance variables) and methods, accessed via dot
notation.
Object: Instance of a class. An object comprises both data
members (class variables and instance variables) and
methods.
5. OOP in Python: Defining a class
A class is a special data type which defines how to build a
certain kind of object.
The class also stores some data items that are shared by all the
instances of this class
Instances are objects that are created which follow the
definition given inside of the class
Python doesn’t use separate class interface definitions as in
some languages
You just define the class and then use it
6. Defining Methods
Define a method in a class by including function definitions within the
scope of the class block
There must be a special first argument self in all method definitions which
gets bound to the calling instance
There is usually a special method called __init__ in most classes
There is no “new” keyword in python
Use the class name with ( ) notation and assign the result to a
variable
__init__ serves as a constructor for the class. Usually does some
initialization work
The arguments passed to the class name are given to its __init__()
method
So, the __init__ method for employee is passed “Bob” and 15000
and the new class instance is bound to b:
b=Employee(“Bob”,15000)
7. Simple class example
class shareddata(object):
a=44
x=shareddata()
y=shareddata()
z=shareddata()
print(x.a)
print(y.a)
print(z.a)
# Creates three instances
# Inherit and share a
8. Creating classes
class ClassName:
class variables
methods # methods are functions inside a class
Example:
class Employee:
empCount = 0
def __init__(self, name, salary): #__init__ runs when a new instance object
is created. #self is an instance
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print(“count”, self.empCount)
def displayDetails(self):
print( "Name : ", self.name, ", Salary: ", self.salary )
9. Constructor: __init__
An __init__ method can take any number of
arguments.
Like other functions or methods, the arguments can be
defined with default values, making them optional to
the caller.
However, the first argument self in the definition of
__init__ is special…
10. Program to update the employee salary.
class Person:
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
def lastName(self): # Behavior methods
return self.name.split()[-1] # self is implied subject
def giveRaise(self, percent):
self.pay = int(self.pay * (1 + percent)) # Must change here only
if __name__ == '__main__':
bob = Person(' Smith')
sue = Person(' Jones', job='dev', pay=10000)
print(bob.name, bob.pay)
print(sue.name, sue.pay)
print(bob.lastName(), sue.lastName()) # Use the new methods
sue.giveRaise(.10) # instead of hardcoding
print(sue.pay)
12. Subclasses
A class can extend the definition of another class
Allows use (or extension ) of methods and attributes
already defined in the previous one.
To define a subclass, put the name of the superclass in
parentheses after the subclass’s name on the first line
of the definition.
Class ECM_student(student):
Python has no ‘extends’ keyword like Java.
Multiple inheritance is supported.
13. Redefining Methods
To redefine a method of the parent class, include a
new definition using the same name in the subclass.
The old code won’t get executed.
To execute the method in the parent class in addition
to new code for some method, explicitly call the
parent’s version of the method.
parentClass.methodName(self, a, b, c)
The only time you ever explicitly pass ‘self’ as an
argument is when calling a method of an
ancestor.
14. Definition of a class extending student
Class Student: #“A class representing a student.”
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
Class ECM_student (student): #class extending student.”
def __init__(self,n,a,s):
student.__init__(self,n,a) #Call __init__ for student
self.section_num = s
def get_age(): #Redefines get_age method entirely
print “Age: ” + str(self.age)
15. Database Programming
The Python standard for database interfaces is the Python DB-
API.
Python Database API supports a wide range of database servers
such as:
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
GadFly
mSQL
16. Working with Databases through Python
Download a separate DB API module for each database
you need to access.
For example, to access an Oracle database as well as a
MySQL database, download both the Oracle and the
MySQL database modules.
17. Database connectivity and display version
import MySQLdb # Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print "Database version : %s " % data
# disconnect from server
db.close()
18. Creating a Table Using python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
empid Number(20) NOT NULL,
NAME CHAR(20),
Job char(10),
Sal number(10))
cursor.execute(sql)
db.close
19. READ Operation
READ Operation on any database means to fetch some useful
information from the database.
Once database connection is established, then we can send a query
into this database.
use either fetchone() method to fetch single record.
fetchall() method to fetch multiple values from a database table.
fetchone(): It fetches the next row of a query result set.
A result set is an object that is returned when a cursor object is
used to query a table.
fetchall(): It fetches all the rows in a result set. If some rows have
already been extracted from the result set, then it retrieves the
remaining rows from the result set.
rowcount: This is a read-only attribute and returns the number of
rows that were affected by an execute() method.
20. Program to display all the records from EMPLOYEE
table having salary more than 1000:
import MySQLdb
db =
MySQLdb.connect("localhost","testuser","test123","TEST
DB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM EMPLOYEE
WHERE INCOME > '%d'" % (1000)
try:
cursor.execute(sql)
21. results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" %
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
db.close()
23. Lists
An ordered group of items
Does not need to be the same type
Could put numbers, strings or donkeys in the same list
List notation
A = [1,”This is a list”, c, Donkey(“kong”)]
24. Methods of Lists
List.append(x)
adds an item to the end of the list
List.extend(L)
Extend the list by appending all in the given list L
List.insert(I,x)
Inserts an item at index I
List.remove(x)
Removes the first item from the list whose value is x
25. Examples of other methods
a = [66.25, 333, 333, 1, 1234.5] //Defines List
print a.count(333), a.count(66.25), a.count('x') //calls
method
2 1 0 //output
a.index(333)
//Returns the first index where the given value appears
1 //ouput
a.reverse() //Reverses order of list
a //Prints list a
[333, 1234.5, 1, 333, -1, 66.25] //Ouput
a.sort()
a //Prints list a
[-1, 1, 66.25, 333, 333, 1234.5] //Output
26. Using Lists as Stacks
The last element added is the first element retrieved
To add an item to the stack,
append() must be used
stack = [3, 4, 5]
stack.append(6)
Stack is now [3, 4, 5, 6]
To retrieve an item from the top of the stack, pop must be used
Stack.pop()
6 is output
Stack is now [3, 4, 5] again
27. Using Lists as Queues
First element added is the first element retrieved
To do this collections.deque
must be implemented
28. List Programming Tools
Filter(function, sequence)
Returns a sequence consisting of the items from the sequence
for which function(item) is true
Computes primes up to 25
29. Map Function
Map(function, sequence)
Calls function(item) for each of the sequence’s
items
Computes the cube for the range of 1 to 11
30. Reduce Function
Reduce(function, sequence)
Returns a single value constructed by calling the binary
function (function)
Computes the sum of the numbers 1 to 10
32. Tuples
Tuple
A number of values separated by commas
Immutable
Cannot assign values to individual items of a tuple
However tuples can contain mutable objects such as lists
Single items must be defined using a comma
Singleton = ‘hello’,
33. Sets
An unordered collection with no duplicate elements
Basket = [‘apple’, ‘orange’, ‘apple’, ‘pear’]
Fruit = set(basket)
Fruit
Set([‘orange’, ‘apple’, ‘pear’])
34. Dictionaries
Indexed by keys
This can be any immutable type (strings, numbers…)
Tuples can be used if they contain only immutable objects
38. Comparisons
Operators “in” and “not in” can be used to see if an item
exists in a sequence
Comparisons can be chained
a < b == c
This tests whether a is less than b and that b equals c
40. Fundamentals of Python: From First Programs Through Data Structures 40
Tree Terminology (continued)
41. Fundamentals of Python: From First Programs Through Data Structures 41
Note: The height of a tree containing one node is 0
By convention, the height of an empty tree is –1
Tree Terminology (continued)
42. Fundamentals of Python: From First Programs Through Data Structures 42
General Trees and Binary Trees
In a binary tree, each node has at most two children:
The left child and the right child
43. Fundamentals of Python: From First Programs Through Data Structures 43
Recursive Definitions of Trees
A general tree is either empty or consists of a finite set of
nodes T
Node r is called the root
The set T – {r} is partitioned into disjoint subsets, each of
which is a general tree
A binary tree is either empty or consists of a root plus a left
subtree and a right subtree, each of which are binary trees
44. Fundamentals of Python: From First Programs Through Data Structures 44
Why Use a Tree?
A parse tree describes the syntactic structure of a
particular sentence in terms of its component parts
45. Fundamentals of Python: From First Programs Through Data Structures 45
Why Use a Tree? (continued)
File system structures are also tree-like
46. Fundamentals of Python: From First Programs Through Data Structures 46
Why Use a Tree? (continued)
Sorted collections can also be represented as tree-like
structures
Called a binary search tree, or BST for short
Can support logarithmic searches and insertions
47. Fundamentals of Python: From First Programs Through Data Structures 47
The Shape of Binary Trees
The shape of a binary tree can be described more
formally by specifying the relationship between its height
and the number of nodes contained in it
N nodes
Height: N – 1
A full binary tree contains
the maximum number of
nodes for a given
height H
48. Fundamentals of Python: From First Programs Through Data Structures 48
The Shape of Binary Trees (continued)
The number of nodes, N, contained in a full binary tree
of height H is 2H
+ 1 – 1
The height, H, of a full binary tree with N nodes is log2(N
+ 1) – 1
The maximum amount of work that it takes to access a
given node in a full binary tree is O(log N)
49. Fundamentals of Python: From First Programs Through Data Structures 49
The Shape of Binary Trees (continued)
50. Fundamentals of Python: From First Programs Through Data Structures 50
Three Common Applications of Binary
Trees
In this section, we introduce three special uses of binary
trees that impose an ordering on their data:
Heaps
Binary search trees
Expression trees
51. Fundamentals of Python: From First Programs Through Data Structures 51
A Binary Tree ADT
Provides many common operations required for building
more specialized types of trees
Should support basic operations for creating trees,
determining if a tree is empty, and traversing a tree
Remaining operations focus on accessing, replacing, or
removing the component parts of a nonempty binary tree
—its root, left subtree, and right subtree
52. Fundamentals of Python: From First Programs Through Data Structures 52
The Interface for a Binary Tree ADT
53. Fundamentals of Python: From First Programs Through Data Structures 53
The Interface for a Binary Tree ADT
(continued)
54. Fundamentals of Python: From First Programs Through Data Structures 54
Processing a Binary Tree
Many algorithms for processing binary trees follow the
trees’ recursive structure
Programmers are occasionally interested in the frontier,
or set of leaf nodes, of a tree
Example: Frontier of parse tree for English sentence shown
earlier contains the words in the sentence
55. Fundamentals of Python: From First Programs Through Data Structures 55
Processing a Binary Tree (continued)
frontier expects a binary tree and returns a list
Two base cases:
Tree is empty return an empty list
Tree is a leaf node return a list containing root item
56. Fundamentals of Python: From First Programs Through Data Structures 56
Implementing a Binary Tree
57. Fundamentals of Python: From First Programs Through Data Structures 57
Implementing a Binary Tree (continued)
58. Fundamentals of Python: From First Programs Through Data Structures 58
Implementing a Binary Tree (continued)
59. Fundamentals of Python: From First Programs Through Data Structures 59
The String Representation of a Tree
__str__ can be implemented with any of the traversals
60. Fundamentals of Python: From First Programs Through Data Structures 60
Developing a Binary Search Tree
A BST imposes a special ordering on the nodes in a
binary tree, so as to support logarithmic searches and
insertions
In this section, we use the binary tree ADT to develop a
binary search tree, and assess its performance
61. Fundamentals of Python: From First Programs Through Data Structures 61
The Binary Search Tree Interface
The interface for a BST should include a constructor and
basic methods to test a tree for emptiness, determine the
number of items, add an item, remove an item, and search
for an item
Another useful method is __iter__, which allows users to
traverse the items in BST with a for loop
62. Fundamentals of Python: From First Programs Through Data Structures 62
Data Structures for the Implementation
of BST
…
63. Fundamentals of Python: From First Programs Through Data Structures 63
Searching a Binary Search Tree
find returns the first matching item if the target item is in
the tree; otherwise, it returns None
We can use a recursive strategy
64. Fundamentals of Python: From First Programs Through Data Structures 64
Inserting an Item into a Binary Search
Tree
add inserts an item in its proper place in the BST
Item’s proper place will be in one of three positions:
The root node, if the tree is already empty
A node in the current node’s left subtree, if new item is less
than item in current node
A node in the current node’s right subtree, if new item is
greater than or equal to item in current node
For options 2 and 3, add uses a recursive helper function
named addHelper
In all cases, an item is added as a leaf node
65. Fundamentals of Python: From First Programs Through Data Structures 65
Removing an Item from a Binary Search
Tree
Save a reference to root node
Locate node to be removed, its parent, and its parent’s
reference to this node
If item is not in tree, return None
Otherwise, if node has a left and right child, replace
node’s value with largest value in left subtree and delete
that value’s node from left subtree
Otherwise, set parent’s reference to node to node’s only child
Reset root node to saved reference
Decrement size and return item
66. Fundamentals of Python: From First Programs Through Data Structures 66
Removing an Item from a Binary Search
Tree (continued)
Fourth step is fairly complex: Can be factored out into a
helper function, which takes node to be deleted as a
parameter (node containing item to be removed is referred
to as the top node):
Search top node’s left subtree for node containing the largest
item (rightmost node of the subtree)
Replace top node’s value with the item
If top node’s left child contained the largest item, set top node’s
left child to its left child’s left child
Otherwise, set parent node’s right child to that right child’s left
child
67. Fundamentals of Python: From First Programs Through Data Structures 67
Complexity Analysis of Binary Search
Trees
BSTs are set up with intent of replicating O(log n)
behavior for the binary search of a sorted list
A BST can also provide fast insertions
Optimal behavior depends on height of tree
A perfectly balanced tree supports logarithmic searches
Worst case (items are inserted in sorted order): tree’s height is
linear, as is its search behavior
Insertions in random order result in a tree with close-to-
optimal search behavior
68. Fundamentals of Python: From First Programs Through Data Structures 68
Case Study: Parsing and Expression
Trees
Request:
Write a program that uses an expression tree to evaluate
expressions or convert them to alternative forms
Analysis:
Like the parser developed in Chapter 17, current program
parses an input expression and prints syntax error messages if
errors occur
If expression is syntactically correct, program prints its value
and its prefix, infix, and postfix representations
69. Fundamentals of Python: From First Programs Through Data Structures 69
Case Study: Parsing and Expression Trees
(continued)
70. Fundamentals of Python: From First Programs Through Data Structures 70
Case Study: Parsing and Expression Trees
(continued)
Design and Implementation of the Node Classes:
71. Fundamentals of Python: From First Programs Through Data Structures 71
Case Study: Parsing and Expression Trees
(continued)
72. Fundamentals of Python: From First Programs Through Data Structures 72
Case Study: Parsing and Expression Trees
(continued)
73. Fundamentals of Python: From First Programs Through Data Structures 73
Case Study: Parsing and Expression Trees
(continued)
Design and Implementation of the Parser Class:
Easiest to build an expression tree with a parser that uses a
recursive descent strategy
parse should now return an expression tree to its caller,
which uses that tree to obtain information about the
expression
factor processes either a number or an expression nested in
parentheses
Calls expression to parse nested expressions
74. Fundamentals of Python: From First Programs Through Data Structures 74
Case Study: Parsing and Expression Trees
(continued)
75. Fundamentals of Python: From First Programs Through Data Structures 75
Case Study: Parsing and Expression Trees
(continued)
76. Fundamentals of Python: From First Programs Through Data Structures 76
An Array Implementation of Binary
Trees
An array-based implementation of a binary tree is difficult
to define and practical only in some cases
For complete binary trees, there is an elegant and
efficient array-based representation
Elements are stored by level
The array representation of a binary tree is pretty rare
and is used mainly to implement a heap
77. Fundamentals of Python: From First Programs Through Data Structures 77
An Array Implementation of Binary Trees
(continued)
78. Fundamentals of Python: From First Programs Through Data Structures 78
An Array Implementation of Binary Trees
(continued)
79. Fundamentals of Python: From First Programs Through Data Structures 79
An Array Implementation of Binary Trees
(continued)
81. Fundamentals of Python: From First Programs Through Data Structures 81
Implementing Heaps (continued)
At most, log2n comparisons must be made to walk up the
tree from the bottom, so add is O(log n)
Method may trigger a doubling in the array size
O(n), but amortized over all additions, it is O(1)
82. Fundamentals of Python: From First Programs Through Data Structures 82
Using a Heap to Implement a Priority
Queue
we can use a heap