scarolan


Joined 1 year ago
Homeworks submitted:
Homework comments:
5
0

About Me

No description provided.

Classes

MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming

Class status: Established
Role: Student
. 29% complete

Submitted Assignments

MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 7, HW 1

Should "growthRates" be all lower-case? My understanding is lower-case is conventional for variables.

#
# Problem 1
#

def nestEggFixed(salary, save, growthRate, years):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    # TODO: Your code here.
    yearlyreturn=[]
    nut = 0
    for i in range(0, years):
        # print "At the end of year",(i),"nut size is:",(round(nut,2))
        nut = nut * (1 + 0.01 * growthRate) + (salary * save * 0.01)
        # Rounded to two decimal places to make this easier to look at!
        yearlyreturn.append(round(nut,2))
    return yearlyreturn

def testNestEggFixed():
    salary     = 10000
    save       = 10
    growthRate = 15
    years      = 5
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2150.0, 3472.5, 4993.375, 6742.3812499999995]

    # TODO: Add more test cases here.
    salary     = 35000
    save       = 5
    growthRate = 3
    years      = 25
    savingsRecord = nestEggFixed(salary, save, growthRate, years)
    print savingsRecord

    salary     = 85000
    save       = 10
    growthRate = 8
    years      = 10
    savingsRecord = nestEggFixed(salary, save, growthRate, years)    
    print savingsRecord

#
# Problem 2
#

def nestEggVariable(salary, save, growthRates):
    # TODO: Your code here.
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: a list of the annual percent increases in your investment
      account (integers between 0 and 100).
    - return: a list of your retirement account value at the end of each year.
    """
    yearlyreturn=[]
    nut = 0
    for i in range(0,len(growthRates)):
        # print "At the end of year",(i),"nut size is:",(round(nut,2))
        nut = nut * (1 + 0.01 * growthRates[i]) + (salary * save * 0.01)
        # Rounded to two decimal places to make this easier to look at!
        yearlyreturn.append(round(nut,2))
    return yearlyreturn

def testNestEggVariable():
    salary      = 10000
    save        = 10
    growthRates = [3, 4, 5, 0, 3]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord
    # Output should have values close to:
    # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002]

    # TODO: Add more test cases here.

    salary      = 100000
    save        = 8
    growthRates = [2, 4, 6, 4, 2]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord

    salary      = 35000
    save        = 3
    growthRates = [1, 2, 3, 4, 5]
    savingsRecord = nestEggVariable(salary, save, growthRates)
    print savingsRecord

#
# Problem 3
#

def postRetirement(savings, growthRates, expenses):
    """
    - savings: the initial amount of money in your savings account.
    - growthRate: a list of the annual percent increases in your investment
      account (an integer between 0 and 100).
    - expenses: the amount of money you plan to spend each year during
      retirement.
    - return: a list of your retirement account value at the end of each year.
    """
    # TODO: Your code here.
    yearlysize = []
    for i in range(0, len(growthRates)):
        savings = savings * (1 + 0.01 * growthRates[i]) - expenses
        # print "In year",(i),"savings is",round(savings,2)
        yearlysize.append(round(savings,2))
    return yearlysize

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]

    # TODO: Add more test cases here.
    savings     = 25000000
    growthRates = [6, 6, 4, 6, 0]
    expenses    = 50000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord

    savings     = 50000
    growthRates = [12, 8, 4, 2, 1]
    expenses    = 3000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print savingsRecord

#
# Problem 4
#

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
                    epsilon):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - preRetireGrowthRates: a list of annual growth percentages on investments
      while you are still working.
    - postRetireGrowthRates: a list of annual growth percentages on investments
      while you are retired.
    - epsilon: an upper bound on the absolute value of the amount remaining in
      the investment fund at the end of retirement.
    """
    # TODO: Your code here.
    startsave = nestEggVariable(salary, save, preRetireGrowthRates)[-1]
    low = 0
    high = startsave
    approx = (low + high)/2.0
    endsave = postRetirement(startsave, postRetireGrowthRates, approx)[-1]
    count = 1
    print approx
    while abs(endsave) > epsilon and count <=100:
        if endsave < 0:
            high = approx
        else:
            low = approx
        approx = (low + high) / 2.0
        print approx
        endsave = postRetirement(startsave, postRetireGrowthRates, approx)[-1]
        count += 1
    return round(approx,2)
    
