8 Feb 2015

Quiz

#Python
#Quiz

 

#Problem 4

def myLog(x, b):
    '''
    x: a positive integer
    b: a positive integer; b >= 2

    returns: log_b(x), or, the logarithm of x relative to a base b.
    '''


    if x < b:
        return 0
    return myLog(x / b, b) + 1



#Problem 5

def laceStrings(s1, s2):
    """
    s1 and s2 are strings.

    Returns a new str with elements of s1 and s2 interlaced,
    beginning with s1. If strings are not of same length,
    then the extra elements should appear at the end.
    """


    s1 = list(s1)
    i = 0
    for j in s2:
        s1.insert(i + 1, j)
        i += 2
    result = ''
    for k in s1:
        result += k
    return result 



#Problem 6

def laceStringsRecur(s1, s2):
    """
    s1 and s2 are strings.

    Returns a new str with elements of s1 and s2 interlaced,
    beginning with s1. If strings are not of same length,
    then the extra elements should appear at the end.
    """
 
    def helpLaceStrings(s1, s2, out):
        if s1 == '':
            return out + s2
        if s2 == '':
            return out + s1
        else:
            return helpLaceStrings(s1[1:], s2[1:], out + s1[0] + s2[0])
    return helpLaceStrings(s1, s2, '')



#Problem 7
def McNuggets(n):
    """
    n is an int

    Returns True if some integer combination of 6, 9 and 20 equals n
    Otherwise returns False.
    """

    if n < 0:
        return False
    elif n == 0:
        return True
    else:
        return any(McNuggets(n - x) for x in [6, 9, 20])



#Problem 8-1

def fixedPoint(f, epsilon):
    """
    f: a function of one argument that returns a float
    epsilon: a small float
 
    returns the best guess when that guess is less than epsilon
    away from f(guess) or after 100 trials, whichever comes first.
    """

    guess = 1.0
    for i in range(100):
        if abs(f(guess) - guess) < epsilon:
            return guess
        else:
            guess = f(guess)
    return guess



#Problem 8-2

def sqrt(a):
    def tryit(x):
        return 0.5 * (a/x + x)
    return fixedPoint(tryit, 0.0001)



#Problem 8-3

def babylon(a):
    def test(x):
        return 0.5 * ((a / x) + x)
    return test

def sqrt(a):
    return fixedPoint(babylon(a), 0.0001)

 

 

Categories: , , , , , , , , , , ,

The 6.00 Word Game

# Python
# The 6.00 Word Game
# Problem Set 4A

 
from ps4a import *
import time



# Problem #6: Computer chooses a word

def compChooseWord(hand, wordList, n):
    """
    Given a hand and a wordList, find the word that gives
    the maximum value score, and return it.

    This word should be calculated by considering all the words
    in the wordList.

    If no words in the wordList can be made from the hand, return None.

    hand: dictionary (string -> int)
    wordList: list (string)
    n: integer (HAND_SIZE; i.e., hand size required for additional points)

    returns: string or None
    """

  
    score = {}
    try:
            for word in wordList:
                if isValidWord(word, hand, wordList):
                    score[word] = score.get(word, 0) + getWordScore(word, n)
            return max(score, key = score.get)
    except:
        return None

#
# Problem #7: Computer plays a hand
#
def compPlayHand(hand, wordList, n):
    """
    Allows the computer to play the given hand, following the same procedure
    as playHand, except instead of the user choosing a word, the computer
    chooses it.

    1) The hand is displayed.
    2) The computer chooses a word.
    3) After every valid word: the word and the score for that word is
    displayed, the remaining letters in the hand are displayed, and the
    computer chooses another word.
    4)  The sum of the word scores is displayed when the hand finishes.
    5)  The hand finishes when the computer has exhausted its possible
    choices (i.e. compChooseWord returns None).

    hand: dictionary (string -> int)
    wordList: list (string)
    n: integer (HAND_SIZE; i.e., hand size required for additional points)
    """

    total = 0
    handNew = hand.copy()
    while True:
        print 'Current Hand:',
        displayHand(handNew)
        compWord = compChooseWord(handNew, wordList, n)
        if compWord != None:
            total += getWordScore(compWord, n)
            print '"'+ str(compWord) + '"', 'earned', getWordScore(compWord, n), 'points.', 'Total:', total, 'points'
            handNew = updateHand(handNew, compWord)
            if calculateHandlen(handNew) == 0:
                print 'Total score:', total, 'points.'
                break
        else:
            print 'Total score:', total, 'points.'
            break
   
