SlideShare a Scribd company logo
1 of 21
Classes - Object-Oriented Programming
• Allow to implement abstract data type to provide logical
description of
• What a data object looks like (its state)
• What it can do (its methods)
• To build a class for this, one can take advantage of the
abstraction process while providing necessary details to use
the abstraction in a program
1
Class Definition
• class class_name:
def __init__(self, para_name_1, para_name_2, ...)
statement body
def other_method_name(self, other_para_1, ...)
statement body
• Constructor method is always __init__ function
• self is always 1st parameter, used to refer back to the object itself
• E.g., self.var_name can be used to refer to the object’s internally defined
variable var_name (as part of the object’s state) 2
Fraction Class as an Example
• Recall that a fraction such as
3
5
consists of two parts
• Top value, i.e., numerator, can be any integer
• Bottom value, i.e., denominator, can be any positive integer
• Negative fractions have a negative numerator
• Operations/methods for Fraction type allow a Fraction data
object to behave like any other numeric value
• Such as add, subtract, multiply and divide
• Fraction should be displayed in “slash” form (e.g., 3/5)
• All methods should return results in lowest terms (i.e., most
common forms, e.g., 3/5 rather than 6/10)
3
Implementation of Fraction Class
• Class definition and its constructor
class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
• Fraction state data, i.e., numerator and denominator are denoted
by internal data objects self.num and self.den, respectively
• __init__ initializes the internal state by assigning values of the top
and bottom parameters to self.num and self.den, respectively
4
Create Instance of Fraction Class
• To create a Fraction instance, we use the name of the class,
which invokes constructor and passes actual values for the
necessary state
• Note that we never directly invoke __init__
• Note that 1st parameter self is never given
actual parameter value upon invocation
• E.g., my_fraction = Fraction(3, 5)
invokes constructor and creates a
Fraction instance
3
5
as show on the right
5
Display Fraction
• print function requires object convert itself into string so as
to be written to output
• To tell Fraction class how to convert itself into string, we
need to override standard method __str__, i.e., to redefine
its behavior:
def __str__(self):
return str(self.num) + “/” + str(self.den)
• Examples on when this function is invoked
print(my_fraction)
my_fraction.__str__()
str(my_fraction)
6
“Add” Operation for Fraction
• Allow two Fraction objects to be added together using “+”
• For this, we need to override __add__ standard method
• So that f1 + f2 will call f1.__add__(f2), the overridden method
• Recall two fractions must have same denominator to be added
• Easiest solution is to multiply two denominators as common
denominator, i.e., for two fractions
𝑎
𝑏
and
𝑐
𝑑
, we add them as
𝑎
𝑏
+
𝑐
𝑑
=
𝑎𝑑
𝑏𝑑
+
𝑏𝑐
𝑏𝑑
=
𝑎𝑑+𝑏𝑐
𝑏𝑑
7
“Add” Operation for Fraction (cont.)
• “Add” operation implementation:
def __add__ (self, other_fractioin):
new_num = self.num * other_fraction.den +
self.den * other_fraction.num
new_den = self.den * other_fraction.den
return Fraction(new_num, new_den)
• Considering print(Fraction(1, 4)+Fraction(1, 2)), what is the result?
• 6/8 will be returned but 3/4 is supposed to be the best answer
8
Make Result in Lowest Term
• For this, we need a helper function to reduce fraction
• We use this function to calculate the greatest common divisor
(GCD) between numerator and denominator
• We can then divide both numerator and denominator by the GCD
to reduce the result to lowest term
• Best-known algorithm to find GCD is Euclid’s algorithm
• The GCD between m and n is n if n divides m evenly, otherwise it is the
GCD between n and m%n
• This algorithm only works for positive integer n, which is our case
(negative fraction is represented by negative numerator)
9
Make Result in Lowest Term (cont.)
• Implementation of Euclid’s algorithm:
def gcd(m, n):
while m % n != 0:
old_m = m
old_n = n
m = old_n
n = old_m % old_n
return n
10
Updated “Add” Operation Implementation
• We update __add__ to use gcd function to reduce result:
def __add__ (self, other_fractioin):
new_num = self.num * other_fraction.den +
self.den * other_fraction.num
new_den = self.den * other_fraction.den
common = gcd(new_num, new_den)
return Fraction(new_num // common, new_den // common)
11
Compare Fractions
• By default, two fractions f1 and f2 are equal (i.e., f1 == f2 is
True) only if f1 and f2 are references to same object, which is
called shallow equality
• What we want is f1 == f2 is True even they are different
objects but with same values (numerator and denominator),
which is called deep equality
12
Equality for Fraction
• Note that our Fraction object now has two
very useful methods as shown in the figures
13
Achieve Deep Equality
• For this, we need to override __eq__ standard method:
def __eq__(self, other):
first_num = self.num * other.den
second_num = other.num * self.den
return first_num == second_num
• Note that there are other operators that can be overridden
• E.g., __le__ (for “<=”), __gt__ (for “>”), __ne__ (for “!=”), __sub__ (for “-”),
__truediv__ (for “/”), etc.
14
Exceptions
• Two types of errors may occur when programming
• Syntax errors
• Mistakes made in the structure of a statement or expression
• Can usually be found by Python interpreter and IDEs
• Runtime errors usually caused by logic errors
• Due to errors in underlying algorithm or in translation/implementation of
that algorithm
• E.g., divide by zero or access item with index out of bound of a list
• Typically called exceptions, and can cause program to terminate
15
Exception Handling
• Provide a way to deal with exceptions that allows programmer to
have some type of intervention
• Use try statement to catch raised exception and use except
statement to handle the caught exception
• E.g., try:
print(math.sqrt(a_number))
except:
print(“Bad value for square root”)
print(“Using absolute value instead”)
print(math.sqrt(abs(a_number)))
16
Exception Handling (cont.)
• Programmers can also create and raise their own exceptions if
they detect a situation in the program execution that warrants it
• E.g., try:
if a_number <0:
raise RuntimeError(“You can’t use a negative number”)
else:
print(math.sqrt(a_number))
except RuntimeError as err_instance:
print(str(err_instance), “nUsing absolute value instead”)
print(math.sqrt(abs(a_number)))
17
List Comprehension
• Allow to easily create a list based on some processing or
selection criteria by using iteration and selection constructs
• a_list = [statement for item in collection if condition]
• If value item takes on from collection makes condition to be True, then the
statement is calculated and the result is added to the a_list being constructed
• It is equivalent to but more concise and efficient than
a_list = []
for item in collection:
if condition:
a_list.append(statement)
18
List Comprehension (cont.)
• E.g., to obtain a list of the squares of the first 10 integers that are odd:
sq_list = [x*x for x in range(1, 11) if x % 2 == 1]
It is equivalent to but more concise and efficient than
sq_list = []
for x in range(1,11):
if x % 2 == 1:
sq_list.append(x*x)
• Another example to build a list from a string
a_list = [ch.upper() for ch in “comprehension” if ch not in “aeiou”]
19
Summary
• Computer science is the study of problem solving and uses
abstraction as a tool for representing both processes and data
• Abstract data types (ADTs) help manage complexity of problem
domain by hiding details of data
• Python is object-oriented, powerful, yet easy-to-use
• Lists, tuples, and strings are built in Python sequential collections
• Dictionaries and sets are nonsequential collections of data
• Classes allow programmers to implement ADTs
• One can override standard methods as well as create new methods
20
Some Useful Links for Python 3
• https://docs.python.org/3/tutorial/, useful Python 3 tutorial to
help quickly get familiar with Python programming
• https://www.tutorialspoint.com/python3/, another good Python
3 tutorial to help quickly get familiar with Python programming
• https://docs.python.org/3/library/index.html, library reference
guide, to find libraries and functions needed for programming
• https://docs.python.org/3/, Python 3 documentation providing
detailed documentation about almost every aspect of Python 3
21

More Related Content

Similar to Data Structures and Algorithms in Python

Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor John(Qiang) Zhang
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDeepikaV81
 
Data structures using C
Data structures using CData structures using C
Data structures using CPdr Patnaik
 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Salman Qamar
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.pptAjit Mali
 
VCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxVCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxskilljiolms
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2Tekendra Nath Yogi
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxskilljiolms
 

Similar to Data Structures and Algorithms in Python (20)

Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
DATA STRUCTURE.pdf
DATA STRUCTURE.pdfDATA STRUCTURE.pdf
DATA STRUCTURE.pdf
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURE
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02Ds12 140715025807-phpapp02
Ds12 140715025807-phpapp02
 
Python functions
Python functionsPython functions
Python functions
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
30csharp
30csharp30csharp
30csharp
 
30c
30c30c
30c
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
VCE Unit 01 (1).pptx
VCE Unit 01 (1).pptxVCE Unit 01 (1).pptx
VCE Unit 01 (1).pptx
 
Algorithm.pptx
Algorithm.pptxAlgorithm.pptx
Algorithm.pptx
 
Algorithm.pptx
Algorithm.pptxAlgorithm.pptx
Algorithm.pptx
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptx
 

Recently uploaded

Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night EnjoyCall Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night EnjoyPooja Nehwal
 
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort ServiceDelhi Call girls
 
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779Night 7k Call Girls Noida Sector 128 Call Me: 8448380779
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779Delhi Call girls
 
Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)Chameera Dedduwage
 
