Gpyti


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 9, HW 1

Problem Set 5: 6.00 Word Game

Name:

Collaborators:

Time:

import sys

import random import string totalscore=0 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
"""

# TO DO ...
SCORE = 0
word_len = len(word) 
if word_len>=7:          #checking for bonus points
    SCORE = 50
for letter in range(0,word_len):
    t = SCRABBLE_LETTER_VALUES[word[letter]]
    SCORE = t + SCORE
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)
"""
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)
"""
lenword = len(word)
for letter in range(0,lenword):
    z = hand[word[letter]]
    if z > 1:
        hand[word[letter]] = z-1
    if z == 1:
        del hand[word[letter]]
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 """ count=0 v=0 lenwordlist=len(word_list) valid=False value=0 lenword=len(word) for letter in word: q = letter in hand if q == False: valid=False
else: v=letter # print v if word.count(letter) 0 and valid == True: valid=True else: valid=False return valid

lenwordlist=len(word_list)

temphand=[]

tempword=[]

value=0

valid=False

valid1=False

lenhand=len(hand)

lenword = len(word)

for v in range(0,lenword):

tempword.append(word[v])

print tempword

print hand

for k in range(lenword):

if word[k] in hand is None:

value=value

else:

z=hand[word[k]]

if z=1:

lentemp=len(tempword)

for z in range(0,tempword):

if word[k] != tempword[z]:

# need to update the letter into the list

# if the letter exists already dont update

# if the value is higher?

value=value+1

for z in range(0,lenwordlist):

if word == word_list[z]:

valid=True

if value==lenword and valid==True:

valid1=True

return valid1,valid,value,lenword

for letter in hand.keys():

for j in range(hand[letter]):

for k in range(0,lenword):

if L[k] == letter:

z=hand[letter]

if z==1:

value=value+1

del hand[letter]

del L[k]

if z>1:

hand[letter]=z-1

value=value+1

print hand,value,L

for letter in hand.keys():

for j in range(hand[letter]):

for k in range(0,lenword):

if word[k] == letter:

z=hand[letter]

if z>1:

hand[letter]=z-1

value=value+1

if hand[word[k]] == word[k]:

value=value+1

print 'yes', value

z = hand[word[letter]]

if z == 1:

del hand[word[letter]]

if z > 1:

hand[word[letter]] = z-1

return hand,value

f=[]

for letter in hand.keys():

for j in range(hand[letter]):

f.append(letter)

lenwrd=len(word)

lenhand=len(f)

for j in range(0,lenwrd):

for k in range(0,lenhand):

#print f[k], word[j]

if word[j] == f[k]:

print word[j],f[k]

value=value+1

for

a=0

lenword=len(word)

valid=False

valid1=False

wordvalid=False

lenwordlist=len(word_list)

#print lenwordlist

for a in range(0,lenword):

for letter in hand.keys():

if word[a]==letter:

a=a+1

if a>0:

valid=True

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 ...

# print "play_hand not implemented." # replace this with your code...

print 'Here are the letters you can use: ', display_hand(hand)
word=raw_input('Enter a word: ')
if word=='.':
    print'Your total score is: ',f
    play_game(word_list)
valid=is_valid_word(word,hand,word_list)
#print valid
if valid==False:
    print'Are you kidding?, try again',play_hand(hand,word_list)
if valid==True:
    update_hand(hand,word)
    if len(hand) > 0:
        display_hand(hand)
        f = get_word_score(word,HAND_SIZE)
        totalscore = f
        print 'Score so far: ',f
        play_hand(hand,word_list)
    if len(hand)==0:
        print 'your total score is: ',f + totalscore
    if word=='.':
        print 'lala'

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)


Gpyti 11 months ago
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 7, HW 1
    F=[]
    b = salary*save*0.01
    F.append(b)
    for a in range (1,years):
       #print growthRates[a]
        c = b * (1 + 0.01 * preRetireGrowthRates[a]) + salary * save * 0.01
        F.append(c)
        b=c
    return F

