CSC111 Homework 12 Solutions

From dftwiki3
Revision as of 12:18, 30 April 2010 by Thiebaut (talk | contribs) (Created page with '==Problem #1== Solution provided by Andrea. <br /> <source lang="python"> # hw12a.py # Andrea Spain 111c-aw # This program gets the html from the Smith College dining website …')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Problem #1

Solution provided by Andrea.


# hw12a.py
# Andrea Spain 111c-aw
# This program gets the html from the Smith College dining website
# for today. It asks the user to input what they want to eat.
# It then splits the html into house menu sections to be searched
# for these items. The search returns the full name of the wanted
# food and outputs it next to the house that is offering it.

import urllib2
import sys
import time
import datetime

#--- constants used by program ---#
baseurl = "http://www.smith.edu/diningservices/10Menus/"

#--- returns the date from the computer, formatting it ---#
def getDate():
    #--- creates dictionary to pair number returned with month name ---#
    months = { "01":"January", "02":"February", "03":"March", "04":"April",
               "05":"May", "06":"June", "07":"July", "08":"August",
               "09":"September", "10":"October", "11":"November",
               "12":"December" }

    #--- finds today's date ---#
    today = datetime.date.today()
    today = str(today)

    #--- splits the date from the form "####-##-##" ---#
    splitToday = today.split("-")

    #--- gets year, month, and day ---#
    year = splitToday[0]
    monthNum = splitToday[1]

    #--- uses the dictionary to turn month number into name ---#
    month = months[ monthNum ]
    day = splitToday[2]
    return month, day, year

#--- returns the html source of the dining web page for that day ---#
def getPageInfo(month, day, year):

    #--- creates url out of base and date info ---#
    url = baseurl + year[2:] + month.lower()[:3] + day + ".php"
    f = urllib2.urlopen( url )

    #--- gets html text ---#
    htmlText = f.read()
    return htmlText

#--- breaks the html text into sections corresponding to the houses ---#
def breakIntoHouses(html):

    #--- splits into houses, but with irrelevant text at index 0 ---#
    almostHouses = html.split('bgcolor="#FFCC66" class="TemplaceCDEBodyCopy"><strong>')

    #--- gets rid of extra text ---#
    houses = almostHouses[1:]
    houseAndName = []

    #--- splits the text again to get the house name ---#
    for house in houses:
        togetName = house.split("</strong>")
        name = togetName[0]

        #--- special case for Kosher because returns large white space ---#
        if name.find("Kosher") != -1:
            #--- remove white space and adds back spaces around "-" ---#
            czkosher = name.split()
            name = czkosher[0] + " " + czkosher[1] + " " + czkosher[2]

        #--- appends the name and menu info to a list as a pair ---#
        houseAndName.append( [name, house] )

    return houseAndName

#--- searches the menus for the user's input ---#
def searchMenus(dishes, houses):
    foundDishes = []

    #--- splits user's input into a list of dishes ---#
    dishList = dishes.split()

    #--- try to find every dish ---#
    for dish in dishList:
        for name, menu in houses:
            menu = menu.lower() # make lower-case
            #--- finds the dish in the menu ---#
            position = menu.find(dish)

            #--- if dish found append to list of found dishes ---#
            if position != -1:
                #--- gets the full name of the dish from the menu ---#
                #--- slices menu starting 50 before position of dish ---#
                lookForStart = menu[position-50:]
                #--- specifies start as last > before dish ---#
                start = lookForStart.find(">") + 1
                #--- slices menu further, starting at start of dish name ---#
                lookForEnd = lookForStart[start:]
                #--- specifies end as the <br> after dish name ---#
                end = lookForEnd.find("<br>") + start
                #--- takes slice to get the full dish name ---#
                fullDish = lookForStart[start:end]
                fullDishName = fullDish.strip() # strips of space at end
                #--- if the dish ends in a comma, remove it! ---#
                try:
                    if fullDishName[-1] == ",":
                        fullDishName2 = fullDishName[:-1]
                    #--- else keep name the same ---#               
                    else:
                        fullDishName2 = fullDishName
                except IndexError:
                    fullDishName2 = fullDishName

                #--- keeps house name with the dish ---#
                foundDishes.append([name, fullDishName2])
    return foundDishes
                
