Difference between revisions of "CSC111 Homework 8 Solution Programs 2014"

From dftwiki3
Jump to: navigation, search
(Created page with "--~~~~ ---- =Program 1= <br /> <source lang="python"> # hw8a.py # Arcadia Kratkiewicz (ap) # Marianne Staknis (au) # 3/30/2014 # # a modified version of a simple eliza-like pr...")
 
(Program 2)
Line 211: Line 211:
 
<br />
 
<br />
 
<source lang="python">
 
<source lang="python">
 +
# hw8b.py
 +
# Youyou Tian (bm)
 +
# (slightly edited by D. Thiebaut)
 +
# 4/2/14
 +
#
 +
# This program expects data stored in the file; the data comes from this
 +
# URL: http://www.metoffice.gov.uk/climate/uk/stationdata/
 +
# where temperatures in the UK have been recorded over the past 200 years or so.
 +
# The format for each line is the following:
 +
# year
 +
# month of the year (1 for January, 2 for February, etc.)
 +
# max temperature that month (in Celcius)
 +
# min temperature that month
 +
# number of days of air-frost
 +
# amount of rain (millimeter)
 +
# number of sun hours that month
 +
#
 +
# The original data files can be found on this site. The following legend appears on all the data files:
 +
# Estimated data is marked with a * after the value. Missing data (more than 2 days missing in month)
 +
#  is marked by ---. Sunshine data taken from an automatic Kipp & Zonen sensor marked with a #,
 +
# otherwise sunshine data taken from a Campbell Stokes recorder.'
 +
#
 +
# Given the temperatures data, this program:
 +
# finds the coldest temperature for the year recorded,
 +
# the hottest temperature recorded,
 +
# the coldest city in December 2011
 +
# and the largest difference between temperatures
  
 +
from temp import temperatures
 +
 +
tempList = temperatures.split("\n") #Splits the temperature table into lists
 +
 +
#
 +
# findColdestTemp(list temperatures)
 +
# finds the coldest temperature, with the city, year and month
 +
#
 +
def findColdestTemp(temperatures):
 +
    tempList = []
 +
    for temp in temperatures:
 +
        tempList.append(getColdestTempList(temp))
 +
    return min(tempList)
 +
 +
#
 +
# getColdestTemp(list temperatures)
 +
# reorders the elements in temp list so that it is
 +
# [tempMin, year, month, city]
 +
 +
def getColdestTempList(temperatures):
 +
    temp = temperatures.split()
 +
    city = temp[0]
 +
    year = int(temp[1])
 +
    month = int(temp[2])
 +
    tempMin = float(temp[4].rstrip("*-"))
 +
    return[tempMin, year, month, city]
 +
 +
#
 +
# findHottestTemp(list temperatures)
 +
# finds the hottest temperature, with the city, year and month
 +
#
 +
def findHottestTemp(temperatures):
 +
    tempList = []
 +
    for temp in temperatures:
 +
        tempList.append(getHottestTempList(temp))
 +
    return max(tempList)
 +
 +
#
 +
# getColdestTemp(list temperatures)
 +
# reorders the elements in temp list so that it is
 +
# [tempMax, year, month, city]
 +
 +
def getHottestTempList(temperatures):
 +
    temp = temperatures.split()
 +
    city = temp[0]
 +
    year = int(temp[1])
 +
    month = int(temp[2])
 +
    tempMax = float(temp[3].rstrip("*-"))
 +
    return[tempMax, year, month, city]
 +
 +
#
 +
# findColdestCity(list temperatures, int year)
 +
# finds the coldest city in december given a year
 +
 +
def findColdestCity(temperatures, year):
 +
    tempList = []
 +
    for temp in temperatures:
 +
        returnedTemp = getColdestTempList(temp)
 +
        if returnedTemp[1] == year and returnedTemp[2] == 12:
 +
            tempList.append(returnedTemp)   
 +
    return min(tempList)
 +
 +
#
 +
# findLargestSwing(list temperatures)
 +
# finds the largest difference of temperatures, with the year
 +
# month and city
 +
 +
def findLargestSwing(temperatures):
 +
    tempList = []
 +
    for temp in temperatures:
 +
        tempList.append(getSwingTemp(temp))
 +
    return max(tempList)
 +
 +
 +
