Program 1

Simple Scripts

ICS-31: Introduction to Programming


Introduction This first real programming assignment is designed to ensure that you know the fundamentals of writing, testing, and debugging simple scripts using the Eclipse Integrated Development Environment (Eclipse IDE). In the process you will
  • Use various functions defined in the prompt module to prompt the user to input information (values).
  • Use assignment statements to store the input values into names
  • Use expression to calculate results based on these inputs and use assignment statements to store these calculated values into names.
  • Use the print function to output the calculated results.

Before starting this assignment, download and unzip the droptime project folder; put this folder into your workspace and open it in Eclipse (as you did in Program 0). It contains one script that you should examine and run; it inputs some information, performs some calculation on this information,and then outputs the results. Use this script as a model for the scripts you must write in this assignment.

To start working on this assignment, download and unzip the program1 project folder; put this folder into your workspace and open it in Eclipse. It contains one script that you will modify (named expresiontest), and is a place to store all the other scripts that you will write from scratch (escapevelocity, stringops, changemaker, and cartrip). You will create each modules in this project folder, and submit each module separately in Checkmate.

You should work on this assignment in pairs, with someone in your lab section. Try to find someone who lives near you, with similar work habits/schedule: e.g., talk about whether you prefer to work mornings, nights, or weekends; what kind of commitment you will make to submit program early. If you believe that it is impossible for you to work with someone, because of some special reason(s), you should send me email stating them and asking for special permission to work alone (which I do grant, but not frequently).

Only one student should submit all parts of the the assignment, but both student's names should appear in the comments at the top of each submitted .py file. It should look something like


# Romeo Montague, Lab 1
# Juliet Capulet, Lab 1
# We certify that we worked cooperatively on this programming
#   assignment, according to the rules for pair programming
Please turn in each program as you finish it, so that I can accurately assess the progress of the class as a whole during this assignment.

Print this document and carefully read it, marking any parts that contain important detailed information that you find (for review before you turn in the files). Reread the section on Time Management from Programming Assignment 0 before starting this assignment.

All these scripts prompt the user for information on the console. To access the these prompting functions, remember to first import them by writing import prompt in your program; call them by their qualified names (e.g., prompt.for_float). Many of these scripts also use mathematical functions like the square-root function (sqrt) defined in the math module. Import them by writing import math and call them by their names (e.g., math.sqrt); or you can use the alternative form of import from math import sqrt and then just call the name sqrt. The droptime script shows examples of both prompt and math imports.

Finally, it is a mistake to try to do all these problems in one sitting (especially on the night that they all are due). While all are simple, none are trivial and each part gets progressively harder. Sit down during the first lab and try to finish the first part; over the weekend, try to finish the second and third parts; if you succeed and have more time, finsh the last part (otherwise save it for next week) -maybe you will finish them all quickly. Even though the programming problems get more complicated, the first few are likely to cause you the most trouble: understanding the basics of the assignment (shared by all the programs), setting up everything, etc. It is important that you encounter all these difficulties early, by attempting to finish one problem over the first lab/weekend, well before the entire assignment is due; this will give you time to seek and obtain help, if you need it.


Part 1:
Calculating Escape Velocity
The velocity needed to escape the gravitation field of a planet is given by the mathematical formula

           +---------
          /  2 g mp
  ev =   /  --------
       \/      rp
where g is the Gravitational constant (6.67x10-11 in the metric system), mp is the mass of the planet (in kilograms), rp is the radius of the planet (in meters) and ev is the escape velocity in (in meters/second).

Here is a short table of planets and their (approximate) calculated escape velocities.

PlanetMass
(kilograms)
Radius
(meters)
Approximate Escape
Velocity (meters/sec)
Earth5.983x10246.357x10611,200
Venus4.906x10246.185x10610,300
Mars6.581x10233.382x1065,100
Jupiter1.904x10276.974x10760,300
Earth's Moon7.347x10221.738x1062,370

