Lecture 04 More Iteration, Nested Loops. Meet UTA Jarrett s dog Greta, lying in her nest

Similar documents
1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

LOOPS. Repetition using the while statement

Textbook. Topic 5: Repetition. Types of Loops. Repetition

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

STUDENT LESSON A12 Iterations

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Chapter 2: Understanding Structure. Programming Logic and Design, 4 th Edition Introductory

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Intro. Speed V Growth

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Announcements. Project 5 is on the street. Second part is essay questions for CoS teaming requirements.

Problem 1. Remove consecutive duplicates (6 points, 11 mintues)

Conditionals and Recursion. Python Part 4

Flow Control. CSC215 Lecture

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Flow Control: Branches and loops

Lecture 7 Tao Wang 1

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Lab 5 - Repetition. September 26, 2018

Chapter 5: Loops and Files

Control of Flow. There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests.

Practical Questions CSCA48 Week 6

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Introduction to Python (All the Basic Stuff)

Test #2 October 8, 2015

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

logical operators and else-if statements

Chapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:

(Python) Chapter 3: Repetition

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Intro. Scheme Basics. scm> 5 5. scm>

The story so far. Elements of Programming Languages. While-programs. Mutable vs. immutable

CS100: CPADS. Decisions. David Babcock / Don Hake Department of Physical Sciences York College of Pennsylvania

How many ways to make 50 cents? first-denomination Solution. CS61A Lecture 5. count-change. cc base cases. How many have you figured out?

Control Flow: Branching booleans and selection statements CS GMU

Scope of this lecture. Repetition For loops While loops

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

Lecture 10: Recursion vs Iteration

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Quiz Determine the output of the following program:

CS110D: PROGRAMMING LANGUAGE I

CS3 Midterm 2 Standards and Solutions

Lecture Transcript While and Do While Statements in C++

Iteration Part 1. Motivation for iteration. How does a for loop work? Execution model of a for loop. What is Iteration?

Repetition Structures II

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

Decision Making in C

Execution order. main()

4.2 Function definitions the basics

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

Introduction to Computer Programming for Non-Majors

Condition Controlled Loops. Introduction to Programming - Python

CS 106 Introduction to Computer Science I

Introduction to CS. Welcome to CS 5! 1 handout. We don't have words strong enough to describe this class. Everyone will get out of this course a lot!

CS302: Self Check Quiz 2

CSE200 Lecture 6: RECURSION

Chapter 8. Statement-Level Control Structures

Loop structures and booleans

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Iterative Statements. Iterative Statements: Examples. Counter-Controlled Loops. ICOM 4036 Programming Languages Statement-Level Control Structure

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Fundamentals of Programming Session 13

Lecture 02 Making Decisions: Conditional Execution

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

CS1150 Principles of Computer Science Loops (Part II)

LECTURE 5 Control Structures Part 2

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

CSSE 120 Introduction to Software Development Practice for Test 1 paper-and-pencil part Page 1 of 6

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Loops. Upsorn Praphamontripong. CS 1110/CS 1111 Introduction to Programming Spring 2018

Introduction to Recursion

Lecture #5: Higher-Order Functions. A Simple Recursion. Avoiding Recalculation. Redundant Calculation. Tail Recursion and Repetition

Introduction to Programming I

Chapter 1. Fundamentals of Higher Order Programming

CMSC201 Computer Science I for Majors

Looping. Arizona State University 1

Conditionals & Control Flow

Chapter 8. Statement-Level Control Structures

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Control flow statements

CMSC 201 Fall 2018 Python Coding Standards

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

User-defined Functions. Conditional Expressions in Scheme

Python Programming: An Introduction to Computer Science

Introduction to Computers and Programming. Recap

Transcription:

Lecture 4 More Iteration, Nested Loops Meet UTA Jarrett s dog Greta, lying in her nest

Indefinite Loops Rest Chase tail Got tail! Almost got it... Based in part on notes from the CS-for-All curriculum developed at Harvey Mudd College

So far: Two Types of for Loops vals[] vals[] vals[] vals[3] vals = [3, 5, 7, 7] vals = [3, 5, 7, 7] 3 x i def sum(vals): result = for x in vals: result += x return result element-based loop def sum(vals): result = for i in range(len(vals)): result += vals[i] return result index-based loop Both are examples of definite loops (i.e., fixed number of iterations) 3

Indefinite Loops Use an indefinite loop when the # of repetitions you need is: not obvious or known impossible to determine before the loop begins, e.g., Finding an element Computing an estimate up to some error bound Playing a game of rock, paper, scissors (as opposed to one round) Toy problem: print_multiples(n, bound) should print all multiples of n that are less than bound output for print_multiples(9, ): 9 8 7 36 45 54 63 7 8 9 99 4

