contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : }
|
|
- Nickolas Robinson
- 6 years ago
- Views:
Transcription
1 Chapter 8 More Data Structures We have seen the list data structure and its uses. We will now examine two, more advanced data structures: the set and the dictionary. In particular, the dictionary is an important, very useful part of Python as well as generally useful to solve many problems. 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. Key Value Pairs 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. Python Dictionary Use the { } marker to create a dictionary Use the : marker to indicate key:value pairs: contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : } Keys and Values Key must be immutable: strings, integers, tuples are fine lists are NOT Value can be anything. 1
2 Collection but not a 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? Access Dictionary Elements 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 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 2 mydict[ bill ] = 100 print mydict[ bill ] # prints 100 Again, Common 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 Lots of Methods 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 2
3 Dictionaries are Iterable 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 Building Dictionaries Faster zip creates pairs from two parallel lists: zip( abc,[1,2,3]) yields [( a,1),( b,2),( c,3)] 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} Word Frequency Analysis of Gettysburg Address def addword(w, wcdict): '''Update the word frequency: word is the key, frequency is the value.''' if w in wcdict: wcdict[w] += 1 else: wcdict[w] = 1 import string def processline(line, wcdict): '''Process the line to get lowercase words to add to the dictionary.''' line = line.strip() wordlist = line.split() for word in wordlist: # ignore the '--' that is in the file if word!= '--': word = word.lower() word = word.strip() # get commas, periods and other punctuation out as well word = word.strip(string.punctuation) addword(word, wcdict) def prettyprint(wcdict): '''Print nicely from highest to lowest frequency.''' # create a list of tuples, (value, key) # valkeylist = [(val,key) for key,val in d.items()] valkeylist=[] for key,val in wcdict.items(): valkeylist.append((val,key)) # sort method sorts on list's first element, here the frequency. # Reverse to get biggest first valkeylist.sort(reverse=true) print '%-10s%10s'%('Word', 'Count') print '_'*21 for val,key in valkeylist: print '%-12s %3d'%(key,val) 3
4 sort(...) L.sort(cmp=None, key=none, reverse=false) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 def main (): wcdict={} fobj = open('gettysburg.txt','r') for line in fobj: processline(line, wcdict) print 'Length of the dictionary:',len(wcdict) prettyprint(wcdict) Passing Mutables Because we are passing a mutable data structure, such as a dictionary, we do not have to return the dictionary when the function ends. If all we do is update the dictionary (change the object) then the argument will be associated with the changed object. The only built-in sort method works on lists, so if we sort we must sort a list. For complex elements (like a tuple), the sort compares the first element of each complex element: (1, 3) < (2, 1) # True (3,0) < (1,2,3) # False Sets, as in Mathematical Sets In mathematics, a set is a collection of objects, potentially of many different types. In a set, no two elements are identical. That is, a set consists of elements each of which is unique compared to the other elements. There is no order to the elements of a set A set with no elements is the empty set Creating a Set myset = set( abcd ) The set keyword creates a set. The single argument that follows must be iterable, that is, something that can be walked through one item at a time with a for. The result is a set data structure: print myset set(['a', 'c', 'b', 'd']) Diverse Elements A set can consist of a mixture of different types of elements: myset = set([ a,1, ,true]) As long as the single argument can be iterated through, you can make a set of it. Duplicates are automatically removed. myset = set( aabbccdd ) print myset set(['a', 'c', 'b', 'd']) 4
5 Common 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 Set Operators The set data structure provides some special operators that correspond to the operators you learned in middle school. These are various combinations of set contents. Unlike most Python names, these are full names (this changes in Python 3.x). Set Ops, Intersection myset=set( abcd ); newset=set( cdef ) myset.intersection(newset) # returns set([ c, d ]) Set Ops, Difference myset=set( abcd ); newset=set( cdef ) myset.difference(newset) # returns set([ a, b ]) Set Ops, Union myset=set( abcd ); newset=set( cdef ) myset.union(newset) # returns set([ a, b, c, d, e, f ]) Set Ops, symmetricdifference myset=set( abcd ); newset=set( cdef ) myset.symmetric_difference(newset) # returns set([ a, b, e, f ]) Set Ops, super and sub set myset=set( abc ); newset=set( abcdef ) myset.issubset(newset) # returns True newset.issuperset(myset) # returns True Other Set Ops myset.add( g ) Adds to the set, no effect if item is in set already. myset.clear() Empties the set. myset.remove( g ) versus myset.discard( g ) remove throws an error if g isn t there. discard doesn t care. Both remove g from the set. myset.copy() - Returns a shallow copy of myset. 5
6 Common/Unique Words def addword(w, theset): '''A the word to the set. if len(w) > 3: theset.add(w) No word smaller than length 3.''' def processline(line, theset): '''Process the line to get lowercase words to be added to the set.''' line = line.strip() wordlist = line.split() for word in wordlist: # ignore the '--' thatt is in the file if word!= '--': word = word.strip( () # get commas, periods and other punctuation out as well word = word.strip( (string.punctuation) word = word.lower( () addword(word, theset) def main (): '''Compare the Gettysburg Address and the Declaration of Independence.''' GASet = set() DoISet = set() GAFileObj = open('gettysburg.txt') DoIFileObj = open('declofind.txt') for line in GAFileObj: processline(line, GASet) for line in DoIFileObj: processline(line,doiset) prettyprint(gaset, DoISet) 6
7 def prettyprint(gaset, doiset): # print some stats about the two sets print 'Count of unique words of length 4 or greater' print 'Gettysburg Addr: %d, Decl of Ind: %d\n'%(len(gaset),len(doiset)) print '%15s %15s'%('Operation', 'Count') print '-'*35 print '%15s %15d'%('Union', len(gaset.union(doiset))) print '%15s %15d'%('Intersection', len(gaset.intersection(doiset))) print '%15s %15d'%('Sym Diff', len(gaset.symmetric_difference(doiset))) print '%15s %15d'%('GA-DoI', len(gaset.difference(doiset))) print '%15s %15d'%('DoI-GA', len(doiset.difference(gaset))) # list the intersection words, 5 to a line, alphabetical order intersectionset = gaset.intersection(doiset) wordlist = list(intersectionset) wordlist.sort() print '\n Common words to both' print '-'*20 cnt = 0 for w in wordlist: if cnt % 5 == 0: print print '%13s'% (w), cnt += 1 Common words in Gettysburg Address and Declaration of Independence Can reuse or only slightly modify much of the code for document frequency. The overall outline remains much the same. For clarity, we will ignore any word that has three characters or less (typically stop words). More on Scope What is a Namespace? We ve had this discussion, but let s review: A namespace is an association of a name and a value. It looks like a dictionary, and for the most part it is (at least for modules and classes). Scope What namespace you might be using is part of identifying the scope of the variables and function you are using. By scope, we mean the context, the part of the code, where we can make a reference to a variable or function. Multiple Scopes Often, there can be multiple scopes that are candidates for determining a reference. Knowing which one is the right one (or more importantly, knowing the order of scope) is important. Two Kinds of Namespaces Unqualified namespaces: this is what we have pretty much seen so far - functions, assignments, etc. Qualified namespaces: these are modules and classes (we ll talk more about this one later in the Classes section). Unqualified This is the standard assignment and def we have seen so far. 7
8 Determining the scope of a reference identifies what its true value is. Unqualified Follow the LEGB Rule Local - inside the function in which it was defined. If not there, enclosing/encompassing. Is it defined in an enclosing function? If not there, is it defined in the global namespace? Finally, check the built-in, defined as part of the special builtin scope. Else, ERROR. Local def myfn (myparam = 25): print myparam myfn(100) # prints 100 myparam # ERROR Function Local Values If a reference is assigned in a function, then that reference is only available within that function. If a reference with the same name is provided outside the function, the reference is reassigned. Local and Global myvar = 123 # global def myfn(myvar=456): # parameter is local yourvar = -10 # assignment local print myvar, yourvar myfn() # prints myfn(500) # prints myvar # prints 123 yourvar # ERROR Builtin This is just the standard library of Python. To see what is there, look at import builtin dir( builtin ) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', ' debug ', ' doc ', ' import ', ' name ', ' package ', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] 8
9 The Global Statement You can cheat by using the global keyword in a function: myvar = 100 def myfn(): global myvar myvar = -1 myfn() print myvar # prints -1 Nested Functions Look up through the nested functions to find a binding: def afunc(): x = 5 def bfunc(): # x = 10 print x bfunc() afunc() # prints 5 bfunc() ERROR, bfunc not defined 9
More Data Structures. What is a Dictionary? Dictionaries. Python Dictionary. Key Value Pairs 10/21/2010
The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 8 Dictionaries and Sets More Data Structures We have seen the list data structure and its uses. We will now examine two, more
More informationModules and scoping rules
C H A P T E R 1 1 Modules and scoping rules 11.1 What is a module? 106 11.2 A first module 107 11.3 The import statement 109 11.4 The module search path 110 11.5 Private names in modules 112 11.6 Library
More informationCSCE 110 Programming I
CSCE 110 Programming I Basics of Python (Part 3): Functions, Lists, For Loops, and Tuples Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2014 Tiffani
More informationBeyond Blocks: Python Session #1
Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike
More informationPython Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8
Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,
More informationLecture 8: A cure for what ails you
Lecture 8: A cure for what ails you When human beings acquired language, we learned not just how to listen but how to speak. When we gained literacy, we learned not just how to read but how to write.
More informationException Handling and Debugging
Exception Handling and Debugging Any good program makes use of a language s exception handling mechanisms. There is no better way to frustrate an end-user then by having them run into an issue with your
More informationPython Reference (The Right Way) Documentation
Python Reference (The Right Way) Documentation Release 0.1 Jakub Przywóski Sep 30, 2017 Contents 1 Contents 1 1.1 Introduction............................................... 1 1.2 Definitions................................................
More informationPython File Modes. Mode Description. Open a file for reading. (default)
UNIT V FILES, MODULES, PACKAGES Files and exception: text files, reading and writing files, format operator; command line arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative
More informationPython. Executive Summary
Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"
More informationOverview. Recap of FP Classes Instances Inheritance Exceptions
Overview Recap of FP Classes Instances Inheritance Exceptions [len(s) for s in languages] ["python", "perl", "java", "c++"] map(len, languages) < 6, 4, 4, 3> [num for num in fibs if is_even(num)] [1, 1,
More informationPython Intro GIS Week 1. Jake K. Carr
GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes
More informationSBT 645 Introduction to Scientific Computing in Sports Science #6
SBT 645 Introduction to Scientific Computing in Sports Science #6 SERDAR ARITAN serdar.aritan@hacettepe.edu.tr Biyomekanik Araştırma Grubu www.biomech.hacettepe.edu.tr Spor Bilimleri Fakültesi www.sbt.hacettepe.edu.tr
More informationCS Lecture 26: Grab Bag. Announcements
CS 1110 Lecture 26: Grab Bag Announcements The End is Nigh! 1. Next (last) lecture will be recap and final exam review 2. A5 due Wednesday night 3. Final exam 7pm Thursday May 15 in Barton Hall (East section)
More informationAdvanced Python. Executive Summary, Session 1
Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.
More informationbioengineering-book Documentation
bioengineering-book Documentation Release 0.1 Thiranja Prasad Babarenda Gamage Sep 15, 2017 Contents 1 Introduction 3 2 Linux FAQ 5 2.1 Find files in a terminal..........................................
More informationPython 3000 and You. Guido van Rossum PyCon March 14, 2008
Python 3000 and You Guido van Rossum PyCon March 14, 2008 Why Py3k Open source needs to move or die Matz (creator of Ruby) To fix early, sticky design mistakes e.g. classic classes, int division, print
More informationPython. Karin Lagesen.
Python Karin Lagesen karin.lagesen@bio.uio.no Plan for the day Basic data types data manipulation Flow control and file handling Functions Biopython package What is programming? Programming: ordered set
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationThere are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:
Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited
More informationData Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.
Data Structures Lists - stores a series of ordered mutable items Tuples - stores a series of ordered immutable items [not commonly used] Sets - stores a series of mutable or immutable(frozen) unsorted
More information\n is used in a string to indicate the newline character. An expression produces data. The simplest expression
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationCIS192 Python Programming
CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1
More informationCIS192 Python Programming
CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline
More informationCIS192 Python Programming
CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline
More informationData Structures. Lists, Tuples, Sets, Dictionaries
Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,
More informationCS2304: Python for Java Programmers. CS2304: Sequences and Collections
CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for
More informationCIS192 Python Programming
CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018
More informationPython Evaluation Rules
Python Evaluation Rules UW CSE 160 https://courses.cs.washington.edu/courses/cse160/15sp/ Michael Ernst and Isaac Reynolds mernst@cs.washington.edu April 1, 2015 Contents 1 Introduction 2 1.1 The Structure
More informationLECTURE 3 Python Basics Part 2
LECTURE 3 Python Basics Part 2 FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for the use of a special kind of function, a lambda function.
More informationLecture #12: Quick: Exceptions and SQL
UC Berkeley EECS Adj. Assistant Prof. Dr. Gerald Friedland Computational Structures in Data Science Lecture #12: Quick: Exceptions and SQL Administrivia Open Project: Starts Monday! Creative data task
More informationExceptions & a Taste of Declarative Programming in SQL
Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts
More informationCSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria
CSE 399-004: Python Programming Lecture 5: Course project and Exceptions February 12, 2007 Announcements Still working on grading Homeworks 3 and 4 (and 2 ) Homework 5 will be out by tomorrow morning I
More informationCNRS ANF PYTHON Objects everywhere
CNRS ANF PYTHON Objects everywhere Marc Poinot Numerical Simulation Dept. Outline Python Object oriented features Basic OO concepts syntax More on Python classes multiple inheritance reuse introspection
More informationIterators & Generators
Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:
More informationPython Tutorial. Day 1
Python Tutorial Day 1 1 Why Python high level language interpreted and interactive real data structures (structures, objects) object oriented all the way down rich library support 2 The First Program #!/usr/bin/env
More informationCOMP 204: Sets, Commenting & Exceptions
COMP 204: Sets, Commenting & Exceptions Yue Li based on material from Mathieu Blanchette, Carlos Oliver Gonzalez and Christopher Cameron 1/29 Outline Quiz 14 review Set Commenting code Bugs 2/29 Quiz 15
More informationPython 3000 and You. Guido van Rossum EuroPython July 7, 2008
Python 3000 and You Guido van Rossum EuroPython July 7, 2008 Why Py3k Open source needs to move or die Matz (creator of Ruby) To fix early, sticky design mistakes e.g. classic classes, int division, print
More informationPython. How You Can Do More Interesting Things With Python (Part II)
Python How You Can Do More Interesting Things With Python (Part II) Python for Statement for in : statement-block my_dict = { k1 : 1, k2 : 2 } for (k,v) in my_dict.items(): print(
More informationMEIN 50010: Python Flow Control
: Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-11 Program Overview Program Code Block Statements Expressions Expressions & Statements An expression has
More informationThe Big Python Guide
The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String
More informationCOMP519 Web Programming Lecture 20: Python (Part 4) Handouts
COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents
More information06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python
CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison
More informationToday: Revisit some objects. Programming Languages. Key data structure: Dictionaries. Using Dictionaries. CSE 130 : Winter 2009
CSE 130 : Winter 2009 Programming Languages Lecture 11: What s in a Name? Today: Revisit some objects Exploit features and build powerful expressions Base: int, float, complex Sequence: string, tuple,
More informationCollections. Lists, Tuples, Sets, Dictionaries
Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again
More informationCIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani
CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 1 / 34
More informationExceptions CS GMU
Exceptions CS 112 @ GMU Exceptions When an unrecoverable action takes place, normal control flow is abandoned: an exception value crashes outwards until caught. various types of exception values can be
More informationData type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.
NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike
More informationInteractive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D
1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.
More informationPart IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,
Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith ("
More informationInteractive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D
1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.
More informationPython Programming: Lecture 2 Data Types
Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float)
More informationCIS192 Python Programming
CIS192 Python Programming Data Types Joseph Cappadona University of Pennsylvania September 03, 2015 Joseph Cappadona (University of Pennsylvania) CIS 192 September 03, 2015 1 / 32 Outline 1 Data Types
More informationIndex. Cache, 20 Callables, 185 call () method, 290 chain() function, 41 Classes attributes descriptors, 145 properties, 143
Index A add_column() method, 284 add() method, 44 addtypeequalityfunc() method, 253 Affero General Public License (AGPL), 260 American Standard Code for Information Interchange (ASCII), 218 219 and operator,
More informationAbsent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99
1. A function is a procedural abstract (a named body of code to perform some action and return a resulting value). The syntax of a function definition is: def functionname([parameter [, parameter]*]):
More informationTHE CONTENT OF THIS BOOK IS PROVIDED UNDER THE TERMS OF THE CREATIVE COMMONS PUBLIC LICENSE BY-NC-ND 3.0.
M A S S I M O D I P I E R R O W E B A U T O M AT I O N W I T H P Y T H O N E X P E R T S 4 S O L U T I O N S Copyright 2008-2013 by Massimo Di Pierro. All rights reserved. THE CONTENT OF THIS BOOK IS PROVIDED
More informationChapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.
Chapter 8 Dictionaries Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values. Creating a Dictionary To create a dictionary, you need
More information(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.
Basics of Python - 2 by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 54 Sunday 16 February 2014 05:30 PM Our First Program - Rewritten! Let us introduce the following
More informationLecture 21. Programming with Subclasses
Lecture 21 Programming with Subclasses Announcements for This Lecture Assignments Prelim 2 A4 is now graded Mean: 90.4 Median: 93 Std Dev: 10.6 Mean: 9 hrs Median: 8 hrs Std Dev: 4.1 hrs A5 is also graded
More informationSharing, mutability, and immutability. Ruth Anderson UW CSE 160 Spring 2018
Sharing, mutability, and immutability Ruth Anderson UW CSE 160 Spring 2018 1 Copying and mutation See in python tutor list1 = ["e1", "e2", "e3", "e4"] list2 = list1 list3 = list(list1) # make a copy; also
More informationCOMP 204: Sets, Commenting & Exceptions
COMP 204: Sets, Commenting & Exceptions Material from Carlos G. Oliver, Christopher J.F. Cameron October 12, 2018 1/31 Reminder CSUS is holding a midterm review session on Monday, October 15th, from 6-9pm.
More informationLecture 21. Programming with Subclasses
Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 10 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops
More informationCollections. Michael Ernst CSE 190p University of Washington
Collections Michael Ernst CSE 190p University of Washington Needed for Homework 4 (social networking assignment) Collections: lists, sets, dictionaries Sorting Graphs Outline for today Collections (built-in
More informationCOMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling
COMP1730/COMP6730 Programming for Scientists Exceptions and exception handling Lecture outline * Errors * The exception mechanism in python * Causing exceptions (assert and raise) * Handling exceptions
More informationLecture 18. Classes and Types
Lecture 18 Classes and Types Announcements for Today Reading Today: See reading online Tuesday: See reading online Prelim, Nov 6 th 7:30-9:30 Material up to next class Review posted next week Recursion
More informationPython Tutorial. Day 2
Python Tutorial Day 2 1 Control: Whitespace in perl and C, blocking is controlled by curly-braces in shell, by matching block delimiters, if...then...fi in Python, blocking is controlled by indentation
More information(CC)A-NC 2.5 by Randall Munroe Python
http://xkcd.com/353/ (CC)A-NC 2.5 by Randall Munroe Python Python: Operative Keywords Very high level language Language design is focused on readability Mulit-paradigm Mix of OO, imperative, and functional
More informationThe Practice of Computing Using PYTHON
The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures
More informationIntroduction to Python programming, II
GC3: Grid Computing Competence Center Introduction to Python programming, II (with a hint of MapReduce) Riccardo Murri Grid Computing Competence Center, University of Zurich Oct. 10, 2012 Today s class
More informationENGR 102 Engineering Lab I - Computation
ENGR 102 Engineering Lab I - Computation Week 07: Arrays and Lists of Data Introduction to Arrays In last week s lecture, 1 we were introduced to the mathematical concept of an array through the equation
More informationSenthil Kumaran S
Senthil Kumaran S http://www.stylesen.org/ Agenda History Basics Control Flow Functions Modules History What is Python? Python is a general purpose, object-oriented, high level, interpreted language Created
More informationCOMP 204: Dictionaries Recap & Sets
COMP 204: Dictionaries Recap & Sets Material from Carlos G. Oliver, Christopher J.F. Cameron October 10, 2018 1/21 Reminder Midterm on Wednesday October 17 at 6:30-8:00 pm. Assignment 2: numpy is allowed
More informationPython for Non-programmers
Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013
More informationExceptions & error handling in Python 2 and Python 3
Exceptions & error handling in Python 2 and Python 3 http://www.aleax.it/pycon16_eh.pdf 2016 Google -- aleax@google.com 1 Python in a Nutshell 3rd ed Chapter 5 of Early Release e-book version 50% off:
More informationCS Summer 2013
CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or
More informationExam #3, Form 3 A CSE 231 Fall 2015 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.
Name: Section: Date: INSTRUCTIONS: (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN. (2) Please fill in the requested information at the top of this exam booklet. (3) Use a #2 pencil
More informationOutline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions
Outline 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating
More information1 Strings (Review) CS151: Problem Solving and Programming
1 Strings (Review) Strings are a collection of characters. quotes. this is a string "this is also a string" In python, strings can be delineated by either single or double If you use one type of quote
More informationPython and Bioinformatics. Pierre Parutto
Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................
More informationFunctions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala
Functions, Scope & Arguments HORT 59000 Lecture 12 Instructor: Kranthi Varala Functions Functions are logical groupings of statements to achieve a task. For example, a function to calculate the average
More informationPYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s
PYTHON FO R K I D S A P l ay f u l I n t r o d u c t i o n to P r o g r a m m i n g Jason R. Briggs Index Symbols and Numbers + (addition operator), 17 \ (backslash) to separate lines of code, 235 in strings,
More informationLecture 21. Programming with Subclasses
Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 9 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops
More informationIntroduction to Python programming, II
Grid Computing Competence Center Introduction to Python programming, II Riccardo Murri Grid Computing Competence Center, Organisch-Chemisches Institut, University of Zurich Nov. 16, 2011 Today s class
More informationSingle Source Python 2 3
Single Source Python 2 3 May 21, 2016 1 Single Source Python 2/3 1.1 A Tutorial at PyData Berlin Dr. Mike Müller Python Academy GmbH & Co. KG mmueller@python-academy.de @pyacademy PyData Berlin 2016 Berlin,
More informationUniversity of Texas at Arlington, TX, USA
Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS,
More informationSoftware Development Python (Part B)
Software Development Python (Part B) Davide Balzarotti Eurecom 1 List Comprehension It is a short way to construct a list based on the content of other existing lists Efficient Elegant Concise List comprehensions
More informationCIS192: Python Programming
CIS192: Python Programming Introduction Harry Smith University of Pennsylvania January 18, 2017 Harry Smith (University of Pennsylvania) CIS 192 Lecture 1 January 18, 2017 1 / 34 Outline 1 Logistics Rooms
More informationPart I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming
2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float
More informationPython Review IPRE
Python Review 2 Jay Summet 2005-12-31 IPRE Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries
More informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More informationCS1 Lecture 3 Jan. 22, 2018
CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow
More informationExceptions and File I/O
Lab 6 Exceptions and File I/O Lab Objective: In Python, an exception is an error detected during execution. Exceptions are important for regulating program usage and for correctly reporting problems to
More informationJohn Perry. Fall 2009
Lecture 5: Sage University of Southern Mississippi Fall 2009 Outline 1 2 3 4 You should be in worksheet mode to repeat the examples. Collections? Collection: group of objects identified as single object
More informationSequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python
Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted
More informationNotebook. March 30, 2019
Notebook March 30, 2019 1 Complex Data Types Some kinds of data can store other kinds of data. 1.1 Lists We ve actually seen the most common complex data type a few times before, I just haven t pointed
More informationChapter 9: Dealing with Errors
Chapter 9: Dealing with Errors What we will learn: How to identify errors Categorising different types of error How to fix different errors Example of errors What you need to know before: Writing simple
More informationAn Introduction to Python
An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many
More informationDEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A
DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.
More informationAnnouncements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration
COMP10001 Foundations of Computing Iteration Announcements Semester 1, 2017 Tim Baldwin & Egemen Tanin First Guest Lecture on Friday (examinable) Grok Worksheets 5 7 due at the end of this week version:
More informationBasic Python Revision Notes With help from Nitish Mittal
Basic Python Revision Notes With help from Nitish Mittal HELP from Documentation dir(module) help() Important Characters and Sets of Characters tab \t new line \n backslash \\ string " " or ' ' docstring
More information