About Me
No description provided.
Classes
|
Class status: Established
Role:
Student
|
.
29% complete
|
Submitted Assignments
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 7, HW 1
# Problem Set 4
# Name: Fredrik Gustafsson
# Python Version: 3.2
# Time: 01:00
#
# 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.
"""
f = []
f.append(salary*save*0.01)
for x in range(years-1):
f.append(f[x]*(1+0.01*growthRate)+salary*save*0.01)
return f
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]
#
# 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.
"""
f = []
f.append(salary*save*0.01)
for x in range(len(growthRates)-1):
f.append(f[x]*(1+0.01*growthRates[x+1])+salary*save*0.01)
return f
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]
#
# 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.
"""
f = []
f.append(savings*(1+0.01*growthRates[0])-expenses)
for x in range(len(growthRates)-1):
f.append(f[x]*(1+0.01*growthRates[x+1])-expenses)
return f
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]
#
# 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.
"""
f = nestEggVariable(salary, save, preRetireGrowthRates
)[len(preRetireGrowthRates)-1]
low = f / len(postRetireGrowthRates)
high = f
guess = (low + high) / 2
ctr = 0
while abs(postRetirement(f, postRetireGrowthRates, guess)
[len(postRetireGrowthRates)-1]) > epsilon and ctr <=100:
if (postRetirement(f, postRetireGrowthRates, guess)
[len(postRetireGrowthRates)-1]) > epsilon:
low = guess
else:
high = guess
guess = (low + high) / 2
ctr += 1
assert ctr <=100, 'Iteration count exceeded'
return guess
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
fredgust
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 5, HW 1
# Problem Set 3
# Name: Fredrik Gustafsson
# Python version: 3.2
# Time: 3:00
##
## Problem 3a
##
def countSubStringMatch(target, key):
"""Takes a target and a key and returns an ingeger number of instances of key in target"""
assert type(target) == str, 'target must be of type string, NOT of type:' + str(type(target))
assert type(key) == str, 'key must be of type string, NOT of type:' + str(type(key))
x = 0
ctr = 0
while x in range(len(target)):
y = str.find(target, key, x)
if y != -1:
x = y + len(key)
ctr += 1
else:
return ctr
def countSubStringMatchRecursive (target, key):
"""Takes a target and a key and returns an integer number of instances of key in target"""
assert type(target) == str, 'target must be of type string, NOT of type:' + str(type(target))
assert type(key) == str, 'key must be of type string, NOT of type:' + str(type(key))
y = str.find(target, key)
if y != -1:
ctr = countSubStringMatchRecursive(target[y+len(key):], key)
else:
ctr = 0
return ctr
return ctr + 1
##
## Problem 3b
##
def subStringMatchExact(target, key):
"""Takes a target and a key and returns A TUPLE of the starting position
of matches of the key string in the target strign"""
assert type(target) == str, 'target must be of type string, NOT of type:' + str(type(target))
assert type(key) == str, 'key must be of type string, NOT of type:' + str(type(key))
ls = []
x = 0
while x in range(len(target)):
y = str.find(target, key, x)
if y != -1:
if len(key) == 0:
x += 1
else:
x = y + len(key)
ls.append (y)
else:
return tuple(ls)
##
## Problem 3c
##
def constrainedMatchPair(firstMatch,secondMatch,length):
"""Takes two tuples of startingpoints and the length of the first keyword,
and returns a tuple of all the members of n in k so that (n + length + 1 = k)"""
if firstMatch != None:
assert type(firstMatch) == tuple, 'firstMatch must be of type tuple, NOT of type:' + str(type(firstMatch))
if secondMatch != None:
assert type(secondMatch) == tuple, 'secondMatch must be of type tuple, NOT of type:' + str(type(secondMatch))
assert type(length) == int, 'length of the first strign must be of type int, NOT of type:' + str(type(length))
if firstMatch == None: return secondMatch
if secondMatch == None: return tuple(firstMatch)
x = 0
z = []
while x in range(len(firstMatch)):
y = 0
while y in range(len(secondMatch)):
if (firstMatch[x] + length + 1) == secondMatch[y]:
z.append(firstMatch[x])
y += 1
x += 1
return tuple(z)
##
## Problem 3d
##
def subStringMatchExactlyOneSub(target,key):
""" """
assert type(target) == str, 'target must be of type string, NOT of type' + str(type(target))
assert type(key) == str, 'key must be of type string, NOT of type' + str(type(key))
# First step splits the key into two lists
string1 = []
string2 = []
x = 1
while x in range(len(key)+1):
string1.append(key[:x-1])
string2.append(key[x:])
x += 1
# Searches for matches between the strings in the two tuples and the target
match1 = []
match2 = []
x = 0
while x in range(len(string1)):
match1.append(subStringMatchExact(target, string1[x]))
match2.append(subStringMatchExact(target, string2[x]))
x += 1
# Searches for members of match1 that satisfy match1[x] + len(string1 in match1[x]) + 1 = match2[x]
member = []
x = 0
while x in range(len(string1)):
member.append(constrainedMatchPair(match1[x], match2[x], len(string1[x])))
x += 1
# Sorts and removes duplicate
a = []
for x in range(len(member)):
z = member[x]
for y in range(len(z)):
if z[y] not in a:
a.append(z[y])
a.sort()
return tuple(a)
fredgust
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 3, HW 1
There is some optimization to do in this solution
# Problem Set 2
# Name: Fredrik Gustafsson
# Python version: 3.2
# Time: 1:00
##
## Problem 2a
##
def mcnuggets(n, p):
x = 0
y = 0
z = 0
count = 0
while x*p[0]+y*p[1]+z*p[2] <= n:
while x*p[0]+y*p[1]+z*p[2] <= n:
while x*p[0]+y*p[1]+z*p[2] <= n:
if x*p[0]+y*p[1]+z*p[2] == n:
return ("Solution found")
count += 1
x += 1
x = 0
y += 1
y = 0
z += 1
return (count)
for i in range (50, 56):
print ("Nr of solutions to the equation: 6x + 9y + 20z =", i, "is:", mcnuggets(i, (6, 9, 20)))
##
## Problem 2b: Any number of McNuggets >= x can be expressed as a linear combination
## 6a+9b+20c if x+1, x+2, ..., x+5 all have a solution
##
##
## Problem 2c
##
def serch(p):
count = 0
x = 0
while count <= (p[0]-1):
if x > 200:
return ("No solution found for largest number of McNuggets that cannot be bought in exact quantity whithin the range 0 - 200")
if mcnuggets(x, (p[0], p[1], p[2])) != 0:
count += 1
x += 1
else:
count = 0
x += 1
return(x-(p[0]+1))
##
## Problem 2d
##
a = int(input("Pleas input nr of McNuggets in smallest package: "))
b = int(input("Pleas input nr of McNuggets in middle package: "))
c = int(input("Pleas input nr of McNuggets in largest package: "))
packages = (a, b, c) # variable that contains package sizes
bestSoFar = serch(packages) # variable that keeps track of largest number
# of McNuggets that cannot be bought in exact quantity
print (bestSoFar)
fredgust
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 2, HW 1
I defined problem 1a as a function
for an simple solution to problem 1b.
to get the 1000th prime simply type
prime(1000)
# Problem Set 1
# Name: Fredrik Gustafsson
# Python version: 3.2
# Time: 1:00
##
## Problem 1a
##
def prime(number):
prime_cand = 1 # Prime candidates
prime_count = 1 # Prime counter
if number == 1:
return(2)
while prime_count < number:
# Variables needed for the prime test
x = 2
y = 1
prime_cand += 2
# Multiplies all the remainders of prime_cand/x for x in: 1 < x < prime_cand/2
while x < (prime_cand / 2):
y = y * (prime_cand % x)
x += 1
# If the product of the remainders is zero then prime_cand is evenly divided by
# some value x for x in 1 < x < prime_cand/2, hence prime_cand is not a prime.
if y != 0:
prime_count += 1
return(prime_cand)
##
## Problem 1b
##
import math
n = int(input("Please input n: "))
su = 0
x = 1
while prime(x) < n:
su = su + math.log(prime(x))
x += 1
print ("The sum of the logarithms of the all primes < n is:", su)
print ("the number n is:", n)
print ("and finaly the ratio log(...) / n is:", su / n)
fredgust
1 year ago
|
 |
|
|
|