lecture 9 composite types

72
Introduction to computational thinking Module 9 : Composite Types Asst Prof Michael Lees Office: N402c76 email: mhlees[at]ntu.edu.sg Module 9 : Composite Types 1

Upload: alvin567

Post on 12-May-2015

193 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Lecture 9  composite types

Introduction to computational thinking

Module 9 : Composite Types

Asst Prof Michael LeesOffice: N4‐02c‐76

email: mhlees[at]ntu.edu.sgModule 9 : Composite Types 1

Page 2: Lecture 9  composite types

Contents

1. What are Composite types/data structures

2. Why are they important3. 4 common data structures in 

python (and their operations)– Lists– Tuples– Dictionaries– Sets

Module 9 : Composite Types

Chapter 7& 

Chapter 9

2

Page 3: Lecture 9  composite types

What is a Composite Type?

• A data type which is constructed (composed) using primitive and other composite types.

• New data  types made from existing ones

Module 9 : Composite Types 3

Page 4: Lecture 9  composite types

Data Structures

• Data structures are particular ways of storing data to make some operation easier or more efficient. That is, they are tunedfor certain tasks.

• Data structures are suited to solving certain problems, and they are often associated with algorithms.

Module 9 : Composite Types

vs.

4

Page 5: Lecture 9  composite types

Data Structures

Roughly two kinds of data structures:• Built‐in data structures ‐ data structures that are so common as to be provided by default.

• User‐defined data structures  ‐ (classes in object oriented programming) designed for a particular task. (Later courses)

Module 9 : Composite Types 5

Page 6: Lecture 9  composite types

Python Compositions

• Python has a number of composite types to use:– Lists– Tuples– Dictionaries– Sets, Strings,…

• Convenient and efficient ways for us to store data.– All 1’s and 0’s underneath.– Course on data structures will cover how to implement.

Module 9 : Composite Types 6

Page 7: Lecture 9  composite types

LISTSModule 9: Composite Types

Module 9 : Composite Types 7

Page 8: Lecture 9  composite types

Python lists

• An ordered sequence of items : simple!

• We have already covered a type of sequence:– Strings are a sequence of…?

Module 9 : Composite Types 8

Page 9: Lecture 9  composite types

Creating a list

• As with all data structures, lists have a constructor. 

• Constructors have the same name as the data structure: l=list(arg) or l=list()

• Can take an iterable data structure as an argument, which adds each item of arg to the constructed list l.

• It also has a shortcut: the use of square brackets [ ] to indicate explicit items: l = []

Module 9 : Composite Types 9

Page 10: Lecture 9  composite types

Creating Lists

aList = list(‘abc’)

aList [‘a’, ‘b’, ‘c’]

newList = [1, 3.14159, ‘a’, True]

Module 9 : Composite Types 10

Page 11: Lecture 9  composite types

Similar to Strings

• concatenate : + (but only of lists – not string + list)

• repeat : *• indexing (the [ ] operator) lst[3] => 4th item in list

• slicing ([:])• membership (the in operator) • length (the len operator)

Module 9 : Composite Types 11

Page 12: Lecture 9  composite types

Differences to Strings

• Lists can contain a mixture of any python object (type); strings can only hold characters.l = [1,’bill’,1.2345, True]

• Lists are mutable; their values can be changed while strings are immutable.

• Lists are designated with [ ], with elements separated by commas; strings use “”.

Module 9 : Composite Types 12

Page 13: Lecture 9  composite types

List structure

Module 9 : Composite Types 13

Page 14: Lecture 9  composite types

[]? Indexing on lists

• [] means a list and also used to retrieve index.[‘a’, ‘b’, ‘c’][1] => ‘b’

[0,1,2][0] => 0

[0][0] => 0

• Context is important. Index is always at the end of an expression and is preceded by something (variable, sequence).

Module 9 : Composite Types 14

Page 15: Lecture 9  composite types

Lists of lists

myLst = [‘a’, [1, 2, 3], ‘z’]• What is the second element (index 1) of that list? 

• Another list:myLst[1][0] #apply left to right

myLst[1] => [1, 2, 3]

