About Me
No description provided.
Classes
|
Class status: Established
Role:
Student
|
.
47% complete
|
Submitted Assignments
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 8, HW 1
##Name: Marc
##Time: ~30 Minutes
#1.1 False
#1.2 False
#1.3 False
#1.4 False
#1.5 False
#1.6 True
#1.7 True
#2.1 yes
#2.2 No, when you enter a negative number compare one prints the opposite, companre two prints the original
#3.1 6
#3.2 f adds all of the digits of the integer together
#4.
def first_N(n):
count = 0
ans = 1
for i in n:
square = ans * ans
if square % 2 != 0:
print square
count += 1
ans += 1
#5.
Def guess_and_check(criteria):
for a in range(...):
for b in range(...):
for c in range(...):
...
if satisfies_critera(a,b,c,..., criteria):
return a,b,c....
#6.
def findSide():
"""asks the user to enter the area of a rectangle and the length of one side of the rectangle. Returns a float that is the length of the adjacent side."""
area = raw_input('Enter the area of the rectangle')
side = raw_input('Enter the length of one side of the rectangle')
answer = float(area)/float(side)
print 'The length of the base is ', answer
#7. No
def f(L):
result = []
for e in L: result.append(l[e])
return result
#8.
def McNuggets(num):
for a in range(num):
for b in range(num):
for c in range(num):
answer = a*6+b*9+C*20
if answer == num
return True
return False
#9. It reverses the digits of the integer given. EX. 21118 = 81112
mjcuva
12 months ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 9, HW 2
# Problem Set 5: Ghost
# Name: Marc
# Collaborators:
# Time: ~1 Hour
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
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 get_frequency_dict(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
return freq
# (end of helper code)
# -----------------------------------
# Actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
# in the program.
wordlist = load_words()
def ghost(wordlist):
print 'Welcome to ghost!!!'
print 'Player one goes first.'
running = True
wordfrag = ''
player = 1
while running:
print 'The current word fragment is ', wordfrag
print 'player %s enter a letter: ' %player
wordfrag += raw_input()
if is_valid(wordfrag,wordlist) == False:
running = False
if is_valid(wordfrag,wordlist) == True:
player = player_switch(player)
print "Word: '%s' is an illegal play, Player %s loses" % (wordfrag, player)
print "Congratulations Player %s, You Win!" % player_switch(player)
print '-'*50
ghost(wordlist)
def is_valid(wordfrag,wordlist):
length = len(wordfrag)
templist = []
for word in wordlist:
if word[:length] == wordfrag:
templist.append(word)
if len(templist) > 1:
if len(wordfrag) > 3 and wordfrag in templist:
return False
else:
return True
return False
def player_switch(player):
if player == 1:
player = 2
else:
player = 1
return player
if __name__ == '__main__':
wordlist = load_words()
ghost(wordlist)
mjcuva
12 months ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 9, HW 1
# Name: Marc
# Collaborators:
# Time: ~1.5 Hours
#
import random
import 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 load_words():
"""
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 get_frequency_dict(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
return freq
# (end of helper code)
# -----------------------------------
#
# Problem #1: Scoring a word
#
def get_word_score(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, plus 50 points if all n letters are used on
the first go.
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.
word: string (lowercase letters)
returns: int >= 0
"""
answer = 0
control = 1
for letter in word:
answer = answer + SCRABBLE_LETTER_VALUES[letter]
if control == 1:
if len(word) == n:
answer = answer + 50
control += 1
else: control += 1
return answer
#
# Make sure you understand how this function works and what it does!
#
def display_hand(hand):
"""
Displays the letters currently in the hand.
For example:
display_hand({'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
#
# Make sure you understand how this function works and what it does!
#
def deal_hand(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
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={}
num_vowels = n / 3
for i in range(num_vowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(num_vowels, 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 update_hand(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 mutate hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
for letters in word:
if hand[letters] > 1:
hand[letters] -= 1
else:
del hand[letters]
return hand
#
# Problem #3: Test word validity
#
def is_valid_word(word, hand, word_list):
"""
Returns True if word is in the word_list and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or word_list.
word: string
hand: dictionary (string -> int)
word_list: list of lowercase strings
"""
frequency = get_frequency_dict(word)#gets the frequency of letters ocurring in 'word'
for letter in word:
if letter not in hand or hand[letter]<frequency[letter]:
return False
if word in word_list:
return True
else: return False
#
# Problem #4: Playing a hand
#
def play_hand(hand, word_list):
"""
Allows the user to play the given hand, as follows:
* The hand is displayed.
* The user may input a word.
* An invalid word is rejected, and a message is displayed asking
the user to choose another word.
* When a valid word is entered, it uses up letters from the hand.
* After every valid word: the score for that word and the total
score so far are 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.
The user can also finish playing the hand by inputing a single
period (the string '.') instead of a word.
* The final score is displayed.
hand: dictionary (string -> int)
word_list: list of lowercase strings
"""
deal_hand(HAND_SIZE)
display_hand(hand)
global totalscore
word = raw_input('Enter word, or a . to indicate that you are finished: ')
if word == '.':
print 'Total Score: ', totalscore, ' points'
elif is_valid_word(word, hand, word_list):
wordscore = get_word_score(word, HAND_SIZE)
totalscore += wordscore
print word, 'earned ', wordscore, ' points. Total: ', totalscore, ' points'
update_hand(hand, word)
play_hand(hand, word_list)
else:
print 'Invalid word, please try again.'
play_hand(hand,word_list)
totalscore = 0
#
# Problem #5: Playing a game
# Make sure you understand how this code works!
#
def play_game(word_list):
"""
Allow the user to play an arbitrary number of hands.
* Asks the user to input 'n' or 'r' or 'e'.
* If the user inputs 'n', let the user play a new (random) hand.
When done playing the hand, ask the 'n' or 'e' question again.
* 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, ask them again.
"""
# TO DO ...
## uncomment the following block of code once you've completed Problem #4
hand = deal_hand(HAND_SIZE) # random init
while True:
cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
if cmd == 'n':
hand = deal_hand(HAND_SIZE)
play_hand(hand.copy(), word_list)
print
elif cmd == 'r':
play_hand(hand.copy(), word_list)
print
elif cmd == 'e':
break
else:
print "Invalid command."
#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
word_list = load_words()
play_game(word_list)
mjcuva
12 months ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 7, HW 1
## Name: Marc
## Time: ~2 Hours
#==========Problem 1==========
def nestEggFixed(salary, save, growthRate, years):
"""
- salary: the amount of money you amke 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 = [] #Create a list to hold all of the values
f.append(salary * save * 0.01) #Add the amount earned for the first year
for i in range(1,years): #Loop that counts through the rest of the years
f.append(f[i - 1] * (1+0.01*growthRate) + salary * save * 0.01) #Add the result of the formula that calculates
#the amount at the end of the year
return f
def testNestEggFixed():
"""
Tests the function NestEggFixed
"""
salary = 10000
save = 10
growthRate = 15
years = 5
savingRecord = nestEggFixed(salary,save,growthRate,years)
print savingRecord
#==========Problem 2==========
def nestEggVariable(salary, save, growthRate):
"""
- salary: thee amount of money you make each year.
- Save: the percent of your salary to save in teh investment account each year9 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 = [] #Create a list to hold all of the values
f.append(salary * save * 0.01) #Add the amount earned for the first year
for i in range(1,len(growthRate)): #Loop that counts through the rest of the years, with
#the length of the list growthRate as the amount of years
f.append(f[i-1] * (1+0.01*growthRate[i]) + salary * save * 0.01) #Add the result of the the formula that calculates
#the amount at the end of the year
return f
def testNestEggVariable():
"""
Tests the function NestEggVariable.
"""
salary = 10000
save = 10
growthRates = [3,4,5,0,3]
savingRecord = nestEggVariable(salary, save, growthRates)
print savingRecord
#==========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
- 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 = [] #Create a list to hold all of the values
f.append(savings*(1+0.01*growthRates[0]) - expenses) #Add the amount earned for the first year, minus your expenses
for i in range(1,len(growthRates)): #Loop that counts through the rest of the years, with the length of
#the list growthRates as the amount of years
f.append(f[i-1]*(1 + 0.01 * growthRates[i]) - expenses) #Add the result of the formula that calculates the amount
#at the end of the year, minus your expeses
return f
def testPostRetirement():
"""
Tests the function Postretirement
"""
savings = 100000
growthRates = [10,5,0,5,1]
expenses = 30000
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.
"""
low = 0 #Set the lower bound of the Binary Search to 0
high = nestEggVariable(salary, save, preRetireGrowthRates)[-1] #Set the upper bound of the Binary Search to the amount of money
#earned before retirment
savings = high
guess = (low + high)/2.0 #Make your guess halfway between the upper and lower bounds
ctr = 1 #Set a control to count the number of iterations
dead = postRetirement(savings, postRetireGrowthRates,guess)[-1] #Determine the amount of money you will have left when you die
#with the guess as your expenses
while abs(dead) > epsilon and ctr <= 100: #Check if the amount left is less than epsilon
if dead > epsilon: #If you didn't spend enough money, change the lower bound to the guess
low = guess
else:
high = guess #If you spent to much money, change the upper bound to the guess
guess = (low + high) / 2.0 #Determine a new guess
dead = postRetirement(savings, postRetireGrowthRates, guess)[-1] #Calculate the amount of money you have left with the new guess as the expense
return guess
def testFindMaxExpenses():
"""
Tests the function FindMaxExpenses
"""
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
mjcuva
12 months ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 5, HW 1
from string import *
##Target Strings
target1 = 'atgacatgcacaagtatgcat'
target2 = 'atgaatgcatggatgtaaatgcag'
##Key Strings
key10 = 'a'
key11 = 'atg'
key12 = 'atgc'
key13 = 'atgca'
##Problem 1
def countSubStringMatch(key,target):
"""This function returns the number of instances of the key in the target string"""
counter = 0 ##Set the counter to 0
start = 0 ##Set the starting place in the string to 0
while find(key,target,start) >=0:
counter += 1 ##Add one to the counter when a match is found
start = find(key,target,start) + 1 ##Change the starting place to the next character in the string
return counter ##Return the final counter
def countSubStringMatchRecursive(target,key):
"""This function returns the number of instances of the key in the target string."""
first = find(target,key) ##Find the first instance of the target string.
if first == -1: ##Exit if there is no instance of the key.
return 0
else:
return 1 + countSubStringMatch(target[first+1:-1],key) ##Return the result of the function with the new slice of the string.
##Problem 2
def subStringMatchExact(target,key):
start = 0 ##Set the starting point to 0
point = [] ##Initialize the list to hold the starting points
while find(target,key,start) >= 0:
point.append(find(target,key,start)) ##Add the starting point to the list
start = find(target,key,start) + 1 ##Find the new starting place in the target string
answertuple = tuple(point) ##Change the answer to a tuple
return answertuple ##Return the tuple
#Problem 3
def subStringMatchOneSub(key,target): # this function was provided by the instructor
"""search for all locations of key in target, with one substitution"""
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
def constrainedMatchPair(firstMatch,secondMatch,length):
match = [] ##Create the list to keep track of the matches
for i in range(0,len(firstMatch)): ##Test if they match up
for j in range(0,len(secondMatch)):
if secondMatch[j] == firstMatch[i] + length + 1:
match.append(firstMatch[i])
break
matchestuple = tuple(match)
return matchestuple
def subStringMatchExactlyOneSub(target,key):
exactmatch = subStringMatchExact(target,key)
allmatch = subStringMatchOneSub(key,target)
output = []
for i in range(0,len(allmatch)):
check = 0
for j in range(0, len(exactmatch)):
if exactmatch[j] == allmatch[i]:
check = 1
break
if check == 0:
output.append(allmatch[i])
outputtuple = tuple(output)
return outputtuple
mjcuva
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 3, HW 1
##Problem 1
##
##50 = 2,2,1
##51 = 1,5,0
##52 = 2,0,2
##53 = 1,3,1
##54 = 0,6,0
##55 = 1,1,2
##
##Problem 2
##
##Since it is possible to buy x,x+1...,x+5 McNuggets,
##you can add the lowest choice 6 to the total and still
##have a number that is able to be purchased with the
##combination of 6, 9,or 20 McNuggets.
##
##Problem 3
nuggets = (6,9,20)
best_so_far = 0
counter = 0
for loop_counter in range(1,200):
checker = False
for a in range(0,loop_counter/nuggets[0] +1):
for b in range(0,loop_counter/nuggets[1] + 1):
for c in range(0,loop_counter/nuggets[2] + 1):
solution = a*nuggets[0]+b*nuggets[1]+c*nuggets[2]
if solution == loop_counter:
counter = counter + 1
checker = True
if checker == True:
break
if checker == True:
break
if checker == True:
break
if checker == False:
counter = 0
best_so_far = loop_counter
print 'Largest number of McNuggets that cannot be bought in an exact quantity is',best_so_far
##Problem 4
nuggets = (6,9,20)
best_so_far = 0
counter = 0
for loop_counter in range(1,200):
checker = False
for a in range(0,loop_counter/nuggets[0] +1):
for b in range(0,loop_counter/nuggets[1] + 1):
for c in range(0,loop_counter/nuggets[2] + 1):
solution = a*nuggets[0]+b*nuggets[1]+c*nuggets[2]
if solution == loop_counter:
counter = counter + 1
checker = True
if checker == True:
break
if checker == True:
break
if checker == True:
break
if checker == False:
counter = 0
best_so_far = loop_counter
print 'Given package sizes',nuggets[0],',',nuggets[1],', and',nuggets[2],' the largest number of McNuggets that cannot be bought in exact quantity is',best_so_far
mjcuva
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 2, HW 1
##Program to find the 1000th prime number
##Problem 1
#Initialize Variables
prime = 3
isprime = 2
counter = 1
#Loop to count to the 1000th prime number
while(counter < 1000):
#Check that divisor is less than the number being checked
if ( isprime < prime):
#Check if the nummber is prime
if(prime%isprime == 0):
prime = prime + 1
isprime = 2
else:
isprime = isprime + 1
else:
#If it is, add one to the counter, and reset the isprime variable
counter = counter + 1
if(counter < 1000):
prime = prime + 1
isprime = 2
#Print the 1000th prime.
print prime
##Problem 2
from math import *
prime = 3
isprime = 2
counter = 1
total = 0
n = input('Enter a number ')
while(counter < n):
if ( isprime < prime):
if(prime%isprime == 0):
prime = prime + 1
isprime = 2
else:
isprime = isprime + 1
else:
total = total + log(prime)
counter = counter + 1
if(counter < n):
prime = prime + 1
isprime = 2
ratio = float(total)/float(n)
print 'The number you entered is ', n
print 'The total of all the log functions is ', total
print 'The ratio is ', ratio
mjcuva
1 year ago
|
 |
|
|
|