#
 +
# getSwingTemp(list temperatures)
 +
# reorders the elements in temp list so that it is
 +
# [absoulte difference between minTemp and maxTemp, year, month, city]
 +
 +
def getSwingTemp(temperatures):
 +
    temp = temperatures.split()
 +
    city = temp[0]
 +
    year = int(temp[1])
 +
    month = int(temp[2])
 +
    tempMin = float(temp[4].rstrip("*-"))
 +
    tempMax = float(temp[3].rstrip("*-"))
 +
    return[abs(tempMin-tempMax), year, month, city]
 +
 +
#
 +
# main()
 +
#
 +
def main():
 +
    #answer to question 1
 +
    coldest = findColdestTemp(tempList)
 +
    print("The coldest temperature recorded is %.1fC in %d/%d, in %s." % (coldest[0], coldest[2], coldest[1], coldest[3]))
 +
 +
    #answer to question 2
 +
    hottest = findHottestTemp(tempList)
 +
    print("The hottest temperature recorded is %.1fC in %d/%d, in %s." % (hottest[0], hottest[2],hottest[1], hottest[3]))
 +
 +
    #answer to question 3
 +
    coldestCity = findColdestCity(tempList, 2011)
 +
    print("The coldest city in 12/%d is %s at a temperature of %.1fC." % (coldestCity[1], coldestCity[3], coldestCity[0]))
 +
   
 +
    #answer to question 4
 +
    diff = findLargestSwing(tempList)
 +
    print("%s saw the largest temperature difference of %.1fC in %d/%d." % (diff[3], diff[0], diff[2], diff[1]))
 +
 +
main()
 +
 +
 
</source>
 
</source>
  

Revision as of 10:47, 12 April 2014

--D. Thiebaut (talk) 10:41, 12 April 2014 (EDT)


Program 1


# hw8a.py
# Arcadia Kratkiewicz (ap)
# Marianne Staknis (au)
# 3/30/2014
#
# a modified version of a simple eliza-like program
# based off of eliza1.py
# 
# 1) greet user
# 2) get user's statement about life
#    first exchange based on user's politeness
# 3) repeat until user leaves:
#   3.1)  do a reflexion first to second person
#         by replacing I by you, me by you,
#         mine by yours, my by your, etc...
#         and also 2nd to first person with correct grammar
#         respond to aggressive user
#   3.2)  figure out what to print
#         if a family word was used, ask user about family
#         if the sentence was reflected, then print it
#         if the sentence contained no or never, then
#         react to it
#         otherwise, just a random canned sentence
#
 
from random import choice

# canned answers that the program will use to get the
# user to keep the conversation going...
canned = [ "\nPlease tell me more",
           "\nI see...",
           "\nGo on...",
           "\nTell me more",
           "\nWhy do you say that?",
           "\nIn what way?",
           "\nI am listening..." ]

# canned answers that the program will use when the
# user is responding in the negative ("no", or "never")
cannedNegative = [ "\nMy, my, so negative!",
                   "\nNo?",
                   "\nIsn't that a bit strong?",
                   "\nReally?",
                   "\nYou really think so?",
                   "\nWhy not?" ]

# make a list of responses if there a family word in user input
cannedFamily = [ "\nIs that typical in your family?",
                 "\nIs that a family trait?",
                 "\nTell me more about your family.",
                 "\nWhat do you think about your family?",
                 "\nHow does your family make you feel?" ]

# --------------------------------------------------------------------------
# Greetings(): greets the user and explains how to stop program
# --------------------------------------------------------------------------
def Greetings():
     print( "Welcome.  Please tell me of your problems: " )
     print( '(You may quit at any time by answering "bye," "goodbye," or "ciao.")' )

# --------------------------------------------------------------------------
# isGoodBye(): tests if user is ready to leave
# --------------------------------------------------------------------------
def isGoodBye( reply ):
    if reply.lower().strip() in [ "bye", "goodbye", "ciao" ]:
        return True
    return False

