CSC111 Homework 3 Solution Programs 2011

From dftwiki3
Jump to: navigation, search

--D. Thiebaut 07:41, 13 October 2011 (EDT)


Interesting/surprising/strange random poems gathered from the class

Here is a sample of what the programs generated...

  • Kevin Devine usually listens to Manchester Orchestra at home every Sunday.
  • Man silently dreams 'neath the old pear tree at twilight
  • Our neighbor invariably does cartwheels at the store every day
  • Goat farmer slowly likes frolicking in the Sahara as often as possible
  • My math professor usually sings at home every Sunday.
  • Professor Thiebaut eats sweet oranges deliciously with bears on early mornings
  • Chuck Norris graciously bosses me around to infinity and beyond at night.
  • Jackie Chan savagely munches on cookies on TV during school
  • Flying Spaghetti Monster viscously lectures on the roof before class.

Peoms

# hw3a.py
# 111a-bg
# Sydney Ness
# This is a program that creates lists of subjects, adverbs, verbs, locations and times
# and uses random list elements to create a number (inputted by user) of random poems
#
# Example of user interaction:
# Welcome to Random Poems of the Day!
# How many poems would you like me to generate for you? 2
#
# Here are your 2 poems:
#
# Kevin Devine usually sings in Talbot House last at night.
# My math professor never loves pizza underwater all the time.


from random import randrange

def main():

   print( "Welcome to the Random Poems of the Day!" )

   # ask user how many poems to print
   numberPoems = eval(input( "How many poems would you like me to generate for you? "))
   print()

   # create lists of subjects, adverbs, verbs, locations, times
   subjects = [ "Kevin Devine", "The record player", "iTunes", "My math professor", "Amy Poehler" ]
   adverbs = [ "usually", "sweetly", "quietly", "never" ]
   verbs = [ "sings", "eats pizza", "loves pizza", "listens to Manchester Orchestra" ]
   locations = [ "at home", "in Talbot House", "underwater" ]
   times = [ "all the time", "late at night", "at sunrise and sunset", "every Sunday" ]

   # create a collection of the lists that loops will reference
   words = [ subjects, adverbs, verbs, locations, times ]

   print( "Here are your", numberPoems, "poems:")
   print()

   # outer loop ensures that desired number of poems is printed
   for j in range( numberPoems ):
      for i in words:
         # pick a random number from the length of the list
         randomIndex = randrange( len(i) )
         #print word in list that corresponds to that number, followed by a space
         print( i[ randomIndex ], end=" " )
      # deletes the last space that was printed and inserts a period
      # goes to new line for next poem
      print( "\b" + ".", end = "\n")

main()

Forms


# hw3b.py
# 111a-bz
# Yingtong Ding
# 111a-by
# Jenny Wang

# The program prompts the user
# for the width of the form, the name
# of the string to display in the box
# under the date box, the number of candidate
# names and the names of the candidates
# for which forms will be generated
# Then the user enters the names and the program
# outputs the forms, one per name.
#
# LIMITATIONS:
# ------------
# The limitations of this program: The width of the form cannot be smaller than
# the length of the names plus the length of the date box plus one.
# The length of the extra label box under the date box cannot be longer than the
# length of the date box.

def main():
    print('''
-------------------------------
 WELCOME TO THE FORM GENERATOR
         P R O G R A M
-------------------------------''')
    print()
    # get data from the user
    width = eval(input("What is the width of the form? "))
    
    # get name of the extra label under the date from the user
    label = input("What is the label of the box under the date? ")
    
    # get the number of candidates from the user
    num = eval(input("How many candidates do you have? "))
    
    # get names of the candidates from the user
    names = []
    for i in range(num):
        names.append (input("Candidate "+str(i+1)+" : "))
    print()


    print()
    # compute various quantities
    bar        = "+" + '-' * (width-2 ) + '+'
    blank      = '|' + ' ' * (width-2 ) + '|'
    commentBlank= '|' + ' Comments'+' ' * (width-2-len(' Comments') ) + '|'
    dateLine   = '| date:        |'
    dateLine2  = '+--------------+'
    labelLine  = '| '+label+' '*(len( dateLine )-3-len(label))+'|'
    noSpacesB4 = width - len( dateLine )-1
    dateLine2  = '|'+' '*noSpacesB4 + dateLine2
    # output the forms for each name
    for name in names:
        print( bar )
        totalNoSpaces  = width - 2 - len( name )
        noSpacesB4Date = totalNoSpaces +1 - len( dateLine )    
 
        print( '|' + name + ' '* noSpacesB4Date + dateLine )
        print( dateLine2 )
        print( '|' + ' '* (noSpacesB4Date + len(name)) + labelLine)
        print( dateLine2 )
        print( blank )
        print( bar )
        print( commentBlank )
        # print the blank box
        for i in range( 3 ):
            print( blank )
        print( bar )
        print()
 
    print()

