0% found this document useful (0 votes)
7 views28 pages

3.2 Creating Data Types

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views28 pages

3.2 Creating Data Types

Uploaded by

Maxi Brad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

COMPUTER SCIENCE

S E D G E W I C K / W A Y N E

SEDGEWICK

ntist WAYNE
Computer Science

ary
A N I N T E R D I S C I P L I N A RY A P P R O A C H

or

d
gs,
of

omputer
C cience Creating Data Types
hem

h.

S
nce
d
wick

ysis
orics;
ver

An Interdisciplinary Approach

ROBERT SEDGEWICK
ANADA
K E V I N WAY N E
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E

Creating Data Types


• Overview
• Complex numbers
Basic building blocks for programming

any program you might want to write

objects

functions and modules

graphics, sound, and image I/O

arrays/lists
Ability to bring life
conditionals and loops to your own
abstractions

Math text I/O

primitive data types assignment statements

3
Object-oriented programming (OOP)

Object-oriented programming (OOP).


• Create your own data types.
• Use them in your programs (manipulate objects). An object holds a data type value.
Variable names refer to objects.

Examples
data type set of values examples of operations

Color three 8-bit integers get red component, brighten

Picture 2D array of colors get/set color of pixel

String sequence of characters length, substring, compare C A T A G C G C

An abstract data type is a data type whose representation is hidden from the client.

Impact: We can use ADTs without knowing implementation details.


• Previous section: how to write client programs for a couple of useful ADTs
• This section: how to implement your own ADTs
4
Implementing a data type

To create a data type, you need provide code that In Python, a data-type implementation
• Defines the set of values (class and instance variables). is known as a class.
• Implements operations on those values (methods).
Broad anatomy of a Python class
• Creates and initializes new objects (constructors).
class variables

Class variables constructors & instance variables


• Constants, or
• Values to be shared by all instances.

methods
Methods
• Specialized functions implementing operations.
• Can refer to instance variables.

Constructors test client


• Called to create new instances (objects).
• Set (initial) values of instances variables.

5
Anatomy of a Python Class

class Employee: def main():


'Records basic employee details.' emp1 = Employee("Delboy", 1000)
employeeCount = 0 emp2 = Employee("Rodney", 600)
emp3 = Employee("Boycie", 2500)
def __init__(self, name, salary): employees = [emp1, emp2, emp3]
self.name = name
self.salary = salary emp1.displayDetails()
self.id = Employee.employeeCount emp2.displayDetails()
Employee.employeeCount += 1 emp3.displayDetails()
Employee.displayCount()
def displayDetails(self): print("Top earner is:",
print("Name : ", self.name, "\nID:",self.id, Employee.topEarner(employees).name,"\n")
"\nSalary:", self.salary, "\n")
if __name__ == '__main__':
@classmethod main()
def displayCount(cls):
print("Total Employees: ", cls.employeeCount, "\n")

@staticmethod
def topEarner(employees):
topEarner = employees[0]
for employee in employees[1:]:
if employee.salary > topEarner.salary:
topEarner = employee
return topEarner

6
Anatomy of a Python Class
optional class documentation string
class Employee: def main():
'Records basic employee details.' emp1 = Employee("Delboy", 1000)
employeeCount = 0 emp2 = Employee("Rodney",class
600) variable
emp3 = Employee("Boycie", 2500)
def __init__(self, name, salary): employees = [emp1, emp2, emp3]
self.name = name
self.salary = salary emp1.displayDetails() constructor
self.id = Employee.employeeCount instance variables
emp2.displayDetails()
Employee.employeeCount += 1 emp3.displayDetails()
Employee.displayCount()
def displayDetails(self): instance method
print("Top earner is:",
print("Name : ", self.name, "\nID:",self.id, Employee.topEarner(employees).name,"\n")
"\nSalary:", self.salary, "\n")
if __name__ == '__main__':
@classmethod main()
class method
def displayCount(cls):
print("Total Employees: ", cls.employeeCount, "\n")
methods
@staticmethod
static method
def topEarner(employees):
topEarner = employees[0]
for employee in employees[1:]:
if employee.salary > topEarner.salary:
topEarner = employee
return topEarner
Anatomy of a Python Class

class Employee: def main():


'Records basic test client details.'
employee emp1 = Employee("Delboy", 1000)
employeeCount = 0 emp2 = Employee("Rodney", 600)
emp3 = Employee("Boycie", 2500)
def __init__(self, name, salary): employees = [emp1, emp2, emp3]
self.name = name
self.salary = salary emp1.displayDetails()
$: python3
self.idemployee.py
= Employee.employeeCount emp2.displayDetails()
Employee.employeeCount += 1 emp3.displayDetails()
Name : Delboy Employee.displayCount()
ID: def
0 displayDetails(self): print("Top earner is:",
print("Name : ", self.name, "\nID:",self.id, Employee.topEarner(employees).name,"\n")
Salary: 1000
"\nSalary:", self.salary, "\n")
if __name__ == '__main__':
Name@classmethod
: Rodney
def displayCount(cls):
main()