#
# Problem #8: Playing a game
#
#
def playGame(wordList):
    """
    Allow the user to play an arbitrary number of hands.

    1) Asks the user to input 'n' or 'r' or 'e'.
        * If the user inputs 'e', immediately exit the game.
        * If the user inputs anything that's not 'n', 'r', or 'e', keep asking them again.

    2) Asks the user to input a 'u' or a 'c'.
        * If the user inputs anything that's not 'c' or 'u', keep asking them again.

    3) Switch functionality based on the above choices:
        * If the user inputted 'n', play a new (random) hand.
        * Else, if the user inputted 'r', play the last hand again.
     
        * If the user inputted 'u', let the user play the game
          with the selected hand, using playHand.
        * If the user inputted 'c', let the computer play the
          game with the selected hand, using compPlayHand.

    4) After the computer or user has played the hand, repeat from step 1

    wordList: list (string)
    """

    while True:
        user = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
        if user == 'n':
            while True:
                user_n = raw_input('Enter u to have yourself play, c to have the computer play: ')
                n = HAND_SIZE
                hand = dealHand(n)
                if user_n == 'u':
                    playHand(hand, wordList, n)
                    break
                elif user_n == 'c':
                    compPlayHand(hand, wordList, n)
                    break
                else:
                    print 'Invalid command.'
        elif user == 'r':
                while True:
                    try:
                        len(hand) > 0
                        user_r = raw_input('Enter u to have yourself play, c to have the computer play: ')
                        if user_r == 'u':
                            playHand(hand, wordList, n)
                            break
                        elif user_r == 'c':
                            compPlayHand(hand, wordList, n)
                            break
                        else:
                            print 'Invalid command.'
                    except:
                        print 'You have not played a hand yet. Please play a new hand first!'
                        break
        elif user == 'e':
            break
        else:
            print 'Invalid command.'
       
#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
    wordList = loadWords()
    playGame(wordList)


Categories: , , , , ,

The 6.00 Word Game

#Python
 
# 6.00x Problem Set 4A
# The 6.00 Word Game


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
}



WORDLIST_FILENAME = "words.txt"

def loadWords():
    """
    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 getFrequencyDict(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 getWordScore(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, multiplied by the length of the word, PLUS 50 points if all n
    letters are used on the first turn.

    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 (see SCRABBLE_LETTER_VALUES)

    word: string (lowercase letters)
    n: integer (HAND_SIZE; i.e., hand size required for additional points)
    returns: int >= 0
    """

    score=0
    for i in range(0,len(word)):
        score+=SCRABBLE_LETTER_VALUES[word[i]]
    score*=len(word)
    if(len(word)==n):
        score+=50   
    return score


def displayHand(hand):
    """
    Displays the letters currently in the hand.

    For example:
    >>> displayHand({'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


def dealHand(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={}
    numVowels = n / 3
   
    for i in range(numVowels):
        x = VOWELS[random.randrange(0,len(VOWELS))]
        hand[x] = hand.get(x, 0) + 1
       
    for i in range(numVowels, 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 updateHand(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 modify hand.

    word: string
    hand: dictionary (string -> int)   
    returns: dictionary (string -> int)
    """

    new= {}
    new=hand.copy()
    for i in new.keys():
        for j in word:
            if i==j and new[i]<>0:
                new[i]-=1
    return new



#
# Problem #3: Test word validity
#
def isValidWord(word, hand, wordList):
    """
    Returns True if word is in the wordList and is entirely
    composed of letters in the hand. Otherwise, returns False.

    Does not mutate hand or wordList.
  
    word: string
    hand: dictionary (string -> int)
    wordList: list of lowercase strings
    """

    new=hand.copy()
    if len(word)==0:
        return False
    if word in wordList:
        for i in range(0,len(word)):
            if not(word[i] in new.keys()) or (new[word[i]]==0):
                return False
            else:
                new[word[i]]-=1  
    else:
        return False
    return True       


#
# Problem #4: Playing a hand
#

def calculateHandlen(hand):
    """
    Returns the length (number of letters) in the current hand.
   
    hand: dictionary (string-> int)
    returns: integer
    """

    counter=0
    for i in hand.keys():
        counter+=hand[i]
    return counter


def playHand(hand, wordList, n):
    """
    Allows the user to play the given hand, as follows:

    * The hand is displayed.
    * The user may input a word or a single period (the string ".")
      to indicate they're done playing
    * Invalid words are rejected, and a message is displayed asking
      the user to choose another word until they enter a valid word or "."
    * When a valid word is entered, it uses up letters from the hand.
    * After every valid word: the score for that word is 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 or the user
      inputs a "."

      hand: dictionary (string -> int)
      wordList: list of lowercase strings
      n: integer (HAND_SIZE; i.e., hand size required for additional points)
     
    """

   
    total = 0
    handNew = hand.copy()
    while calculateHandlen(handNew) >= 0:
        if calculateHandlen(handNew) == 0:
            print 'Run out of letters. Total score:', total, 'points.'
            break
        print 'Current Hand:', displayHand(handNew)
        word = raw_input('Enter word, or a "." to indicate that you are finished: ')
        if word == '.':
            print 'Goodbye! Total score:', total, 'points.'
            break
        elif not isValidWord(word, handNew, wordList):
            print 'Invalid word, please try again.'
            print
        else:
            total += getWordScore(word, n)
            print str(word), 'earned', getWordScore(word, n), 'points.', 'Total:', total, 'points'
            print
            handNew = updateHand(handNew, word)

#
# Problem #5: Playing a game
#

def playGame(wordList):
    """
    Allow the user to play an arbitrary number of hands.

    1) Asks the user to input 'n' or 'r' or 'e'.
      * If the user inputs 'n', let the user play a new (random) hand.
      * 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, tell them their input was invalid.

    2) When done playing the hand, repeat from step 1   
    """

    while True:
        user = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
        if user == 'n':
            n = HAND_SIZE
            hand = dealHand(n)
            playHand(hand, wordList, n)
        elif user == 'e':
            break
        elif user == 'r':
            try:
                playHand(hand, wordList, n)
            except:
                print 'You have not played a hand yet. Please play a new hand first!'
        else:
            print 'Invalid command.' 


#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
    wordList = loadWords()
    playGame(wordList)

Categories: , , , ,

Hangman game

# Python
# Problem Set 3 
# Hangman game



import random
import string

WORDLIST_FILENAME = "words.txt"

def loadWords():
    """
    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)
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = string.split(line)
    print "  ", len(wordlist), "words loaded."
    return wordlist

def chooseWord(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """

    return random.choice(wordlist)

# end of helper code
# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program

wordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''

  
    p=True
    for e in secretWord:
        if not(e in lettersGuessed):
            p=False
            break
    return p

def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''


    stringSoFar=''
    for i in range(0, len(secretWord)):
    if secretWord[i] in lettersGuessed:
        stringSoFar += secretWord[i]
    else:
        stringSoFar += "_ "
    return stringSoFar

def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''


    notGuess='abcdefghijklmnopqrstuvwxyz'
    notGuessed=''
    for e in notGuess:
            if not(e in lettersGuessed):
                notGuessed+=e
    return notGuessed     
   
   

def hangman(secretWord):
    '''
    secretWord: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many
      letters the secretWord contains.

    * Ask the user to supply one guess (i.e. letter) per round.

    * The user should receive feedback immediately after each guess
      about whether their guess appears in the computers word.

    * After each round, you should also display to the user the
      partially guessed word so far, as well as letters that the
      user has not yet guessed.

    Follows the other limitations detailed in the problem write-up.
    '''


    guessCounter = 8
    lettersGuessed = []
    print "Welcome to the game Hangman!"
    print "I am thinknig of a word that is " + str(len(secretWord)) + " letters long."
    while True:
        print "-------------"
        print "You have " + str(guessCounter) + " guesses left."
        print "Available letters: " + getAvailableLetters(lettersGuessed)
        guess = raw_input("Please guess a letter: ").lower()
        if guess not in lettersGuessed and guess in secretWord:
            lettersGuessed.append(guess)
            print "Good guess: " + getGuessedWord(secretWord, lettersGuessed)
        elif guess not in lettersGuessed and guess not in secretWord:
            lettersGuessed.append(guess)
            print "Oops! That letter is not in my word: " + getGuessedWord(secretWord, lettersGuessed)
            guessCounter -= 1
        else:
            print "Oops! You've already guessed that letter: " + getGuessedWord(secretWord, lettersGuessed)
        if guessCounter == 0 or isWordGuessed(secretWord, lettersGuessed) == True:
            print "-------------"
            break
    if (isWordGuessed(secretWord, lettersGuessed)):
        print "Congratulations, you won!"
    else:
        print "Sorry, you ran out of guesses. The word was " + secretWord    