# --------------------------------------------------------------------------
# doReflection( words, newWords ).  replaces I by you and you by I, including
# pronouns such as mine and yours.  The reflected words are stored in newWords
# we added code so that when the user enters a sentence beginning with "you",
# Eliza will reply beginning with "I" with correct grammar.
# --------------------------------------------------------------------------
def doReflection( words, newWords ):        
     for i in range( len( words ) ):           
         # replace 1st by 2nd person              
          if words[i] == "i"   : newWords[i] = "you"
          if words[i] == "i'm" : newWords[i] = "you're"
          if words[i] == "i've": newWords[i] = "you've"
          if words[i] == "am"  : newWords[i] = "are"
          if words[i] == "was" : newWords[i] = "were"
          if words[i] == "my"  : newWords[i] = "your"
          if words[i] == "mine": newWords[i] = "yours"
          if words[i] == "me"  : newWords[i] = "you"

         #if words[0] == "I" and words[2] == "you" :
              #newWords.insert( 0, "Why do" )

         # replace 2nd by 1st person
         # improved reflections by correcting grammar
          if words[i] == "you"   :
               if words[0] == "you":
                    newWords[0] = "I"
                    if words[1] == "are":
                         newWords[1] = "am"
               else:
                    newWords[i] = "me"
          if words[i] == "your"  : newWords[i] = "my"
          if words[i] == "yours" : newWords[i]= "mine"

     # if user is aggressive and says "I ___ you" reply with
     # "Why do you ____ me?"
     if words[0] == "i" and words[2] == "you" :
          newWords.insert( 0, "Why do" )
          # "remember" what user has said, adds "is that why you ___ me"
          # to the list of responses
          canned.append( "Is that why you %s me?" % words[1] )

    # if we changed something, return True, otherwise return False
     return words != newWords

# --------------------------------------------------------------------------
# isNegativeStatement( words )
# return True if one of the words is a negative word, such as no, not, never.
# --------------------------------------------------------------------------
def isNegativeStatement( words ):
    if len( words ) < 1:
        return False
    for word in words:
        if word.lower() in [ "no", "not", "never", "nein", "jamais" ]:
            return True
    return False

#----------------------------------------------------------------------------
# isFamilyWord( words )
# this funciton returns true if the user inputs a family word, wuch as mother,
# father.
#----------------------------------------------------------------------------
def isFamilyWord( words ):
     for word in words:
          if word.lower() in ["mother", "father", "sister", "brother",
                              "mom", "dad"]:
               return True
     return False

# ---------------------------------------------------------------------------
# firstExchange( words )
# this function returns True if user does not say "hello"
# ---------------------------------------------------------------------------
def firstExchange( words ):
     for word in words:
          if words[0].lower() != "hello":
               return True
     return False


# --------------------------------------------------------------------------
# main function
# --------------------------------------------------------------------------                   
def main():

     # 1) greet user
     Greetings()

     # 2) first exchange
     # get user's statement about life
     # if user does not input "Hello" or "hello" as first word, Eliza
     # will respond appropriately.
     user = input ("\n> ").lower().replace( "!", "").replace( "?", "" ).replace( ".", "" )
     words = user.split()     # get individual words
     newWords = words[:]      # create new list with the same words
     
     if firstExchange( words ):
          # user does not say "Hello"
          print( "Do you know it is rude not to greet people when you meet them?" )
          
     # 3) conversation: get user input, and respond
     while True:
         
          if isGoodBye( user ):
               break
            
         # ---------------------------------------------
         # 3.1) do a reflection
         # ---------------------------------------------

          isAReflection = doReflection( words, newWords )
         
         # ---------------------------------------------
         # 3.2) figure out what to print
         # ---------------------------------------------
          if isFamilyWord( words ):
               # includes a family word, uses family response
               print( choice( cannedFamily ) )
     
          elif isAReflection:
             # it's a reflection.  Add a question mark and print
               print( ' '.join( newWords ), '?', sep="" )

          else:
             # figure out if it's a regular canned answer or a negative canned answer
               if isNegativeStatement( words ):
                    print( choice( cannedNegative ) )
               else:
                    print( choice( canned ) )
         
          user = input( "\n> " ).lower().replace( "!", "" ).replace( "?", "" ).replace( ".", "" )
          words = user.split()     # get individual words
          newWords = words[:]      # create new list with the same words
          
main()


Program 2