Write a script that prompts the user for a planet's mass and radius (as float values), and then computes and displays the escape velocity of the planet. Verify that these answers are correct using the table above, to ensure that your script is working correctly: note that values it contains are just approximate. Use the names in this formula in your program. Here is the input/output form you script should duplicate: the user's inputs are shown in italics.

  Enter mass in kilograms: 5.983E24
  Enter radius in meters: 6.357E6
  Escape velocity = 11204.98580007702
Of course you should test your code for other values in the table above, to ensure the correct answers are calculated and printed.

Part 2:
String Operations
Write a script that prompts the user for strings and computes various operations on them. Use section 5.2.7 as a guide having for indexing (computing individual characters) and slicing (computing sequences of characters or substrings) in strings; see section 5.2.3 for concatenation (putting characters and substrings together into strings).
  1. Prompt the user for a word and print a bool value (True or False telling whether the first and last character are the same; try various length words, but always at least of length one.
  2. Prompt the user for a name in the form Smith, Joe; then print the index of the comma in the word and the name in the form Joe Smith.
  3. Prompt the user for a name in the form Joe Smith; then print the index of the space in the word and the name in the form Smith, Joe.
Note that to compute the index of the first occurrence of a character we can use the find method on any string. Here is an example that you can run/test as a script
word = 'balloon'
index = word.find('l')
print('l occurs first at index',index,'of balloon')
Remember that indexes in strings start at 0

Here is the input/output form you script should duplicate: the user's inputs are shown in italics.

  Enter a word: radar
  First and last letter the same? True
  Enter a name (e.g., Smith, Joe): Stern, Hal
  Comma in index 5 (remember first character is in index 0)
  Converted name: Hal Stern
  Enter a name (e.g., Joe Smith): Michael Goodrich
  Space in index 7
  Converted name: Goodrich, Michael
Of course you should test your code for other values in the table above, to ensure the correct answers are calculated and printed.


Part 3:
Change Maker
Write a script that prompts the user for some amount of change to make (an int from 1 to 99 cents; don't worry about bad input), and then computes and displays the number of quarters, dimes, nickels, and pennies needed to make that amount of change. Always compute the fewest coins to make that change. For example, if the user entered 69 the script would display
  To make change for 69 cents:
    2 quarters
    1 dimes
    1 nickels
    4 pennies
Don't worry about displaying things like 1 dimes (mismatching a singular and plural). Before instructing the computer how to make change, think about how you would teach another person to make change.

Algorithm Hint: After the user inputs the amount of change to make, store/remember it in another name for use when we start printing values at the end. Use names, keep track of the amount of change still left to be made (this will be reduced as the script executes), and the number of quarter, dimes, nickels, and pennies. First compute and store in the name quarters the number of quarters in the change (you will find the // operator useful for divison, because it throws away the fractional part, leaving an integer). Then, update the amount of change to make to be the amount remaining after subtracting the number of quarters returned times their worth. Repeat this process (with similar statements) for dimes, then nickels, and finally for pennies. Finally, print the calculated amounts.

For example, to make 69 cents in change, the program computes 69//25 which is 2, meaning we should use two quarters; this leaves 69-2*25 which is 19 cents, meaning that we now must make 19 cents in change by using dimes, nickels, and pennies. To make 19 cents in change, the program computes 19//10 which is 1, meaning we should use one dime; this leaves 19-1*10 which is 9 cents, meaning that we now must make 9 cents in change by using nickels, and pennies. By following this pattern, the program computes and prints the result above. Finally, note that some amounts for coins may be zero:

  To make change for 55 cents:
    2 quarters
    0 dimes
    1 nickels
    0 pennies
The formulas used above compute the right answer even if no coins of that denomination are to be used.

An alternative way is to use the % operator (there are many different ways to solve this problem). For example, to make change for 69 cents, after computing the need to return 2 quarters (same computation above), the amount of change left to make is 69%25 which is the remainder after 69 is divided by 25: 25 goes into 69 twice, with a remainder of19. Before programming the solution in Python, develop a procedure that allows you to calculate the right values when you follow it, and then automate that solution by translating it into a Python script.

Here is the input/output form you script should duplicate: the user's inputs are shown in italics.

  Enter change to make(1..99): 150
    Entry Error: '150';  
    Please enter a value in the range [1,99]
  Enter change to make(1..99): 69
  To make change for 69 cents:
    2 quarters
    1 dimes
    1 nickels
    4 pennies
Notice how the prompt rejects the first input. Examine the documentation for the for_int_between function in the prompt module on the course web index by clicking Course Library References then prompt. Of course you should test your code for other values, to ensure the correct answers are calculated and printed.

Part 4:
Formulas -> Expressions
The following three lines contain a total of 13 formulas

There are 7 on the first line, and 3 each on the second and third lines.

The script expressiontest contains code to test all these formulas: it prompts the user for the information needed by the formula, stores this information into names, and prints the answers. But, you need to translate each of the 13 formulas into a correct Python expression that calculates the answer (now, each now just says answer = 0.). For maximum credit, your expressions should contain no redundant parentheses; parentheses are redundant if they can be removed, but leave the expression always still computing the correct answer, still performing the required operations in the correct order.

For example, the parentheses in (a*b)/c are redundant because even if we remove them, the expression a*b/c will still multiply a by b before dividing by c (by Python's rules of operator precedence and associativity). The parentheses in a/(2.*b) are NOT redundant because if we remove them, the result will be the quantity a/2. times b. Note, some students might write a/2./b but I find this expression more difficult to understand: you don't have to minimize parentheses; you just want to write no redundant ones. There is a difference between these goals (reread the material above for clarification).

Finally, to access the mathematical constants π and e in these formulas, import the name pi and e defined in the math module. Use these names instead of writing your own literals that approximate these values.


Part 5:
Car Trip Calculator
Write a script that prompts the user for information about a car trip and then computes and prints more information about the trip. The program should prompt the user to enter
  • The car's tank size
  • The car's mph (miles per gallon)
  • The distance for the trip
  • The cost of a gallon of gas
Based on this information, the script should print (see the form below)
  • The car's range
  • The amount of fuel needed for the trip
  • The cost of gas for the trip
  • The number of gas stops needed (assuming stopping only when completely empty: dangerous; and completely filling the tank at each stop)
  • The amount of fuel left in the tank when the destination is reached.
Here is the input/output form you script should duplicate: the user's inputs are shown in italics. Round numbers are shown, to make explaining the calculation easier.
  Enter car's tank size in gallons: 10.
  Enter car's mpg: 20.
  Enter distance for trip in miles: 500.
  Enter cost for a gallon of gas: 4.

  This car has a range of 200.0 miles
  Assuming we start with a filled tank
    we will use a total of 25.0 gallons on this trip
    at a cost of 100.0 dollars
    requiring 2 refueling stops
    and when we arrive, the car has 5.0 gallons in its tank
Of course you should test your code for other values, to ensure the correct answers are calculated and printed. Use appropriate names to store the inputs and calculated values

Hints: Computing the first three values is straightforward, but the fourth (refueling stops) is a bit subtle, so let's explore it. The trip distance divided by the car's range computes the number of tanks of gas needed for the trip; recall that the car starts with a full tank, so that ratio minus 1 is the number of refueling stops. For the example above, we compute this ratio it is 500./200. which is 2.5 tanks, so this trip requires 1.5 refueling stops (1.5 more tanks full of gas). But, there is no such thing as half a refueling stop: we either stop to refuel and fill up the tank or don't; This means there are really 2 refueling stops.

The math module defines a function named ceil (for ceiling) which takes as an argument a floating point number and returns that value (if it is integral: math.ceil(2.0) is just 2) or the next bigger integer: math.ceil(1.5) is 2. We can use this function to convert the calculated 1.5 refueling stops to 2 refueling stops. This is similar to the following simpler problem: how many buses do we need to transport 250 passengers if each bus we can use holds 100 passengers; the ratio is 2.5 buses, but there is no such thing as half a bus, so we need to raise the number to 3 buses. We can compute this result as math.ceil(250/100). Use the Python interpreter to import and experiment with this function.

How much fuel do we have when we arrive? Calculate how much fuel we put into the car for the trip (include the fact that we start with a full tank) and subtract the amount of fuel we use on the trip. Use a calculator to check your approach to ensure it is correct, before you write your script.