CS61A Lecture 12: Lists & Dictionaries

3 Pages
47 Views
Unlock Document

Department
Computer Science
Course
COMPSCI 61A
Professor
De Nero
Semester
Fall

Description
For Statements stairs = (1, 2, 3, 4, 5, 4, 3, 4, 5, 6, 7) from operator import getitem def count_while(s, value, getitem=getitem, len=len): """Count the number of occurrences of value in sequence s. >>> stairs.count(4) 3 >>> count_while(stairs, 4) 3 """ total, index = 0, 0 while index < len(s): if getitem(s, index) == value: total = total + 1 index = index + 1 return total def count(s, value): """Count the number of occurrences of value in sequence s. >>> count(stairs, 4) 3 """ total = 0 for elem in s: if elem == value: total = total + 1 return total For simpler than using While Loop Sequence Iteration Using For Statements Name after for bound in the first frame of current environment (not new frame) Execution Procedure: for in : 1. Evaluate header , which yield iterable value (sequence) 2. For each element in sequence, in that order: 1. Bind to that element in first frame of current environment 2. Execute Sequence Unpacking in For Statements A sequence of fixed-length sequences (i.e. pairs) A name for each element in a fixed-length sequence Each name bound to value, multiple assignment Ranges A sequence of consecutive integers Length: ending value - starting value Element selection: starting value + index Ex: range(-2 , 2) is from -2 to 1, not include 2 range(4) is from 0 to 4, assume 0 starting value Can use tuple constructor for ranges Membership & Slicing Membership: 2 in (2, 3): True The in word checks whether the name is found inside the list Slicing: [0:2] creates new objects by splitt
More Less

Related notes for COMPSCI 61A

Log In


OR

Join OneClass

Access over 10 million pages of study
documents for 1.3 million courses.

Sign up

Join to view


OR

By registering, I agree to the Terms and Privacy Policies
Already have an account?
Just a few more details

So we can recommend you notes for your school.

Reset Password

Please enter below the email address you registered with and we will send you a link to reset your password.

Add your courses

Get notes from the top students in your class.


Submit