# hw8b.py
# Youyou Tian (bm)
# (slightly edited by D. Thiebaut)
# 4/2/14
#
# This program expects data stored in the file; the data comes from this
# URL: http://www.metoffice.gov.uk/climate/uk/stationdata/
# where temperatures in the UK have been recorded over the past 200 years or so.
# The format for each line is the following:
# year
# month of the year (1 for January, 2 for February, etc.)
# max temperature that month (in Celcius)
# min temperature that month
# number of days of air-frost
# amount of rain (millimeter)
# number of sun hours that month
#
# The original data files can be found on this site. The following legend appears on all the data files:
# Estimated data is marked with a * after the value. Missing data (more than 2 days missing in month)
#  is marked by ---. Sunshine data taken from an automatic Kipp & Zonen sensor marked with a #, 
# otherwise sunshine data taken from a Campbell Stokes recorder.'
#
# Given the temperatures data, this program:
# finds the coldest temperature for the year recorded,
# the hottest temperature recorded,
# the coldest city in December 2011
# and the largest difference between temperatures 

from temp import temperatures

tempList = temperatures.split("\n") #Splits the temperature table into lists

#
# findColdestTemp(list temperatures)
# finds the coldest temperature, with the city, year and month
#
def findColdestTemp(temperatures):
    tempList = []
    for temp in temperatures:
        tempList.append(getColdestTempList(temp))
    return min(tempList)

#
# getColdestTemp(list temperatures)
# reorders the elements in temp list so that it is
# [tempMin, year, month, city]
#   
def getColdestTempList(temperatures):
    temp = temperatures.split()
    city = temp[0]
    year = int(temp[1])
    month = int(temp[2])
    tempMin = float(temp[4].rstrip("*-"))
    return[tempMin, year, month, city]

#
# findHottestTemp(list temperatures)
# finds the hottest temperature, with the city, year and month
#
def findHottestTemp(temperatures):
    tempList = []
    for temp in temperatures:
        tempList.append(getHottestTempList(temp))
    return max(tempList)

#
# getColdestTemp(list temperatures)
# reorders the elements in temp list so that it is
# [tempMax, year, month, city]
#  
def getHottestTempList(temperatures):
    temp = temperatures.split()
    city = temp[0]
    year = int(temp[1])
    month = int(temp[2])
    tempMax = float(temp[3].rstrip("*-"))
    return[tempMax, year, month, city]

#
# findColdestCity(list temperatures, int year)
# finds the coldest city in december given a year
#   
def findColdestCity(temperatures, year):
    tempList = []
    for temp in temperatures:
        returnedTemp = getColdestTempList(temp)
        if returnedTemp[1] == year and returnedTemp[2] == 12:
            tempList.append(returnedTemp)    
    return min(tempList)

#
# findLargestSwing(list temperatures)
# finds the largest difference of temperatures, with the year
# month and city
#  
def findLargestSwing(temperatures):
    tempList = []
    for temp in temperatures:
        tempList.append(getSwingTemp(temp))
    return max(tempList)


#
# getSwingTemp(list temperatures)
# reorders the elements in temp list so that it is
# [absoulte difference between minTemp and maxTemp, year, month, city]
#  
def getSwingTemp(temperatures):
    temp = temperatures.split()
    city = temp[0]
    year = int(temp[1])
    month = int(temp[2])
    tempMin = float(temp[4].rstrip("*-"))
    tempMax = float(temp[3].rstrip("*-"))
    return[abs(tempMin-tempMax), year, month, city]

#
# main()
# 
def main():
    #answer to question 1
    coldest = findColdestTemp(tempList)
    print("The coldest temperature recorded is %.1fC in %d/%d, in %s." % (coldest[0], coldest[2], coldest[1], coldest[3]))

    #answer to question 2
    hottest = findHottestTemp(tempList)
    print("The hottest temperature recorded is %.1fC in %d/%d, in %s." % (hottest[0], hottest[2],hottest[1], hottest[3]))

    #answer to question 3
    coldestCity = findColdestCity(tempList, 2011)
    print("The coldest city in 12/%d is %s at a temperature of %.1fC." % (coldestCity[1], coldestCity[3], coldestCity[0]))
    
    #answer to question 4
    diff = findLargestSwing(tempList)
    print("%s saw the largest temperature difference of %.1fC in %d/%d." % (diff[3], diff[0], diff[2], diff[1]))

main()