problem set

19
PROBLEM SET -02 -- PAYING OFF CREDIT CARD DEBT Each month, a credit card statement will come with the option for you to pay a minimum amount of your charge, usually 2% of the balance due. However, the credit card company earns money by charging interest on the balance that you don't pay. So even if you pay credit card payments on time, interest is still accruing on the outstanding balance. Say you've made a $5,000 purchase on a credit card with an 18% annual interest rate and a 2% minimum monthly payment rate. If you only pay the minimum monthly amount for a year, how much is the remaining balance? You can think about this in the following way. At the beginning of month 0 (when the credit card statement arrives), assume you owe an amount we will call b0(b for balance; subscript 0 to indicate this is the balance at month 0). Any payment you make during that month is deducted from the balance. Let's call the payment you make in month 0, p0. Thus, your unpaid balance for month 0, ub0, is equal to b0−p0. ub0=b0p0 At the beginning of month 1, the credit card company will charge you interest on your unpaid balance. So if your annual interest rate is r, then at the beginning of month 1, your new balance is your previous unpaid balance ub0, minus the payment p0, plus interest on this new balance for the month. In algebra, this new balance would be b1=ub0+r12.0ub0 In month 1, we will make another payment, p1. That payment has to cover some of the interest costs, so it does not completely go towards paying off the original charge. The balance at the beginning of month 2, b2, can be calculated by first calculating the unpaid balance after paying p1, then by adding the interest accrued: ub1=b1p1 b2=ub1+r12.0ub1 If you choose just to pay off the minimum monthly payment each month, you will see that the compound interest will dramatically reduce your ability to lower your debt. Let's look at an example. If you've got a $5,000 balance on a credit card with 18% annual interest rate, and the minimum monthly payment is 2% of the current balance, we would have the following repayment schedule if you only pay the minimum payment each month: Month Balance Minimum Payment Unpaid Balance Interest 0 5000.00 100 (= 5000 * 0.02) 4900 (= 5000 - 100) 73.50 (= 0.18/12.0 *

Upload: ankit-mishra

Post on 03-Nov-2014

162 views

Category:

Documents


4 download

DESCRIPTION

mit cs6.00x

TRANSCRIPT

Page 1: Problem Set

PROBLEM SET -02 -- PAYING OFF CREDIT CARD DEBT

Each month, a credit card statement will come with the option for you to pay a minimum amount of your charge, usually 2% of the balance due. However, the credit card company earns money by charging interest on the balance that you don't pay. So even if you pay credit card payments on time, interest is still accruing on the outstanding balance.Say you've made a $5,000 purchase on a credit card with an 18% annual interest rate and a 2% minimum monthly payment rate. If you only pay the minimum monthly amount for a year, how much is the remaining balance?You can think about this in the following way.At the beginning of month 0 (when the credit card statement arrives), assume you owe an amount we will call b0 (b for balance; subscript 0 to indicate this is the balance at month 0).Any payment you make during that month is deducted from the balance. Let's call the payment you make in month 0, p0. Thus, your unpaid balance for month 0, ub0, is equal to b0−p0.

ub0=b0−p0

At the beginning of month 1, the credit card company will charge you interest on your unpaid balance. So if your annual interest rate is r, then at the beginning of month 1, your new balance is your previous unpaid balance ub0, minus the payment p0, plus interest on this new balance for the month. In algebra, this new balance would be

b1=ub0+r12.0⋅ub0

In month 1, we will make another payment, p1. That payment has to cover some of the interest costs, so it does not completely go towards paying off the original charge. The balance at the beginning of month 2, b2, can be calculated by first calculating the unpaid balance after paying p1, then by adding the interest accrued:

ub1=b1−p1

b2=ub1+r12.0⋅ub1

If you choose just to pay off the minimum monthly payment each month, you will see that the compound interest will dramatically reduce your ability to lower your debt.Let's look at an example. If you've got a $5,000 balance on a credit card with 18% annual interest rate, and the minimum monthly payment is 2% of the current balance, we would have the following repayment schedule if you only pay the minimum payment each month:

Month Balance Minimum Payment Unpaid Balance Interest

0 5000.00 100 (= 5000 * 0.02) 4900 (= 5000 - 100) 73.50 (=

0.18/12.0 * 4900)