#Problem 3
def testPostRetirement(savings,postRetireGrowthRates,expenses):
    years=len(postRetireGrowthRates)
    f=[]
    b=savings * (1+0.01 * postRetireGrowthRates[0]) - expenses
    f.append(b)
    for a in range(1,years):
        c = b * (1+0.01 * postRetireGrowthRates[a]) - expenses
        f.append(c)
        b=c
    return f


#savingsRecord = 
#print savingsRecord

#Problem 4

def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates, epsilon):
    low=0
    high = testNestEggVariable(save,salary,preRetireGrowthRates)[-1]
    ctr=0
    savings=high
    guess=(low+high)/2.0
    lowest=testPostRetirement(savings,postRetireGrowthRates,guess)[-1]
    while abs(lowest) > epsilon and ctr <= 100:                             
            low = guess
        else:
            high = guess                                                   
        guess = (low + high) / 2.0                                          
        lowest = testPostRetirement(savings, postRetireGrowthRates, guess)[-1]   
    return guess


    
##    pre = len(preRetireGrowthRates)
##    post = len(postRetireGrowthRates)
##    
##    F = totalSavings[-1]
##    Guess = (F + epsilon) / 2
##    totalsavingsafter = testPostRetirement(F,postRetireGrowthRates,Guess)
##    while Guess*10>totalSavings:
##        ctr=ctr+1
##        F = (F + epsilon) / 2
##        totalsavingsafter = testPostRetirement(F,postRetireGrowthRates,F)
##    print F,Guess
##


Gpyti 11 months ago
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 5, HW 1
from string import *
def subStringMatchExact(target,key):
i=0
c=0
tup=()
while c!=-1:
c = find(target,key,i)
if c!=-1:
tup = tup + (c,)
i=c+1
return tup

def subStringMatchOneSub1(target,key):
length=len(key)
for i in range(0,length):
key1=key[0:i]
key2=key[i+1:length]
starts1=subStringMatch(target,key1)
starts2=subStringMatch(target,key2)
print starts1, starts2

def constrainedMatchPair(firstMatch,secondMatch,length):
tup=()
m=len(secondMatch)
lenfirst=len(firstMatch)
lensecond=len(secondMatch)
for n in range(0,lenfirst):
for k in range(0,lensecond):
if firstMatch[n]+m+1 == secondMatch[k]:
tup = tup +(n,)
return tup


def subStringMatchOneSub(target,key):
"""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)
#print match1,match2
# 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 subStringMatchExactlyOneSub(target,key):

Gpyti 11 months ago
MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 2, HW 1
ifprime=2
divisor=2
counter=0

while (counter<1000):
    if divisor<ifprime:
        if (ifprime%divisor==0):
            ifprime=ifprime+1
            divisor=2
        else:
            divisor=divisor+1
    else:
        counter=counter+1
        if counter<1000:
            ifprime=ifprime+1
            divisor=2
print 'the 1000th prime is',ifprime

#problem 2

from math import *
ifprime=3
divisor=2
counter=0
sum=0
n=100
while (counter<1000):
    if divisor<ifprime:
        if (ifprime%divisor==0):
            ifprime=ifprime+1
            divisor=2
        else:
            divisor=divisor+1
    else:
        sum=sum+log(n)
        counter=counter+1
        if counter<n:
            ifprime=ifprime+1
            divisor=2
ratio = float(sum)/float(n)
print 'this is the number',n
print 'this is the sum',sum
print 'this is the ratio',ratio
print 'this is the counter',counter

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

First assignment for MIT 6.00 OpenCourseWare Class from MIT

# Problem Set 0
# Name: Gpyti
# Collaborators: None
# Time 1:00 min

first = raw_input('What is your First name?')
last = raw_input('What is your last name?')
print 'your first name is',first,'and your last mame is',last
                 

Gpyti 1 year ago