[1, 2, 3][0] => 1

[1, [2,[3,4]], 5][1][1][0]=>?

Module 9 : Composite Types 15

Page 16: Lecture 9  composite types

Operators

[1, 2, 3] + [4] [1, 2, 3, 4]

[1, 2, 3] * 2 [1, 2, 3, 1, 2, 3]

1 in [1, 2, 3] True

[1, 2, 3] < [1, 2, 4] TrueCompare index to index, the first difference determines the result. As with strings.

Module 9 : Composite Types 16

Page 17: Lecture 9  composite types

Some list functions

• len(lst): Number of elements in list (top level). len([1, [1, 2], 3]) 3

• min(lst): Minimum element in the list. If list of lists, looks at first element of each list.

• max(lst): Max element in the list.• sum(lst): Sum the elements, numeric only. 

Module 9 : Composite Types 17

Page 18: Lecture 9  composite types

Iterate on a list

for element in [1, [1, 2], ‘a’, True]:

print(element)

1

[1, 2]

‘a’

True

Module 9 : Composite Types 18

Page 19: Lecture 9  composite types

Mutable vs Immutable

• mutability n : the quality of being capable of mutation.

• Mutable : After creation can be changed• Immutable : After creation can’t be changed• Lists are mutable• Strings are immutablemyStr = ‘abc’myStr[0] = ‘z’ #Not possiblenewStr= myStr.replace(‘a’, ‘z’) #make

a new string

Module 9 : Composite Types 19

Page 20: Lecture 9  composite types

Lists are mutable

• Unlike strings, lists are mutable. You can change the object’s contents!

myLst = [1, 2, 3]

myLst[0] = 127

print(myLst) [127, 2, 3]

Module 9 : Composite Types 20

Page 21: Lecture 9  composite types

List methods

• Remember, a function is a small program (such as len()) that takes some arguments, the stuff in the parenthesis, and returns some value.

• A method is called in a special way, the “dot call”. It is called in the context of an object (or a variable holding an object).

Module 9 : Composite Types 21

Page 22: Lecture 9  composite types

List methods

• A list is mutable and can change:myList[0]=‘a’ #index assignment

myList.append(), myList.extend()

myList.pop()

myList.insert(), myList.remove()

myList.sort()

myList.reverse()

Module 9 : Composite Types 22

Page 23: Lecture 9  composite types

Return values

• Notice, when compared to string methods. Most of these methods do not return a value.

• This is because lists are mutable so the methods modify the list directly; there is no need to return a new list.

• This can be confusing.• Remember the python standard is your friend!

Module 9 : Composite Types 23

Page 24: Lecture 9  composite types

Warnings about results

myLst = [4, 7, 1, 2]

myLst = myLst.sort()

myLst None #what happened?

• What is the return value of myLst.sort()?• Be careful what you are assigning!

Module 9 : Composite Types 24

Page 25: Lecture 9  composite types

Split

• The string method split generates a sequence of characters by splitting the string at certain split‐characters.

• It, too, returns a list:splitLst = ‘this is a test’.split()

splitLst

[‘this’, ‘is’, ‘a’, ‘test’]

Module 9 : Composite Types 25

Page 26: Lecture 9  composite types

Sorting

• Only lists have a built‐in sorting method. Thus you often convert your data to a list if it needs sorting:

myLst = list(‘xyzabc’) #iterable to constructor

myLst [‘x’,’y’,’z’,’a’,’b’,’c’]myLst.sort() # convert back to a stringsortStr = ‘’.join(myLst)

‘abcxyz’

Module 9 : Composite Types 26

Page 27: Lecture 9  composite types

Sorted Function

• The sorted function will break a sequence into elements and sort the sequence, placing the results in a list:

aStr = ‘hi mom’

sortLst = sorted(aStr)

[‘ ‘,’h’,’i’,’m’,’m’,’o’]

Module 9 : Composite Types 27

Page 28: Lecture 9  composite types

COMPOSITE TYPESPIMITIVE TYPES

Types and terminology

Module 9 : Composite Types 28

int

long

floatcomplex