Rock, Paper, Scissors, Lizard, Spock 5

Indefinite Loop for Printing Multiples while loops are how you code indefinite loops in Python: def print_multiples(n, bound): mult = n while mult < bound: print(mult, end=" ") mult = mult + n print() 6

while Loops while <loop test>: <body of the loop> loop test Steps:. evaluate the loop test (a boolean expression). if it's True, execute the statements in the body, and go back to step 3. if it's False, skip the statements in the body and go to the statement after the loop False True 7

Tracing a while Loop Let's trace the loop for print_multiples(5, 7): mult = n while mult < bound: print(mult, end=' ') mult = mult + n print() mult < bound output thus far n bound Prints everything on the same line with spaces in between! Neat! mult 8

Tracing a while Loop Let's trace the loop for print_multiples(5, 7): mult = n while mult < bound: print(mult, end=' ') mult = mult + n print() mult < bound output thus far n bound mult 5 5 < 7 (True) 5 3 3 < 7 (True) 5 3 45 45 < 7 (True) 5 3 45 6 6 < 7 (True) 5 3 45 6 75 75 < 7 (False) so we exit the loop and print() 9

Important! In general, a while loop's test includes a key "loop variable". We need to update that loop variable in the body of the loop. Failing to update it can produce an infinite loop! Recall the loop in print_multiples: mult = n while mult < bound: print(mult, end=' ') mult = mult + n What is the loop variable? Where is it updated?

Important! In general, a while loop's test includes a key "loop variable". We need to update that loop variable in the body of the loop. Failing to update it can produce an infinite loop! Recall the loop in print_multiples: mult = n while mult < bound: print(mult, end=' ') mult = mult + n What is the loop variable? mult Where is it updated? In the body of the loop

Important! In general, a while loop's test includes a key "loop variable". We need to update that loop variable in the body of the loop. Failing to update it can produce an infinite loop! Showing every iteration makes progress towards making the while loop condition false is one way to show a while loop will terminate

Factorial Using a while Loop We don't need an indefinite loop, but we can still use while! def fac(n): result = while n > : result *= n return result # what do we need here? Let's trace fac(4): n n > result 3

Factorial Using a while Loop We don't need an indefinite loop, but we can still use while! def fac(n): result = while n > : result *= n n = n return result Let's trace fac(4): n n > result 4

Factorial Using a while Loop We don't need an indefinite loop, but we can still use while! def fac(n): result = while n > : result *= n n = n return result Let's trace fac(4): n 4 4 3 n > result *4 = 4 4*3 = * = 4 4* = 4 4 > (True) 3 > (True) > (True) > (True) > (False) so we exit the loop and return 4 5

Factorial Four Ways! recursion map def fac(n): if n == : return else: rest = fac(n-) return n * rest Mo re on the se lat er! def fac(n): return reduce(lambda x,y : x*y,\ range(,max(,n+))) for loop def fac(n): result = for x in range(, n+): result *= x return result while loop def fac(n): result = while n > : result *= n n = n - return result 6

Extreme Looping! What does this code do? print('it keeps') while True: print('going and') print('phew! Done!') 7

Extreme Looping! What does this code do? print('it keeps') while True: print('going and') print('phew! Done!') # never gets here! An infinite loop! Use Ctrl-C to stop a program inside python Use W-F to stop a program in PyCharm 8

Breaking Out of A Loop import random while True: print('help!') if random.choice(range()) == : break print('let me out!') print('at last!') What are the final two lines that are printed? 9

Breaking Out of A Loop import random while True: print('help!') if random.choice(range()) == : break print('let me out!') print('at last!') What are the final two lines that are printed? Help! At last! How could we count the number of repetitions?

Counting the Number of Repetitions import random count = while True: print('help!') if random.choice(range()) == : break print('let me out!') count += print('at last! It took', count, 'tries to escape!')

Important! In general, a while loop's test includes a key "loop variable". We need to update that loop variable in the body of the loop. Failing to update it can produce an infinite loop! Can rely on a statistical argument (e.g., rock, paper, scissors) Counting the number of iterations and exiting after a maximum has been reached is a safer way to loop indefinitely

Counting the Number of Repetitions import random count = while count<=5: print('help!') if random.choice(range()) == : break print('let me out!') count += print('at last! It took', count, 'tries to escape!') 3

How many values does this loop print? a = 4 while a > : a = a // print(a - ) A. B. C. D. E. a > a prints 3 4 5 none of these 4

