Difference between revisions of "CSC111 Lab 3 2015b"
(→Challenge #7: (Challenging!)) |
(→Challenge #1: A Change Machine) |
||
Line 243: | Line 243: | ||
Amount to withdraw = 84 cent(s) | Amount to withdraw = 84 cent(s) | ||
− | |||
Please lift keyboard and find: | Please lift keyboard and find: | ||
3 quarter(s) | 3 quarter(s) | ||
Line 252: | Line 251: | ||
<br /> | <br /> | ||
<br /> | <br /> | ||
+ | |||
==<font color="magenta">Moodle Submission</font>== | ==<font color="magenta">Moodle Submission</font>== | ||
<br /> | <br /> |
Revision as of 15:14, 23 September 2015
--D. Thiebaut (talk) 10:42, 20 September 2015 (EDT)
The lab today deals with several concepts covered in Chapter 3 of Zelle. You have two programs to submit to Moodle, one for Challenge 1, and another one for Challenge 4. The deadline for the submission is Friday 9/25 at 11:55 p.m.
You should work on this lab with a programming-pair partner.
We are now moving to a more professional way of writing programs that always contain a main() function.
We are also changing the way you evaluate your programs on Moodle. Your program will be evaluated automatically when you submit it. If you want to make a change to the program, you will have to change it in IDLE first, then resubmit to Moodle. IDLE is a much better editor to edit code, and we want to reinforce good programming practice, and make sure you use IDLE, and not Moodle, to write programs!
Contents
- 1 Understanding how Floats take over Expressions
- 2 Teller Machine Program
- 2.1 Reviewing the Division Operators, // and %
- 2.2 Beginning Program
- 2.3 Define original amount
- 2.4 Compute the number of $20s to give out
- 2.5 Computing the Left-Over Amount
- 2.6 Computing the Remaining Quantities
- 2.7 Flexibility and Adaptability
- 2.8 Challenge #1: A Change Machine
- 2.9 Moodle Submission
- 3 Formatted Output
- 4 Accumulating Quantities
- 5 Solution Program
Understanding how Floats take over Expressions
In this section I am asking you to play and get an understanding of important functions, and also how floating point numbers (numbers with a decimal point) take over expressions, when they are present in them.
Open the Python shell and type the expressions below. Try to predict the output of the interpreter when you are about to press the ENTER key.
>>> a = 3 >>> x = 1.5 >>> type( a ) >>> type( x ) >>> type( a * x ) >>> type( a * 100 ) >>> type( 1 ) >>> type( 1.0 ) >>> type( "1" ) >>> a / 3 >>> a // 3 >>> type( a/3 ) >>> type( 5/4 ) >>> type( 5//4 ) >>> type( int( 1.5 ) ) >>> int( 1.5 ) >>> round( 1.6 ) >>> round( 1.4 ) >>> round( -1.8 ) >>> type( round( 1.4 ) ) >>> round( -1.8 ) >>> abs( -4 ) >>> abs( 10 ) >>> type( abs( -19.3 ) ) >>> type( abs( -4 ) )
- Note how once something is a float, if forces whatever it gets combined with to yield a result that is float, except for the int() function, of course.
Challenge #0: (we always start at 0 in Computer Science!) |
- Write a small program (either in the Python Shell, or in the Edit window), that asks the user to enter a number between 0 and 100, and that prints out 0 if the number is between 0 and 25 (25 not included), 1 if the number is between 25 and 50 (50 not included), 2 if the number is between 50 and 75 (75 not inclulded), and 3 if the number is between 75 and 100 (100 not included).
- Here is an example of the type of exchange I had with
>>> >>> x = eval( input( "Enter a number: " ) ) Enter a number: 75.7 >>> result = ... write an expression here that takes x and computes the expected result >>> result 3 >>> x = 1 >>> result = ... use the same expression you wrote above... >>> result 0 >>> x = 24.99999 >>> result = ... use the same expression you wrote above... >>> result 0 >>> x = 25.00000001 >>> result = ... use the same expression you wrote above... >>> result 1 >>>
Teller Machine Program
This section will get you to write a program similar (though not necessarily the same) to the program we wrote in class on Monday. The program takes an integer (without a decimal part) amount of dollars and figures out how to break it down into the least number of 20-, 10-, 5-, and 1-bills.
Reviewing the Division Operators, // and %
Use the Python shell, and try to predict the result of the following operations.
>>> 21 // 5 >>> 21 % 5 >>> 9 // 2 >>> 9 % 2 >>> 13 // 3 >>> 13 % 3 >>> 139 // 20 >>> 139 % 20
Beginning Program
- Write a program that contains
- a short header with the program name (lab3.py, for example),
- your name,
- the date, and
- A short description of the program.
- A main() function
- 3 different comment lines inside the main function, that will create an outline of your program.
- A call to main()
# lab3.py # yourName 1 # yourName 2 # date # A 1-paragraph description of what the program does. # def main(): # get the initial amount # compute number of bills # output number of bills to give out main()
- Save and Run the program, just to make sure you do not have a syntax error.
Define original amount
- Under the #get the initial amount comment, create a variable called amount and initialize it with a value of your choice. Pick a value that is not a multiple of 5.
- Add a print() statement under the #output number of bills comment, and make it print the amount the user wants to withdraw.
- Verify that your program works.
Compute the number of $20s to give out
- Using the right operator (//, /, or %), make your program compute the number of $20 and store that value in a new variable, called no20s. Add this code under the # compute number of bills.
- Make your program output the no20s variable in the output section.
- Verify that your program works.
Computing the Left-Over Amount
- Go back to the computation of the number of $20s, and compute the amount of money left over once the $20s are taken out of the amount. You have several ways of doing this. You can do it using the % modulo operator, or using multiplication and subtraction. Whichever method you use is fine for today.
- Make your program output the left-over amount, just to make sure that value is computed correctly.
- Verify that your program works fine.
Computing the Remaining Quantities
- Now that you have the structure for your program, add enough Python code to make your code display
- The total amount
- The number of $20-bills
- The number of $10-bills
- The number of $5-bills
- The number of $1-bills
- Verify that your program works. Below is a typical output you should try to emulate:
Amount to withdraw = 97 Please lift keyboard and find: 4 $20-bill(s) 1 $10-bill(s) 1 $5-bill(s) 2 $1-bill(s)
Flexibility and Adaptability
Imagine that your program will be used in an area where the bills do not come in 20, 10, 5 or 1 denominations, but in 100, 50, 10, and 1.
Figure out a way to make the least amount of change to your program so that it now outputs the correct break down for any amount, but in $100-, $50-, $10- and $1-bills.
Make sure your program works! Below is the output of the program if the amount is set to $97:
Amount to withdraw = $ 97 Please lift keyboard and find: 0 $ 100 bill(s) 1 $ 50 bill(s) 4 $ 10 bill(s) 7 $ 1 bill(s)
Challenge #1: A Change Machine |
- Using a similar approach, write a program that, given some number of pennies, will output the correct number of quarters, dimes, nickels, and pennies. You should initialize the amount of pennies with an integer, like this:
pennies = 84
- Here is an example of what your program should output for 84 pennies:
Amount to withdraw = 84 cent(s) Please lift keyboard and find: 3 quarter(s) 0 dime(s) 1 nickel(s) 4 cent(s)
Moodle Submission
- Modify your program for Challenge 1, and rename it Lab3_1.py. It should now prompt the user for a number of pennies, and then, once it has received that number, it will print the number of coins that make up that quantity. We assume that the user may not be fully well behaved and might enter negative numbers, or numbers with a decimal point. For example, if the user enters -84, your program will treat this number as +84. If the user enters 84.5, your program will treat it as 84.
- Submit your program to the LAB 3 PB 1 section on Moodle. Note that the Moodle test program will strip all words from your output and will look only at the numbers, so you do not need to worry about the exact phrasing of your output.
Formatted Output
Strings
In this section you will work on formatting strings, ints, and floats using the {...} formatting command.
- Try this statement out:
name = "Snow White" print( "Hello {0:1}! How are you?".format( name ) )
- Then modify the {0:1} part and try these different combinations: {0:5}, {0:10}, {0:15}, {0:20}. For each one, make sure you understand why the output changes (or not).
- Then try these different formats: {0:>1}, {0:>5}, {0:>10}, {0:>15}, {0:>20}. Notice the right-justification of the string Snow White in this second set of outputs.
- Now try this piece of code:
print( ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "Hello {0:10}!".format( friend ) )
Printing 2 strings at once
- Change the print() statement so that you now print two different strings, each with its own {...} format:
print( ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "{0:1} wants to take {1:1} to the Valentine's ball." . format( friend, "Snow White" ) )
- Now switch the 0 and the 1 in the two {...} expressions, as illustrated in the line below:
print( "{1:1} wants to take {0:1} to the Valentine's ball." . format( friend, "Snow White" ) )
- Notice how the first number in the {...} expressions is used to figure out which string to pick in the format(...) block.
Printing a String and an Int
- Try this formatting command:
name = "Valentine's Day" day = 15 print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) ) name = "My birthday" day = 6 print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) )
- Here's another statement to try:
name = "Snow White"
length = len( name )
print( "the string {0:1} contains {1:1} characters" . format( name, length ) ) )
Printing Floats
- Copy/paste this block of code below in your program. Then run it. Verify that the output makes sense.
def main(): print( "Printing PI" ) pi = 3.14159 print( "-------------------------" ) print( "Pi={0:1.0f}!".format( pi ) ) print( "Pi={0:2.0f}!".format( pi ) ) print( "Pi={0:3.0f}!".format( pi ) ) print( "Pi={0:4.0f}!".format( pi ) ) print( "Pi={0:5.0f}!".format( pi ) ) print( "Pi={0:6.0f}!".format( pi ) ) print( "Pi={0:7.0f}!".format( pi ) ) print( "Pi={0:8.0f}!".format( pi ) ) print( "Pi={0:9.0f}!".format( pi ) ) print( "-------------------------" ) print( "Pi={0:9.1f}!".format( pi ) ) print( "Pi={0:9.2f}!".format( pi ) ) print( "Pi={0:9.3f}!".format( pi ) ) print( "Pi={0:9.4f}!".format( pi ) ) print( "Pi={0:9.5f}!".format( pi ) ) print( "-------------------------" ) print( "Pi={0:<9.1f}!".format( pi ) ) print( "Pi={0:<9.2f}!".format( pi ) ) print( "Pi={0:<9.3f}!".format( pi ) ) print( "Pi={0:<9.4f}!".format( pi ) ) print( "Pi={0:<9.5f}!".format( pi ) ) main()
Temperature Conversion
- Remember that we saw that a temperature in Celsius is computed as the temperature in Fahrenheit - 32, the difference multiplied by 5/9?
- Write a program with a main() function that contains a for-loop that displays two columns of numbers, the column on the left showing degrees Fahrenheit, and the column on the right showing Celsius.
- Your program should prompt the user for the beginning and end temperatures in Fahrenheit, and display 2 columns of numbers.
Starting temperature? 20 Ending temperature? 40 20 -6.666666666666667 22 -5.555555555555555 24 -4.444444444444445 26 -3.3333333333333335 28 -2.2222222222222223 30 -1.1111111111111112 32 0.0 34 1.1111111111111112 36 2.2222222222222223 38 3.3333333333333335 40 4.444444444444445
Challenge #3: |
- Use the {...} formatting command to make your output look nicer:
Starting temperature? 20 Ending temperature? 40 20.00 -6.67 22.00 -5.56 24.00 -4.44 26.00 -3.33 28.00 -2.22 30.00 -1.11 32.00 0.00 34.00 1.11 36.00 2.22 38.00 3.33 40.00 4.44
- (Note the blank line between the input section, and the output of the program. You need your program to output it!)
Challenge #5: |
- Replace the list of numbers [100, 10, -30, -2, 20, 5 ] by the range() function and make your program compute the sum of all the even numbers between 0 and 100, included.
- Verify that your program outputs 2550 as the result! You do not need to make your program output all the intermediate values of sumAll.
Count the Items in a List
- Try this piece of code now:
count = 0 for n in [ 100, 10, -30, -2, 20, 5 ]: count = count + 1 print( "there are", count, "items in the list" )
- See how this code is different from the loop in the previous section. Here we add 1 to the counter every time we go through the loop. In other words, we add 1 for every item we find in the list. So, in effect, we are counting the items in the list.
- Run your code and see what it outputs.
- Add print statement inside the loop, below the count = count + 1 line, and make the print statement print n and count. Don't worry about the formatting.
- Run your code. Do you see the program counting the items it finds in the list of numbers?
Challenge #6: |
- Write a program that uses a for-loop that scans a list of numbers: [1, 2, 2, 1, 2, 3, 3, 2, 1, 0]
- Make your program compute the average of the numbers in the list. The average is the sum of all numbers divided by the number of items.
- Your program should output the average at the end, as a floating-point number.
- Run your program. Verify that you get the correct result (sum = 17 average = 1.70).
Accumulating Strings
- Here's a new program to try:
line = "" for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy" ]: line = line + friend + ", " print( "line =", line )
Challenge #7: (Challenging!) |
- Write a program that contains a single loop, of the form for n in [ 2, 3, 5, 3, 2 ]:, and that accumulates a string, which, when it is fully computed, is equal to "**---*****---**".
<showafterdate after="20150926 9:00" before="20151231 00:00">
Solution Program
# lab3Solutions.py # D. Thiebaut # Solution programs for CSC111 Lab #3 # # All the solutions are group into one large main program. def main(): # Challenge 0 for x in [ 0, 1, 24.99, 25, 25.001, 30, 51, 79, 99]: result = int( x/25 ) print( "x = ", x, " result = ", result ) # Teller Machine # Takes some amount of $ and breaks it down in 20, 10, 5, and 1 # dollar bills. # set the amount amount = 97 # break it down no20s = amount // 20 leftOver = amount % 20 no10s = leftOver // 10 leftOver = leftOver % 10 no5s = leftOver // 5 leftOver = leftOver % 5 no1s = leftOver # printout the number of bills print() print( "You want to withdraw ${0:1}".format( amount) ) print( "Lift the keyboard and find:" ) print( "{0:4} $20-bill(s)". format( no20s ) ) print( "{0:4} $10-bill(s)". format( no10s ) ) print( "{0:4} $5-bill(s)". format( no5s ) ) print( "{0:4} $1-bill(s)". format( no1s ) ) # ========================================================== # Teller Machine with a different set of denominations # set the amount amount = 197 # break it down no100s = amount // 100 leftOver = amount % 100 no50s = leftOver // 50 leftOver = leftOver % 50 no10s = leftOver // 10 leftOver = leftOver % 10 no1s = leftOver # printout the number of bills print() print( "You want to withdraw ${0:1}".format( amount) ) print( "Lift the keyboard and find:" ) print( "{0:4} $100-bill(s)". format( no20s ) ) print( "{0:4} $50-bill(s)". format( no10s ) ) print( "{0:4} $10-bill(s)". format( no5s ) ) print( "{0:4} $1-bill(s)". format( no1s ) ) # simple output print() name = "Snow White" print( "Hello {0:1}! How are you?".format( name ) ) print( "Hello {0:5}! How are you?".format( name ) ) print( "Hello {0:10}! How are you?".format( name ) ) print( "Hello {0:15}! How are you?".format( name ) ) print( "Hello {0:20}! How are you?".format( name ) ) print( "Hello {0:>1}! How are you?".format( name ) ) print( "Hello {0:>5}! How are you?".format( name ) ) print( "Hello {0:>10}! How are you?".format( name ) ) print( "Hello {0:>15}! How are you?".format( name ) ) print( "Hello {0:>20}! How are you?".format( name ) ) # Formatted output, Version 1 print( ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "Hello {0:10}!".format( friend ) ) # Swapping first and second strings print( ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "{1:1} wants to take {0:1} to the Valentine's ball." . format( friend, "Snow White" ) ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "{0:1} wants to take {1:1} to the Valentine's ball." . format( friend, "Snow White" ) ) # Unformatted dwarf names and length of names for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( friend, len(friend) ) # Formatted output, Version 2 bar = "+-" + 10*'-' + "-+-" + 3*'-' + "-+" print( bar ) for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: print( "| {0:10} | {1:3} |".format( friend, len(friend) ) ) print( bar ) # print string and int name = "Valentine's Day" day = 15 print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) ) name = "My birthday" day = 6 print( "{0:>20} is on the {1:1}th of the month" . format( name, day ) ) # printing floats print() print( "Printing PI" ) pi = 3.14159 print( "Pi={0:1.0f}!".format( pi ) ) print( "Pi={0:2.0f}!".format( pi ) ) print( "Pi={0:3.0f}!".format( pi ) ) print( "Pi={0:4.0f}!".format( pi ) ) print( "Pi={0:5.0f}!".format( pi ) ) print( "Pi={0:6.0f}!".format( pi ) ) print( "Pi={0:7.0f}!".format( pi ) ) print( "Pi={0:8.0f}!".format( pi ) ) print( "Pi={0:9.0f}!".format( pi ) ) print( "-------------------------" ) print( "Pi={0:9.1f}!".format( pi ) ) print( "Pi={0:9.2f}!".format( pi ) ) print( "Pi={0:9.3f}!".format( pi ) ) print( "Pi={0:9.4f}!".format( pi ) ) print( "Pi={0:9.5f}!".format( pi ) ) print( "-------------------------" ) print( "Pi={0:<9.1f}!".format( pi ) ) print( "Pi={0:<9.2f}!".format( pi ) ) print( "Pi={0:<9.3f}!".format( pi ) ) print( "Pi={0:<9.4f}!".format( pi ) ) print( "Pi={0:<9.5f}!".format( pi ) ) # Print table of temperatures print() for Fahr in range( 20, 41, 2 ): print( Fahr, (Fahr-32.0)*5.0/9 ) print() for Fahr in range( 20, 41, 2 ): print( "{0:10.2f}F = {1:10.2f}C".format( Fahr*1.0, (Fahr-32.0)*5.0/9 ) ) # Print table of temperatures with bars around bar = "+-" + 10*'-' + "--+-" + 10*'-' + "--+" print( bar ) print( "| {0:>10} | {1:>10} |".format( "Fahrenheit", "Celsius" ) ) print( bar ) for Fahr in range( 20, 41, 2 ): print( "| {0:10.2f}F | {1:10.2f}C |".format( Fahr*1.0, (Fahr-32.0)*5.0/9 ) ) print( bar ) def main2(): # compute the sum a list of numbers # (note that there's a much simpler way to do this in Python, which # we'll see later during the semester.) print() sumAll = 0 for n in [100, 10, -30, -2, 20, 5 ]: sumAll = sumAll + n print( "n = {0:3} sum = {1:3}" . format( n, sumAll ) ) print( "sum = ", sumAll ) # add-up the even numbers between 0 and 100. print() sumAll = 0 for n in range( 0, 101, 2 ): sumAll = sumAll + n print( "the sum of all the even numbers from 0 to 100, included, is", sumAll ) # count how many items are in the list print() count = 0 for n in [ 100, 10, -30, -2, 20, 5 ]: count = count + 1 print( "n = {0:3} count = {1:3}" . format( n, count ) ) print( "there are", count, "items in the list" ) # compute the sum and average of a list of numbers print() sumAll = 0 count = 0 for n in [1, 2, 2, 1, 2, 3, 3, 2, 1, 0]: sumAll = sumAll + n count = count + 1 print( "sum = {0:1} average = {1:1.2f}" . format( sumAll, sumAll*1.0/count ) ) # compute the factorial of a number # factorial( 10 ) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 print() n = 20 fact = 1 for i in range( 1, n+1 ): print( "computing fact * i = {0:1} * {1:1} = {2:1}" .format( fact, i, fact*i ) ) fact = fact * i print( "factorial({0:1}) = {1:1}".format( n, fact ) ) # create a string with all the names of the 7 dwarves print() line = "" for friend in [ "Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]: line = line + friend + ", " print( "line =", line ) # Challenge print() line = "" char1 = "*" char2 = "-" for n in ( 2, 3, 5, 3, 2 ): line = line + n*char1 char1, char2 = char2, char1 print( "line = ", line ) main2()
</showafterdate>