1 / 20

Introduction to Computing Using Python

Introduction to Computing Using Python. Dictionary c ontainer c lass + modules. Container Class dict Modules, revisited. User-defined indexes and dictionaries. Introduction to Computing Using Python. Goal: a container of employee records indexed by employee SS#. >>> employee[987654321]

val
Download Presentation

Introduction to Computing Using Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Computing Using Python Dictionary containerclass + modules • Container Class dict • Modules, revisited

  2. User-defined indexes and dictionaries Introduction to Computing Using Python Goal: a container of employee records indexed by employee SS# >>> employee[987654321] ['Yu', 'Tsun'] >>> employee[864209753] ['Anna', 'Karenina'] >>> employee[100010010] ['Hans', 'Castorp'] Problems: • the range of SS#sis huge • SS#s are not really integers Solution: the dictionary class dict >>> employee = { '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun'], '100-01-0010': ['Hans', 'Castorp']} >>> >>> employee = { '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun'], '100-01-0010': ['Hans', 'Castorp']} >>> employee['987-65-4321'] ['Yu', 'Tsun'] >>> employee['864-20-9753'] ['Anna', 'Karenina'] A dictionary contains (key, value) pairs A key can be used as an index to access the corresponding value

  3. Properties of dictionaries Introduction to Computing Using Python >>> employee = { '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun'], '100-01-0010': ['Hans', 'Castorp']} >>> employee {'100-01-0010': ['Hans', 'Castorp'], '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun']} >>> >>> employee = { '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun'], '100-01-0010': ['Hans', 'Castorp']} >>> employee {'100-01-0010': ['Hans', 'Castorp'], '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun']} >>> employee['123-45-6789'] = 'Holden Cafield' >>> employee {'100-01-0010': ['Hans', 'Castorp'], '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun'], '123-45-6789': 'Holden Cafield'} >>> >>> employee = { '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun'], '100-01-0010': ['Hans', 'Castorp']} >>> employee {'100-01-0010': ['Hans', 'Castorp'], '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun']} >>> employee['123-45-6789'] = 'Holden Cafield' >>> employee {'100-01-0010': ['Hans', 'Castorp'], '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun'], '123-45-6789': 'Holden Cafield'} >>> employee['123-45-6789'] = 'Holden Caulfield' >>> employee {'100-01-0010': ['Hans', 'Castorp'], '864-20-9753': ['Anna', 'Karenina'], '987-65-4321': ['Yu', 'Tsun'], '123-45-6789': 'Holden Caulfield’} Dictionaries are not ordered Dictionaries are mutable Dictionaries are mutable • new (key,value) pairs can be added Dictionaries are mutable • new (key,value) pairs can be added • the value corresponding to a key can be modified The empty dictionary is {} >>> employee = {[1,2]:1, [2,3]:3} Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> employee = {[1,2]:1, [2,3]:3} TypeError: unhashable type: 'list' Dictionary keys must be immutable

  4. Dictionary operators Introduction to Computing Using Python Class dict supports some of the same operators as class list >>> days = {'Mo':1, 'Tu':2, 'W':3} >>> days['Mo'] 1 >>> days['Th'] = 5 >>> days {'Mo': 1, 'Tu': 2, 'Th': 5, 'W': 3} >>> days['Th'] = 4 >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> 'Fr' in days False >>> len(days) 4 Class dictdoes not support all the operators that class list supports • + and * for example

  5. Dictionary methods Introduction to Computing Using Python >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days.pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days2 = {'Tu':2, 'Fr':5} >>> days.update(days2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days.items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days.keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> >>> vals = days.values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days.pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days2 = {'Tu':2, 'Fr':5} >>> days.update(days2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days.items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days.keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> >>> vals = days.values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> for val in vals: print(val, end=' ') 5 3 4 1 2 >>> The containers returned by d.items(), d.keys(), and d.values() (called views) can be iterated over

  6. Dictionary vs. multi-way if statement Introduction to Computing Using Python Uses of a dictionary: • container with custom indexes Uses of a dictionary: • container with custom indexes • alternative to the multi-way if statement def complete(abbreviation): 'returns day of the week corresponding to abbreviation' if abbreviation == 'Mo': return 'Monday' elif abbreviation == 'Tu': return 'Tuesday' elif ...... else: # abbreviation must be Su return 'Sunday' def complete(abbreviation): 'returns day of the week corresponding to abbreviation' days = {'Mo': 'Monday', 'Tu':'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday', 'Fr': 'Friday', 'Sa': 'Saturday', 'Su':'Sunday'} return days[abbreviation]

  7. Dictionary as a container of counters Introduction to Computing Using Python Uses of a dictionary: • container with custom indexes • alternative to the multi-way if statement • container of counters Problem: computing the number of occurrences of items in a list >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] >>> frequency(grades) {96: 1, 90: 1, 100: 3, 85: 1, 95: 3} >>> Solution: Iterate through the list and, for each grade,increment the counter corresponding to the grade. • Problems: • impossible to create counters before seeing what’s in the list • how to store grade counters so a counter is accessible using the corresponding grade Solution: a dictionary mapping a grade (the key) to its counter (the value)

  8. Dictionary as a container of counters Introduction to Computing Using Python Problem: computing the number of occurrences of items in a list >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ ⌃ counters def frequency(itemList): 'returns frequency of items in itemList' counters = {} for item in itemList: if item in counters: # increment item counter counters[item] += 1 else: # create item counter counters[item] = 1 return counters def frequency(itemList): 'returns frequency of items in itemList' counters = {}

  9. Exercise Introduction to Computing Using Python Implement function wordcount()that takes as input a text—as a string— and prints the frequency of each word in the text; assume there is no punctuation in the text. def wordCount(text): 'prints frequency of each word in text' wordList = text.split() # split text into list of words counters ={} # dictionary of counters for word in wordList: if word in counters: # counter for word exists counters[word] += 1 else: # counter for word doesn't exist counters[word] = 1 for word in counters: # print word counts if counters[word] == 1: print('{:8} appears {} time.'.format(word, counters[word])) else: print('{:8} appears {} times.'.format(word, counters[word])) >>> text = 'all animals are equal but some animals are more equal than other' >>> wordCount(text) all appears 1 time. animals appears 2 times. some appears 1 time. equal appears 2 times. but appears 1 time. other appears 1 time. are appears 2 times. than appears 1 time. more appears 1 time. >>> def numChars(filename): 'returns the number of characters in file filename' infile = open(filename, 'r') content = infile.read() infile.close() return len(content)

  10. Built-in class tuple Introduction to Computing Using Python The class tuple is the same as class list … except that it is immutable >>> lst = ['one', 'two', 3] >>> lst[2] 3 >>> lst[2] = 'three' >>> lst ['one', 'two', 'three'] >>> tpl = ('one', 'two', 3) >>> tpl ('one', 'two', 3) >>> tpl[2] 3 >>> tpl[2] = 'three' Traceback (most recent call last): File "<pyshell#131>", line 1, in <module> tpl[2] = 'three' TypeError: 'tuple' object does not support item assignment >>> Why do we need it? Why do we need it? Sometimes, we need to have an “immutable list”. • For example, when we need a dictionary that has lists as keys

  11. Exercise Introduction to Computing Using Python Implement function lookup() that implements a phone book lookup application. Your function takes, as input, a dictionary representing a phone book, mappingtuples (containing the first and last name) to strings (containing phone numbers) >>> phonebook = { ('Anna','Karenina'):'(123)456-78-90', ('Yu', 'Tsun'):'(901)234-56-78', ('Hans', 'Castorp'):'(321)908-76-54'} >>> lookup(phonebook) Enter the first name: Anna Enter the last name: Karenina (123)456-78-90 Enter the first name: def lookup(phonebook): '''implements interactive phone book service using the input phonebook dictionary''' while True: first = input('Enter the first name: ') last = input('Enter the last name: ') person = (first, last) # construct the key if person in phonebook: # if key is in dictionary print(phonebook[person]) # print value else: # if key not in dictionary print('The name you entered is not known.')

  12. Modules, revisited Introduction to Computing Using Python A module is a file containing Python code. • When the module is executed (imported), then the module is (also) a namespace. • This namespace has a name, typically the name of the module. • In this namespace live the names that are defined in the global scope of the module: the names of functions, values, and classes defined in the module. • When the module is executed (imported), then the module is (also) a namespace. • When the module is executed (imported), then the module is (also) a namespace. • This namespace has a name, typically the name of the module. • When the module is executed (imported), then the module is (also) a namespace. • This namespace has a name, typically the name of the module. • In this namespace live the names that are defined in the global scope of the module: the names of functions, values, and classes defined in the module. • These names are the module’s attributes. Built-in function dir()returns the names defined in a namespace >>> import math >>> dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc’] >>> >>> import math >>> dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc’] >>> math.sqrt <built-in function sqrt> >>> math.pi 3.141592653589793 >>> import math >>> To access the imported module’s attributes, the name of the namespace must be specified

  13. Importing a module Introduction to Computing Using Python • When the Python interpreter executes an import statement, it: • Looks for the file corresponding to the module to be imported. • Runs the module’s code to create the objects defined in the module. • Creates a namespace where the names of these objects will live. • When the Python interpreter executes an import statement, it: • Looks for the file corresponding to the module to be imported. • An import statement only lists a name, the name of the module • without any directory information or .py suffix. • Python uses the Python search path to locate the module. • The search path is a list of directories where Python looks for modules. • The variable name path defined in the Standard Library module sys refers to this list. Standard Library folders current working directory >>> import sys >>> sys.path ['/Users/me', '/Library/Frameworks/Python.framework/Versions/3.2/lib/python32.zip', . . . '/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages'] >>>

  14. The Python search path Introduction to Computing Using Python • By just adding folder /Users/me to the search path, module example can be imported • Suppose we want to import module example stored in folder /Users/me that is not in list sys.path names in the shell namespace; note that example is not in no folder in the Python search path contains module example >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> 'an example module' def f(): 'function f' print('Executingf()') def g(): 'function g' print('Executingg()') x = 0 # global var >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import example Traceback (most recent call last): File "<pyshell#79>", line 1, in <module> import example ImportError: No module named example >>> >>> ================ RESTART ================ >>> >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import example Traceback (most recent call last): File "<pyshell#79>", line 1, in <module> import example ImportError: No module named example >>> import sys >>> sys.path.append('/Users/me') >>> import example >>> example.f <function f at 0x10278dc88> >>> example.x 0 >>> >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import example Traceback (most recent call last): File "<pyshell#79>", line 1, in <module> import example ImportError: No module named example >>> import sys >>> sys.path.append('/Users/me') >>> import example >>> example.f <function f at 0x10278dc88> >>> example.x 0 >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'example', 'sys’] When called without an argument, function dir() returns the names in the top-level module • the shell, in this case.

  15. Three ways to import module attributes Introduction to Computing Using Python 'an example module' def f(): 'function f' print('Executingf()') def g(): 'function g' print('Executingg()') x = 0 # global var 1. Import the (name of the) module >>> import example >>> >>> import example >>> example.x 0 >>> example.f <function f at 0x10278dd98> >>> example.f() Executing f() >>> >>> example.py f g x example module example namespace __main__ 0 f() g()

  16. Three ways to import module attributes Introduction to Computing Using Python 'an example module' def f(): 'function f' print('Executingf()') def g(): 'function g' print('Executingg()') x = 0 # global var 2. Import specific module attributes >>> from example import f >>> >>> from example import f >>> f() Executing f() >>> x Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> x NameError: name 'x' is not defined >>> >>> example.py f g x f module example namespace __main__ 0 f() g()

  17. Three ways to import module attributes Introduction to Computing Using Python 'an example module' def f(): 'function f' print('Executingf()') def g(): 'function g' print('Executingg()') x = 0 # global var 3. Import allmodule attributes >>> from example import * >>> f() Executing f() >>> g() Executing g() >>> x 0 >>> >>> >>> from example import * >>> example.py x f g x f g module example namespace __main__ 0 f() g()

  18. A class is a namespace Introduction to Computing Using Python A class is really a namespace • The name of this namespace is the name of the class • Thenames defined in this namespace are the class attributes (e.g., class methods) • The class attributes can be accessedusing the standard namespace notation A class is really a namespace • The name of this namespace is the name of the class • Thenames defined in this namespace are the class attributes (e.g., class methods) >>> list.pop <method 'pop' of 'list' objects> >>> list.sort <method 'sort' of 'list' objects> >>> dir(list) ['__add__', '__class__', ... 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> list.pop <method 'pop' of 'list' objects> >>> list.sort <method 'sort' of 'list' objects> >>> Function dir() can be used to list the class attributes __add__ x count pop . . . namespace list sort() __add__() count() pop()

  19. Class methods Introduction to Computing Using Python >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> lst.append(6) >>> lst [1, 2, 3, 7, 8, 9, 6] >>> list.append(lst, 5) >>> lst [1, 2, 3, 7, 8, 9, 6, 5] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> lst.append(6) >>> lst [1, 2, 3, 7, 8, 9, 6] >>> >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> lst.sort() >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list.sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> A class method is really a function defined in the class namespace; when Python executes it first translates it to and actually executes this last statement instance.method(arg1, arg2, …) lst.append(6) lst.sort() class.method(instance, arg1, arg2, …) list.append(lst, 6) list.sort(lst) The function has an extra argument, which is the object invoking the method __add__ x count pop . . . namespace list sort() __add__() count() pop()

  20. Exercise Introduction to Computing Using Python Rewrite the below Python statement so that instead of making the usual method invocations you use the notation instance.method(arg1, arg2, …) lst.append(6) lst.sort() class.method(instance, arg1, arg2, …) list.append(lst, 6) list.sort(lst) >>> s = 'hello' >>> s = 'ACM' >>> s.lower() 'acm' >>> s.find('C') 1 >>> s.replace('AC', 'IB') 'IBM' >>> s = 'ACM' >>> str.lower(s) 'acm' >>> str.find(s, 'C') 1 >>> str.replace(s, 'AC', 'IB') 'IBM' >>>

More Related