The Python Data Model UW CSE 190p Summer 2012.

Slides:



Advertisements
Similar presentations
List comprehensions UW CSE 140 Winter Ways to express a list 1.Explicitly write the whole thing: squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81,
Advertisements

ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Lilian Blot PART III: ITERATIONS Core Elements Autumn 2012 TPOP 1.
Container Types in Python
Introduction to Computing Using Python Imperative Programming  Python Programs  Interactive Input/Output  One-Way and Two-Way if Statements  for Loops.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Title An Introduction to Python. What is Python exactly? Python is a modern rapid development language. Code is very clean and easy to read. Emphasizes.
Data Structures UW CSE 190p Summer >>> xs = range(3) >>> xs = [1,2,3] >>> xs = [‘a’,’b’,’c’] >>> xs = [1, ‘a’, 3] >>> xs = [[1,2,3], [‘a’,’b’,’c’]]
Introduction to Python (for C++ programmers). Background Information History – created in December 1989 by Guido van Rossum Interpreted Dynamically-typed.
Recitation 1 Programming for Engineers in Python.
Python Control of Flow.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
UW CSE 190p Section 8/2, Summer 2012 Dun-Yu Hsiao.
Built-in Data Structures in Python An Introduction.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
List comprehensions (and other shortcuts) UW CSE 160 Spring 2015.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 10 Iteration: Loops 05/02/09 Python Mini-Course: Day 3 - Lesson 10 1.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
Dictionaries Ruth Anderson CSE 160 University of Washington 1.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Dictionaries Ruth Anderson UW CSE 160 Winter
Xi Wang Yang Zhang. 1. Strings 2. Text Files 3. Exceptions 4. Classes  Refer to basics 2.py for the example codes for this section.
Equality, references and mutability COMPSCI 105 SS 2015 Principles of Computer Science.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Based on slides by Shawn.
Catapult Python Programming Wednesday Morning session
Sharing, mutability, and immutability
CSc 120 Introduction to Computer Programing II Adapted from slides by
Python Let’s get started!.
Computer Programming Fundamentals
Catapult Python Programming Thursday Session
Basic operators - strings
Topic: Functions – Part 2
Sharing, mutability, and immutability
Ruth Anderson UW CSE 160 Spring 2018
Ruth Anderson UW CSE 160 Winter 2017
Ruth Anderson UW CSE 160 Winter 2017
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
Introduction to Python
Sharing, mutability, and immutability
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
Sharing, mutability, and immutability
Ruth Anderson UW CSE 140 Winter 2014
I210 review.
CS 1111 Introduction to Programming Fall 2018
Sharing, mutability, and immutability
Control flow : if statements
Ruth Anderson UW CSE 160 Winter 2017
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Building Java Programs
Python Primer 1: Types and Operators
Sharing, mutability, and immutability
Michael Ernst CSE 140 University of Washington
Michael Ernst CSE 140 University of Washington
Reference semantics, variables and names
G. Pullaiah College of Engineering and Technology
(more) Python.
Dictionaries: Keeping track of pairs
For loops Taken from notes by Dr. Neil Moore
CISC101 Reminders Assignment 2 due today.
Ruth Anderson CSE 160 University of Washington
By Ryan Christen Errors and Exceptions.
Python Review
Ruth Anderson UW CSE 160 Spring 2018
Python fundamental.
Ruth Anderson UW CSE 160 Winter 2016
Control 9 / 25 / 19.
Presentation transcript:

The Python Data Model UW CSE 190p Summer 2012

>>> conjugations = { “see”:[“saw”, “sees”], “walk”:[”walked”, “walks”] “do”:[”did”, “does”] “be”:[“was”, “is”] } >>> conjugations[“see”] ??? >>> conjugations[“walk”][1] >>> conjugations[“walk”][1][0] >>> [word[0] for word in conjugations[“be”]] >>> [pair for pair in conjugations.items()][0] >>> [(pair[0][0], pair[1][0][0]) for pair in conjugations.items()][1] >>> {pair[0]:pair[1] for pair in conjugations.items()}

>>> def double(x): ... print “double:”, x + x ... >>> print double(2) ???

