This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 1 Midterm Solutions Recap from last Python lecture Interpreted, imperative, OO Language • Everything is an object • Dynamic Typing Programs are made up of: • Expressions • Statements – Assignment – if/elif/else – whileloops – Functions • Classes (still to come) Show recap code Today: Revisit some objects • Exploit features and build powerful expressions Base : int, float, complex Sequence : string, tuple, list What can sequences do ? Select • ith element: s[i] • subsequence (“slice”): s[i:j] Update  For mutable sequences (e.g. Lists) • Update ith element: s[i] = e • Update subsequence: s[i:j] = e Update subsequence Update subsequence: s[i:j] = e • Changes the “object” referred to by s • May change the length of the sequence – Increase: if RHS length > ji – Decrease: if RHS length < ji s[i:j]=e 2 Update subsequence >>> z = [1,2,3,4,5,6,7,8,9,10] >>> z[3:6] = [“a”,“b”,“c”] >>> z [1,2,3,”a”,”b”,”c”,7,8,9,10] >>> z[3:6] = [“a”, “b”] * 2 >>> z [1,2,3,”a”,”b”,”a”,”b”,7,8,9,10] >>> z[4:]= >>> z [1,2,3,”a”] >>> z[:0] = [“al”, “be”] >>> z [“al”,”be”,1,2,3,”a”,”b”,”a”,”b”,7,8,9,10] s[i:j]=e What else can sequences do ? Q: Suppose you are given a sequence s How to find if the element x appears in s ? x in s Works for any sequence type … Sequence “contains” x in s >>> “a” in “cat” True >>> “a” in “entebbe” False >>> “a” in (“c”, “a”, “t”) True >>> 2 in [1,2,3,4,5] True >>> 2 in [1,4,“92”,2.4] False What can sequences do ? Select • ith element: s[i] • subsequence (“slice”): s[i:j] Update For mutable sequences (e.g. Lists ) • Update ith element: s[i] = e • Update subsequence: s[i:j] = e Member • Is an element in a sequence: x in s Doesn’t Python have ForLoops ? Why haven’t we seen Forloops yet ? • Because they are connected to sequences Forloops are used to iterate over sequences • Unlike in C, but similar to new Java foreach • Elegant, powerful mechanism – use it!...
View
Full Document
 Fall '10
 CS
 subsequence, Iterator, d.keys

Click to edit the document details