Working with Lists 4

Similar documents
CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013

61A LECTURE 8 SEQUENCES, ITERABLES

61A LECTURE 8 SEQUENCES, ITERABLES. Steven Tang and Eric Tzeng July 8, 2013

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Python List built-in methods, accessing elements, selection, slicing, recursive functions, list comprehension

Chapter 2: Building Abstractions with Data

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Teaching London Computing

Chapter 2: Building Abstractions with Objects

Introduction to Bioinformatics

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

CS1 Lecture 12 Feb. 11, 2019

Functional programming in LISP

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

CPSC 217 Midterm (Python 3 version)

Python Basics. Lecture and Lab 5 Day Course. Python Basics

Babu Madhav Institute of Information Technology, UTU 2015

Full file at C How to Program, 6/e Multiple Choice Test Bank

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Introduction to Python: Data types. HORT Lecture 8 Instructor: Kranthi Varala

ENGR 101 Engineering Design Workshop

Lecture 16: Static Semantics Overview 1

G Programming Languages - Fall 2012

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Advanced Algorithms and Computational Models (module A)

Shell CSCE 314 TAMU. Haskell Functions

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Scheme as implemented by Racket

Homework 7: Subsets Due: 11:59 PM, Oct 23, 2018

61A Lecture 6. Friday, September 7

CS1 Lecture 3 Jan. 18, 2019

VHDL Lexical Elements

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections)

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Introduction to Scheme

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

CS1 Lecture 3 Jan. 22, 2018

Python Evaluation Rules

Chapter 17. Fundamental Concepts Expressed in JavaScript

Lecture 3. Input, Output and Data Types

CSCE 110 Programming I

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

ENGR 102 Engineering Lab I - Computation

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

CSE : Python Programming

Announcements for this Lecture

In addition to the primary macro syntax, the system also supports several special macro types:

Ruby: Introduction, Basics

C Basics. Chapter 2: C Basics. C Programming Language. v3.3 February 6, 2017

Lecture #12: Mutable Data. Last modified: Sun Feb 19 17:15: CS61A: Lecture #12 1

Introduction to Python

DSC 201: Data Analysis & Visualization

COMP1730/COMP6730 Programming for Scientists. Strings

Python in 10 (50) minutes

61A Lecture 3. Friday, September 5

Algorithmic Thinking: Computing with Lists

SECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING

PYTHON DATA SCIENCE TOOLBOX II. List comprehensions

Variables, Constants, and Data Types

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Learning Language. Reference Manual. George Liao (gkl2104) Joseanibal Colon Ramos (jc2373) Stephen Robinson (sar2120) Huabiao Xu(hx2104)

MUTABLE LISTS AND DICTIONARIES 4

Python Basics. 1 of 7 9/5/2018, 8:51 AM. txt1 = "ada lovelace, english mathematician and writer" print(txt1)

Level 3 Computing Year 2 Lecturer: Phil Smith

QUark Language Reference Manual

Copied from: on 3/20/2017

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

CMSC201 Computer Science I for Majors

And Parallelism. Parallelism in Prolog. OR Parallelism

SCHEME AND CALCULATOR 5b

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

Getting Started Values, Expressions, and Statements CS GMU

Chapter 2 Working with Data Types and Operators

Lecture 7: Lambda & Abstract Data Types

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

This exam is worth 70 points, or about 23% of your total course grade. The exam contains 15 questions.

CMSC201 Computer Science I for Majors

Lecture #12: Mutable Data. map rlist Illustrated (III) map rlist Illustrated. Using Mutability For Construction: map rlist Revisited

Lecture 10: Strings. CS1068+ Introductory Programming in Python. Dr Kieran T. Herley 2018/19. Department of Computer Science University College Cork

A Small Interpreted Language

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

61A Lecture 4. Monday, September 9

ENVIRONMENT DIAGRAMS AND RECURSION 2

LECTURE 3 Python Basics Part 2

CIS192: Python Programming

C311 Lab #3 Representation Independence: Representation Independent Interpreters

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Transcription:

CS 61A Lecture 10

Announcements

Lists ['Demo']

Working with Lists 4