Mathematics of Finance Presentation.pptx
Mathematics of Finance Presentation.pptxMathematics of Finance Presentation.pptx
Mathematics of Finance Presentation.pptxMoumonDas2
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Vipesco
 
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...Hasting Chen
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxraffaeleoman
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar TrainingKylaCullinane
 
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024eCommerce Institute
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaKayode Fayemi
 
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...Kayode Fayemi
 
Air breathing and respiratory adaptations in diver animals
Air breathing and respiratory adaptations in diver animalsAir breathing and respiratory adaptations in diver animals
Air breathing and respiratory adaptations in diver animalsaqsarehman5055
 
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptx
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptxMohammad_Alnahdi_Oral_Presentation_Assignment.pptx
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptxmohammadalnahdi22
 
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, YardstickSaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, Yardsticksaastr
 
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara ServicesVVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara ServicesPooja Nehwal
 
ANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docxANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docxNikitaBankoti2
 
Presentation on Engagement in Book Clubs
Presentation on Engagement in Book ClubsPresentation on Engagement in Book Clubs
Presentation on Engagement in Book Clubssamaasim06
 
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdfThe workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdfSenaatti-kiinteistöt
 
George Lever - eCommerce Day Chile 2024
George Lever -  eCommerce Day Chile 2024George Lever -  eCommerce Day Chile 2024
George Lever - eCommerce Day Chile 2024eCommerce Institute
 

