0% found this document useful (0 votes)
11 views39 pages

Dsap l03 PDF

Uploaded by

cheno0809
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)
11 views39 pages

Dsap l03 PDF

Uploaded by

cheno0809
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/ 39

Data Structures and

Algorithms Using Python


Lecture 3: Data Structures and OOP

Heikki Peura
[email protected]
1 def K(n):
2 """ assume n is a nonnegative integer """
3 y = 0
4 i = n
5 j = 0
6 while i > 0:
7 while j < i:
8 y += y
9 j += 1
10 i = i//2
11 return y

https://goo.gl/qnXpYW

2 / 19
Last time

Algorithm complexity
I Asymptotic analysis and Big-O notation
I Searching and sorting

Plan for today:


I Introduction to data structures
I Object-oriented programming (OOP)

3 / 19
Data structures

How to organize data for quick access?


I Like with algorithms: recipe → translate to Python

Examples: lists, stacks, queues, dictionaries (hash


tables), graphs, trees, etc

Different data structures are suitable for different


tasks
I Support different sets of operations (list vs dict)
I How to choose?

4 / 19
We have already been using data structures

1 'Hello World'
2 3.14159
3 9
4 L = [1, 1999, 0, -2, 9]

5 / 19
We have already been using data structures

1 'Hello World'
2 3.14159
3 9
4 L = [1, 1999, 0, -2, 9]

These are all objects. An object has:


I A type: int, str, list (L is an instance of a list)
I An internal representation of data
I A set of functions that operate on that data (methods)

5 / 19
We have already been using data structures

1 'Hello World'
2 3.14159
3 9
4 L = [1, 1999, 0, -2, 9]

These are all objects. An object has:


I A type: int, str, list (L is an instance of a list)
I An internal representation of data
I A set of functions that operate on that data (methods)

An object bundles data and relevant actions

5 / 19
A Python list has many operations
Some of the operations:
len(L),max(L),min(L),...
L[start:stop:step]: returns elements of L from start to stop
with step size step
L[i]= e: sets the value at index i to e
L.append(e): adds e to the end of L
L.count(e): returns how many times e occurs in L
L.insert(i,e): inserts e at index i of L
L.extend(L1): appends the items of L1 to the end of L
L.remove(e): deletes the first occurrence of e from L
L.index(e): returns the index of first occurrence of e in L
L.pop(i): removes and returns the item at index i, default i = -1
L.sort(): sorts elements of L
L.reverse(): reverses the order of elements of L

6 / 19
A list is an object

An object bundles data and actions

7 / 19
A list is an object

An object bundles data and actions

1 L = [1,1999,0,-2,9]
2 L.append(8)
3 L.insert(2,1000)
4 t = L.pop()
5 L.remove(1)
6 help(L)

7 / 19
A list is an object

An object bundles data and actions

1 L = [1,1999,0,-2,9]
2 L.append(8)
3 L.insert(2,1000)
4 t = L.pop()
5 L.remove(1)
6 help(L)

The point:
I Interface: the user knows what she can do with a list
I Abstraction: the user does not need to know the details of what
goes on under the hood (similarly to functions)
I Invaluable in managing complexity of programs

7 / 19
List operations complexity?

1 L = [1,1999,0,-2,9]
2 L.append(9)
3 t = L[2]
4 t = L.pop(0)

We have assumed that list operations like retrieving or adding an


item are O(1)
I A list has internal functions with algorithms to perform these
operations

8 / 19
List operations complexity?

1 L = [1,1999,0,-2,9]
2 L.append(9)
3 t = L[2]
4 t = L.pop(0)

We have assumed that list operations like retrieving or adding an


item are O(1)
I A list has internal functions with algorithms to perform these
operations

But we have seen that how we write algorithms matters a lot...


I Does it matter how you implement a list?
I Yes!
I What is the internal data representation of a list?

8 / 19
How can we implement a list?

For a list, we would like to:


I Add and remove elements, look up values, change values, . . .

9 / 19
How can we implement a list?

For a list, we would like to:


I Add and remove elements, look up values, change values, . . .

An indexed array?

56 24 99 32 9 61 57 79

9 / 19
How can we implement a list?

For a list, we would like to:


I Add and remove elements, look up values, change values, . . .

An indexed array?

56 24 99 32 9 61 57 79

I Reserve n slots of memory for list from computer memory


I Easy to access an item at index i: O(1)

9 / 19
How can we implement a list?

For a list, we would like to:


I Add and remove elements, look up values, change values, . . .

An indexed array?

56 24 99 32 9 61 57 79

I Reserve n slots of memory for list from computer memory


I Easy to access an item at index i: O(1)

I Easy to add an item to end: O(1) (but details are advanced...)

9 / 19
How can we implement a list?

For a list, we would like to:


I Add and remove elements, look up values, change values, . . .

An indexed array?

56 24 99 32 9 61 57 79

I Reserve n slots of memory for list from computer memory


I Easy to access an item at index i: O(1)

I Easy to add an item to end: O(1) (but details are advanced...)


I Difficult to add item to beginning: O(n) (need to move all
other elements)

9 / 19
A linked list of “nodes”?

Linked list?

56 24 99 32 9 61 57 79

10 / 19
A linked list of “nodes”?

Linked list?

56 24 99 32 9 61 57 79

I Each node contains information on the next node – the list


itself just knows the first and last one

10 / 19
A linked list of “nodes”?

Linked list?

56 24 99 32 9 61 57 79

I Each node contains information on the next node – the list


itself just knows the first and last one
I Easy to add items to either end: O(1)

10 / 19
A linked list of “nodes”?

Linked list?

