Lecture 10: Lists and Sequences

Similar documents
CS 1110: Introduction to Computing Using Python Lists and Sequences

Lecture 12. Lists (& Sequences)

CS 1110: Introduction to Computing Using Python Loop Invariants

Lecture 24: Loop Invariants

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

Lecture 9: Memory in Python

CS1110. Lecture 6: Function calls

Conditionals & Control Flow

Lecture 7. Memory in Python

Lecture 17: Classes (Chapter 15)

Lecture 8: Conditionals & Control Flow (Sections ) CS 1110 Introduction to Computing Using Python

CS Lecture 19: Loop invariants

Announcements for this Lecture

CS1110. Lecture 6: Function calls

Lecture 2: Variables & Assignments

Lecture 5: Strings

Lecture 19: Subclasses & Inheritance (Chapter 18)

Lecture 11: Iteration and For-Loops

Announcements For This Lecture

CS1110. Lecture 22: Prelim 2 Review Session. Announcements. Processed prelim regrade requests: on the front table.

Lecture 17: Classes (Chapter 15)

Lecture 18: Using Classes Effectively (Chapter 16)

Lecture 3: Functions & Modules

Lecture 7: Objects (Chapter 15) CS 1110 Introduction to Computing Using Python

Iteration and For Loops

Lecture 6: Specifications & Testing

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python

Lecture 20: While Loops (Sections 7.3, 7.4)

CS 1110 Prelim 1 October 4th, 2012

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS First Name: Last Name: NetID:

isinstance and While Loops

PREPARING FOR PRELIM 1

Overview of List Syntax

Announcements For This Lecture

Lecture 4. Defining Functions

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

Lecture 4: Defining Functions (Ch ) CS 1110 Introduction to Computing Using Python

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

CS 1110 Prelim 1 October 17th, 2013

CS Prelim 1 Review Fall 2018

CS Prelim 1 Review Fall 2017

CS 1110, LAB 3: STRINGS; TESTING

CS Prelim 1 Review Fall 2013

Lecture 5. Defining Functions

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

CS 1110 Prelim 1 October 15th, 2015

Last Name: First Name: Cornell NetID, all caps: CS 1110 Regular Prelim 1 Solutions March 2018

CS 1110 Prelim 2 November 14th, 2013

Lecture 4: Defining Functions

CS Lecture 26: Grab Bag. Announcements

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CS Prelim 1 Review Fall 2012

CS 1110 Final, December 8th, Question Points Score Total: 100

CS 1110 Final, December 8th, Question Points Score Total: 100

CS 1110 Prelim 1, March 2018

Python Review IPRE

CS Prelim 1 Review Fall 2016

Lecture 10. Memory in Python

CS 1110, LAB 10: ASSERTIONS AND WHILE-LOOPS 1. Preliminaries

CS Prelim 2 Review Fall 2018

Python: common syntax

Lecture 9. Memory and Call Stacks

CS 1110, LAB 12: SEQUENCE ALGORITHMS First Name: Last Name: NetID:

Lecture 14. Nested Lists and Dictionaries

Lecture 8. Conditionals & Control Flow

Lecture 19. Operators and Abstraction

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Not-So-Mini-Lecture 6. Modules & Scripts

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

CS 1110 Final, May 2017

Notebook. March 30, 2019

Lecture 1: Introduction, Types & Expressions

Acct. balance Acct. balance 50 25

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Course Overview, Python Basics

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Lecture 3. Strings, Functions, & Modules

Announcements. Project 2 due next Monday. Next Tuesday is review session; Midterm 1 on Wed., EE 129, 8:00 9:30pm

CS 1110 Prelim 2 November 12th, 2015

MUTABLE LISTS AND DICTIONARIES 4

Python Programming: Lecture 2 Data Types

Announcements for This Lecture

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

Accelerating Information Technology Innovation

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Python Review IPRE

Lists How lists are like strings

Lists, loops and decisions

CS Prelim 1 Review Fall 2013

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Types, lists & functions

CMSC201 Computer Science I for Majors

CS Lecture 25: Models, Views, Controllers, and Games. Announcements

CS Lecture 18: Card Tricks. Announcements. Slides by D. Gries, L. Lee, S. Marschner, W. White

CS 1110, Spring 2018: Prelim 1 study guide Prepared Tuesday March 6, 2018

Announcements for This Lecture

Python and Bioinformatics. Pierre Parutto

CS 1110 Prelim 2 November 13th, 2014

CS 1110 Prelim 1 March 7th, 2013 SOLUTIONS

Transcription:

http://www.cs.cornell.edu/courses/cs/8sp Lecture : Lists and Sequences (Sections.-.,.4-.6,.8-.) CS Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]

Lecture Announcements Last call for a one-on-one! CMS: OPTIONAL: one-on-ones Prelim is March. LAST DAY to register a conflict or a need for accommodation. See website: http://www.cs.cornell.edu/courses/cs/8sp/exams/index.php CMS: Prelim conflicts A Revisions: open from Mar st thru Mar 7, :9pm. just means not done. many people got a due to test cases.

Lecture Announcements A is out and about! Handout provides links to worked examples of diagramming call frames, objects, variables, etc. Preparatory to starting A: (a) immediately try those worked examples (b) go to office/consulting hours if you have any difficulty This will make A go much smoother!

Sequences: Lists of Values s = 'abc d' String 4 List x = [, 6,, 9,, ] 4 a b c d 6 9 Put characters in quotes Use \' for quote character Access characters with [] s[] is 'a' s[] causes an error s[:] is 'ab' (excludes c) s[:] is 'c d' Put values inside [ ] Separate by commas Access values with [] x[] is x[6] causes an error x[:] is [, 6] (excludes nd ) x[:] is [9,, ] Sequence is a name we give to both 4

Lists Have Methods Similar to String x = [, 6,, 9,, ] <list>.index(<value>) Return position of the value ERROR if value is not there x.index(9) evaluates to <list>.count(<value>) Returns number of times value appears in list x.count() evaluates to But to get the length of a list you use a function, not a class method: len(x) x.len()

A Word about Testing Suppose you hear a rumor that the count method is not implemented correctly. >>> lab_scores = [, 6,, 9,,, 8,,7] >>> lab_scores.count() Looks good to me! Are we done? 6

What should I be testing? Common Cases: typical usage (see previous slide) Edge Cases: live at the boundaries Target location in list: first, middle, last elements Input size:,,, many (length of lists, strings, etc.) Input Orders: max(big, small), max(small, big) Element values: negative/positive, zero, odd/even Element types: int, float, str, etc. Expected results: negative,,,, many Not all categories/cases apply to all functions. Use your judgement! 7

Things that Work for All Sequences s = slithy x = [, 6, 9, 6,, ] s.index( s ) s.count( t ) len(s) 6 s[4] h s[:] li s[:] thy s[ ] h s + toves slithy toves s * slithyslithy t in s True methods built-in fns slicing operators x.index() x.count(6) len(x) 6 x[4] x[:] [6, 9] x[:] [6,, ] x[ ] x + [, ] [, 6, 9, 6,,,, ] x * [, 6, 9, 6,,,, 6, 9, 6,, ] in x True 8

Wrong: x, 6, 7, - Representing Lists Correct: x id id 7 4 - list x = [, 7, 4,-] Indices 9

Lists vs. Class Objects List Attributes are indexed Example: x[] Objects Attributes are named Example: p.x x id id list p id id Point 7 4 - x y z

Lists Can Hold Any Type list_of_integers = [,7,4,-] list_of_strings = [ h, i,, there! ] list_of_integers id id 7 4 - list list_of_strings id id list h i there!

No Really, Lists Can Hold Any Type! list_of_points = [Point(8,,), Point(6,,) ] list_of_points id id id id id6 id7 list id Point x 8 y z id Point x 6 y z id6 Point x 4 y 4 z id7 Point list_of_various_types id9 id9 x y z list.46 happy id id Point x y z

Lists of Objects List elements are variables Can store base types and ids Cannot store folders p id id Point p = Point(,, ) p = Point(4,, 6) p = Point(7, 8, 9) x = [p,p,p] p p x id id id4 How do I get this y? x[].y x y z id Point x 4 y z 6 id Point x 7 y 8 z 9 id4 id id id list

List Assignment Format: <var>[<index>] = <value> Reassign at index Affects folder contents Variable is unchanged Strings cannot do this Strings are immutable x = [, 7,4,-] x[] = 8 s = Hello! s[] = J TypeError: 'str' object does not support item assignment x s id Hello! id 7 4 - x 8 list

List Methods Can Alter the List x = [, 6,, 9] See Python API for more <list>.append(<value>) Adds a new value to the end of list x.append(-) changes the list to [, 6,, 9, -] <list>.insert(<index>,<value>) Puts value into list at index; shifts rest of list right x.insert(,-) changes the list to [, 6, -,, 9] <list>.sort() What do you think this does?

Execute the following: >>> x = [, 6,, 9, ] >>> x[] = - >>> x.insert(, ) What is x[4]? A: B: 9 C: - D: ERROR E: I don t know st Clicker Question 6