1 4973.50 (= 4900 + 73.50) 99.47 (= 4973.50 * 0.02) 4874.03 (= 4973.50 - 99.47) 73.11 (=

0.18/12.0 *

4874.03)

2 4947.14 (= 4874.03 + 73.11) 98.94 (= 4947.14 * 0.02) 4848.20 (= 4947.14 - 98.94) 72.72 (=

0.18/12.0 *

4848.20)

Page 2: Problem Set

You can see that a lot of your payment is going to cover interest, and if you work this through month 12, you will see that after a year, you will have paid $1165.63 and yet you will still owe $4691.11 on what was originally a $5000.00 debt. Pretty depressing!

PROBLEM 1: PAYING THE MINIMUM : 10.0 POINTS

Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.The following variables contain values as described below:balance - the outstanding balance on the credit cardannualInterestRate - annual interest rate as a decimalmonthlyPaymentRate  - minimum monthly payment rate as a decimal

A summary of the required math is found below:Monthly interest rate= (Annual interest rate) / 12.0

Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance)

Monthly unpaid balance = (Previous balance) - (Minimum monthly payment)

Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)

For each month, calculate statements on the monthly payment and remaining balance, and print to screen something of the format:Month: 1Minimum monthly payment: 96.0Remaining balance: 4784.0Be sure to print out no more than two decimal digits of accuracy - so printRemaining balance: 813.41

def card(b, air, mpr): m=1 mmp=0 ub=0 nb=0 r=0 while m<13: mmp=mpr*b mmp=round(mmp, 2) ub=b-mmp r=air/12 b= ub+(r*ub) b=round(b,2) print("Month :"+str(m)) print("Minimum monthly payment:"+str(mmp)) print("Remaining balance:"+str(b)) m=m+1 returncard(balance, annualInterestRate, monthlyPaymentRate)

Page 3: Problem Set

# 6.00 Problem Set 3# # Hangman game#

# Helper code# You don't need to understand this helper code, but you will have to know how to use the functions

import randomimport string

WORDLIST_FILENAME = "words.txt"

def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist

def chooseWord(wordlist): """ wordlist (list): list of words (strings)

Returns a word from wordlist at random """ return random.choice(wordlist)

# end of helper code# -----------------------------------

# Load the list of words into the variable wordlist# so that it can be accessed from anywhere in the programwordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' a=list(secretWord) b=set(a)

Page 4: Problem Set

x=lettersGuessed c=set(lettersGuessed) d=b.issubset(c) c=x return d

def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' a=list(secretWord) b=len(a) c=len(lettersGuessed) d=0 e=0 f=[] while(d<b): if a[d] in lettersGuessed: x=a[d] f.append(x) else: z='_' f.append(z) d=d+1 return "".join(f)

def getAvailableLetters(lettersGuessed): a='abcdefghijklmnopqrstuvwxyz' b=list(a) c = b[:] for e1 in c: if e1 in lettersGuessed: b.remove(e1) #print("".join(b)) return ("".join(b))

def hangman(secretWord): ''' secretWord: string, the secret word to guess.

Starts up an interactive game of Hangman.

* At the start of the game, let the user know how many letters the secretWord contains.

* Ask the user to supply one guess (i.e. letter) per round.

Page 5: Problem Set

* The user should receive feedback immediately after each guess about whether their guess appears in the computers word.

* After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed.

Follows the other limitations detailed in the problem write-up. ''' print(str(secretWord)) n=8 lettersGuessed=[] print("Welcome to the game, Hangman!") print("I am thinking of a word that is "+str(len(secretWord))+" letters long.") print("You have "+str(n)+" guesses left.") while(n>0): print("Available Letters:"+str(getAvailableLetters(lettersGuessed))) z=raw_input("Please guess a letter:") lettersGuessed.append(z) f=lettersGuessed x=isWordGuessed(secretWord, f) print(x) if x==True: y=getGuessedWord(secretWord,lettersGuessed) print("Good guess:"+str(y)) else: print("Oops! That letter is not in my word:") n=n-1 return ("Congratulations, you won!")

secretWord = chooseWord(wordlist).lower()hangman(secretWord)

Page 6: Problem Set

# 6.00x Problem Set 3## Successive Approximation: Newton's Method#

# Problem 1: Polynomialsdef evaluatePoly(poly, x): ''' Computes the value of a polynomial function at given value x. Returns that value as a float. poly: list of numbers, length > 0 x: number returns: float ''' # FILL IN YOUR CODE HERE...