• Everything in python is an object of a certain type

string

list

function is called without . chr(34) len(“astring”)

method is called on an object using .

dictionary

tuple set

aList.sort() newString = aString.split(‘a’)

methods can take argumentsmutable

Page 29: Lecture 9  composite types

How do I know?

dir(object) – will return all methods that the object can use

Python reference:all functions: http://docs.python.org/library/functions.htmlall built in types (including methods)http://docs.python.org/library/stdtypes.html#

Module 9 : Composite Types 29

Page 30: Lecture 9  composite types

CHALLENGE 9.1 – Checking anagramsGiven two words print ‘YES’ if they are an anagram and ‘NO’ if not.

Module 9 : Composite Types 30

Page 31: Lecture 9  composite types

Thought process

• Can iterate through one string, check if each character is in the other? Careful here, once a character has been matched we should remove it.

• If we have two characters the same this can be complicated

Module 9 : Composite Types 31

Page 32: Lecture 9  composite types

a b c x y zd w

Option One

Module 9 : Composite Types 32

1. take each letter in string one and add a ball to the basket of corresponding letter2. take each letter in string two and remove a ball from the corresponding basket

If at the end our baskets are all empty, then we have an anagram

“cdxc”“dccx”

Page 33: Lecture 9  composite types

Option two

• Computer science way.• Sort both strings.• Anagrams should be identical after sorting.• Just compare sorted versions.

Module 9 : Composite Types 33

Page 34: Lecture 9  composite types

w1 = ‘THE EYES’w2 = ‘THEY SEE’w1sorted = sorted(w1)w2sorted = sorted(w2)

if w1sorted == w2sorted:print(‘YES’)

else:print(‘NO’)

Module 9 : Composite Types 34

Page 35: Lecture 9  composite types

TUPLESModule 9: Composite Types

Module 9 : Composite Types 35

Page 36: Lecture 9  composite types

Tuples

• Tuples are easy: they are simply immutable lists.

• They are designated with (,):

myTuple = (1,’a’,3.14,True)

Module 9 : Composite Types 36

Page 37: Lecture 9  composite types

What’s the point?

• The real question is, why have an immutable list, a tuple, as a separate type?

• An immutable list gives you a data structure with some integrity, some permanency, if you will.

• You know you cannot accidentally change one.

Module 9 : Composite Types 37

Page 38: Lecture 9  composite types

Lists vs Tuples

• Everything that works with a list works with a tuple exceptmethods that modify the tuple.

• Thus indexing, slicing, len, print all work as expected.

• However, none of the mutable methods work: append, extend, del.

Module 9 : Composite Types 38

Page 39: Lecture 9  composite types

Commas create tuples

• For tuples, you can think of a comma as the operator that makes a tuple, where the ( ) simply acts as a grouping:

myTuple = 1,2 # creates (1,2)

myTuple = (1,) # creates (1)

myTuple = (1) # creates 1 not (1)

myTuple = 1, # creates (1)

Module 9 : Composite Types 39

Page 40: Lecture 9  composite types

A SIDE : DATA STRUCTURES IN GENERAL

Module 9: Composite Types

Module 9 : Composite Types 40

Page 41: Lecture 9  composite types

Data structures in general 

• Strings, lists and tuples…• Each is an organization of data is some specific way. The organization is useful for particular tasks, makes things simpler. Choosing the right data structure for you program/algorithm is important.

Module 9 : Composite Types 41

Page 42: Lecture 9  composite types

LIST COMPREHENSIONModule 9: Composite Types

Module 9 : Composite Types 42

Page 43: Lecture 9  composite types

Lists are IMPORTANT

• The use of lists in Python is a major part of its power. 

• Lists are very useful and can be used to accomplish many tasks.

• Therefore Python provides some pretty powerful support to make common list tasks easier.

Module 9 : Composite Types 43

Page 44: Lecture 9  composite types

Constructing lists

• List comprehension : syntactic structure for concise construction of lists from existing lists.

[n for n in range(1,5)]

Module 9 : Composite Types

[ n for n in range(1,5)]

mark the comp with [ ]