st Clicker Answer Execute the following: >>> x = [, 6,, 9, ] >>> x[] = - >>> x.insert(, ) What is x[4]? A: B: 9 C: - D: ERROR E: I don t know CORRECT x id id 6 x9-4 list (Original elements -4 are shifted down to be elements -) 7

Recall: identifier assignment à no swap import shapes def swap(p, q): tmp = p p = q q = tmp p = shapes.point(,,) q = shapes.point(,4,) swap(p, q) p id6 q id7 Call Frame swap p id7 q id6 tmp id6 RETURN NONE id6 Point x y z id7 Point x y 4 z At the end of swap: parameters p and q are swapped global p and q are unchanged 8

Recall: Attribute Assignment à swap! import shapes def swap(p, q): tmp = p.x p.x = q.x q.x = tmp p = shapes.point(,,) q = shapes.point(,4,) swap(p, q) p id6 q id7 Call Frame swap p id6 q id7 tmp RETURN NONE id6 Point x y z id7 Point x y 4 z At the end of swap: parameters p and q are unchanged global p and q are unchanged, attributes x are swapped 9

nd Clicker Question def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] x id4 b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] What gets printed? A: B: 6 C: Something else D: I don t know id4 4 7 6 4

def swap(b, h, k): nd Clicker Answer """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] x id4 b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] What gets printed? A: CORRECT B: 6 C: Something else D: I don t know Swaps b[h] and b[k], because parameter b contains name of list. id4 4 7 6 4

nd Clicker Explanation () def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] x swap id4 Call Frame b id4 h k 4 id4 4 7 6 4

nd Clicker Explanation () def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] x swap id4 Call Frame b id4 h id4 4 7 6 4 temp 6 k 4

nd Clicker Explanation () def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] x swap id4 Call Frame b id4 h temp 6 k 4 id4 4 7 6 4 4

nd Clicker Explanation (4) def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] x swap id4 Call Frame b id4 h temp 6 k 4 id4 4 7 6 4 6 RETURN None

List Slices Make Copies x = [, 6,, 9] y = x[:] x id y id6 id 6 9 list copy means new folder id6 6 list 6

Execute the following: >>> x = [, 6,, 9, ] >>> y = x[:] >>> y[] = 7 What is x[]? A: 7 B: C: 6 D: ERROR E: I don t know rd Clicker Question 7

rd Clicker Answer Execute the following: >>> x = [, 6,, 9, ] >>> y = x[:] >>> y[] = 7 What is x[]? A: 7 B: C: 6 D: ERROR E: I don t know CORRECT x id y id6 id 6 9 4 id6 6 9 list 7 list 8

Execute the following: >>> x = [, 6,, 9, ] >>> y = x >>> y[] = 7 What is x[]? A: 7 B: C: 6 D: ERROR E: I don t know 4 th Clicker Question 9

4 th Clicker Answer Execute the following: >>> x = [, 6,, 9, ] >>> y = x >>> y[] = 7 What is x[]? A: 7 B: C: 6 D: ERROR E: I don t know CORRECT x id y id id 6 9 4 7 list

Lists and Expressions / th Clicker Q List brackets [] can contain expressions This is a list expression Python must evaluate it Evaluates each expression Puts the value in the list Example: >>> a = [+,+4,+6] >>> a [, 7, ] Execute the following: >>> a = >>> b = 7 >>> x = [a, b, a+b] What is x[]? A: 'a+b' B: C: 7 D: ERROR E: I don t know

Lists and Expressions / th Clicker A a b 7 x id id 7 list Execute the following: >>> a = >>> b = 7 >>> x = [a, b, a+b] What is x[]? A: 'a+b' B: C: 7 D: ERROR E: I don t know CORRECT

Lists and Strings Go Hand in Hand text.split(<sep>): return a list of words in text (separated by <sep>, or whitespace by default) <sep>.join(words): concatenate the items in the list of strings words, separated by <sep>. >>> text = 'A sentence is just\n a list of words' >>> words = text.split() >>> words ['A', 'sentence', 'is', 'just', 'a', 'list', 'of', 'words'] >>> lines = text.split('\n') >>> lines ['A sentence is just', ' a list of words'] >>> hyphenated = '-'.join(words) >>> hyphenated 'A-sentence-is-just-a-list-of-words' >>> hyphenated = '- '.join(lines[].split()+lines[].split()) >>> hyphenated 'A-sentence-is-just-a-list-of-words' Turns string into a list of words Turns string into a list of lines Combines elements with hyphens Merges lists, combines elements with hyphens