Working with Lists >>> digits = [1, 8, 2, 8] 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] The number of elements 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] The number of elements >>> len(digits) 4 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] The number of elements >>> len(digits) 4 An element selected by its index 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] The number of elements >>> len(digits) 4 An element selected by its index >>> digits[3] 8 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] The number of elements >>> len(digits) 4 An element selected by its index >>> digits[3] 8 >>> getitem(digits, 3) 8 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] The number of elements >>> len(digits) 4 An element selected by its index >>> digits[3] 8 >>> getitem(digits, 3) 8 Concatenation and repetition 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] The number of elements >>> len(digits) 4 An element selected by its index >>> digits[3] 8 >>> getitem(digits, 3) 8 Concatenation and repetition >>> [2, 7] + digits * 2 [2, 7, 1, 8, 2, 8, 1, 8, 2, 8] 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] The number of elements >>> len(digits) 4 An element selected by its index >>> digits[3] 8 >>> getitem(digits, 3) 8 Concatenation and repetition >>> [2, 7] + digits * 2 [2, 7, 1, 8, 2, 8, 1, 8, 2, 8] >>> add([2, 7], mul(digits, 2)) [2, 7, 1, 8, 2, 8, 1, 8, 2, 8] 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] The number of elements >>> len(digits) 4 An element selected by its index >>> digits[3] 8 >>> getitem(digits, 3) 8 Concatenation and repetition >>> [2, 7] + digits * 2 [2, 7, 1, 8, 2, 8, 1, 8, 2, 8] >>> add([2, 7], mul(digits, 2)) [2, 7, 1, 8, 2, 8, 1, 8, 2, 8] Nested lists 4

Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] The number of elements >>> len(digits) 4 An element selected by its index >>> digits[3] 8 >>> getitem(digits, 3) 8 Concatenation and repetition >>> [2, 7] + digits * 2 [2, 7, 1, 8, 2, 8, 1, 8, 2, 8] >>> add([2, 7], mul(digits, 2)) [2, 7, 1, 8, 2, 8, 1, 8, 2, 8] Nested lists >>> pairs = [[10, 20], [30, 40]] >>> pairs[1] [30, 40] >>> pairs[1][0] 30 4

Containers

Containers 6

Containers Built-in operators for testing whether an element appears in a compound value 6

Containers Built-in operators for testing whether an element appears in a compound value >>> digits = [1, 8, 2, 8] 6

Containers Built-in operators for testing whether an element appears in a compound value >>> digits = [1, 8, 2, 8] >>> 1 in digits True 6

Containers Built-in operators for testing whether an element appears in a compound value >>> digits = [1, 8, 2, 8] >>> 1 in digits True >>> 8 in digits True 6

Containers Built-in operators for testing whether an element appears in a compound value >>> digits = [1, 8, 2, 8] >>> 1 in digits True >>> 8 in digits True >>> 5 not in digits True 6

Containers Built-in operators for testing whether an element appears in a compound value >>> digits = [1, 8, 2, 8] >>> 1 in digits True >>> 8 in digits True >>> 5 not in digits True >>> not(5 in digits) True 6

Containers Built-in operators for testing whether an element appears in a compound value >>> digits = [1, 8, 2, 8] >>> 1 in digits True >>> 8 in digits True >>> 5 not in digits True >>> not(5 in digits) True (Demo) 6

For Statements (Demo)

Sequence Iteration 8

Sequence Iteration def count(s, value): total = 0 for element in s: if element == value: total = total + 1 return total 8

Sequence Iteration def count(s, value): total = 0 for element in s: Name bound in the first frame of the current environment (not a new frame) if element == value: total = total + 1 return total 8

For Statement Execution Procedure 9

For Statement Execution Procedure for <name> in <expression>: <suite> 9

For Statement Execution Procedure for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which must yield an iterable value (a sequence) 9

For Statement Execution Procedure for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which must yield an iterable value (a sequence) 2. For each element in that sequence, in order: 9

For Statement Execution Procedure for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which must yield an iterable value (a sequence) 2. For each element in that sequence, in order: A. Bind <name> to that element in the current frame 9

For Statement Execution Procedure for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which must yield an iterable value (a sequence) 2. For each element in that sequence, in order: A. Bind <name> to that element in the current frame B. Execute the <suite> 9

Sequence Unpacking in For Statements 10

Sequence Unpacking in For Statements >>> pairs = [[1, 2], [2, 2], [3, 2], [4, 4]] >>> same_count = 0 10

Sequence Unpacking in For Statements A sequence of fixed-length sequences >>> pairs = [[1, 2], [2, 2], [3, 2], [4, 4]] >>> same_count = 0 10

Sequence Unpacking in For Statements A sequence of fixed-length sequences >>> pairs = [[1, 2], [2, 2], [3, 2], [4, 4]] >>> same_count = 0 >>> for x, y in pairs:... if x == y:... same_count = same_count + 1 >>> same_count 2 10