what wecollect

what we iteratethrough. Note thatwe iterate over a set of values and collect some(in this case all) of them

returns [1,2,3,4]

44

Page 45: Lecture 9  composite types

Other examples

[ n**2 for n in range(1,6)] => ?

[x+y for x in range(1,4) for y in range (1,4)] =>?

[c for c in “Hi There Mom” if c.isupper()]

Module 9 : Composite Types

It is as if we had done the following:myList = [ ]for x in range (1,4):for y in range (1,4):myList.append(x+y)

[2,3,4,3,4,5,4,5,6]

45

Page 46: Lecture 9  composite types

DICTIONARIESModule 9: Composite Types

Module 9 : Composite Types 46

Page 47: Lecture 9  composite types

What is a dictionary?

• In data structure terms, a dictionary is better termed an associative array or associative list or a map.

• You can think if it as a list of pairs, where the first element of the pair, the key, is used to retrieve the second element, the value.

• Thus we map a key to a value.

Module 9 : Composite Types 47

Page 48: Lecture 9  composite types

<Key=>Value>

• The key acts as a “lookup” to find the associated value.

• Just like a dictionary, you look up a word by its spelling to find the associated definition.

• A dictionary can be searched to locate the value associated with a key.

Module 9 : Composite Types 48

Page 49: Lecture 9  composite types

Python Dictionary

• Use the { } marker to create a dictionary• Use the : marker to indicate key:value pairs:

contacts= {‘bill’: ‘353-1234’, ‘rich’: ‘269-1234’, ‘jane’: ‘352-1234’}

print(contacts) =>{‘jane’: ‘352-1234’, ‘bill’: ‘353-1234’, ‘rich’: ‘369-1234’}

Module 9 : Composite Types 49

Page 50: Lecture 9  composite types

Module 9 : Composite Types 50

Page 51: Lecture 9  composite types

What are Keys and Values

• Key must be immutable (think about why?)– strings, integers, tuples are fine– lists are NOT

• Value can be anything.

Module 9 : Composite Types 51

Page 52: Lecture 9  composite types

Collections vs Sequence

• Dictionaries are collections, but they are not sequences like lists, strings or tuples:– there is no order to the elements of a dictionary– in fact, the order (for example, when printed) might change as elements are added or deleted. 

• So how to access dictionary elements?

Module 9 : Composite Types 52

Page 53: Lecture 9  composite types

Access dictionary

Access requires [ ], but the key is the index!myDict={}

– an empty dictionary

myDict[‘bill’]=25– added the pair ‘bill’:25

print(myDict[‘bill’])– prints 25

Module 9 : Composite Types 53

Page 54: Lecture 9  composite types

Dictionaries are mutable

• Like lists, dictionaries are a mutable data structure:– you can change the object via various operations, such as index assignment

myDict = {‘bill’:3, ‘rich’:10}

print(myDict[‘bill’]) # prints 3

myDict[‘bill’] = 100

print(myDict[‘bill’]) # prints 100

Module 9 : Composite Types 54

Page 55: Lecture 9  composite types

Familiar operators

Like others, dictionaries respond to these:• len(myDict)

– number of key:value pairs in the dictionary

• element in myDict– boolean, is element a key in the dictionary

• for key in myDict:– iterates through the keys of a dictionary

Module 9 : Composite Types 55

Page 56: Lecture 9  composite types

Other methods and operations

• myDict.items() – all the key/value pairs• myDict.keys() – all the keys• myDict.values() – all the values• key in myDict

does the key exist in the dictionary• myDict.clear() – empty the dictionary• myDict.update(yourDict) – for each key in yourDict, updates myDict with that key/value pair

Module 9 : Composite Types 56

Page 57: Lecture 9  composite types

Iterating on dictionary

for key in myDict:print(key)

– prints all the keys

for key,value in myDict.items():print(key, value)

– prints all the key/value pairs

for value in myDict.values():print(value)

– prints all the values

Module 9 : Composite Types 57

Page 58: Lecture 9  composite types

View Objects

• Notice the return type of:– myDict.items() – dict_items– myDict.keys() – dict_keys– myDict.values() – dict_values