#--- prints the output (houses: dish1, dish2, etc.) ---#
def main():
    #--- welcomes user, calling function to get date ---#
    print "Welcome to the Smith Menu Selection program."
    month, day, year = getDate()
    print "Today is", month, day + ",", year

    #--- asks for dishes to search for ---#
    dishes = raw_input("What are your favorite dishes? ")
    print
    #--- ask for no commas in input ---#
    while dishes.find(",") != -1:
        dishes = raw_input("Please input without commas. ")
    dishes = dishes.lower() # lower-case the input  

    #--- gets html text from dining website ---#
    html = getPageInfo(month, day, year)
    #--- breaks html into house sections ---#
    houses = breakIntoHouses(html)
    #--- searches the menus for the dishes ---#
    foundDishes = searchMenus(dishes, houses)
    #--- sorts so that same house is next to itself ---#
    sortedDishes = foundDishes[:]
    sortedDishes.sort()

    #--- OUTPUT ---#
    print "Your favorite dishes are offered today in:"
    print
    #--- if no matches, tell user ---#
    if sortedDishes == []:
        print "Sorry, nowhere!"
    keptDishes = []
    for i in range(len(sortedDishes)):
        house, dish = sortedDishes[i]
        #--- so that doesn't check for a dish that isn't there ---#
        if i + 1 < len(sortedDishes):
            #--- if next house is the same as this house ---#
            if house == sortedDishes[i+1][0]:
                #--- append to list of dishes for that house ---#
                keptDishes.append(dish)
                continue
        #--- if there is more than one dish for this house... ---#
        if keptDishes != []:
            print house + ":", dish + ",",
            #--- print kept dishes as well ---#
            for i in range(len(keptDishes)):
                if i != len(keptDishes) -1:
                    print keptDishes[i] + ",",
                else:
                    print keptDishes[i]
        #--- else just print the one dish with its house ---#
        else:
            print house + ":", dish
        keptDishes = [] # re-empty list

main()


Problem #2

Solution provided by Weici


#hw12b.py
#111c-ar
#Weici Hu
#This program generates random poem,
#under two themes,city and sea.
#Themes will be selected random by
#the program.
#Total ten lines will be generated. 
#Lists of words and pattern are copied
#from website given below:
#http://thinkzone.wlonk.com/PoemGen/PoemGen.htm
#A few assumptions are made:
#--1. only 9 word lists for each theme
#--2. an alphabet + punctuaion mark will 
#--   not exist in pattern (that'll be
#--   grammatically wrong in English)
#--3. 's' is the only letter that can be
#--   together with a number. 
#--   No past tense will be considered.


from random import *

#---create lists for SEA, CITY, Pattern
SEA = [#List1--Concrete nouns
       ['SEA', 'SHIP', 'SAIL', 'WIND', 'BREEZE', 'WAVE', 'CLOUD', 'MAST',
          'CAPTAIN', 'SAILOR', 'SHARK', 'WHALE', 'TUNA', 'SEASHELL', 
          'PIRATE', 'LAD', 'GIRL', 'GULL', 'REEF', 'SHORE', 'MAINLAND', 
          'MOON', 'SUN'],

       #List2--Abstract Nouns
       ['ADVENTURE','COURAGE','ENDURANCE','DESOLATION','DEATH',
            'LIFE','LOVE','FAITH'],

       #List3--Transitive verbs
       ['COMMAND','VIEW','LEAD','PULL','LOVE','DESIRE','FIGHT'],

       #List4--Intrasitive verbs
       ['TRAVEL','SAIL','WAVE','GROW','RISE','FALL','ENDURE','DIE'],

       #List5--Adjectives
       ['BIG','SMALL', 'OLD','COLD','WARM','SUNNY','RAINY','MISTY',
            'CLEAR','STORMY','ROUGH','LIVELY','DEAD'],

       #List6--Adverbs
       ['SWIFTLY','CALMLY','QUIETLY','ROUGHLY'],

       [], 
       [],
 
       #List9--Interjections
       ['O', 'OH', 'OOH', 'AH','LORD','GOD','WOW','GOLLY GOSH']]