# Problem 2: Derivativesdef computeDeriv(poly): ''' Computes and returns the derivative of a polynomial function as a list of floats. If the derivative is 0, returns [0.0]. poly: list of numbers, length &gt; 0 returns: list of numbers (floats) ''' # FILL IN YOUR CODE HERE...

# Problem 3: Newton's Methoddef computeRoot(poly, x_0, epsilon): ''' Uses Newton's method to find and return a root of a polynomial function. Returns a list containing the root and the number of iterations required to get to the root. poly: list of numbers, length > 1. Represents a polynomial function containing at least one real root. The derivative of this polynomial function at x_0 is not 0. x_0: float epsilon: float > 0 returns: list [float, int] ''' # FILL IN YOUR CODE HERE...

Page 7: Problem Set

# Problem set 04# The 6.00 Word Game# Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens># Modified by: Sarina Canelake <sarina>#

import randomimport string

VOWELS = 'aeiou'CONSONANTS = 'bcdfghjklmnpqrstvwxyz'HAND_SIZE = 7

SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10}

# -----------------------------------# Helper code# (you don't need to understand this helper code)

WORDLIST_FILENAME = "words.txt"

def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordList: list of strings wordList = [] for line in inFile: wordList.append(line.strip().lower()) print " ", len(wordList), "words loaded." return wordList

def getFrequencyDict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence.

sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1

Page 8: Problem Set

return freq

# (end of helper code)# -----------------------------------

## Problem #1: Scoring a word#def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word.

The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, PLUS 50 points if all n letters are used on the first turn.

Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)

word: string (lowercase letters) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: int >= 0 """ # TO DO ... <-- Remove this comment when you code this function

## Problem #2: Make sure you understand how this function works and what it does!#def displayHand(hand): """ Displays the letters currently in the hand.

For example: >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant.

hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print # print an empty line

## Problem #2: Make sure you understand how this function works and what it does!#def dealHand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS.

Hands are represented as dictionaries. The keys are

Page 9: Problem Set

letters and the values are the number of times the particular letter is repeated in that hand.

n: int >= 0 returns: dictionary (string -> int) """ hand={} numVowels = n / 3 for i in range(numVowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(numVowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand

## Problem #2: Update a hand by removing letters#def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it.

Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it.

Has no side effects: does not modify hand.

word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ # TO DO ... <-- Remove this comment when you code this function

## Problem #3: Test word validity#def isValidWord(word, hand, wordList): """ Returns True if word is in the wordList and is entirely composed of letters in the hand. Otherwise, returns False.

Does not mutate hand or wordList. word: string hand: dictionary (string -> int) wordList: list of lowercase strings """ # TO DO ... <-- Remove this comment when you code this function

Page 10: Problem Set

## Problem #4: Playing a hand#

def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ # TO DO... <-- Remove this comment when you code this function

def playHand(hand, wordList, n): """ Allows the user to play the given hand, as follows:

* The hand is displayed. * The user may input a word or a single period (the string ".") to indicate they're done playing * Invalid words are rejected, and a message is displayed asking the user to choose another word until they enter a valid word or "." * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters or the user inputs a "."

hand: dictionary (string -> int) wordList: list of lowercase strings n: integer (HAND_SIZE; i.e., hand size required for additional points) """ # BEGIN PSEUDOCODE <-- Remove this comment when you code this function; do your coding within the pseudocode (leaving those comments in-place!) # Keep track of the total score # As long as there are still letters left in the hand: # Display the hand # Ask user for input # If the input is a single period: # End the game (break out of the loop)

# Otherwise (the input is not a single period): # If the word is not valid:

Page 11: Problem Set

# Reject invalid word (print a message followed by a blank line)

# Otherwise (the word is valid):

# Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line # Update the hand

# Game is over (user entered a '.' or ran out of letters), so tell user the total score

## Problem #5: Playing a game#

def playGame(wordList): """ Allow the user to play an arbitrary number of hands.