main()



Centered Poems


# hw3c.py
# 111a-ah
# Kate Aloisio
# Edited by D. Thiebaut
#
# This program creates a number (specified by user) of random poems. Then it
# finds the longest poem and centers the other poems relative to the longest.
#
# Limitation: Needs at least one poem otherwise the sum() function crashes

from random import randrange

def main():

    # create lists of subjects, adverbs, verbs, locations, times
    subjects = ["The bank ", "Newton ", "The cloud ", "Agent green ", "The brain "]
    adverbs = ["practically ", "simply ", "foolishly ", "unnecessarily ", "suitably "]
    verbs = ["correlates ", "responds ", "analyzes ", "computes ", "conspires "]
    locations = ["at a candlelit table ", "under the ivy vine ", "in the kitchen "]
    times = ["everyday ", "at twilight ", "at dawn "]
    
    # greeting
    print("Welcome to the Random Poems of the Day!")
    noPoems = eval(input("How many poems would you like me to generate for you? "))

    # length of each list
    subjectCount = len(subjects) 
    adverbCount = len(adverbs)
    verbCount = len(verbs)
    locationCount = len(locations)
    timeCount = len(times)

    print("\nHere are your",noPoems,"poems: \n" )
    
    # loop for number of poems requested
    poems=[]
    poemsLen=[]
    for i in range(noPoems):

        # pick a random number for each list
        randomIndexS = randrange(subjectCount)
        randomIndexA = randrange(adverbCount)
        randomIndexV = randrange(verbCount)
        randomIndexL = randrange(locationCount)
        randomIndexT = randrange(timeCount)

        # create poem and calculate length of poem
        poem =  Subjects[randomIndexS] + adverbs[randomIndexA] + verbs[randomIndexV] \
                   + locations[randomIndexL] + times[randomIndexT]
        poemLength = len(poem)
        
        # add poem to list of poems
        poems.append(poem)
        # add length of poem to list of lengths
        poemsLen.append(poemLength)
        
    # finding the poem with the maximum length
    mPoem=max(poemsLen)
    
    # print poems with indents
    for poem in poems:
        pLen = len(poem)
        print(" "*((mPoem-pLen)//2)+poem)

    print()


main()



Money


A very short and concise solution for this problem is provided by Kate.

# hw3d.py
# 111a-ah
# Kate Aloisio
#
# This program asks the user how much money she wants
# to withdraw from the cash machine, and will output
# how many 20, 10, 5, and 1 dollar bills she will get in return.
#

def main():
    
    # greeting
    print("\nWelcome to the Virtual Cash Machine\n")

    # how much money?
    amount = eval( input( "How much money do you need today? " ) )

    # break down of bills
    print( "\nPlease lift your keyboard and find: ", end=" ")
    bills = [ 20, 10, 5, 1 ]
    for bill in bills:
        count = amount//bill
        amount = amount%bill
        line = "%2d $%d-bill(s)" % (count, bill)
        print( line + "\n" + " "*36, end=" " )
    
    # closing
    print( "\nThank you for your transaction!" )

main()



Extra Credit


# 111a-bz -  Yingtong Ding
# 111a-by -  Jenny Wang
# Edited by D. Thiebaut
#
# This program the user for the number of different
# bill denominations she wants, the denomination,
# and the amount to withdraw, and will output
# how many bills she will get in return in a box.
#
# Limitations: the denominations must be entered in 
# decreasing order of value, i.e. 20s before 10s, etc.
# Also, the box will not be formatted correctly if the
# user gets more than 99 bills in any of the denominations.
#

def main():

    # Get user input 
    width = len('Welcome to the SMITH Virtual Cash Machine        ')
    print ('+'+'-'*(width-2)+'+')
    print('|   Welcome to the SMITH Virtual Cash Machine   |')
    print ('+'+'-'*(width-2)+'+')
    print()

    # get different denominations wanted
    num = eval(input('The number of different bill denominations? '))
    dems = []
    for i in range(num):
        dems.append ( eval( input( 'Denomination '+str(i+1)+'? ' ) ) )         

    # get amount to withdraw 
    money = eval(input('How much money do you need today? '))

    # print out resulting break down in bills
    print()
    print ('+'+'-'*(width-2)+'+')
    print ('|Please lift your keyboard and find:            |')
    for dem in dems:
        no = money//dem
        money = money - dem*no
        print('|                                 ', no, '$' + "%2d" % dem + '-bill(s)|' )

    # close the box
    print ("|                                               |")        
    print ("|Don't buy too much chocolate with that!        |")
    print ("|                                               |")
    print ('+'+'-'*(width-2-len('Good Bye!')-5)+'Good Bye!'+'-'*5+'+')

main()