2/15 announcements + pick up "CS100M Reminders" at front if you didn't pick one up at Prelim T1 (also included in this lecture sketch) + ProgramLive + serial number for public labs: [censored: for cs100 only -- do not publicize] + highly recommended for high-level concept of loop invariants + highly recommended for high-level concept of function calls + P3 has been revised and clarified; *must* submit online + most of P3 should be within your reach after lecture today + at least, start doing it with scripts if not ready for functions (until now, everything you've written is a matlab script) + see also posted "connections" in the "hints" column of the Projects page + Course & Prelim evaluation available next week (pre-evaluation is up now) + deadline for online due dates is 8am, but no guarantees of extensions if there are problems after 2am. + there will be small E5 due tuesday; posted saturday + T1 scores are available online from the Exams page reminders + be concerned, but don't stress too much if you had trouble with T1: we drop lowest 10% of E, P, T1, T2, T3, T4 -- since T1 is worth 10%, it can dropped entirely + T1 solutions up, stats posted; will be returned in section next week + many sources of help -- use them! + course website + newsgroup + e-mail + consultants + open office hours + appointment slots (made through upson 303 for tas, e-mail for TKY) + right after a due date often good time to come in for help: + you've thought about it recently, so you should be familiar with the issues + we can reveal the answers + results from past online evaluations are available; i do respond to comments topics + another example of processing input: $max$ of input sequence + loop invariants/storyline, e.g. E4 solution + functions future topics + extend "box scope diagram" memory model to encompass functions + function development: start as script or use $keyboard$ or use debugger + sieve of eratosthenes (loops, logical arrays) + more on uses of logical arrays (note: not used much on P3) + arrays as lookups _______________________________________________________________________________ CS100M Reminders + you are required to monitor the course webpage. + you are required to monitor the course newsgroup. + unexcused, omitted projects count as -2. + you get the most out of lecture if you actually run the code presented in lecture, which is available as part of the Lecture Sketches posted to the Examples page. + even if you received a good score, you should pick up graded work to learn from it, + homework submission is now online unless specified otherwise. + you can get bonus points for course participation: + posting about errors on the newsgroup + asking questions in lecture + completing online evaluation forms _______________________________________________________________________________ programming approach: *introspection* figure out how *you* do it: pay attention to the steps you are taking also, try to play computer: + sit at computer + type in $var$: $value$ pairs + ask friend/partner to slowly call out input values + type in updated values + delete old values: like destructive update, old value is lost! + pay attention to how you figure out how and when to update values _______________________________________________________________________________ example: find maximum value of 0-terminated input sequence (i.e. input value of 0 terminates sequence; 0 is not part of sequence) i'll call out a sequence; at the end, you tell me the max. introspect: how did *you* compute the answer? solution: keep track of max so far matlab code with line numbers shown for assignments: % read first value and set things up stopping = 0; % stopping value prompt = 'value (0 to stop)? '; 1 num = input(prompt); % next input value 2 curmax = -inf; % max so far, excluding $num$ % inv: read input until hit stopping value; maintain $curmax$ while num ~= stopping % process num if num > curmax 3 curmax = num; end % read next input value 4 num = input(prompt); end _______________________________________________________________________________ loop storylines (invariants) -- secret weapon for understanding loops! (loop invariants take a while to get used to, but if you learn them, they are *very* useful.) look again at our code above. + it follows our general template for processing an input sequence + it does *not* store all elements of input sequence: even if read a billion numbers, essentially only two numbers ($num$, $curmax$) are stored -- efficient use of memory! + use of $prompt$ and $stopping$ makes it easy to change stopping value: just change their initializations. (not such a big deal in this example, but if their values are used in many places in the code, this means we make changes in just 2 places (initialization) instead of the numerous places where their values are used.) + the loop has something labeled "inv": every loop should have an *invariant* or *storyline$ that explains *what* the loop does, but usually not *how* (for now, $for$ loops won't have an invariant -- that's a little tricky. in some sense, this means $while$ loops are better.) + the storyline must be true each time the loop guard is tested, i.e. before and after each time the loop body is executed. "it is true at snapshots between execution of loop body". + analogy: storyline for an animated movie where the storyline is true at each frame of film, but might not be true between the snapshots at each frame. example: "in _chicken run_, a chicken smoothly raises its wing". actual animation process *between* frames can involve all sorts of contortions. + the loop and its invariant are at the same level of indentation: conceptually, they form a unit -- the loop is *not* a substructure of the invariant. + to a large extent, a loop invariant is just a clear picture (drawing) of what is happening, from start to middle to end. _______________________________________________________________________________ trace on input: 5, -3, 8, 17, 5, 19, 18, 0 (omit $stopping$, $prompt$ from table; include line#s) note: we can see what input has been read by looking at the row for $num$ in the tracing trable (imagine box scope diagram evolving as a movie. storyline explains what happens at each instant that loop guard is tested.) inv inv inv inv inv inv inv inv true true true true true true true true :( :( | :( | | :( | :( | | :( | | line#: | 1 | 2 | 3 | 4 | 4 | 3 | 4 | 3 | 4 | 4 | 3 | 4 | 4 | num | 5 | | | -3 | 8 | | 17 | | 5 | 19 | | 18 | 0 | curmax | | -oo | 5 | | | 8 | | 17 | | | 19 | | | _______________________________________________________________________________ E4: power of loop invariants question: what can be said about the last student? While there are 2 or more CS100 students Pick 2 students at random. If they are from the same class (both J or both M) then They both leave. A J student enters. If they are from different classes (one J and one M) then The M student stays. The J student leaves. solution: last student is from M = m is odd ("=" = "if and only if") proof: parity (remainder mod 2) of # M students is constant (*invariant*) Proof by case analysis on the loop body: + if both students are from M, then N <-- N-2, so parity is unchanged. + else (either or both are from J) N is unchanged, so parity is unchanged. _______________________________________________________________________________ function: named, parametrized piece of code ! motivation: ! + clarity and abstraction ! + often easier to understand name than (lines of) code, e.g. $max$ ! + often don't care or want to know implementation details ! + conciseness and reduce redundancy ! + shorter to type name than (lines of) code ! + if need to make changes, only need to make changes in one place ! ! abstract, high-level example: P2.5, birthday/shared-question problem ! ! + same basic code can be used to solve multiple questions ! + use of constants/variables ($nbuckets$, $ntrials$) helps: ! + change definition of constant instead of searching through code ! + the *name* is often more meaningful than number, e.g. if see 6, is it: ! nmonthsInHalfYear? dollarsInYourWallet? minInTenthOfHour? sidesOfDie? ! + however, if want to use multiple times, then without functions must use ! + a loop (e.g P2.5 solution) ! + doesn't help if want to use code in another setting ! + copy/paste ! + painful to maintain: if find a mistake or wish to add improvement, ! must change all copies! ! ! solution: ! + name the piece of code: ! + when want to use it, $invoke$ it by name ! + *parametrize* the code: ! + leave variables/parameters unspecified in definition (function code) ! (like prelim questions: *if* given a value, *then* do task) ! + when invoke the function, *pass* ("send") values of parameters to code _______________________________________________________________________________ concrete example: T1.2 capitalization file $capitalize.m$: ________________________________________________________________________ | function s = capitalize(str) | | % CAPITALIZE capitalize first letter of each word. | | % s = capitalize(str): | | % pre: $str$ contains only letters and spaces | | % post: $s$ is equal to $str$ with first letter of words capitalized | | | | s = str; up = upper(s); | | s(1) = up(1); | | for i = 2:length(s) | | if s(i-1) == ' ' | | s(i) = up(i); | | end | | end | |______________________________________________________________________| notes: + a function $name$ MUST be defined in a file named $name$.m + syntax is: function returnValue = functionName(parameters) ----------- ------------ ---------- + should have a comment that gives: + function name, brief description + how to call the function and specification of behavior + matlab convention: first line is $function$, comment goes after + when you turn in matlab function files, place your identification block (project/exercise label, you and your partner's name, cuid, netid, section) after comments for function + answer is returned by assigning to the returnValue variable + returnValue is allowed to be a parameter, e.g. function str = capitalize(str) function topics for next lecture: + clarify the difference between *printing* and *returning* values + extend "box scope diagram" memory model to encompass functions + how to develop and test functions _______________________________________________________________________________ Q: can you have more than one function in a file? A: for now, no. (we'll do that later.)