1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, tell them their input was invalid. 2) When done playing the hand, repeat from step 1 """ # TO DO ... <-- Remove this comment when you code this function print "playGame not yet implemented." # <-- Remove this line when you code the function

## Build data structures used for entire session and play game#if __name__ == '__main__': wordList = loadWords() playGame(wordList)

Page 12: Problem Set

# 6.00x Problem Set 5## Part 1 - HAIL CAESAR! (caeser cipher)

import stringimport random

WORDLIST_FILENAME = "words.txt"

# -----------------------------------# Helper code# (you don't need to understand this helper code)def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." inFile = open(WORDLIST_FILENAME, 'r') wordList = inFile.read().split() print " ", len(wordList), "words loaded." return wordList

def isWord(wordList, word): """ Determines if word is a valid word.

wordList: list of words in the dictionary. word: a possible word. returns True if word is in wordList.

Example: >>> isWord(wordList, 'bat') returns True >>> isWord(wordList, 'asdf') returns False """ word = word.lower() word = word.strip(" !@#$%^&*()-_+={}[]|\\:;'<>?,./\"") return word in wordList

def randomWord(wordList): """ Returns a random word.

wordList: list of words returns: a word from wordList at random """ return random.choice(wordList)

def randomString(wordList, n): """

Page 13: Problem Set

Returns a string containing n random words from wordList

wordList: list of words returns: a string of random words separated by spaces. """ return " ".join([randomWord(wordList) for _ in range(n)])

def randomScrambled(wordList, n): """ Generates a test string by generating an n-word random string and encrypting it with a sequence of random shifts.

wordList: list of words n: number of random words to generate and scamble returns: a scrambled string of n random words

NOTE: This function will ONLY work once you have completed your implementation of applyShifts! """ s = randomString(wordList, n) + " " shifts = [(i, random.randint(0, 25)) for i in range(len(s)) if s[i-1] == ' '] return applyShifts(s, shifts)[:-1]

def getStoryString(): """ Returns a story in encrypted text. """ return open("story.txt", "r").read()

# (end of helper code)# -----------------------------------

## Problem 1: Encryption#def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers and spaces.

shift: 0 <= int < 26 returns: dict """ ### TODO. return "Not yet implemented." # Remove this comment when you code the function

def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text.

text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text

Page 14: Problem Set

""" ### TODO. return "Not yet implemented." # Remove this comment when you code the function

def applyShift(text, shift): """ Given a text, returns a new text Caesar shifted by the given shift offset. Lower case letters should remain lower case, upper case letters should remain upper case, and all other punctuation should stay as it is.

text: string to apply the shift to shift: amount to shift the text (0 <= int < 26) returns: text after being shifted by specified amount. """ ### TODO. ### HINT: This is a wrapper function. return "Not yet implemented." # Remove this comment when you code the function

## Problem 2: Decryption#def findBestShift(wordList, text): """ Finds a shift key that can decrypt the encoded text.

text: string returns: 0 <= int < 26 """ ### TODO return "Not yet implemented." # Remove this comment when you code the function

def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Use the functions getStoryString and loadWords to get the raw data you need.

returns: string - story in plain text """ ### TODO. return "Not yet implemented." # Remove this comment when you code the function

## Build data structures used for entire session and run encryption#

if __name__ == '__main__': # To test findBestShift: wordList = loadWords() s = applyShift('Hello, world!', 8) bestShift = findBestShift(wordList, s) assert applyShift(s, bestShift) == 'Hello, world!' # To test decryptStory, comment the above four lines and uncomment this line: # decryptStory()

Page 15: Problem Set

# 6.00x Problem Set 5## Part 2 - RECURSION

## Problem 3: Recursive String Reversal#def reverseString(aStr): """ Given a string, recursively returns a reversed copy of the string. For example, if the string is 'abc', the function returns 'cba'. The only string operations you are allowed to use are indexing, slicing, and concatenation. aStr: a string returns: a reversed string """ ### TODO.

## Problem 4: X-ian#def x_ian(x, word): """ Given a string x, returns True if all the letters in x are contained in word in the same order as they appear in x.

>>> x_ian('eric', 'meritocracy') True >>> x_ian('eric', 'cerium') False >>> x_ian('john', 'mahjong') False x: a string word: a string returns: True if word is x_ian, False otherwise """ ###TODO.

## Problem 5: Typewriter#def insertNewlines(text, lineLength): """ Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character ("\n") after each word that reaches or exceeds the desired line length.

text: a string containing the text to wrap. line_length: the number of characters to include on a line before wrapping the next word. returns: a string, with newline characters inserted appropriately.

Page 16: Problem Set

""" ### TODO.