ID: 1 print("Total Employees: ", cls.employeeCount, "\n")


Salary: 600
@staticmethod
def topEarner(employees):
Name : topEarner
Boycie = employees[0]
for employee in employees[1:]:
• conditional statement ensures that
ID: 2 if employee.salary > topEarner.salary:
main() is only executed if the class
Salary:return topEarner = employee
2500topEarner
code is being run directly
Top earner is: Boycie • but not if it’s been imported by a client
• visit here for a longer explanation
Total Employees: 3
8
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E

Creating Data Types


• Overview
• Complex numbers
Crash course in complex numbers

A complex number is a number of the form a + bi where a and b are real and

Complex numbers are a quintessential mathematical abstraction that


have been used for centuries to give insight into real-world problems
not easily addressed otherwise.

To perform algebraic operations on complex numbers, use real Leonhard Euler A. L. Cauchy
1707−1783 1789−1857
algebra, replace i 2 by −1 and collect terms.
• Addition example: (3 + 4i ) + (−2 + 3i ) = 1 + 7i .
Example: | 3 + 4i | = 5
• Multiplication example: (3 + 4i ) x (−2 + 3i ) = −18 + i .

The magnitude or absolute value of a complex number a + bi is | + |= +

Applications: Signal processing, control theory, quantum mechanics, analysis of algorithms...

10
ADT for complex numbers

A complex number is a number of the form a + bi where a and b are real and

An ADT allows us to write Python programs that manipulate complex numbers.

complex number 3 + 4i −2 + 2i
Values real part 3.0 −2.0
imaginary part 4.0 2.0

class Complex

c = Complex(real, imag), create complex number c

c + b or c.__add__(b) sum of complex numbers c and b


API (operations) c * b or c._mul__(b) product of complex numbers c and b
abs(c) or c.__abs()__ magnitude of c
str(c) or __str__c) string representation of c
11
Complex number data type implementation: test client

Best practice. Begin by implementing a simple test client. class variables

constructors & instance


variables

#-----------------------------------------
methods

# For testing.
# Create and use some Complex objects.

test client
def main():

z0 = Complex(1.0, 1.0)
z = z0
z = z * z + z0
$ python3 complex.py
z = z * z + z0
-7.0 + 7.0i
print(z)

if __name__ == '__main__': Output when the implementation is complete.


main()
12
Complex number data type implementation: constructor and instance variables

class variables
Class variables define data-type values that are shared by all objects.
constructor & instance
variables

Constructors create and initialize new objects.


methods

Instance variables define data-type values that will be specific to each object.

#---------------------------------------------- test client


# complex.py
#----------------------------------------------
import math

# A Complex object is a complex number.


Values
# A Complex object is immutable. So once you create and initialize
# a Complex object, you cannot change it. complex number 3 + 4i −2 + 2i
class Complex: real part 3.0 −2.0

# Construct self with real (re) and imaginary (im) parts imaginary part 4.0 2.0
# both parts default to 0.0
def __init__(self, re=0.0, im=0.0):
self._re = re
self._im = im
13
Complex number data type implementation: methods

# Return the real part of self. class variables


def re(self):
constructors & instance
return self._re variables

# Return the imaginary part of self.


def im(self): methods
return self._im

# Return the conjugate of self.


def conjugate(self):
return Complex(self._re, -self._im)
test client
# Return a new Complex object which is the sum of self and
# Complex object other.
def __add__(self, other):
re = self._re + other._re
im = self._im + other._im
return Complex(re, im)

# Return a new Complex object which is the product of self and


# Complex object other.
def __mul__(self, other):
re = self._re * other._re - self._im * other._im
im = self._re * other._im + self._im * other._re
return Complex(re, im)

14
Complex number data type implementation: methods

# Return True if self and Complex object other are equal, and class variables
# False otherwise.
constructors & instance
def __eq__(self, other): variables
return (self._re == other._re) and (self._im == other._im)

# Return True if self and Complex object other are unequal, and methods
# False otherwise.
def __ne__(self, other):
return not self.__eq__(other)

# Return the absolute value of self.


def __abs__(self): test client
return math.sqrt(self._re*self._re + self._im*self._im)
# Alternative: return math.hypot(self._re, self._im)
# Alternative: return self.__mul__(self.conjugate())

# Return a string representation of self.


def __str__(self):
return str(self._re) + ' + ' + str(self._im) + 'i'

15
The Mandelbrot set

The Mandelbrot set is a set of complex numbers.


• Represent each complex number x + yi by a point
(x, y ) in the plane.
(1, 1)
• If a point is in the set, we color it BLACK.
• If a point is not in the set, we color it WHITE. B. Mandelbrot
1924−2010

Examples
• In the set: −0.5 + 0i.
• Not in the set: 1 + i.

Challenge (−0.5, 0)

• No simple formula exists for testing whether a


number is in the set.
• Instead, the set is defined by an algorithm.
16
Determining whether a point is in the Mandelbrot set

Is a complex number z0 in the set?


• Iterate zt+1 = (zt )2 + z0.
• If |zt | diverges to infinity, z0 is not in the set.
• If not, z0 is in the set.

t zt t zt
(−0.5, 0)

0 −1/2 + 0i 0 1+i

1 −1/4 + 0i 1 1 + 3i

2 −7/16 + 0i 2 −7 + 7i

3 −79/256 + 0i 3 1 − 97i (1+i )2 + (1+i ) = 1 + 2i + i 2 + 1 + i = 1+3i

4 −26527/65536 + 0i 4 −9407 − 193i (1+3i )2 + (1+i ) = 1 + 6i + 9i 2 + 1 + i = −7+7i

always between −1/2 and 0 diverges to infinity


z = −1/2 + 0i is in the set z = 1 + i is not in the set
17
Plotting the Mandelbrot set

(-1.5, 1)
Practical issues
• Cannot plot infinitely many points.
• Cannot iterate infinitely many times.

Approximate solution for first issue (−0.5, 0)

• Sample from an N-by-N grid of points in the plane.


• Zoom in to see more detail (stay tuned!).

Approximate solution for second issue


Important note: Solutions imply
• Fact: if | zt | > 2 for any t, then z is not in the set.
significant computation.
• Pseudo-fact: if | z255 | ≤ 2 then z is "likely" in the set.

18
Complex number client: Mandelbrot set visualization (helper method)

Mandelbrot function of a complex number.


• Returns RED if the number is not in the set.
• Returns BLACK if the number is (probably) in the set.

def mandelbrot(candidate, limit):


z = candidate For a more dramatic picture,
for t in range(limit): return new Color(255-t, 255-t, 255-t)
if abs(z) > 2.0: return “red”
or colours picked from a colour table.
z = z * z
z = z + candidate
return “black”

19
Complex number client: Mandelbrot set visualization

from graphics import *


from complex import * $ python3 mandelbrot.py 80 -0.5 0 2

def main():
n = int(sys.argv[1]) # try 80
xc = float(sys.argv[2]) # try -0.5
yc = float(sys.argv[3]) # try 0
size = float(sys.argv[4]) # try 2

limit = 255
win = GraphWin("Mandelbrot Set", n, n)

for column in range(n):


for row in range(n):
x0 = xc - (size / 2) + (size * column) / n
y0 = yc - (size / 2) + (size * row) / n
z0 = Complex(x0, y0)
colour = mandelbrot(z0, limit)
win.plot(column, n - 1 - row, colour)

win.getMouse()
win.close()

20
Mandelbrot Set

this has been coded as a class, so compare it with


$: python3 greymandelbrot.py 512 -0.5 0 2
mandelbrot.py to also see the structural differences

21
Mandelbrot Set

ColorMandelbrot

color map

–1.5 0 2

–1.5 0 .002

22
23
Mandelbrot Set

(-1.5, -1)
24
OOP summary

Object-oriented programming (OOP)


• Create your own data types (sets of values and ops on them).
• Use them in your programs (manipulate objects).

OOP helps us simulate the physical world


• Python objects model real-world objects.
• Not always easy to make model reflect reality.

OOP helps us extend the Python language


• Python doesn't have a data type for every possible application.
• Data types enable us to add our own abstractions.
• Examples: complex, vector, polynomial, matrix, picture.... T A G A T G T G C T A G C

25
You have come a long way

any program you might want to write

objects

functions and modules


def main():
print(“Hello world”)
graphics, sound, and image I/O

arrays
T A G A T G T G C T A G C

conditionals and loops

Math text I/O

primitive data types assignment statements

Course goal. Open a whole new world of opportunity for you (programming).
✓ 26
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E

Image sources

http://en.wikipedia.org/wiki/Leonhard_Euler#/media/File:Leonhard_Euler.jpg

http://en.wikipedia.org/wiki/Augustin-Louis_Cauchy

http://upload.wikimedia.org/wikipedia/commons/e/e9/Benoit_Mandelbrot_mg_1804-d.jpg

http://upload.wikimedia.org/wikipedia/commons/f/fc/Mandel_zoom_08_satellite_antenna.jpg

http://upload.wikimedia.org/wikipedia/commons/1/18/Mandelpart2.jpg
http://upload.wikimedia.org/wikipedia/commons/f/fb/Mandel_zoom_13_satellite_seehorse_tail_with_julia_island.jpg

http://upload.wikimedia.org/wikipedia/commons/4/44/Mandelbrot_set_à_la_Pop_Art_-_Wacker_Art_Fractal_Generator.jpg

C S . 9 . D . C r e a t i n g D Ts . M a n d e l b r o t
Reading and References

These Slides
• principally based on slides by Robert Sedgewick and Kevin Wayne, and Manrique Mata-Montero
Recommended Reading
• online booksite (Python version) chapter 3
Wider reading and recommended independent learning:
• Elijah Wilson’s suggested structure for a Python class
• Q&A at the end of section 3.2 of the online booksite
• review/learn/re-learn Exception Handling
• there’s a good tutorial at codementor
• or you can also go to the more formal python.org tutorial
• read Designing Data Types from section 3.3 of the online booksite
Activity:
• see the Data Types Practice Exercises in the course shell

28

You might also like