CITY = [
        #List1--Concrete nouns 
        ['CITY','STREET','SIDEWALK','CORNER','DOOR',
             'WINDOW','CAR','TRUCK','GUY','GIRL',
             'JOB','FLOWER','LIGHT','CIGARETTE',
             'RAIN','SKYSCRAPER','JACKHAMMER',
             'DRIVER','WORKER'],

        #List2--Abstract Nouns
        ['ACTION','WORK','NOISE','DESOLATION',
             'DEATH','LIFE','LOVE','FAITH','ANGER',
             'EXHAUSTION'],

        #List3--Transitive verbs
        ['GET','GRAB','PUSH','LOVE','DESIRE','BUY',
             'SELL','FIGHT','HUSTLE'],

        #List4--Intrasitive verbs
        ['TALK','WALK','GOSSIP','RUN','GO','STOP',
             'EAT','GROW','SHRINK','SHOP','WORK'],

        #List5--Adjectives
        ['BIG','SMALL','OLD','FAST','COLD','HOT',
             'DARK','DUSTY','GRIMY','DRY','RAINY',
             'MISTY','NOISY','FACELESS','DEAD'],

        #List6--Adverbs
        ['QUICKLY','LOUDLY','CALMLY','QUIETLY',
             'ROUGHLY'],
        [],
        [],

        #List9--Interjections
        ['O','OH','OOH','AH','LORD','GOD','DAMN']]

Pattern = ['THE 5 1 6 3S THE 1.',\
            '5, 5 1S 6 3 A 5, 5 1.',\
            '2 IS A 5 1.',\
            '9, 2!',\
            '1S 4!',\
            'THE 1 4S LIKE A 5 1.',\
            '1S 4 LIKE 5 1S.',\
            'WHY DOES THE 1 4?',\
            '6 LIKE A 5 1.',\
            '2, 2, AND 2.',\
            'WHERE IS THE 5 1?',\
            'ALL 1S 3 5, 5 1S.',\
            'NEVER 3 A 1.']

#---create dictionary for word lists
#---so each list of word corresponds to 
#---a number.
def createDict(List):
    Dict = {}
    listCounter = 1
    for List in List:
        Dict[listCounter] = List
        listCounter += 1
    return Dict

#---create poem based on the theme and 
#---pattern given.
def createPoem(dic,pattern):
    #pick a pattern ramdonly and get its component
    compo = pattern[randrange(len(pattern))].split()
    numList  = ['1','2','3','4','5','6','7','8','9']
    punList = [',', '.', '?', '!']    

    poem = []

    for item in compo:
        if item in numList:
            # item is a number
            n = int(item)
            poem.append(dic[n][randrange(len(dic[n]))])

        elif item[-1] in punList:
           if len(item)==2:
               # item is a number + punctuation mark
               n = int(item[0])
               word = dic[n][randrange(len(dic[n]))]
               pun = item[-1]
               poem.append(word+pun)
               
           elif item[0] in numList:
               # item is a number + "s" + punc
               n = int(item[0])
               word = dic[n][randrange(len(dic[n]))]
               pun = item[-1]
               poem.append(word+"S"+pun)
               
           else:
               # item is a word + punc
               pun = item[-1]
               poem.append(item[ :-1]+pun)

        elif item[0] in numList:
            # item is a number + 's'
            n = int(item[0])
            word = dic[n][randrange(len(dic[n]))]
            poem.append(word+'S')
        
        else:
            # item is a given word
            poem.append(item)

    #---print out the line
    print " ".join(poem)
    

def main():
    global SEA, CITY, Pattern
   
    #---generate dictionary for SEA
    seaDict = createDict(SEA)
    #---generate dictionary for CITY
    cityDict = createDict(CITY)

    #---combine 2 into 1 dictionary
    bigDict = [seaDict, cityDict]
    

    #---generate 10 lines of poem
    for i in range(10):
        # generate a theme randomly
        dic = bigDict[randrange(2)]
        createPoem(dic, Pattern)  
        print

main()