56 24 99 32 9 61 57 79

I Each node contains information on the next node – the list


itself just knows the first and last one
I Easy to add items to either end: O(1)
I Difficult to look up item by index... O(n) (need to walk through
the nodes)

10 / 19
A Python list has many operations
Some of the operations:
len(L),max(L),min(L),...
L[start:stop:step]: returns elements of L from start to stop
with step size step
L[i]= e: sets the value at index i to e
L.append(e): adds e to the end of L
L.count(e): returns how many times e occurs in L
L.insert(i,e): inserts e at index i of L
L.extend(L1): appends the items of L1 to the end of L
L.remove(e): deletes the first occurrence of e from L
L.index(e): returns the index of first occurrence of e in L
L.pop(i): removes and returns the item at index i, default i = -1
L.sort(): sorts elements of L
L.reverse(): reverses the order of elements of L

11 / 19
Object-oriented programming (OOP)

Everything is an object with a type: L=[1,2,3,4] is an instance


of a list object

Abstraction — creating an object type:


I Define internal representation and interface for interacting with
object — user only needs interface

12 / 19
Object-oriented programming (OOP)

Everything is an object with a type: L=[1,2,3,4] is an instance


of a list object

Abstraction — creating an object type:


I Define internal representation and interface for interacting with
object — user only needs interface
I Then we can create new instances of objects and delete them

12 / 19
Object-oriented programming (OOP)

Everything is an object with a type: L=[1,2,3,4] is an instance


of a list object

Abstraction — creating an object type:


I Define internal representation and interface for interacting with
object — user only needs interface
I Then we can create new instances of objects and delete them

Benefits similar to functions


I Modularity — treat a complex thing like a list as primitive
I Easier to reuse code — keep code clean: eg ‘+’ method for
integers and strings

12 / 19
Why define objects?

Suppose you’re designing a game where players catch pocket


monsters and make them fight each other

13 / 19
Why define objects?

Suppose you’re designing a game where players catch pocket


monsters and make them fight each other

1 # Using lists?
2 monsters = ['Pikachu','Squirtle','Mew']
3 combat_points = [20,82,194]
4 hit_points = [53,90,289]

13 / 19
Why define objects?

Suppose you’re designing a game where players catch pocket


monsters and make them fight each other

1 # Using lists?
2 monsters = ['Pikachu','Squirtle','Mew']
3 combat_points = [20,82,194]
4 hit_points = [53,90,289]

1 # Using a dictionary?
2 monsters = {'Pikachu':[20,53],'Squirtle':[82,90],'Mew':[194,289]}

13 / 19
Defining an object type

An object contains
I Data: attributes (of a monster)
I Functions: methods that operate on that data

14 / 19
Defining an object type

An object contains
I Data: attributes (of a monster)
I Functions: methods that operate on that data

Suppose you’re designing a game where players catch pocket


monsters and make them fight each other

1 class Monster(object):
2 """
3 Attributes and methods
4 """

class statement defines new object type

14 / 19
We’ve created a Monster
Attributes of a monster?

15 / 19
We’ve created a Monster
Attributes of a monster?

1 class Monster(object):
2 """
3 Pocket monster
4 """
5 def __init__(self,combat_points):
6 self.combat_points = combat_points
7
8 Pikachu = Monster(65)
9 Squirtle = Monster(278)
10 print(Pikachu.combat_points)

self: Python passes the object itself as the first argument —


convention to use word “self”
I But you omit this when calling the function

15 / 19
We’ve created a Monster
Attributes of a monster?

1 class Monster(object):
2 """
3 Pocket monster
4 """
5 def __init__(self,combat_points):
6 self.combat_points = combat_points
7
8 Pikachu = Monster(65)
9 Squirtle = Monster(278)
10 print(Pikachu.combat_points)

self: Python passes the object itself as the first argument —


convention to use word “self”
I But you omit this when calling the function

I Notice the “.” operator (like with a list)


I The __init__ method is called when you call Monster()
15 / 19
Growing our monsters

1 class Monster(object):
2 def __init__(self, name, combat_points, hit_points):
3 self.name = name
4 self.combat_points = combat_points
5 self.hit_points = hit_points
6 self.health = hit_points
7
8 def hurt(self, damage):
9 self.health = self.health - damage
10 if self.health <= 0:
11 print(self.name + ' is dead!')

More in the workshop!

16 / 19
Why OOP is useful

Easy to handle many “things” with common attributes

Abstraction isolates the use of objects from


implementation details

Build layers of abstractions — our own on top of


Python’s classes
I Keeping track of different monsters and their attributes

17 / 19
Accessing data

1 class Monster(object):
2 def __init__(self, name, combat_points, hit_points):
3 self.name = name
4 self.combat_points = combat_points
5 self.hit_points = hit_points
6 self.health = hit_points
7
8 def get_combat_points(self): # access data through method
9 return self.combat_points
10
11 # more Monster code...
12
13 Pikachu = Monster('Pikachu', 100, 30)
14 print(Pikachu.combat_points == 100) # risky - what if you make a mistake?
15 print(Pikachu.get_combat_points() == 100) # safer - cannot mess stuff up

(If you go deeper into OOP, there are more advanced ways of making data
“private”)

18 / 19
Review

Data structures and OOP


I OOP is a way of designing programs to bundle data
and actions
I Data structures are ways to organize data efficiently
I Python has excellent data structures for common
tasks

Workshop after the break


I More Monsters
I A data structure we’ll need later: queue

19 / 19
Workshop

Workshop zip file on the Hub


I HTML instructions
I At some point, you’ll need the .py-file with skeleton
code (open in Spyder)

You might also like