How many values does this loop print? a = 4 while a > : a = a // print(a - ) A. B. C. D. E. a > True True True True False a 4 5 prints 9 9 4 3 4 5 none of these 5

For what inputs does this function return True? def mystery(n): while n!= : if n %!= : return False n = n // return True A. B. C. D. E. Try tracing these two cases: mystery() mystery(8) n n 8 odd numbers even numbers multiples of 4 powers of none of these 6

For what inputs does this function return True? def mystery(n): while n!= : if n %!= : return False n = n // return True A. B. C. D. E. Try tracing these two cases: mystery() mystery(8) n n 8 6 4 3 False True odd numbers even numbers multiples of 4 powers of none of these 7

Wesley says it s break time so it s break time 8

Nested Loops! for y in range(84): for m in range(): for d in range(f(m,y)): for h in range(4): for mn in range(6): for s in range(6): tick() 9

Nested Loops! Nested Loops are loops where a loop appears inside the body of another loop. The loop inside the body is called the inner loop. The other is called the outer loop. The inner loop completes all passes for a single pass of the outer loop This is very useful for many types of algorithms, especially with data that has more than one dimension. 3

Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) inner loop outer loop 3

Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,, 3 3

Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,, 3 33

Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,, 3 34

Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,, 3 3 35

Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,, 3 3 3 36

Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) #,, #,,, 3 3 3 3 37

Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) print('---') inner loop outer loop 38

Repeating a Repetition! for i in range(3): for j in range(4): print(i, j) print('---') inner loop outer loop 3 -- 3 -- 3 --39

How many lines are printed? for i in range(5): for j in range(7): print(i, j) A. B. C. D. E. 4 5 7 4 35 4

How many lines are printed? for i in range(5): for j in range(7): print(i, j) A. B. C. D. E. 4 5 7 4 35 = 5*7 executions of inner code block full output: 3 4 5 6 3 4 5 6 3 4 5 6 3 3 3 3 3 3 4 3 5 3 6 4 4 4 4 3 4 4 4 5 4 6 4

Tracing a Nested for Loop for i in range(5): for j in range(i): print(i, j) i range(i) j # [,,,3,4] value printed 4

Tracing a Nested for Loop for i in range(5): for j in range(i): print(i, j) # [,,,3,4] i range(i) [] [] [,] 3 [,,] 4 [,,,3] value printed nothing (we exit the inner loop) full output: 3 3 3 4 3 4 4 3 4 3 3 4 4 4 4 3 j none 3 43

Second Example: Tracing a Nested for Loop for i in range(4): for j in range(i, 3): print(i, j) print(j) i range(i, 3) j value printed 44

Second Example: Tracing a Nested for Loop for i in range(4): # [,,, 3] for j in range(i, 3): print(i, j) print(j) # would go here next i 3 range(i, 3) [,, ] j value printed [, ] [] [], so body of inner loop doesn't execute full output: 45

Side Note: Staying on the Same Line When Printing By default, print puts an invisible newline character at the end of whatever it prints. causes separate prints to print on different lines Example: What does this output? for i in range(7): print(i * 5) 5 5 5 3 46

Staying on the Same Line When Printing (cont.) To get separate prints to print on the same line, we can replace the newline with something else. Examples: for i in range(7): print(i * 5, end=' ') 5 5 5 3 for i in range(7): print(i * 5, end=','),5,,5,,5,3, 47

Printing Patterns for row in range(3): for col in range(4): print('#', end=' ') print() # go to next line col row 3 # # # # # # # # # # # # 48 48

Fill in the Blank # for row in range(3): for col in range(6): print(, end=' ') print() # go to next line row col 3 4 5 3 4 5 3 4 5 49 49

Fill in the Blank # for row in range(3): for col in range(6): print(col, end=' ') print() # go to next line row col 3 4 5 3 4 5 3 4 5 5 5

Fill in the Blank # for row in range(3): for col in range(6): print(, end=' ') print() # go to next line row col 5 5

Fill in the Blank # for row in range(3): for col in range(6): print(row, end=' ') print() # go to next line row col 5 5

What is needed in the blanks to get this pattern? for row in range(5): for col in : print(, end=' ') print() # go to next line first blank A. B. C. D. E. 3 4 3 second blank range(row) row range(row) col range(5 - row) row range(5 - row) col none of the above 53 53

What is needed in the blanks to get this pattern? for row in range(5): for col in : print(, end=' ') print() # go to next line first blank A. B. C. D. E. 3 4 3 second blank range(row) row range(row) col range(5 - row) row range(5 - row) col none of the above 54 54