Difference between revisions of "CSC111 Lab 13 2015"

From dftwiki3
Jump to: navigation, search
Line 37: Line 37:
 
Write a program that will:
 
Write a program that will:
 
# Ask the user for the year she was born in, e.g. 1995,
 
# Ask the user for the year she was born in, e.g. 1995,
# Read the contents of the file at the URL specified above
+
# Read the contents of the file at the URL specified above (you may want to take a look back at the [[CSC111_Lab_5_2015|Lab 5 companion program]] that reads a page of text stored at a URL).
 
# Find all the movies that were released in the year specified by the user
 
# Find all the movies that were released in the year specified by the user
 
# Output the movies sorted by alphabetical order.  The year (or parentheses around the year) should '''not''' appear in the lines listing the movie titles.  
 
# Output the movies sorted by alphabetical order.  The year (or parentheses around the year) should '''not''' appear in the lines listing the movie titles.  

Revision as of 08:32, 28 April 2015

--D. Thiebaut (talk) 09:59, 27 April 2015 (EDT)




<showafterdate after="20150429 13:00" before="20150601 00:00">

This lab is a preparation for the Final Exam. You will notice that the amount of explanations is limited, and you are asked to start from scratch writing a program. The lab will start with a general discussion about approaching the problems, and getting started with such assignments.
Feel free to work in pair programming mode on this assignment.


Problem 1


Write a graphics program that uses a white background, and makes a fish appear wherever the user clicks the mouse. Once the fish appears on the screen it moves slowly to one side and disappears. While the fish is moving, the user may click on the screen, and make other fish appear. The new fish will then move at the same pace as the first fish, assuming it is still visible.
Your program should stop when the user clicks in the top-left area of the screen. Imagine a 30x30 square at the top left of the screen; if the user clicks the mouse in this square, then the program exits and closes the window.
Helpful links:

  1. page with fish images
  2. Documentation for the graphics library
  3. Zelle's graphic library


Submission


Locate the LAB13 PB 1 links on your Moodle page, and submit a running version of your program, called lab13_1.py, as well as a screen capture of the graphics window showing several fish.

Problem 2


Part 1


The file at URL http://cs.smith.edu/dftwiki/media/1000movies0.txt contains the list of the best 1000 movies of all times, according to The New York Times (the file actually contains 1004 movies). Note, also, that some foreign characters have been removed from the movie titles to prevent Python from crashing on non standard characters (it could crash in some implementations, and work fine in others).

Write a program that will:

  1. Ask the user for the year she was born in, e.g. 1995,
  2. Read the contents of the file at the URL specified above (you may want to take a look back at the Lab 5 companion program that reads a page of text stored at a URL).
  3. Find all the movies that were released in the year specified by the user
  4. Output the movies sorted by alphabetical order. The year (or parentheses around the year) should not appear in the lines listing the movie titles.
  5. Save the list to a file called movies1995.txt (replace 1995 by whatever number the user specified as year).


Typical Output File


  • Below is the contents of movies1995.txt:


Apollo 13
Before the Rain
Clueless
Dead Man Walking
Lamerica
Leaving Las Vegas
Living in Oblivion
Persuasion
Sense and Sensibility
Toy Story
The Usual Suspects


Part 2


When your program works for Part 1, change the URL to this: http://cs.smith.edu/dftwiki/media/1000movies.txt. The new URL contains extra lines that do not contain valid movie names. For example a line containing only the letter B, indicating that all following movie titles start with B. Make your program work with the new URL, assuming the same interaction with the user.

Important Requirement


  • Your program must include a main() function that is the main entry point of your program. The test program will call your main() function to run your program, and if there isn't a main() function, your program will not be tested correctly.


Submission


Submit your solution to the second problem to Moodle, in the Lab13 section.
</showafterdate>


<showafterdate after="20150501 11:00" before="20150601 00:00">

Solution Programs


Program 1


# lab13_1.py
# D. Thiebaut
# Graphics program that puts fish wherever the user
# clicks on the window.   The fish wrap around when they go
# off the window, although this was not a required feature in
# the lab.
# The program stops when the user clicks close to the top-left
# corner of the window (within 20 pixels of the point 0,0).
from graphics import *
import random

WIDTH = 800
HEIGHT = 600

class Fish:
    """A class that represents a fish, with an image."""
    
    def __init__( self, refP ):
        """constructs the fish with an image"""
        self.image = Image( refP, "fish10.gif" )
    
    def draw( self, win ):
        """draws the fish on the window..."""
        self.image.draw( win )

    def autoMove( self ):
        """make the fish move to the right, some random distance"""
        self.image.move( random.randrange( 4 ), 0 )
        if self.image.getAnchor().getX() > WIDTH+50:
            self.image.move( -WIDTH-100, 0 )

def isInCorner( p ):
    """Returns True if the point p is within 20 pixels of the top left
    corner of the window, and False otherwise."""
    if p.getX() < 20 and p.getY() < 20:
        return True
    return False
        
def main():
    win = GraphWin( "Lab 13", WIDTH, HEIGHT )

    # get ready to add fish...
    fishList = []
    
    #animation loop
    while True:
        p = win.checkMouse()

        # user clicked the mouse...
        if p != None:

            # is it in the upper-left corner?
            if isInCorner( p ):
                break

            fish = Fish( p )
            fish.draw( win )
            fishList.append( fish )

        # move all the fish, a tiny bit...
        for fish in fishList:
            fish.autoMove()

    win.close()

main()


Program 2


# lab13_2.py
# D. Thiebaut
# This program reads a text file stored at a given URL and 
# extracts information that matches the user's specified string.
#
import urllib.request  # the lib that handles the url stuff

url = "http://cs.smith.edu/dftwiki/media/1000movies.txt"


def getText( url ):
    """gets the contents of the text file at the given URL"""
    # fetch the file and put its contents in the
    # string text.
    response = urllib.request.urlopen( url )
    text     = response.read().decode( 'UTF-8' )
    return text

def saveToFile( fileName, text ):
    """save the text into the given file """
    file = open( fileName, "w" )
    file.write( text + "\n" )
    file.close()
    
def main():
    """retrieve the file at the given URL, gets a year
    from the user, and outputs all the lines containing that
    given year.  The output is also saved to a file."""
    text = getText( url )

    year = input( "Year you were born? " ).strip()

    list = []
    for line in text.split( "\n" ):
        if line.find( year ) != -1:
            index = line.find( "(" + year )
            line = line[0:index].strip()
            print( line )
            list.append( line )

    saveToFile( "movies"+year+".txt", "\n".join( list ) )


main()



...