Common Loop Algorithms - Westmont College

2y ago
23 Views
2 Downloads
2.38 MB
52 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Jayda Dunning
Transcription

Common LoopAlgorithms9/21/1642

Common Loop Algorithms1. Sum and Average Value2. Coun4ng Matches3. Promp4ng un4l a Match Is Found4. Maximum and Minimum5. Comparing Adjacent Values9/21/1643

Sum Example Sum of Values Ini4alize total to 0 Use while loop with sen4neltotal 0.0inputStr input("Enter value: ")while inputStr ! "" :value float(inputStr)total total valueinputStr input("Enter value: ")9/21/1644

Average ExampleAverage of Values First total the values Ini4alize count to 0 Increment per input Check for count 0 Before divide!total 0.0count 0inputStr input("Enter value: ")while inputStr ! "" :value float(inputStr)total total valuecount count 1inputStr input("Enter value: ")if count 0 :average total / countelse :average 0.09/21/1645

Counting Matches (e.g., NegativeNumbers) Coun4ng Matches Ini4alize nega4ves to 0 Use a while loop Add to nega4ves permatchnegatives 0inputStr input("Enter value: ")while inputStr ! "“ :value int(inputStr)if value 0 :negatives negatives 1inputStr input("Enter value: ")print("There were", negatives,"negative values.")9/21/1646

Prompt Until a Match is Found Ini4alize boolean flag to False Test sen4nel in while loop Get input, and compare to range If input is in range, change flag to True Loop will stop execu4ngvalid Falsewhile not valid :value int(input("Please enter a positive value 100: "))if value 0 and value 100 :valid Trueelse :print("Invalid input.")This is an excellent way to validate use provided inputs9/21/1647

Maximum Get first input value By defini4on, this is the largest that you have seen so far Loop while you have a valid number (non-sen4nel) Get another input value Compare new input to largest (or smallest) Update largest if necessarylargest int(input("Enter a value: "))inputStr input("Enter a value: ")while inputStr ! ””:value int(inputStr)if value largest :largest valueinputStr input("Enter a value: ")9/21/1648

Minimum Get first input value This is the smallest that you have seen so far! Loop while you have a valid number (non-sen4nel) Get another input value Compare new input to largest (or smallest) Update smallest if necessarysmallest int(input("Enter a value: "))inputStr input("Enter a value: ")while inputStr ! "“ :value int(inputStr)if value smallest :smallest valueinputStr input("Enter a value: ")9/21/1649

Comparing Adjacent Values Get first input value Use while to determine if there are more to check Copy input to previous variable Get next value into input variable Compare input to previous, and output if samevalue int(input("Enter a value: "))inputStr input("Enter a value: ")while inputStr ! "“ :previous valuevalue int(inputStr)if value previous :print("Duplicate input")inputStr input("Enter a value: ")9/21/1650

Grades Example Open the file: Grades.py Look carefully at the source code. The maximum possible score is read as user input There is a loop to validate the input The passing grade is computed as 60% of the available points9/21/1651

The for Loop9/21/1652

The for Loop Uses of a for loop: The for loop can be used to iterate over the contents of anycontainer. A container is an object (Like a string) that contains or stores acollec4on of elements A string is a container that stores the collec4on of characters in thestring9/21/1653

while loop - for loopstateName "Virginia"i 0while i len(stateName) :letter stateName[i]print(letter)while versioni i 19/21/1654

while loop - for loopstateName "Virginia"i 0while i len(stateName) :letter stateName[i]print(letter)while versioni i 1stateName "Virginia"for letter in stateName :print(letter)for version9/21/1655

while loop - for loop Note an important difference between the while loop and the for loop. In the while loop, the index variable i is assigned 0, 1, and so on. In the for loop, the element variable is assigned stateName[0],stateName[1], and so on.stateName "Virginia"i 0while i len(stateName) :letter stateName[i]print(letter)while versioni i 1stateName "Virginia"for letter in stateName :print(letter)for version9/21/1656

The for Loop (2) Uses of a for loop: A for loop can also be used as a count-controlled loop that iteratesover a range of integer values.i 1while i 10 :print(i)i i 1while versionfor i in range(1, 10) :print(i)for version9/21/1657

Syntax of a for Statement (Container) Using a for loop to iterate over the contents of a container, an elementat a 4me.9/21/1658

Syntax of a for Statement (Range) You can use a for loop as a count-controlled loop to iterate over arange of integer values We use the range func4on for genera4ng a sequence of integers thatless than the argument that can be used with the for loop9/21/1659

