while loops announcements for this lecture
play

While Loops Announcements for This Lecture Assignments Prelim 2 - PowerPoint PPT Presentation

Lecture 22 While Loops Announcements for This Lecture Assignments Prelim 2 A6 due on Wednesday TONIGHT , 5:15 or 7:30 First two should be done K Z at 5:15pm Start Algorithm by weekend A J at 7:30 pm Next Week :


  1. Lecture 22 While Loops

  2. Announcements for This Lecture Assignments Prelim 2 • A6 due on Wednesday • TONIGHT , 5:15 or 7:30 § First two should be done § K – Z at 5:15pm § Start Algorithm by weekend § A – J at 7:30 pm § Next Week : Partition/Update § See website for room § Conflicts received e-mail • A7 will be last assignment § Will talk about next week • Will have 4-5 questions § Posted on Wednesday § Might drop short answer • There is lab next week § Similar to previous years § No lab week of Turkey Day • Graded by the weekend 11/8/18 While-Loops 2

  3. Recall: For Loops # Print contents of seq The for-loop: x = seq[0] for x in seq: print(x) print(x) x = seq[1] print(x) … • Key Concepts x = seq[len(seq)-1] § loop sequence: seq print(x) § loop variable : x § body : print(x) § Also called repetend 11/8/18 While-Loops 3

  4. Important Concept in CS: Doing Things Repeatedly 1. Process each item in a sequence § Compute aggregate statistics for a dataset, for x in sequence: such as the mean, median, standard deviation, etc. process x § Send everyone in a Facebook group an appointment time 2. Perform n trials or get n samples. § A4: draw a triangle six times to make a hexagon for x in range(n): Run a protein-folding simulation for 10 6 time steps § do next thing 3. Do something an unknown number of times ???? § CUAUV team, vehicle keeps moving until reached its goal 11/8/18 While-Loops 4

  5. Beyond Sequences: The while-loop while < condition >: statement 1 repetend or body … statement n • Relationship to for-loop § Broader notion of “still stuff to do” § Must explicitly ensure true condition repetend condition becomes false § You explicitly manage false what changes per iteration 11/8/18 While-Loops 5

  6. While-Loops and Flow print('Before while') Output: count = 0 Before while i = 0 Start loop 0 while i < 3: End loop print('Start loop '+str(i)) Start loop 1 count = count + i End loop i = i + 1 Start loop 2 print('End loop ') End loop print('After while') After while 11/8/18 While-Loops 6

  7. while Versus for # process range b..c-1 # process range b..c-1 for k in range(b,c) k = b while k < c: process k process k Must remember to increment k = k+1 # process range b..c # process range b..c for k in range(b,c+1) k = b while k <= c: process k process k k = k+1 11/8/18 While-Loops 7

  8. Range Notation • m..n is a range containing n+1-m values § 2..5 contains 2, 3, 4, 5. Contains 5+1 – 2 = 4 values § 2..4 contains 2, 3, 4. Contains 4+1 – 2 = 3 values § 2..3 contains 2, 3. Contains 3+1 – 2 = 2 values § 2..2 contains 2. Contains 2+1 – 2 = 1 values § 2..1 contains ??? A: nothing B: 2,1 C: 1 What does 2..1 contain? D: 2 E: something else 11/8/18 While-Loops 8

  9. Range Notation • m..n is a range containing n+1-m values § 2..5 contains 2, 3, 4, 5. Contains 5+1 – 2 = 4 values § 2..4 contains 2, 3, 4. Contains 4+1 – 2 = 3 values § 2..3 contains 2, 3. Contains 3+1 – 2 = 2 values § 2..2 contains 2. Contains 2+1 – 2 = 1 values § 2..1 contains ??? • The notation m..n, always implies that m <= n+1 § So you can assume that even if we do not say it § If m = n+1, the range has 0 values 11/8/18 While-Loops 9

  10. while Versus for # incr seq elements # incr seq elements for k in range(len(seq)): k = 0 while k < len(seq): seq[k] = seq[k]+1 seq[k] = seq[k]+1 k = k+1 Makes a range object . while is more flexible, but requires more code to use 11/8/18 While-Loops 10

  11. Patterns for Processing Integers range a..b-1 range c..d i = a i= c while i < b: while i <= d: process integer i process integer i i= i + 1 i = i + 1 # store in count # of '/'s in String s # Store in double var. v the sum count = 0 # 1/1 + 1/2 + …+ 1/n i = 0 v = 0; # call this 1/0 for today while i < len(s): i = 1 if s[i] == '/': while i <= n: count= count + 1 v = v + 1.0 / i i= i +1 i= i +1 # count is # of '/'s in s[0..s.length()-1] # v= 1/1 + 1/2 + …+ 1/n 11/8/18 While-Loops 11

  12. while Versus for # table of squares to N # table of squares to N seq = [] seq = [] n = floor(sqrt(N)) + 1 k = 0 for k in range(n): while k*k < N: seq.append(k*k) seq.append(k*k) k = k+1 A while loop can use A for-loop requires that complex expressions to you know where to stop check if the loop is done the loop ahead of time 11/8/18 While-Loops 12

  13. while Versus for Fibonacci numbers: F 0 = 1 F 1 = 1 F n = F n –1 + F n –2 # Table of n Fibonacci nums # Table of n Fibonacci nums fib = [1, 1] fib = [1, 1] for k in range(2,n): while len(fib) < n: fib.append(fib[-1] + fib[-2]) fib.append(fib[-1] + fib[-2]) Sometimes you do not use Do not need to have a loop the loop variable at all variable if you don’t need one 11/8/18 While-Loops 13

  14. Cases to Use while Great for when you must modify the loop variable # Remove all 3's from list t # Remove all 3's from list t while 3 in t: i = 0 while i < len(t): t.remove(3) # no 3’s in t[0..i–1] if t[i] == 3: del t[i] else: i = i+1 11/8/18 While-Loops 14

  15. Cases to Use while Great for when you must modify the loop variable # Remove all 3's from list t # Remove all 3's from list t while 3 in t: i = 0 while i < len(t): t.remove(3) # no 3’s in t[0..i–1] if t[i] == 3: The stopping condition is not del t[i] a numerical counter this time. Stopping else: Simplifies code a lot. point keeps i = i+1 changing. 11/8/18 While-Loops 15

  16. Cases to Use while def sqrt(c): • Want square root of c """Return: square root of c § Make poly f (x) = x 2 - c Uses Newton’s method § Want root of the poly Pre: c >= 0 (int or float)""" ( x such that f ( x ) is 0) x = c/2 • Use Newton’s Method # Check for convergence § x 0 = GUESS ( c /2??) while abs(x*x – c) > 1e-6: § x n +1 = x n – f ( x n )/ f ' ( x n ) # Get x n+1 from x n = x n – ( x n x n - c )/(2 x n ) x = x / 2 + c / (2*x) = x n – x n /2 + c /2 x n return x = x n /2 + c /2 x n § Stop when x n good enough 11/8/18 While-Loops 16

  17. Recall Lab 9 Welcome to CS 1110 Blackjack. Rules: Face cards are 10 points. Aces are 11 points. All other cards are at face value. Your hand: 2 of Spades 10 of Clubs Dealer's hand: Play until player 5 of Clubs stops or busts Type h for new card, s to stop: 11/8/18 While-Loops 17

  18. Recall Lab 9 Welcome to CS 1110 Blackjack. Rules: Face cards are 10 points. Aces are 11 points. All other cards are at face value. Your hand: How do we design 2 of Spades this as a loop? 10 of Clubs Dealer's hand: Play until player 5 of Clubs stops or busts Type h for new card, s to stop: 11/8/18 While-Loops 18

  19. Recall Lab 9 halted = False while not game.playerBust() and not halted: # ri: input received from player ri = input('Type h for new card, s to stop: ') halted = (ri == 's') if (ri == 'h'): game.playerHand.append(game.deck.pop(0) print('You drew the ' + str(game.playerHand[-1]) +'\n') 11/8/18 While-Loops 19

  20. Recall Lab 9 halted = False Explicit loop variable while not game.playerBust() and not halted: # ri: input received from player ri = input('Type h for new card, s to stop: ') halted = (ri == 's') Set to False to break the loop if (ri == 'h'): game.playerHand.append(game.deck.pop(0) print('You drew the ' + str(game.playerHand[-1]) +'\n') 11/8/18 While-Loops 20

  21. Recall Lab 9 halted = False More than one way to stop while not game.playerBust() and not halted: # ri: input received from player ri = input('Type h for new card, s to stop: ') halted = (ri == 's') if (ri == 'h'): game.playerHand.append(game.deck.pop(0) print('You drew the ' + str(game.playerHand[-1]) +'\n') 11/8/18 While-Loops 21

  22. Using while-loops Instead of for-loops Advantages Disadvantages • Better for modifying data • Performance is slower § More natural than range § Python optimizes for -loops § Works better with deletion § Cannot optimize while • Better for convergent tasks • Infinite loops more likely § Loop until calculation done § Easy to forget loop vars § Exact steps are unknown § Or get stop condition wrong • Easier to stop early • Debugging is harder § Just set loop var to False § Will see why in later lectures 11/8/18 While-Loops 22

  23. Our Goal From Here: Sorting 0 i 0 i 2 5 6 3 4 2 3 5 6 4 0 i 0 i 2 5 3 6 5 2 4 5 4 6 Will see how to do this with while -loops 0 i 0 i 2 3 5 6 5 2 3 4 5 6 0 i 0 2 3 5 6 4 2 3 4 5 6 11/8/18 While-Loops 23

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend