Tuesday, January 22, 2019

MIT Intro to CS and Programming PS1B

Here is the solution to problemset1 question B of 6.0001 entitled Introduction to Computer Science and Programming in Python (Fall 2016).

Problem

Part B: Saving, with a raise
Background  
In Part A, we unrealistically assumed that your salary didn’t change.  But you are an MIT graduate, and clearly you are going to be worth more to your company over time! So we are going to build on your solution to Part A by factoring in a raise every six months.  

In ps1b.py, copy your solution to Part A (as we are going to reuse much of that machinery).  Modify your program to include the following

  1. Have the user input a semi-annual salary raise semi_annual_raise (as a decimal percentage) 
  2. After the 6th month, increase your salary by that percentage. Do the same after the 12 th th month, the 18 month, and so on.
Write a program to calculate how many months it will take you save up enough money for a down payment.  Like before, assume that your investments earn a return of r = 0.04 (or 4%) and the required down payment percentage is 0.25 (or 25%).  Have the user enter the following variables:

  1. The starting annual salary (annual_salary) 
  2. The percentage of salary to be saved (portion_saved) 
  3. The cost of your dream home (total_cost) 
  4. The semi­-annual salary raise (semi_annual_raise)
Hints To help you get started, here is a rough outline of the stages you should probably follow in writing your code:

  • Retrieve user input. 
  • Initialize some state variables. You should decide what information you need. Be sure to be careful about values that represent annual amounts and those that represent monthly amounts.
  • Be careful about when you increase your salary – this should only happen after the 6th, 12 th, 18 th month, and so on.
Try different inputs and see how quickly or slowly you can save enough for a down payment.  Please make your program print results in the format shown in the test cases below.

Test Case 1
>>>   
Enter your starting annual salary: 120000
Enter the percent of your salary to save, as a decimal: .05
Enter the cost of your dream home: 500000
Enter the semi­annual raise, as a decimal: .03 Number of months: 142
>>>

Test Case 2  
>>>   
Enter your starting annual salary: 80000
Enter the percent of your salary to save, as a decimal: .1
Enter the cost of your dream home: 800000
Enter the semi­annual raise, as a decimal: .03
Number of months: 159  
>>>

Test Case 3  
>>>   
Enter your starting annual salary: 75000
Enter the percent of your salary to save, as a decimal: .05
Enter the cost of your dream home: 1500000
Enter the semi­annual raise, as a decimal: .05
Number of months: 261
>>>

(Bell, Grimson & Guttag, 2016)

Solution
The solution to this problem is essentially the same as the solution to problem set A with one small change. They say that you are getting a raise every six months.

You can easily calculate the raise by adding the extra money to the salary variable, but you need to do this only every six months.

The % operator gives returns remainders. Whenever the remainder of 6 is zero you are going to know that that number is a multiple of 6. You can add this condition in as an if statement into the while loop.

Code

annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))
semi_annual_raise = float(input("Enter the semi­annual raise, as a decimal: "))

portion_down_payment = total_cost * 0.25
current_savings = 0
r = 0.04
months = 0
while current_savings < portion_down_payment:
   current_savings += (annual_salary/12)*portion_saved + current_savings*(r/12)
   months += 1
   if months%6 == 0:
       annual_salary += annual_salary * semi_annual_raise

print("Number of months: ", months)

Output

Test case 1
Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .05
Enter the cost of your dream home: 500000
Enter the semi­annual raise, as a decimal: .03
Number of months:  142

Test case 2
Enter your annual salary: 80000
Enter the percent of your salary to save, as a decimal: .1
Enter the cost of your dream home: 800000
Enter the semi­annual raise, as a decimal: .03
Number of months:  159

Test case 3
Enter your annual salary: 75000
Enter the percent of your salary to save, as a decimal: .05
Enter the cost of your dream home: 1500000
Enter the semi­annual raise, as a decimal: .05
Number of months:  261

Reference
Ana Bell, Eric Grimson, and John Guttag. 6.0001 Introduction to Computer Science and Programming in Python. Fall 2016. Massachusetts Institute of Technology: MIT OpenCourseWare, https://ocw.mit.edu. License: Creative Commons BY-NC-SA.

MIT Intro to CS and Programming PS1A

This is the solution to problemset1 question A of 6.0001 entitled Introduction to Computer Science and Programming in Python (Fall 2016).
Part A: House Hunting You have graduated from MIT and now have a great job! You move to the San Francisco Bay Area and decide that you want to start saving to buy a house.  As housing prices are very high in the Bay Area, you realize you are going to have to save for several years before you can afford to make the down payment on a house. In Part A, we are going to determine how long it will take you to save enough money to make the down payment given the following assumptions:

  1. Call the cost of your dream home total_cost. 
  2. Call the portion of the cost needed for a down payment portion_down_payment. For simplicity, assume that portion_down_payment = 0.25 (25%). 
  3. Call the amount that you have saved thus far current_savings. You start with a current savings of $0. 
  4. Assume that you invest your current savings wisely, with an annual return of r (in other words, at the end of each month, you receive an additional current_savings*r/12 funds to put into your savings – the 12 is because r is an annual rate). Assume that your investments earn a return of r = 0.04 (4%). 
  5. Assume your annual salary is annual_salary. 
  6. Assume you are going to dedicate a certain amount of your salary each month to saving for the down payment. Call that portion_saved. This variable should be in decimal form (i.e. 0.1 for 10%). 
  7. At the end of each month, your savings will be increased by the return on your investment, plus a percentage of your monthly salary (annual salary / 12).