Recently uploaded (20)

Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night EnjoyCall Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
Call Girl Number in Khar Mumbai📲 9892124323 💞 Full Night Enjoy
 
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 93 Noida Escorts >༒8448380779 Escort Service
 
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779Night 7k Call Girls Noida Sector 128 Call Me: 8448380779
Night 7k Call Girls Noida Sector 128 Call Me: 8448380779
 
Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)Introduction to Prompt Engineering (Focusing on ChatGPT)
Introduction to Prompt Engineering (Focusing on ChatGPT)
 
Mathematics of Finance Presentation.pptx
Mathematics of Finance Presentation.pptxMathematics of Finance Presentation.pptx
Mathematics of Finance Presentation.pptx
 
Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510Thirunelveli call girls Tamil escorts 7877702510
Thirunelveli call girls Tamil escorts 7877702510
 
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
Re-membering the Bard: Revisiting The Compleat Wrks of Wllm Shkspr (Abridged)...
 
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptxChiulli_Aurora_Oman_Raffaele_Beowulf.pptx
Chiulli_Aurora_Oman_Raffaele_Beowulf.pptx
 
Report Writing Webinar Training
Report Writing Webinar TrainingReport Writing Webinar Training
Report Writing Webinar Training
 
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024
Andrés Ramírez Gossler, Facundo Schinnea - eCommerce Day Chile 2024
 
If this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New NigeriaIf this Giant Must Walk: A Manifesto for a New Nigeria
If this Giant Must Walk: A Manifesto for a New Nigeria
 
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
Governance and Nation-Building in Nigeria: Some Reflections on Options for Po...
 
Air breathing and respiratory adaptations in diver animals
Air breathing and respiratory adaptations in diver animalsAir breathing and respiratory adaptations in diver animals
Air breathing and respiratory adaptations in diver animals
 
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptx
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptxMohammad_Alnahdi_Oral_Presentation_Assignment.pptx
Mohammad_Alnahdi_Oral_Presentation_Assignment.pptx
 
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, YardstickSaaStr Workshop Wednesday w/ Lucas Price, Yardstick
SaaStr Workshop Wednesday w/ Lucas Price, Yardstick
 
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara ServicesVVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
VVIP Call Girls Nalasopara : 9892124323, Call Girls in Nalasopara Services
 
ANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docxANCHORING SCRIPT FOR A CULTURAL EVENT.docx
ANCHORING SCRIPT FOR A CULTURAL EVENT.docx
 
Presentation on Engagement in Book Clubs
Presentation on Engagement in Book ClubsPresentation on Engagement in Book Clubs
Presentation on Engagement in Book Clubs
 
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdfThe workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
The workplace ecosystem of the future 24.4.2024 Fabritius_share ii.pdf
 
George Lever - eCommerce Day Chile 2024
George Lever -  eCommerce Day Chile 2024George Lever -  eCommerce Day Chile 2024
George Lever - eCommerce Day Chile 2024
 

Data Structures and Algorithms in Python

  • 1. Classes - Object-Oriented Programming • Allow to implement abstract data type to provide logical description of • What a data object looks like (its state) • What it can do (its methods) • To build a class for this, one can take advantage of the abstraction process while providing necessary details to use the abstraction in a program 1
  • 2. Class Definition • class class_name: def __init__(self, para_name_1, para_name_2, ...) statement body def other_method_name(self, other_para_1, ...) statement body • Constructor method is always __init__ function • self is always 1st parameter, used to refer back to the object itself • E.g., self.var_name can be used to refer to the object’s internally defined variable var_name (as part of the object’s state) 2
  • 3. Fraction Class as an Example • Recall that a fraction such as 3 5 consists of two parts • Top value, i.e., numerator, can be any integer • Bottom value, i.e., denominator, can be any positive integer • Negative fractions have a negative numerator • Operations/methods for Fraction type allow a Fraction data object to behave like any other numeric value • Such as add, subtract, multiply and divide • Fraction should be displayed in “slash” form (e.g., 3/5) • All methods should return results in lowest terms (i.e., most common forms, e.g., 3/5 rather than 6/10) 3
  • 4. Implementation of Fraction Class • Class definition and its constructor class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom • Fraction state data, i.e., numerator and denominator are denoted by internal data objects self.num and self.den, respectively • __init__ initializes the internal state by assigning values of the top and bottom parameters to self.num and self.den, respectively 4
  • 5. Create Instance of Fraction Class • To create a Fraction instance, we use the name of the class, which invokes constructor and passes actual values for the necessary state • Note that we never directly invoke __init__ • Note that 1st parameter self is never given actual parameter value upon invocation • E.g., my_fraction = Fraction(3, 5) invokes constructor and creates a Fraction instance 3 5 as show on the right 5
  • 6. Display Fraction • print function requires object convert itself into string so as to be written to output • To tell Fraction class how to convert itself into string, we need to override standard method __str__, i.e., to redefine its behavior: def __str__(self): return str(self.num) + “/” + str(self.den) • Examples on when this function is invoked print(my_fraction) my_fraction.__str__() str(my_fraction) 6
  • 7. “Add” Operation for Fraction • Allow two Fraction objects to be added together using “+” • For this, we need to override __add__ standard method • So that f1 + f2 will call f1.__add__(f2), the overridden method • Recall two fractions must have same denominator to be added • Easiest solution is to multiply two denominators as common denominator, i.e., for two fractions 𝑎 𝑏 and 𝑐 𝑑 , we add them as 𝑎 𝑏 + 𝑐 𝑑 = 𝑎𝑑 𝑏𝑑 + 𝑏𝑐 𝑏𝑑 = 𝑎𝑑+𝑏𝑐 𝑏𝑑 7
  • 8. “Add” Operation for Fraction (cont.) • “Add” operation implementation: def __add__ (self, other_fractioin): new_num = self.num * other_fraction.den + self.den * other_fraction.num new_den = self.den * other_fraction.den return Fraction(new_num, new_den) • Considering print(Fraction(1, 4)+Fraction(1, 2)), what is the result? • 6/8 will be returned but 3/4 is supposed to be the best answer 8
  • 9. Make Result in Lowest Term • For this, we need a helper function to reduce fraction • We use this function to calculate the greatest common divisor (GCD) between numerator and denominator • We can then divide both numerator and denominator by the GCD to reduce the result to lowest term • Best-known algorithm to find GCD is Euclid’s algorithm • The GCD between m and n is n if n divides m evenly, otherwise it is the GCD between n and m%n • This algorithm only works for positive integer n, which is our case (negative fraction is represented by negative numerator) 9
  • 10. Make Result in Lowest Term (cont.) • Implementation of Euclid’s algorithm: def gcd(m, n): while m % n != 0: old_m = m old_n = n m = old_n n = old_m % old_n return n 10
  • 11. Updated “Add” Operation Implementation • We update __add__ to use gcd function to reduce result: def __add__ (self, other_fractioin): new_num = self.num * other_fraction.den + self.den * other_fraction.num new_den = self.den * other_fraction.den common = gcd(new_num, new_den) return Fraction(new_num // common, new_den // common) 11
  • 12. Compare Fractions • By default, two fractions f1 and f2 are equal (i.e., f1 == f2 is True) only if f1 and f2 are references to same object, which is called shallow equality • What we want is f1 == f2 is True even they are different objects but with same values (numerator and denominator), which is called deep equality 12
  • 13. Equality for Fraction • Note that our Fraction object now has two very useful methods as shown in the figures 13
  • 14. Achieve Deep Equality • For this, we need to override __eq__ standard method: def __eq__(self, other): first_num = self.num * other.den second_num = other.num * self.den return first_num == second_num • Note that there are other operators that can be overridden • E.g., __le__ (for “<=”), __gt__ (for “>”), __ne__ (for “!=”), __sub__ (for “-”), __truediv__ (for “/”), etc. 14
  • 15. Exceptions • Two types of errors may occur when programming • Syntax errors • Mistakes made in the structure of a statement or expression • Can usually be found by Python interpreter and IDEs • Runtime errors usually caused by logic errors • Due to errors in underlying algorithm or in translation/implementation of that algorithm • E.g., divide by zero or access item with index out of bound of a list • Typically called exceptions, and can cause program to terminate 15
  • 16. Exception Handling • Provide a way to deal with exceptions that allows programmer to have some type of intervention • Use try statement to catch raised exception and use except statement to handle the caught exception • E.g., try: print(math.sqrt(a_number)) except: print(“Bad value for square root”) print(“Using absolute value instead”) print(math.sqrt(abs(a_number))) 16
  • 17. Exception Handling (cont.) • Programmers can also create and raise their own exceptions if they detect a situation in the program execution that warrants it • E.g., try: if a_number <0: raise RuntimeError(“You can’t use a negative number”) else: print(math.sqrt(a_number)) except RuntimeError as err_instance: print(str(err_instance), “nUsing absolute value instead”) print(math.sqrt(abs(a_number))) 17
  • 18. List Comprehension • Allow to easily create a list based on some processing or selection criteria by using iteration and selection constructs • a_list = [statement for item in collection if condition] • If value item takes on from collection makes condition to be True, then the statement is calculated and the result is added to the a_list being constructed • It is equivalent to but more concise and efficient than a_list = [] for item in collection: if condition: a_list.append(statement) 18
  • 19. List Comprehension (cont.) • E.g., to obtain a list of the squares of the first 10 integers that are odd: sq_list = [x*x for x in range(1, 11) if x % 2 == 1] It is equivalent to but more concise and efficient than sq_list = [] for x in range(1,11): if x % 2 == 1: sq_list.append(x*x) • Another example to build a list from a string a_list = [ch.upper() for ch in “comprehension” if ch not in “aeiou”] 19
  • 20. Summary • Computer science is the study of problem solving and uses abstraction as a tool for representing both processes and data • Abstract data types (ADTs) help manage complexity of problem domain by hiding details of data • Python is object-oriented, powerful, yet easy-to-use • Lists, tuples, and strings are built in Python sequential collections • Dictionaries and sets are nonsequential collections of data • Classes allow programmers to implement ADTs • One can override standard methods as well as create new methods 20
  • 21. Some Useful Links for Python 3 • https://docs.python.org/3/tutorial/, useful Python 3 tutorial to help quickly get familiar with Python programming • https://www.tutorialspoint.com/python3/, another good Python 3 tutorial to help quickly get familiar with Python programming • https://docs.python.org/3/library/index.html, library reference guide, to find libraries and functions needed for programming • https://docs.python.org/3/, Python 3 documentation providing detailed documentation about almost every aspect of Python 3 21