Planning a for Loop Print the balance at the end of each year for anumber of years9/21/1660

Good Examples of for Loops Keep the loops simple!9/21/1661

Investment Example9/21/1662

Programming Tip Finding the correct lower and upper bounds for a loop can beconfusing. Should you start at 0 or at 1? Should you use b or b as a termina4on condi4on? Coun4ng is easier for loops with asymmetric bounds. The following loops are executed b - a 4mes.int i awhile i b :. . .i i 19/21/16for i in range(a, b) :. . .63

Programming Tip The loop with symmetric bounds (“ ”, is executed b - a 1 4mes. That “ 1” is the source of many programming errors.i awhile i b :. . .i i 19/21/16# For this version of the loop the‘ 1’ is very noticeable!for year in range(1, numYears 1) :64

Summary of the for Loop for loops are very powerful The for loop can be used to iterate over the contents of any container,which is an object that contains or stores a collec4on of elements a string is a container that stores the collec4on of characters in the string. A for loop can also be used as a count-controlled loop that iteratesover a range of integer values.9/21/1665

Steps to Writing a Loop Planning: Decide what work to do inside the loop Specify the loop condi4on Determine loop type Setup variables before the first loop Process results when the loop is finished Trace the loop with typical examples Coding: Implement the loop in Python9/21/1666

A Special Form of the printFunction Python provides a special form of the print func4on that does not starta new line ajer the arguments are displayed This is used when we want to print items on the same line usingmul4ple print statements For example the two statements:print(“00”, end ””)print(3 4) Produce the output:007 Including end “” as the last argument to the print func4on prints anempty string ajer the arguments, instead on a new line The output of the next print func4on starts on the same line9/21/1667

Nested Loops9/21/1668

Loops Inside of Loops In Chapter Three we learned how to nest if statements to allow us tomake complex decisions Remember that to nest the if statements we need to indent thecode block Complex problems some4mes require a nested loop, one loop nestedinside another loop The nested loop will be indented inside the code block of the firstloop A good example of using nested loops is when you are processing cellsin a table The outer loop iterates over all of the rows in the table The inner loop processes the columns in the current row9/21/1669

Our Example Problem Statement Print a Table Header that contains x1, x2, x3, and x4 Print a Table with four columns and ten rows that contain the powersof x1, x2, x3, and x4 for x 1 to 109/21/1670

Applying Nested Loops How would you print a table with rows and columns? Print top line (header) Use a for loop Print table body How many rows are in the table? How many columns in the table? Loop per row Loop per column In our example there are: Four columns in the table Ten rows in the table9/21/1671

Pseudocode to Print the TablePrint the table headerfor x from 1 to 10print a new table rowprint a new line How do we print a table row?For n from 1 to 4print xn We have to place this loop inside the preceding loop The inner loop is “nested” inside the outer loop9/21/1672

Pseudocode to Print the TablePrint the table header:for x from 1 to 10for n from 1 to 4print Xnxprint a new line !9/21/16n!73

Flowchart of a Nested Loopx 1x 10?Truen 1FalseTruen 4?Print xnFalsen n 1Inner LoopPrint new lineDone9/21/16x x 174

Powertable.pyThe end “” suppresses the newline, so the numbers are allprinted on the same lineBody of outer loop, x 1 ! 10Body of inner loop, n 1 ! 49/21/1675

The Results9/21/1676

First Exercise Open the program: powertable.py Run the program and review the results Make the following changes: Change the value of NMAX to 6 and run the program What changes in the table? Change the value of NMAX back to 4 Change the value of XMAX to 4 What changes in the table?9/21/1677

Nested Loop Examples9/21/1678

Hand Tracing the Loop i will have the values: 0, 1, 2, 3 – So we will have four lines ofstars j will have the values 0 - So we will have one star 0, 1 - So we will have two stars 0, 1, 2 - So we will have three stars 0, 1, 2, 3 - So we will have four stars9/21/1679

Nested Loop Examples (2)9/21/1680

Second Problem Statement Print the following papern of brackets:[][][][][][][][][][][][] The papern consists of: Three rows Each row has four pairs of brackets What do we know? We need two nested loops The first loop (the outer loop) will print each of the three rows The second loop (the inner loop) will print the four pairs ofbrackets9/21/1681

Pseudocode Code, ResultsFor i 1 to 3For j 1 to 4Print “[]”Print a new line9/21/1682

Exam Averages Problem Statement It is common to repeatedly read and process mul4ple groups of values: Write a program that can compute the average exam grade formul4ple students. Each student has the same number of exam grades Prompt the user for the number of exams When you finish a student prompt the user to see if there are morestudents to process What do we know? What do we need to compute? What is our algorithm / approach?9/21/1683

Step One: Understand the Problem To compute the average grade for a student, we must read and tally allof the grades for that student We can use a loop to do this. (we have working code to do thispor8on) We need to compute grades for mul4ple students That implies a set of nested Loops The outer loop processes each student The inner loop process the student’s grades9/21/1684

Step Two Compute the grade for one student Set up the variables and loop We know how many grades to process, so we can use a countcontrolled looptotal score 0For i in range (1, number of exams 1) :Read the next exam scoreAdd the exam score to the total scoreCompute the exam averagePrint the exam average9/21/1685

Step Three Repeat the process for each student Since we don’t know how many students there are, we will use awhile loop with a sen4nel value For simplicity we will use “Y” as the sen4nel value9/21/1686

Step Four: Translate to Python9/21/1687

Exam Averages Example Open the file: examaverages.py No4ce that the second loop (the for loop) is nested inside the while loop In Wing you should see a line (the indent guide) connec4ng the for loopon line 17 down to the statement on line 21 The line is showing you the statements that are included in the for loop If you don’t see the indent guide: Click on the edit tab Select “Preferences ” Under Editor, select Inden4on Click the “Show Indent Guides” box Click the Apply bupon Click the Okay Bupon9/21/1688

Turning the Indent Guides On9/21/1689

Application: RandomNumbers and Simulations9/21/1690

Random Numbers/Simulations Games ojen use random numbers to make things interes4ng Rolling Dice Spinning a wheel Pick a card A simula4on usually involves looping through a sequence of events Days Events9/21/1691

Generating Random Numbers The Python library has a random number generator that producesnumbers that appear to be random The numbers are not completely random. The numbers are drawnfrom a sequence of numbers that does not repeat for a long 4me random() returns a number that is 0 and 19/21/1692

Simulating Die Tosses Goal: To generate a random integer in a given range we use the randint()func4on Randint has two parameters, the range (inclusive) of numbersgenerated9/21/1693

Trace the loop with typical examples Coding: Implement the loop in Python 9/21/16 66 . A Special Form of the print Function . Pseudocode to Print the Table Print the table header: for x from 1 to 10 for n from 1 to 4 print Xn print a new line 9/21/16 73 n ! x! Inner Loop

Related Documents:

Westmont College Academic Catalog 2019-2020 Westmont College 955 La Paz Road Santa Barbara, CA 93108-1089 805-565-6000 www.westmont.edu

3:C Writing for the Liberal Arts is typically satisfied by taking an English Composition course at the college level, such as ENG-002 Composition at Westmont. ENG-002 Composition is a great way to prepare new students for writing at the college level. Strong writing skills are essential for success at Westmont College.

managed SAN and cloud storage, Westmont used Egnyte Storage Sync. This solution enabled Westmont to store, share and access files from anywhere with any device by combining the access of the cloud with the speed of local storage. This also helped reduce and/or eliminate costs of on-premises storage, Once we began to go with Egnyte, it was

power system: the automatic load frequency control loop (ALFC) and the automatic voltage control loop (AVR). There is little interaction from the ALFC loop to the AVR loop but the AVR loop does affect the ALFC loop to a certain extent. The AVR loop tends to be much faster than the ALFC loop with time constants of much less than one second.

the opinions of those with direct ties to the West Loop. I live in the West Loop I work in the West Loop I own property in the West Loop I own a business in the West Loop I am generally interested in the West Loop* Other (please specify) * 0 20 40 60 80 100 23.6% 59.7% 5.6% 4.9% 85.4% 32.6% 18 West Loop Design Guidelines Community Feedback 1 .

The Do-While and For loop structures are pretest loops. In a posttest loop, the condition is evaluated at the end of the repeating section of code. This is also called an exit-controlled loop. The Do/Loop Until construct is a posttest loop. Do While Loop The while loop allows you to di

while loop Format: while condition: loop body loop body 18 one or more instructions to be repeated condition loop body false true After the loop condition becomes false during the loop body, the loop body still runs to completion (before its check before the next turn) and exit the loop and go on with the next step.

The new 2nd grade Reading Standard 6 has been created by merging two separate reading standards: “Identify examples of how illustrations and details support the point of view or purpose of the text. (RI&RL)” Previous standards: 2011 Grade 2 Reading Standard 6 (Literature): “Acknowledge differences in the