Presentation is loading. Please wait.

Presentation is loading. Please wait.

Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.

Similar presentations


Presentation on theme: "Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game."— Presentation transcript:

1 Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game

2 Sequences so far  Strings "", tuples ()  General sequence functions/operators/methods –len(seq) –"w" in "word" –seq[i] (indexing) –seq[beg:end] (slicing) –seq1 + seq2 (concatenation) –"abc".index("a")  for loops: iterates over a sequence –for letter in "word": –for idx in range(len("word")): –while idx < len("word")

3 Objectives  Lists are similar to tuples in many senses –Create, index, and slice a list (similarly to tuple)  Lists are mutable sequences (tuples are immutable) – Add and delete elements from a list –Use list methods to append, sort, and reverse a list  Use nested sequences to represent even more complex information –NumPy (http://numpy.scipy.org/)  Use dictionaries (not ordered!) to work with pairs of data –Add and delete dictionary items  Understanding sorting algorithms Guide to Programming with Python 3

4 Lists are Similar to Tuples  List: A mutable (changeable) sequence of any type  Creating List inventory = [] inventory = ["sword", "armor", "shield", "healing potion"]  Using len() function and in operator if "healing potion" in inventory: print "You will live to fight another day.”  Indexing and slicing inventory[1], inventory[1:3]  Concatenating lists list1 + list2 Guide to Programming with Python4 Tuple: inventory = (“sword”, “armor”, “shield”, “healing potion”) [ ]

5 Understanding List Mutability  Mutable: Changeable  Lists are mutable –Elements (or slices) can be added –Elements (or slices) can be removed Guide to Programming with Python5

6 Assigning a New Element Or Slice >>> inventory = ["sword", "armor", "shield", "healing potion", "gold", "gems"] >>> inventory[0] = "crossbow" >>> print inventory ['crossbow', 'armor', 'shield', 'healing potion', 'gold', 'gems’] >>> inventory[4:6] = ["orb of future telling"] >>> print inventory ['crossbow', 'armor', 'shield', 'healing potion', 'orb of future telling'] (Replaces the two elements inventory[4] and inventory[5] with "orb of future telling”) Guide to Programming with Python6

7 Deleting an Element or a Slice >>> inventory = ["crossbow", "armor", "shield", "healing potion", "orb of future telling"] >>> del inventory[2] >>> print inventory ['crossbow', 'armor', 'healing potion', 'orb of future telling'] >>> del inventory[:2] >>> print inventory ['healing potion', 'orb of future telling’] Guide to Programming with Python7 Designate element to delete after del

8 List Methods Table 5.1: Selected list methods Guide to Programming with Python8 ascending order by default

9 When to Use Tuples Instead of Lists  Tuples are faster than lists  Tuples’ immutability makes them perfect for creating constants because they can’t change  Rule of thumb: Use lists over tuples in most cases Guide to Programming with Python9

10 Using Nested Sequences  Nested Sequence: A sequence inside another sequence  A list can contain lists or tuples  A tuple can contain tuples or lists scores = [("Moe", 1000), ("Larry", 1500), ("Curly", 3000)] scores[2] is the element of the list at position 2 scores[2][0] is the element at position 0 of scores[2] Guide to Programming with Python10 multiple indexing

11 Unpacking a Sequence >>> name, score = ("Shemp", 175) >>> print name Shemp >>> print score 175  Sequence unpacking: Automatically accessing each element of a sequence  The tuple is unpacked as result of assignment statement Guide to Programming with Python11

12 Accessing Elements of a Nested Sequence scores = [("Moe", 1000), ("Larry", 1500)] for entry in scores: score, name = entry print name, "\t", score Guide to Programming with Python12 Sequence unpacking: Automatically accessing each element of a sequence as a result of assignment statement scores[1][0] multiple indexing

13 Variable References  A variable refers to a place in memory where the value (or empty) is stored language = “Python”  Variable assignment can be –initial (creates a new box in the computer’s memory the first time a variable name is seen) –shared (assign lists; default for mutable items) a = b = [] # both names will point to the same list –copied (numbers, strings, tuples) “Python” language # All variables refer to same single list

14 Shared Reference – Changes Applied to All Variables Sharing References Guide to Programming with Python14 “red sweater” mike[2] = “red sweater” Then mr_dawson[2], and honey[2] => “red sweater” Shared reference could cause serious problem if you are not aware of this (see the Sodoku puzzle solver)

15 Avoid Shared References >>> mike = ["khakis", "dress shirt", "jacket"] >>> honey = mike[:] >>> honey[2] = "red sweater" >>> print honey ['khakis', 'dress shirt', 'red sweater'] >>> print mike ['khakis', 'dress shirt', 'jacket’]  List slicing can create a new copy of a list and avoid shared references (but NOT for nested sequences) a = [1, 2, [3, 4]] b = a[:] b[1] = "22” b[2][0] = "33" Guide to Programming with Python 15

16 Using copy.deepcopy()  Module: copy –ref: http://docs.python.org/library/copy.html import copy b = copy.copy(a) #shallow copy, => b = a[:] b = copy.deepcopy(a) #deep copy of an object #A deep (shallow) copy constructs a new compound object and then, recursively, inserts copies (references) into it of the objects found in the original. Example: sokodu1 = copy.deepcopy(sokodu)

17 NumPy for Arrays of Numeric Numbers (instead of Using Nested Sequences)  Initialize a 2D-array a = [[0]*3]*3 a[1][1] = 1  Ref: http://numpy.scipy.org/ Ref: http://numpy.scipy.org/ import numpy numpy.zeros([3,3], int) Guide to Programming with Python17 # It has the “shared reference problem”

18 Using Dictionaries  Dictionary: A mutable collection of key-value pairs  Like tuple and list, dictionary is another built-in type  Unlike tuples and lists, dictionaries don’t organize data into sequences, but pairs  Works like actual dictionary; look up one thing to get another  Look up a key to get a value  The Geek Translator Program Guide to Programming with Python18

19 Creating Dictionaries geek = {"404" : "clueless.", "Uninstalled" : "being fired."}  Creates new dictionary called geek  geek has two entries or items  Each item is made up of a key and a value  404 is a key of one item; use it to look up value "clueless."  Create dictionary by pairing values with colon, separated by commas, surrounded by curly braces Guide to Programming with Python19

20 Using a Key to Retrieve a Value >>> geek["404"] 'clueless.' >>> geek["Uninstalled"] 'being fired.'  Use key as index to get value  Cannot use value as index to get key  Using non-existent key as index produces error  Dictionaries don't have position numbers – no order Guide to Programming with Python20

21 Testing for a Key with the in Operator >>> if "Dancing Baloney" in geek: print "I know what Dancing Baloney is." else: print "I have no idea what Dancing Baloney is." I have no idea what Dancing Baloney is.  Use the in operator to test for key  Condition is True if key exists in dictionary, False otherwise  in operator can't be used to test for dictionary values Guide to Programming with Python21

22 The Dictionary get() Method >>> geek.get("404") 'clueless.' >>> geek.get("Dancing Baloney") None >>> geek.get("Dancing Baloney", "I have no idea.") 'I have no idea.'  Used for retrieving value based on key  Has built-in safety net for handling non-existent key –If key exists, returns associated value –If key doesn’t exist, returns a default value Guide to Programming with Python22

23 Adding a Key-Value Pair geek["Link Rot"] = "process by which web page links become obsolete."  Dictionaries are mutable  Add item by assigning value to dictionary indexed by key  Overwrites current entry if key already exists in dictionary Guide to Programming with Python23

24 Deleting a Key-Value Pair del geek["404"]  Removes key-value pair if key exists  Generates error if key doesn’t exist Guide to Programming with Python24

25 Selected Dictionary Methods Table 5.1: Selected dictionary methods Guide to Programming with Python25

26 Dictionary Requirements  Keys –Must be unique –Must be immutable  Values –Can be mutable or immutable –Don’t have to be unique Guide to Programming with Python26

27 The Hangman Game V2 Guide to Programming with Python27

28 Sorting Algorithms  What’s sorting: an operation that segregates items into groups according to specified criterion.  Sorting algorithms: bubble sort, selection sort, insertion sort, merge sort, heap sort, quick sort, radix sort, swap sort, etc

29 Bubble Sort  Smaller elements "bubble" to the top of the list.  Only uses comparisons to operate on elements (a comparison sort.)  Simple implementation but not efficient for sorting large lists  How it works: –Start from the beginning of a list, compare every adjacent pair, swap their position if they are not in the right order. After each iteration, one less element (the last one) is needed to be compared until there is no more element left to be compared or no more swaps are made in one iteration. Guide to Programming with Python29

30 Summary  A list is a mutable sequence of any type  You can add or remove list elements or slices  A nested sequence is a sequence inside another sequence; access an element by using multiple indexing  Sequence unpacking is the process of automatically accessing each element of a sequence  A shared reference is a reference to an object, which has at least one other reference to it Guide to Programming with Python30

31 Summary (continued)  A dictionary is a mutable collection of key-value pairs  In a dictionary, an item is a key-value pair  In a dictionary, a key is an object used to look up another object  In a dictionary, a value is an object that is returned when its corresponding key is looked up  The in operator can be used to test if a dictionary contains a specific key Guide to Programming with Python31

32 Summary (continued)  A dictionary can’t contain multiple items with the same key  A dictionary can contain multiple items with the same value  Dictionary keys must be immutable  Dictionary values can be mutable Guide to Programming with Python32

33 Lists vs. Arrays  Python lists are very flexible and can hold completely heterogeneous, arbitrary data  Array can only be used for specific types, whereas lists can be used for any object.  Arrays may be more efficient for some numerical computation.  If you're going to be using arrays, consider the numpy or scipy packages. Guide to Programming with Python33

34 Data Types and Data Structures  Data types vs. data structures –A data type is a well-defined collection of data with a well-defined set of operations on it. (int, float, etc) –A data structure is an actual implementation of a particular abstract data type. (tree, graph, etc)  Building data structures from lists, dictionaries, etc Guide to Programming with Python34


Download ppt "Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game."

Similar presentations


Ads by Google