Write a program to calculate how many months it will take you to save up enough money for a down payment. You will want your main variables to be floats, so you should cast user inputs to floats.    1 Your program should ask the user to enter the following variables:

  1. The starting annual salary (annual_salary)
  2. The portion of salary to be saved (portion_saved)
  3. The cost of your dream home (total_cost)
Hints To help you get started, here is a rough outline of the stages you should probably follow in writing your code:

  • Retrieve user input. Look at input() if you need help with getting user input. For this problem set, you can assume that users will enter valid input (e.g. they won’t enter a string when you expect an int)
  • Initialize some state variables. You should decide what information you need. Be careful about values that represent annual amounts and those that represent monthly amounts.
Try different inputs and see how long it takes to save for a down payment.  Please make your program print results in the format shown in the test cases below.    


Test Case 1
>>>
Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .10
Enter the cost of your dream home: 1000000
Number of months: 183  
>>>


Test Case 2
>>>
Enter your annual salary: 80000  
Enter the percent of your salary to save, as a decimal: .15
Enter the cost of your dream home: 500000
Number of months: 105
>>>


(Bell, Grimson & Guttag, 2016)

The first thing you need to do in order to solve this problem is to read through the variables very carefully to ensure that you have everything set up properly.

Once you have the values you can set up a while loop that stops once the once the savings is greater than the deposit. You are going to need to add up the amount of money that is being saved as well as the return that you are making on the investment.

The return they are looking for is the number of months which you can keep track of with a simple counter.

Solution


annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))


portion_down_payment = total_cost * 0.25
current_savings = 0
r = 0.04
months = 0
while current_savings < portion_down_payment:
   current_savings += (annual_salary/12)*portion_saved + current_savings*(r/12)
   months += 1


print("Number of months: ", months)


Output

Test Case 1
Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .10
Enter the cost of your dream home: 1000000
Number of months:  183


Test Case 2
Enter your annual salary: 80000
Enter the percent of your salary to save, as a decimal: .15
Enter the cost of your dream home: 500000
Number of months:  105

Reference
Ana Bell, Eric Grimson, and John Guttag. 6.0001 Introduction to Computer Science and Programming in Python. Fall 2016. Massachusetts Institute of Technology: MIT OpenCourseWare, https://ocw.mit.edu. License: Creative Commons BY-NC-SA.

MIT Intro to CS and Programming PS0

I am going to post the solutions to the MIT Problem Sets that have no solutions on their websites. Here is the solution to problemset0 of 6.0001 entitled Introduction to Computer Science and Programming in Python (Fall 2016).

Assignment

Write a program that does the following in order:
  1. Asks the user to enter a number “x” 
  2. Asks the user to enter a number “y” 
  3. Prints out number “x”, raised to the power “y”. 
  4. Prints out the log (base 2) of “x”.
Use Spyder to create your program, and save your code in a file named ‘ps0.py’. An example of an interaction with your program is shown below. The words printed in blue are ones the computer should print, based on your commands, while the words in black are an example of a user's input. The colors are simply here to help you distinguish the two components.


Enter number x: 2
Enter number y: 3
X**y = 8
log(x) = 1


(Bell, Grimson & Guttag, 2016)

As this is the zero problem set it is very easy. All you need to do is get the user input and store in a variable. Convert the string to an int and perform the operations. I used numpy to calculate the logarithm.

My Solution


import numpy as np


x = int(input("Enter number x: "))
y = int(input("Enter number y: "))


print("x**y = ", x**y)
print("log(x) = ", np.log2(x))


Sample output

Enter number x: 2
Enter number y: 2
x**y =  4
log(x) =  1.0

Reference
Ana Bell, Eric Grimson, and John Guttag. 6.0001 Introduction to Computer Science and Programming in Python. Fall 2016. Massachusetts Institute of Technology: MIT OpenCourseWare, https://ocw.mit.edu. License: Creative Commons BY-NC-SA.

Python Basics 2 - String Operations, Concatenation and More!

In the previous lesson I introduced you to the most basic operation in Python which is the print statement. It is very useful for telling what things are and for what you program is doing. In this lesson we are going to talk about a operations on strings.

Strings are a datatype in Python that hold things like characters, numbers or basically anything that you want to put in them. They are enclosed in quotation marks. We will speak more about different data types in a later lesson.

Have a look at the following code:


print("Strings are wrapped in double quotes")
print('Or they can be wrapped in single quotes')
print('1000')
print("Beware the savage jaw of 1984")
print(',./<>:;[]{}!@#$%^&*()-_=+~`')


When you run the file you should get this output:


Strings are wrapped in double quotes
Or they can be wrapped in single quotes
1000
Beware the savage jaw of 1984
,./<>:;[]{}!@#$%^&*()-_=+~`

Strings can be wrapped in either double or single quotes and everything in the above file is a string. You can even have most special characters in your code except for a few that hold special meaning. More on this later.

We can bring two strings together by using the + operator. We can also bring them together with the , (comma) operator, but this will also add a space between the strings.

Type out the following code exactly as I have written it.


print("Strings are wrapped" + "in double quotes")
print("Strings are wrapped", "in double quotes")
print('Or they can', 'be wrapped in ' + 'single quotes')
print('1000' + '1000')
print("Beware the ", "savage jaw of", "1984")


You should get this output:


Strings are wrappedin double quotes
Strings are wrapped in double quotes
Or they can be wrapped in single quotes
10001000
Beware the  savage jaw of 1984

Notice the lack of space between wrapped and in in the first line of output and the extra space between the and savage in the last line of output. Also note that the numbers did not get added, but simply moved together.

Now add these three lines to the program:


print("-" * 15)
print("Strings are wrapped" + "in double quotes")
print("Strings are wrapped", "in double quotes")
print('Or they can', 'be wrapped in ' + 'single quotes')
print("This is fun " * 3)
print('1000' + '1000')
print("Beware the ", "savage jaw of", "1984")
print("-" * 15)


To get this output:


---------------
Strings are wrappedin double quotes
Strings are wrapped in double quotes
Or they can be wrapped in single quotes
This is fun This is fun This is fun
10001000
Beware the  savage jaw of 1984
---------------

The multiplier is a operator that repeats the string the number of times that you indicate. I would like to show you one more thing.

Have a look at the following program:


print("You cannot add an integer to a string" + 3)


Which produces this output:


 File "tut2.py", line 1, in <module>
   print("You cannot add an integer to a string" + 3)
TypeError: can only concatenate str (not "int") to str

Oh no! We have encountered an error here. Why do you think we got this error? It is because of the fact that we are attempting to concatenate a string to integer. This is not possible. You can only concatenate a string with another string. We will speak more about different data types in a following lesson.

Exercises:

  1. Create several strings, concatenate them together and print them out
  2. We know that “3” + “3” will output 33. What do you think 3 + 3 (without the quotes) will output? Why don’t you try it?

Python Basics 1 - Print Statement Basics

Once you have Python installed, it is a good idea to jump in and start building programs right away. I recommend that you go through this blog page after page and type out all of the code that I am presenting to you. Do not copy and paste things into the python file. Type out each word until you get used to writing things in the Python way. Then run the program to see what it does.

Do not worry about harming your computer, not understanding or any other worry you may have. Programming is a lot of fun and nothing on this blog will harm your computer.

The first statements we will be learning about are print statements. This is the way that you get the program to give you feedback on what you have done. The program can print out anything that you would like it to. Start off by typing out this simple program:

print("Hello World!")
print("This is a string")
print("This is another string")
print("I'm having fun!")


print(10)
print(1984)
print(10.0)


print("10")
print("2012: A Space Odyssey")
print("143.0")


print("Goodbye World!")

Save the file as tut1.py. Open up your consol. You can do this by searching for “cmd”, “consol” or “shell” in the start menu in the bottom left corner of the screen. In the place where it says “Type here to search”, type in one of the above commands without the quotes and open the consol.

Navigate to the directory where your file is saved by typing in cd (which stands for Change Directory), one space and then the directory location that you would like to move to. For instance I type in “cd C:\Users\UserName\desktop\python” (without the quotes) because my files are saved in a folder named python on my desktop.

Once you have navigated to the correct folder you are going to need to type in the word “python” (no quotes), one space and then the name of the file you are going to run. On some computers, it is “py” instead of “python”. So you are going to need to type in “python tut1.py” or “py tut1.py”.

The file will run and show the output. The output should be as follows:

Hello World!
This is a string
This is another string
I'm having fun!
10
1984
10.0
10
2012: A Space Odyssey
143.0
Goodbye World!

If you are getting errors, then look at my code again. If you are still having trouble trying reading through all of the code backwards line by line to ensure that they are exactly the same.

Here are some exercises for you:
  1. Print out your name, age, address, work address, etc. 
  2. Print out some numbers 
  3. Print out more lines of code until you are comfortable with print statements 
  4. Notice that one of the 10s has quotes around it, one of the 10s has no quotes and one of the 10s is 10.0. What do you think the difference could be between these? Did they all print out the same?

MIT Intro to CS and Programming PS1B

Here is the solution to problemset1 question B of 6.0001 entitled Introduction to Computer Science and Programming in Python (Fall 2016). ...