Sequence Unpacking in For Statements A sequence of fixed-length sequences >>> pairs = [[1, 2], [2, 2], [3, 2], [4, 4]] >>> same_count = 0 A name for each element in a fixed-length sequence >>> for x, y in pairs:... if x == y:... same_count = same_count + 1 >>> same_count 2 10

Sequence Unpacking in For Statements A sequence of fixed-length sequences >>> pairs = [[1, 2], [2, 2], [3, 2], [4, 4]] >>> same_count = 0 A name for each element in a fixed-length sequence Each name is bound to a value, as in multiple assignment >>> for x, y in pairs:... if x == y:... same_count = same_count + 1 >>> same_count 2 10

Ranges

The Range Type A range is a sequence of consecutive integers. * 12

The Range Type A range is a sequence of consecutive integers. * * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... range(-2, 2) * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... range(-2, 2) * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... range(-2, 2) * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... range(-2, 2) * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... Length: ending value - starting value range(-2, 2) * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... Length: ending value - starting value Element selection: starting value + index range(-2, 2) * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... Length: ending value - starting value Element selection: starting value + index range(-2, 2) >>> list(range(-2, 2)) [-2, -1, 0, 1] >>> list(range(4)) [0, 1, 2, 3] * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... Length: ending value - starting value Element selection: starting value + index range(-2, 2) >>> list(range(-2, 2)) [-2, -1, 0, 1] List constructor >>> list(range(4)) [0, 1, 2, 3] * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... Length: ending value - starting value Element selection: starting value + index range(-2, 2) >>> list(range(-2, 2)) [-2, -1, 0, 1] >>> list(range(4)) [0, 1, 2, 3] List constructor Range with a 0 starting value * Ranges can actually represent more general integer sequences. 12

The Range Type A range is a sequence of consecutive integers. *..., -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,... range(-2, 2) Length: ending value - starting value Element selection: starting value + index (Demo) >>> list(range(-2, 2)) [-2, -1, 0, 1] >>> list(range(4)) [0, 1, 2, 3] List constructor Range with a 0 starting value * Ranges can actually represent more general integer sequences. 12

List Comprehensions

List Comprehensions >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'm', 'n', 'o', 'p'] >>> [letters[i] for i in [3, 4, 6, 8]]

List Comprehensions >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'm', 'n', 'o', 'p'] >>> [letters[i] for i in [3, 4, 6, 8]] ['d', 'e', 'm', 'o']

List Comprehensions 14

List Comprehensions [<map exp> for <name> in <iter exp> if <filter exp>] 14

List Comprehensions [<map exp> for <name> in <iter exp> if <filter exp>] Short version: [<map exp> for <name> in <iter exp>] 14

List Comprehensions [<map exp> for <name> in <iter exp> if <filter exp>] Short version: [<map exp> for <name> in <iter exp>] A combined expression that evaluates to a list using this evaluation procedure: 14

List Comprehensions [<map exp> for <name> in <iter exp> if <filter exp>] Short version: [<map exp> for <name> in <iter exp>] A combined expression that evaluates to a list using this evaluation procedure: 1. Add a new frame with the current frame as its parent 14

List Comprehensions [<map exp> for <name> in <iter exp> if <filter exp>] Short version: [<map exp> for <name> in <iter exp>] A combined expression that evaluates to a list using this evaluation procedure: 1. Add a new frame with the current frame as its parent 2. Create an empty result list that is the value of the expression 14

List Comprehensions [<map exp> for <name> in <iter exp> if <filter exp>] Short version: [<map exp> for <name> in <iter exp>] A combined expression that evaluates to a list using this evaluation procedure: 1. Add a new frame with the current frame as its parent 2. Create an empty result list that is the value of the expression 3. For each element in the iterable value of <iter exp>: 14

List Comprehensions [<map exp> for <name> in <iter exp> if <filter exp>] Short version: [<map exp> for <name> in <iter exp>] A combined expression that evaluates to a list using this evaluation procedure: 1. Add a new frame with the current frame as its parent 2. Create an empty result list that is the value of the expression 3. For each element in the iterable value of <iter exp>: A. Bind <name> to that element in the new frame from step 1 14

List Comprehensions [<map exp> for <name> in <iter exp> if <filter exp>] Short version: [<map exp> for <name> in <iter exp>] A combined expression that evaluates to a list using this evaluation procedure: 1. Add a new frame with the current frame as its parent 2. Create an empty result list that is the value of the expression 3. For each element in the iterable value of <iter exp>: A. Bind <name> to that element in the new frame from step 1 B. If <filter exp> evaluates to a true value, then add the value of <map exp> to the result list 14

