Lecture 23: Loop Invariants
[Online Reading]
CS 1110 Introduction to Computing Using Python
[E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]
http://www.cs.cornell.edu/courses/cs1110/2019sp
Lecture 23: Loop Invariants [Online Reading] CS 1110 Introduction - - PowerPoint PPT Presentation
http://www.cs.cornell.edu/courses/cs1110/2019sp Lecture 23: Loop Invariants [Online Reading] CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White] Recall: Important
[E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]
http://www.cs.cornell.edu/courses/cs1110/2019sp
2
3
condition true false body
precondition postcondition
4
5
precondition: n_forks tells us how many forks are needed postcondition: n_forks tells us how many forks are needed
place setting
6
postcondition: n_forks tells us how many forks are needed precondition: n_forks tells us how many forks are needed
7
postcondition: n_forks tells us how many forks are needed precondition: n_forks tells us how many forks are needed
8
k = 2 k <= 5 k = k +1
True False total = total + k*k
9
10
11
2..1 (empty)
k = 2 k <= 5 k = k +1
True False
total = total + k*k
none
k = 2 k <= 5 k = k +1
True False
total = total + k*k
2..2 2
12
1
k = 2 k <= 5 k = k +1
True False
total = total + k*k
2..3 2, 3
13
2
k = 2 k <= 5 k = k +1
True False
total = total + k*k
2..4 2, 3, 4
14
3
k = 2 k <= 5 k = k +1
True False
total = total + k*k
2..5 2, 3, 4, 5
15
4
k = 2 k <= 5 k = k +1
True False
total = total + k*k
16
17
18
19
20
A: 0..k B: 1..k C: 0..k–1 D: 1..k–1 E: I don’t know
21
A: n_pair = num adj. equal pairs in s[1..k] B: n_pair = num adj. equal pairs in s[0..k] C: n_pair = num adj. equal pairs in s[1..k–1] D: n_pair = num adj. equal pairs in s[0..k–1] E: I don’t know
22
A: k = 0 B: k = 1 C: k = –1 D: I don’t know
23
A: s[k] and s[k+1] B: s[k-1] and s[k] C: s[k-1] and s[k+1] D: s[k] and s[n] E: I don’t know
24
25
postcondition: n_pair = # adjacent equal pairs in s[0..len(s)-1] precondition: s is a string
k k-1
26
postcondition: n_pair = # adjacent equal pairs in s[0..len(s)-1] precondition: s is a string
k+1 k
k k-1
27
postcondition: n_pair = # adjacent equal pairs in s[0..len(s)-1] precondition: s is a string
k+1 k
28
29
A: k = 0; big = int_list[0] B: k = 1; big = int_list[0] C: k = 1; big = int_list[1] D: k = 0; big = int_list[1] E: None of the above
30
A: k = 0; big = int_list[0] B: k = 1; big = int_list[0] C: k = 1; big = int_list[1] D: k = 0; big = int_list[1] E: None of the above
31
32