程序代写CS代考 python CS 61A Lecture 10 – cscodehelp代写
CS 61A Lecture 10
Announcements
Lists
[‘Demo’]
Working with Lists
>>> digits = [1, 8, 2, 8]
The number of elements
>>> len(digits)
4
An element selected by its index
>>> digits = [2//2, 2+2+2+2, 2, 2*2*2]
>>> digits[3] 88
Concatenation and repetition
>>> [2, 7] + 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
>>> getitem(digits, 3)
>>> add([2, 7], mul(digits, 2))
[2, 7, 1, 8, 2, 8, 1, 8, 2, 8]
4
Containers
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
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
for
1. Evaluate the header
A. Bind
9
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 Each name is bound to a value, as in fixed-length sequence multiple assignment
>>> for x, y in pairs:
… ifx==y:
… same_count = same_count + 1
>>> same_count
2
10
Ranges
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
>>> 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
[