• There are view objects (new to python 3)– view object is iterable (use in for loop)– order of view objects correspond!– view objects are dynamic, changing dictionary will update view!

Module 9 : Composite Types 58

Page 59: Lecture 9  composite types

Quick construction of dictionary

• zip creates pairs from two parallel lists:– zip(“abc”,[1,2,3]) creates a zip object

• That’s good for building dictionaries. We call the dict function which takes a list of pairs to make a dictionary:– dict(zip(“abc”,[1,2,3])) yields– {'a': 1, 'c': 3, 'b': 2}

Module 9 : Composite Types 59

Page 60: Lecture 9  composite types

Challenge 9.2 : Music collection storageDesign a data structure for storing someone’s music collection. For each piece of music assume you have the following data: artist, title, album, genre.Create an example of the data structure.

Module 9 : Composite Types 60

Page 61: Lecture 9  composite types

Thought process

• What are you options:– list, tuple, dictionary

• How will the data be used/changed? What’s a logical way for us to think about it?

• Dictionary?• What is the key?

Module 9 : Composite Types 61

Page 62: Lecture 9  composite types

Challenge 9.3 : Adding Album detailsExtend 9.2 so that instead of just the album name, we create another data structure to store album name and the songs on the album

Module 9 : Composite Types 62

Page 63: Lecture 9  composite types

Thought process

• Data for album:– Title– [songTitle1, songTitle2,…]

• How will the data be used/changed? What’s a logical way for us to think about it?

• List?• How to modify 9.2

Module 9 : Composite Types 63

Page 64: Lecture 9  composite types

SETSModule 9: Composite Types

Module 9 : Composite Types 64

Page 65: Lecture 9  composite types

What is a set?

• Mathematical?– collection of objects–No two elements are the same (all items unique)

– There is no order.– Set with no elements is the empty set

Module 9 : Composite Types 65

Page 66: Lecture 9  composite types

Creating a set

mySet = set(“abcd”)

• set constructor creates a set• The single argument must be an iterable. Iterable is something that can be ‘walked’ through by for

• Set is another data structure:print(mySet)

set([‘a’,’b’,’c’,’d’])

Module 9 : Composite Types 66

Page 67: Lecture 9  composite types

Duplicates??

mySet = set([1,1,1,2,2,2,3,3,3])

#List as input

• Automatically removed when added or created:

print(mySet)

set([1,2,3])

Module 9 : Composite Types 67

Page 68: Lecture 9  composite types

Familiar operators

Most data structures respond to these:• len(mySet)

– the number of elements in a set• element in mySet

– boolean indicating whether element is in the set• for element in mySet:

– iterate through the elements in mySet

Module 9 : Composite Types 68

Page 69: Lecture 9  composite types

Set specific operators

• Set data structure contains things you might expectmySet=set(“abcd”); newSet=set(“cdef”)

Module 9 : Composite Types

mySet.intersection(newSet) returns set([‘c’,’d’])

e fa b c d

69

Page 70: Lecture 9  composite types

Others

• setA.difference(setB): – Things in setA not in setB

• setA.union(setB): – Things in setA or setB

• setA.symmetric_difference(setB)– Things in setA or setB, but not in both

• Also subset, superset,… see library for more

Module 9 : Composite Types 70

e fa b c d

e fa b c d

e fa b c d

setA SetB

setA SetB

setA SetB

Page 71: Lecture 9  composite types

Take home lessons

• What is a data structure, what does it do? Why? IMPORTANT FOR FUTURE

• 4 data structures:– List, Tuple, Dictionary, Set (what are they good for)

• List comprehension – very powerful python tool

• Think about ways to arrange data using these structures.

Module 9 : Composite Types 71

Page 72: Lecture 9  composite types

Further reading

• http://www.youtube.com/watch?v=EPYupizJYQI

• http://code.google.com/edu/languages/google‐python‐class/lists.html

• http://docs.python.org/tutorial/datastructures.html

• http://docs.python.org/library/stdtypes.html#typesseq

Module 9 : Composite Types 72