'''

# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)


secretWord = chooseWord(wordlist).lower()
#secretWord='tact'
hangman(secretWord)

Categories: , , ,

Minimum Monthly Payment of Credit Card using Bisection Search

#Python

'''
Program to calculate minimum Monthly Payment of a Credit Card using Bisection Search
'''

balance = 320000
annualInterestRate = 0.2
newbalance=balance
i=1
monthlyInterestRate=annualInterestRate/12.0
lowerb=newbalance/12.0
upperb=(newbalance *(1+monthlyInterestRate)**12)/12.0
minimumMonthlyPay=(lowerb+upperb)/2.0
while(i<=12):
    monthlyUnpaidBal=newbalance-minimumMonthlyPay
    newbalance=monthlyUnpaidBal+monthlyInterestRate*monthlyUnpaidBal
    i+=1     
 
    if(i==13 and round(newbalance,2)>0.00):
        i=1
        lowerb=minimumMonthlyPay

        minimumMonthlyPay=(lowerb+upperb)/2.0
        newbalance=balance
    elif(i==13 and round(newbalance,2)<0.00):
        i=1
        upperb=minimumMonthlyPay
        minimumMonthlyPay=(lowerb+upperb)/2.0
        newbalance=balance      
   
print "Lowest Payment:", round(minimumMonthlyPay,2)

Categories: , , , ,

Monthly Payment of a Credit Card

#Python

#Program to calculate minimum Monthly Payment of a Credit Card

balance = 3329
annualInterestRate = 0.2
minimumMonthlyPay=100
newbalance=balance
i=1
monthlyInterestRate=annualInterestRate/12.0

while(i<=12):
    monthlyUnpaidBal=newbalance-minimumMonthlyPay
    newbalance=monthlyUnpaidBal+monthlyInterestRate*monthlyUnpaidBal
    i+=1
       
    if(i==13 and newbalance>0):
        i=1
        a=int(monthlyUnpaidBal/12-monthlyInterestRate*monthlyUnpaidBal)
        if(a<10):
            a=10
        else:
            a=a-a%10
        minimumMonthlyPay+=a
        newbalance=balance       
   
print "Lowest Payment:", minimumMonthlyPay

Categories: , , ,

Receipt of Credit Card

#Python

#Program to calculate receipt of a Credit Card

balance = 4842
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
totalPaid=0.0
 
i=1
while(i<=12):
    monthlyInterestRate=annualInterestRate/12.0
    minimumMonthlyPay=monthlyPaymentRate*balance
    monthlyUnpaidBal=balance-minimumMonthlyPay
    balance=monthlyUnpaidBal+monthlyInterestRate*monthlyUnpaidBal
    totalPaid+=minimumMonthlyPay
    print "Month:", i
    print "Minimum monthly payment:", round(minimumMonthlyPay,2)
    print "Remaining balance:", round(balance,2)
    i+=1
 
print "Total paid:", round(totalPaid,2)
print "Remaining balance:", round(balance,2)   

Categories: , ,

Tower of Hanoi

#Python

'''
Recursive program to implement Tower of Hanoi for n rings and 3 stacks
'''

def printMove(fr, to):
    print('move from ' + str(fr) + ' to ' + str(to))

def Towers(n, fr, to, spare):
    if n == 1:
        printMove(fr, to)
    else:
        Towers(n-1, fr, spare, to)
        Towers(1, fr, to, spare)
        Towers(n-1, spare, to, fr)




Categories: , ,

Semordnilap using Recursion

#PYTHON

'''
A semordnilap is a word or a phrase that spells a different word when backwards ("semordnilap" is a semordnilap of "palindromes"). Here are some examples:

    nametag / gateman
    dog / god
    live / evil
    desserts / stressed
 

Recursive program, semordnilap, that takes in two words and says if they are semordnilap.
'''

'''
 
This wrapper function performs some checks, then makes a call to the recursive function
'''

def semordnilapWrapper(str1, str2):
    # A single-length string cannot be semordnilap
    if len(str1) == 1 or len(str2) == 1:
        return False

    # Equal strings cannot be semordnilap
    if str1 == str2:
        return False

    return semordnilap(str1, str2)




def semordnilap(str1, str2):
    '''

    returns: True if str1 and str2 are semordnilap;
             False otherwise.
    '''

    if len(str1)<>len(str2) or str1[0]<>str2[len(str2)-1] :
        return False
    elif len(str1)==1:
        return True
    else:
        return semordnilap(str1[1:],str2[:-1])


Categories: , , ,

Copyright © UPgradeCODING | Powered by Blogger