def testFindMaxExpenses():
    salary                = 10000
    save                  = 10
    preRetireGrowthRates  = [3, 4, 5, 0, 3]
    postRetireGrowthRates = [10, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses
    # Output should have a value close to:
    # 1229.95548986

    # TODO: Add more test cases here.
    salary                = 100000
    save                  = 5
    preRetireGrowthRates  = [2, 4, 5, 4, 2]
    postRetireGrowthRates = [8, 5, 0, 5, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses    

    salary                = 85000
    save                  = 8
    preRetireGrowthRates  = [8, 8, 9, 5, 4]
    postRetireGrowthRates = [2, 2, 2, 2, 1]
    epsilon               = .01
    expenses = findMaxExpenses(salary, save, preRetireGrowthRates,
                               postRetireGrowthRates, epsilon)
    print expenses

scarolan 1 year ago
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 5, HW 1

Did they do this to make sure we were paying attention?

close = subStringMatchOneSub(key, target)

# Problem Set 3

from string import *

#  target strings
target1 = 'atgacatgcacaagtatgcat'
target2 = 'atgaatgcatggatgtaaatgcag'
target3 = 'accaccaccaccaccaccaccacca'

# key strings
key10 = 'a'
key11 = 'atg'
key12 = 'atgc'
key13 = 'atgca'
key14 = 'acca'

###################
# Problem 3a                   #
###################

def countSubStringMatch(target, key):
    """ Iteratively counts the number of times a term appears in a string"""
    count = next = 0
    while find(target, key, next) != -1:
        next = find(target, key, next) + 1
        count += 1
    return count

def countSubStringMatchRecursive (target, key):
    """ Recursively counts the number of times a term appears in a string"""
    index = find(target, key)
    if index == -1:
        return 0
    else:
        # Slice notation says "Everything except the first part that we already searched"
        # Eg, start next recursion one place after the previous match that we have found.
        return 1 + countSubStringMatchRecursive(target[index+1:], key)

###################
# Problem 3b                   #
###################

def subStringMatchExact(target,key):
    matchList = []
    startFrom = 0
    index = find(target, key, startFrom)
    while index != -1:
        matchList.append(index)
        startFrom = index + 1
        index = find(target, key, startFrom)
    return tuple(matchList)

###################
# Problem 3c                   #
###################

def constrainedMatchPair(firstMatch,secondMatch,length):
    # firstMatch and secondMatch are tuples
    # n is the starting point of the first substring match
    # m is the length of the first substring
    # k is the sum of n + m + 1
    matches = []
    for n in firstMatch:
        for k in secondMatch:
            m = length
            if n + m + 1 == k:
                matches.append(n)
    return tuple(matches)

def subStringMatchOneSub(key, target):
    """search for all locations of key in target, with one substitution"""
    # Uncomment the print statements to get more output.
    allAnswers = ()
    for miss in range(0,len(key)):
        # miss picks location for missing element
        # key1 and key2 are substrings to match
        key1 = key[:miss]
        key2 = key[miss+1:]
        # print 'breaking key',key,'into',key1,key2
        # match1 and match2 are tuples of locations of start of matches
        # for each substring in target
        match1 = subStringMatchExact(target,key1)
        match2 = subStringMatchExact(target,key2)
        # when we get here, we have two tuples of start points
        # need to filter pairs to decide which are correct
        filtered = constrainedMatchPair(match1,match2,len(key1))
        allAnswers = allAnswers + filtered
        # print 'match1',match1
        # print 'match2',match2
        # print 'possible matches for',key1,key2,'start at',filtered
    return allAnswers

###################
# Problem 3d                   #
###################
   
def subStringMatchExactlyOneSub(key, target):
    """Returns tuple of ONLY partial matches"""
    onesub = () # One heart, lets get together and feel all right
    exact = subStringMatchExact(target, key)
    close = subStringMatchOneSub(key, target)
    for i in close:
        if i not in exact:
            onesub += (i,)
    return onesub

###################
# Code test output          #
###################

print "Testing code..."
print "The target strand of DNA is",(target2),"and the search key is",(key13)
print "Exact matches for",(key13),"were found at these positions:",subStringMatchExact(target2, key13)
print "Possible one-substitution matches were found at:",subStringMatchOneSub(key13, target2)
print "DNA sequences with only one different base pair found at:",subStringMatchExactlyOneSub(key13, target2)

scarolan 1 year ago
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 3, HW 1

Problem sets 2a and 2b

# This script calculates solutions to a diophantine equation with McDonalds
# Chicken McNuggets as the integer values of 6, 9, and 20.

def nuggerator(x):
    for num6p in range(0,x/6+1):
        for num9p in range(0,x/9+1):
            for num20p in range(0,x/20+1):
                n = (6 * num6p) + (9 * num9p) + (20 * num20p)
                if n == x:
                    #print (x),"McNuggets can be purchased with",(num6p),"six packs,",(num9p),"nine packs, and",(num20p),"twenty packs."
                    return True

testval = 0
count = 0

while count < 6:
    if nuggerator(testval) == True:
        count = count + 1
    else:
        count = 0
    testval = testval + 1
print "Largest number of McNuggets that cannot be bought in exact quantity:",(testval - 7)

## Problem set 2b

# Packages tuple as requested in the handout.
packages=(6,9,20)

# This is sort of a brute force hack but it works.
def nuggerator(a):
    for small in range(0,a/packages[0]+1):
        for medium in range(0,a/packages[1]+1):
            for large in range(0,a/packages[2]+1):
                n = (packages[0] * small) + (packages[1] * medium) + (packages[2] * large)
                if n == a:
                    print (a),"McNuggets can be purchased with",(small),(packages[0]),"packs,",(medium),(packages[1]),"packs, and",(large),(packages[2]),"packs."
                    return True

testval = 200
while nuggerator(testval) == True:
    testval = testval - 1
print "Given package sizes",(packages[0]),(packages[1]),"and",(packages[2]),"the largest number of McNuggets that cannot be bought in exact quantity is:",(testval)

scarolan 1 year ago
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 2, HW 1

Problem sets 1a and 1b

def isprime(n):
    '''Check whether integer n is a prime number'''
    # First we make sure n is a positive integer
    n = abs(int(n))
    # Zero and one are not primes
    if n < 2:
        return False
    # Two is the only even prime
    if n == 2:
        return True
    # All other even numbers are not primes
    # & is the bitwise AND operator, it tells us whether the number is even
    if not n & 1:
        return False
    # Start with three and go up to square root of n for all odd numbers
    for x in range (3, int(n**0.5)+1, 2):
        if n % x == 0:
            return False
    return True

# Start our index at one because we increment it in the if statement
index=1
testnum=3

while index < 1000:
    if isprime(testnum) == True:
        index=index+1
        if index == 1000:
            # Using sys.stdout.write because python is retarded and keeps putting
            # spaces after the index and before "th"
            import sys
            sys.stdout.write(testnum)
            sys.stdout.write(" is the ")
            sys.stdout.write(index)
            sys.stdout.write("th prime number.")
    testnum=testnum+2


## Problem set 1b


from math import *

# We'll recycle our handy "isprime" function from part A of the homework
def isprime(n):
    '''Check whether integer n is a prime number'''
    # First we make sure n is a positive integer
    n = abs(int(n))
    # Zero and one are not primes
    if n < 2:
        return False
    # Two is the only even prime
    if n == 2:
        return True
    # All other even numbers are not primes
    # & is the bitwise AND operator, it tells us whether the number is even
    if not n & 1:
        return False
    # Start with three and go up to square root of n for all odd numbers
    for x in range (3, int(n**0.5)+1, 2):
        if n % x == 0:
            return False
    return True

n=100000
testnum=3
# We'll set log(2) as the initial value of logsum, since two is the only even
# prime number.
logsum=log(2)
while testnum < n:
    if isprime(testnum) == True:
        logsum=logsum+log(testnum)
    testnum=testnum+2
print "The sum of the logarithms of all primes below",(n),"is",(logsum)
print "The ratio of logsum to n is",(logsum)/(testnum)

scarolan 1 year ago
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 1, HW 1

Problem 1. Write a program that does the following in order:

  1. Asks the user to enter his/her last name.
  2. Asks the user to enter his/her first name.
  3. Prints out the user’s first and last names in that order.
print ('Enter your last name: ')
lastname = raw_input()
print ('Enter your first name: ')
firstname = raw_input()
print (firstname + " " + lastname)

scarolan 1 year ago