Types: some definitions and context Some historical languages were untyped You could, say, divide a string by a number, and the program would continue. The result was still nonsense, of course, and program behavior was completely undefined. This was considered unacceptable Modern languages may be staticly typed or dynamically typed “staticly typed” means that types are assigned before the program is executed “dynamically typed” means that types are assigned (and type errors caught) at runtime Modern languages may be strongly typed or weakly typed For our purposes, “weakly typed” means the language supports a significant number of implicit type conversions. For example, (5 + “3”) could trigger a conversion from “3” to 3 For our purposes, Python can be considered strongly typed dynamically typed

Guess the Types def mbar_to_mmHg(pressure): return pressure * 0.75006

Guess the Types def abs(x): if val < 0: return -1 * val else:

Guess the Types def debug(x): print x

Guess the Type def index(value, somelist): i = 0 for c in somelist: if c == value: return i i = i + 1

Duck Typing “If it walks like a duck and it talks like a duck, then it must be a duck.” (Note: this analogy can be misleading!) At runtime, the operands are checked to make sure they support the requested operation. >>> 3 + “3” >>> for i in 5: ... print i

Takeaway Think about types when designing functions, when debugging, when reading code, when writing code….all the time. Ask yourself “What operations are being applied to this variable?” and “What values may this variable hold?” A list, or just anything compatible with a for loop? An integer, or anything that can be multiplied by an integer?

Mutable and Immutable Types >>> def increment(uniquewords, word): ... “““increment the count for word””” ... uniquewords[word] = uniquewords.setdefault(word, 1) + 1 >>> mywords = dict() >>> increment(mywords, “school”) >>> print mywords {'school': 2} >>> def increment(value): ... “““increment the value???””” ... value = value + 1 >>> myval = 5 >>> increment(myval) >>> print myval 5

What’s going on? Python’s Data Model Everything is an object Each object has an identity, a type, and a value id(obj) returns the object’s identity type(obj) returns the object’s type

Identity The identity of an object can never change (Currently) implemented as the object’s address in memory. You can check to see if two objects are identical with the keyword is

Identity >>> A = [1] >>> B = [1] >>> A == B True >>> A is B False >>> C = A >>> A is C ???? >>> A = [1] >>> B = [1] >>> A == B True >>> A is B False

Type The type of an object cannot change It specifies two things: what operations are allowed the set of values the object can hold

Back to the Data Model Everything is an object Each object has an identity, a type, and a value id(obj) returns the object’s identity type(obj) returns the object’s type An object’s identity can never change An object’s type can never change An object’s value can never change, unless it has a mutable type

Example: Tuples vs. Lists def updaterecord(record, position, value): “““change the value at the given position””” record[position] = value mylist = [1,2,3] mytuple = (1,2,3) updaterecord(mylist, 1, 10) print mylist updaterecord(mytuple, 1, 10) print mytuple

Why did they do this? >>> citytuple = (“Atlanta”, “GA”) >>> type(citytuple) <type 'tuple’> >>> citylist = [“Atlanta”, “GA”] <type ’list'> >>> weather[citytuple] = “super hot” >>> weather[citylist] = “super hot” Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'

What would this mean? >>> citylist = [“Atlanta”, “GA”] >>> weather[citylist] = “super hot” >>> citylist[1] = “Georgia” >>> weather[[“Atlanta”, “GA”]] ???

Mutable and Immutable Types numbers, strings, tuples Mutable lists and dictionaries Note: a set is mutable, but a frozenset is immutable

Comprehension Example names = [“John von Neumann”, “Grace Hopper”, “Alan Turing”, “Charles Babbage”, “Ada Lovelace”] split_names = [name.split(“ “) for name in names] last_names = [split_name[1] for split_name in split_names] last_name_first = [sn[1] + “, “ + sn[0] for sn in split_names]

Digression: More with Comprehensions You are given a function def sim(sequence1, sequence2) “””Return a number representing the similarity score between the two arguments“”” … You are given two lists of sequences org1 = [“ACGTTTCA”, “AGGCCTTA”, “AAAACCTG”] org2 = [“AGCTTTGA”, “GCCGGAAT”, “GCTACTGA”] You want to find all pairs of similar sequences: similarity(A,B) > threshold [(x,y) for x in org1 for y in org2 if sim(x,y) > threshold]

Evaluating Comprehensions [(x,y) for x in org1 for y in org2 if sim(x,y) > threshold] an expression something that can be iterated zero or more if clauses for clause (required) assigns value to the variable x zero or more aditional for clauses