Strings

Strings are an Abstraction 16

Strings are an Abstraction Representing data: '200' '1.2e-5' 'False' '[1, 2]' 16

Strings are an Abstraction Representing data: '200' '1.2e-5' 'False' '[1, 2]' Representing language: """And, as imagination bodies forth The forms of things unknown, the poet's pen Turns them to shapes, and gives to airy nothing A local habitation and a name. """ 16

Strings are an Abstraction Representing data: '200' '1.2e-5' 'False' '[1, 2]' Representing language: """And, as imagination bodies forth The forms of things unknown, the poet's pen Turns them to shapes, and gives to airy nothing A local habitation and a name. """ Representing programs: 'curry = lambda f: lambda x: lambda y: f(x, y)' 16

Strings are an Abstraction Representing data: '200' '1.2e-5' 'False' '[1, 2]' Representing language: """And, as imagination bodies forth The forms of things unknown, the poet's pen Turns them to shapes, and gives to airy nothing A local habitation and a name. """ Representing programs: 'curry = lambda f: lambda x: lambda y: f(x, y)' (Demo) 16

String Literals Have Three Forms >>> 'I am string!' 'I am string!' >>> "I've got an apostrophe" "I've got an apostrophe" >>> ' ' ' ' 17

String Literals Have Three Forms >>> 'I am string!' 'I am string!' >>> "I've got an apostrophe" "I've got an apostrophe" Single-quoted and double-quoted strings are equivalent >>> ' ' ' ' 17

String Literals Have Three Forms >>> 'I am string!' 'I am string!' >>> "I've got an apostrophe" "I've got an apostrophe" Single-quoted and double-quoted strings are equivalent >>> ' ' ' ' >>> """The Zen of Python claims, Readability counts. Read more: import this.""" 'The Zen of Python\nclaims, Readability counts.\nread more: import this.' 17

String Literals Have Three Forms >>> 'I am string!' 'I am string!' >>> "I've got an apostrophe" "I've got an apostrophe" Single-quoted and double-quoted strings are equivalent >>> ' ' ' ' >>> """The Zen of Python claims, Readability counts. Read more: import this.""" 'The Zen of Python\nclaims, Readability counts.\nread more: import this.' A backslash "escapes" the following character 17

String Literals Have Three Forms >>> 'I am string!' 'I am string!' >>> "I've got an apostrophe" "I've got an apostrophe" Single-quoted and double-quoted strings are equivalent >>> ' ' ' ' >>> """The Zen of Python claims, Readability counts. Read more: import this.""" 'The Zen of Python\nclaims, Readability counts.\nread more: import this.' A backslash "escapes" the following character "Line feed" character represents a new line 17

Dictionaries {'Dem': 0}

Limitations on Dictionaries 19

Limitations on Dictionaries Dictionaries are unordered collections of key-value pairs 19

Limitations on Dictionaries Dictionaries are unordered collections of key-value pairs Dictionary keys do have two restrictions: 19

Limitations on Dictionaries Dictionaries are unordered collections of key-value pairs Dictionary keys do have two restrictions: A key of a dictionary cannot be a list or a dictionary (or any mutable type) 19

Limitations on Dictionaries Dictionaries are unordered collections of key-value pairs Dictionary keys do have two restrictions: A key of a dictionary cannot be a list or a dictionary (or any mutable type) Two keys cannot be equal; There can be at most one value for a given key 19

Limitations on Dictionaries Dictionaries are unordered collections of key-value pairs Dictionary keys do have two restrictions: A key of a dictionary cannot be a list or a dictionary (or any mutable type) Two keys cannot be equal; There can be at most one value for a given key This first restriction is tied to Python's underlying implementation of dictionaries 19

Limitations on Dictionaries Dictionaries are unordered collections of key-value pairs Dictionary keys do have two restrictions: A key of a dictionary cannot be a list or a dictionary (or any mutable type) Two keys cannot be equal; There can be at most one value for a given key This first restriction is tied to Python's underlying implementation of dictionaries The second restriction is part of the dictionary abstraction 19

Limitations on Dictionaries Dictionaries are unordered collections of key-value pairs Dictionary keys do have two restrictions: A key of a dictionary cannot be a list or a dictionary (or any mutable type) Two keys cannot be equal; There can be at most one value for a given key This first restriction is tied to Python's underlying implementation of dictionaries The second restriction is part of the dictionary abstraction If you want to associate multiple values with a key, store them all in a sequence value 19