About Me
No description provided.
Classes
|
Class status: Established
Role:
Student
|
.
35% complete
|
Submitted Assignments
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 9, HW 2
# Problem Set 5: Ghost
# Name:
# Collaborators:
# Time:
#
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.
# TO DO: your code begins here!
def get_letter(player):
letter = raw_input('Please enter the letter: ').lower()
print 'player',player , 'says', letter,'.'
return letter
def up_date_fragment(letter,fragment):
fragment = fragment + letter
return fragment
def is_valid(fragment,wordlist):
if fragment in wordlist and len(fragment)>3:
print 'The fragment {0} is a word longer than 3 letter, the game is over.'.format(fragment)
return False
for word in wordlist:
if str.find(word,fragment) != -1:
print 'The fragment {0} is valid. The game continues.'.format(fragment)
print
return True
print 'The fragment {0} is invalid. The game is over.'.format(fragment)
return False
##is_valid('work',['worked','word'])
def player_goes(player,fragment,wordlist):
print 'Current word fragment:',fragment
letter = get_letter(player)
fragment = up_date_fragment(letter,fragment)
if not is_valid(fragment,wordlist):
print player,'has lost.'
return False
return fragment
def play_ghost(wordlist):
fragment = ''
letter = ''
print 'Welcome to Ghost!'
p1 = raw_input('Please enter the name of player 1: ')
p2 = raw_input('Please enter the name of player 2: ')
raw_input('Press ENTER to begin the game.')
while True:
print 'Player {0}\'s turn.'.format(p1)
fragment = player_goes(p1,fragment,wordlist)
if fragment == False:return
print 'Player {0}\'s turn.'.format(p2)
fragment = player_goes(p2,fragment,wordlist)
if fragment == False:return
if __name__ == '__main__':
word_list = load_words()
play_ghost(word_list)
xwb1989
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 9, HW 1
# Problem Set 5: 6.00 Word Game
# Name:
# Collaborators:
# Time:
#
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 10
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
"""
# TO DO ...
score = 0
word = word.lower()
for letter in word:
point = SCRABBLE_LETTER_VALUES['{0}'.format(letter)]
score = score + point
if n == len(word): score = score + 50
return score
# 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)
"""
print 'Current hand:',
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)
"""
# TO DO ...
newhand = hand.copy()
for letter in word:
newhand[letter] = newhand.get(letter, 0)-1
if newhand[letter] == 0:
del newhand[letter]
return newhand
#
# 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
"""
# TO DO ...
for letter in word:
if hand.get(letter,0) == 0:
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
"""
# TO DO ...
sumscore = 0
newhand = hand
while newhand != {}:
display_hand(newhand)
word = raw_input('Please input the word: ')
if word == '.':
print 'The sum of the scores is',sumscore
return sumscore
if is_valid_word(word, hand, word_list):
singlescore = get_word_score(word, len(hand))
print word,'earned',singlescore, 'points.',
sumscore = sumscore + singlescore
print 'The sum:',sumscore
newhand = update_hand(newhand, word)
else:
print 'The word is not valid, please enter again.'
return sumscore
## print "play_hand not implemented." # replace this with your code...
#
# 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 ...
## print "play_game not implemented." # delete this once you've completed Problem #4
## play_hand(deal_hand(HAND_SIZE), word_list) # delete this once you've completed Problem #4
##
## 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)
xwb1989
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 7, HW 1
# Problem Set 4
# Name:
# Collaborators:
# Time:
#
# 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.
RA = [salary*save*0.01]
ctr = 1
while ctr<years:
RA.append(salary*save*0.01 +(1+growthRate*0.01)*RA[len(RA)-1])
ctr += 1
return RA
##savings = 0
##RA = []
##def nestEggFixedR(savings,RA,salary, save, growthRate, years):
##
## if years == 0:
## return RA
## else:
## savings = salary*save*0.01 + savings*(1+growthRate*0.01)
## RA.append(savings)
## return nestEggFixedR(savings,RA,salary, save, growthRate, years-1)
def testNestEggFixed():
salary = 10000
save = 10
growthRate = 15
years = 5
savingsRecord = nestEggFixed(salary, save, growthRate, years)
print(savingsRecord)
def testNestEggFixedR():
salary = 10000
save = 10
growthRate = 15
years = 5
savingsRecord = nestEggFixedR(savings,RA,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.
testNestEggFixedR()
#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.
"""
RA = []
ctr = 0
savings = 0
while ctr<len(growthRates):
ctr += 1
savings = savings*(1+growthRates[ctr-1]*0.01)+salary*save*0.01
RA.append(savings)
return RA
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.
testNestEggVariable()
#####
#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.
RA = []
ctr = 0
while ctr<len(growthRates):
savings = savings*(1+growthRates[ctr]*0.01) - expenses
RA.append(savings)
ctr += 1
return RA
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.
testPostRetirement()
# 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.
def Bimethod(savings,epsilon, postRetireGrowthRates):
assert savings>0
assert epsilon>0
ctr = 1
low = 0
high = max(1,savings)
expenses = (low+high)/2.0
print(expenses)
lastleft = postRetirement(savings, postRetireGrowthRates, expenses)[len(postRetireGrowthRates)-1]
print(lastleft)
while abs(lastleft) > epsilon:
if lastleft > 0:
low = expenses
else:
high = expenses
expenses = (high + low)/2
## print(expenses)
lastleft = postRetirement(savings, postRetireGrowthRates, expenses)[len(postRetireGrowthRates)-1]
return expenses
savings = nestEggVariable(salary, save, preRetireGrowthRates)[len(preRetireGrowthRates)-1]
return Bimethod(savings, epsilon, postRetireGrowthRates)
def testFindMaxExpenses():
salary = 20000
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)
testFindMaxExpenses()
# Output should have a value close to:
# 1229.95548986
# TODO: Add more test cases here.
xwb1989
1 year ago
|
 |
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 3, HW 1
def solve(n,a,b,c):
for x in range(0,int(n/a)+1):
for y in range(0,int(n/b)+1):
for z in range(0,int(n/c)+1):
if n==a*x + b*y + c*z:
return n
return False
def item(a,b,c):
n = 6
while True:
if solve(n,a,b,c) and solve(n+1,a,b,c)\
and solve(n+2,a,b,c) and solve(n+3,a,b,c)\
and solve(n+4,a,b,c) and solve(n+5,a,b,c):
print(n-1,'is the last sum of Mcnuggets that can\'t be bought.')
return
n+=1
xwb1989
1 year ago
|
 |
|
 |
|
|
|