Author: | Dave Kuhlman |
---|---|
Address: | dkuhlman (at) davekuhlman (dot) org http://www.davekuhlman.org |
Revision: | 1.3b |
Date: | October 05, 2014 |
Copyright: | Copyright (c) 2007 Dave Kuhlman. All Rights Reserved. This software is subject to the provisions of the MIT License http://www.opensource.org/licenses/mit-license.php. |
---|---|
Abstract: | This document provides exercises for an introductory course on programming in Python. |
Contents
Create (define) the following strings:
Use the string formatting operator to insert your name and the number of characters in your name into a string.
Build up a list of strings, then convert them to a single string with (1) two colons between the original strings, (2) a new-line between each string, (3) nothing between each string.
Create a list of integers. Now "join" them together to form a string of comma-separated values. (Hint: look at the map built-in function or consider using a list comprehension.)
Create a sample string, then try each of the following string methods:
Implement a function that takes a string as an argument. Split the string into "words". Return (1) a count of the number of words and (2) the list of words.
Given the following data:
Alice Appleby:501-511-5111:1.5:bird watching Bill Barnaby:501-511-5111:4009.2:gardening
Print a report that has column headers ("Name", "Phone", "Activity", and "Interest/hobby") and prints the data in aligned columns.
Open an existing file for input. Read in the entire contents of the file as a single string. Close the file. Print the contents.
Now, split the contents into lines. Then print each line.
Open an existing file for input. Read each line and print out each line in the file with a line number.
Now, add to this solution, code that splits each line on blanks and counts the "words" in the file. Or, for a CSV (comma separated value) file, split on comma.
Open a file (that does not exist) for output. Write 3 lines of text to your file. Close the file. Now, check the contents of your new file to see if it is as you expect.
Question: How can you check to ensure that the file you are about to write to does not already exist? Hint: Look in module os.path.
Open an existing file and append two lines of text to it.
Question: How do you obtain a list of files in a directory? Hint: Look at module glob.
Question: How do you obtain a list of files in a directory and its sub-directories? Hint: Look at the walk function in module os.path.
Create a file name in a platform independent way. Hint: Look at os.sep.
Write a script that reads standard input (sys.stdin) and writes to standard output (sys.stdout). Add the string "## " to the beginning of each line.
Perform the following import operations:
Write a function that takes no arguments and returns an integer.
Write a function that takes two strings as arguments and returns the concatenated value of those strings.
Write a function that has one regular argument and one argument with a default value. Print out both values. Now, call your function both with and without the optional, second argument.
Write a function that takes a string and a list as arguments. Search the list for the string. Return true if the string is in the list, else return false.
Call one of your functions using keyword arguments.
Write a function that takes two arguments: (1) a function that takes one argument and (2) a list. This (outer) function should apply the function argument to each item in the list argument. Next, define another function that takes one argument. Call the first function, passing it the second function.
Implement the a generator function -- The generator produced should yield all values from a list/iterable that satisfy a predicate. It should apply the transforms before return each value. The function takes these arguments:
values -- A list of values
predicate -- A function that takes a single argument, performs a test on that value, and returns True or False.
transforms -- (optional) A list of functions. Apply each function in this list and returns the resulting value. So, for example, if the function is called like this:
result = transforms([11, 22], p, [f, g])
then the resulting generator might return:
g(f(11))
Implement a very simple class containing no members.
Create an instance of your class; set and get a attribute x.
Implement a simple class containing getters and setters for data members name (a string) and size (an integer).
Create an instance of your class; set the name and size member variables; then get these values from your instance and print them.
Add a show method, which prints out the name and size.
Implement a simple class containing getters and setters for data members name (a string) and size (an integer). Add a constructor that initializes the name and size data members.
Implement a subclass of the above class. Add a description data member. Add getter and setter for description. Add a constructor that (1) calls the super-class ctor and (2) sets the description member variable.
Add show method to your sub-class, overriding the show method in the super-class. Also, call the super-class method from the sub-class.
Implement a class that represents a node in a binary tree. Each node should have a name and a left_child (a node) and right_child. Also implement a (recusive) method that displays the node and the two children under it.
Implement a tree data structure in one of the following ways:
Implement the Vehicle class hierarchy described by your instructor. Here is an outline of that hierarchy:
Suggestion: Try to think of your classes (and instances of them) as modeling objects (vehicles) out in the real world. Imagine that you are implementing the data model for a vehicle tracking system.
Implement a command line interface. Use (subclass) the cmd module in the Python standard library. Example:
import cmd class MySimpleCmd(cmd.Cmd):
Write a module that contains two (or more functions). Add one more function that calls these two functions. (1) Run your script from the command line. (2) Import your script from within the interactive interpreter, then call your functions.
Move your module to a sub-directory under your current directory. Now import your module and call a function in it. (Hint: You will need an __init__.py file.
Add a print statement to your __init__.py file, to show that it is really being evaluated.
Move your module to a separate directory that is not under your current directory. Now import your module and call a function in it. (Hint: You will need to add the path to your directory to your PYTHONPATH environment variable.)
Congratulations. You have implemented a Python/Python (mini-)package.
The remaining sections of this document describe additional Python exercises. These additional exercises focus on text processing, XML processing, processing several special file formats, object-oriented programming, and handling files and directories.
Find a .zip or .jar file or an ODF/.odt (OpenOfficeWriter). (1) Read the contents and print a list of the contents. (2) Create a Zip archive, add several files to it, and write it to disk.
Hint: The Python standard library contains a zipfile module.
The Zip file exercise above can also be performed using tarfile for archiving and one of gzip, bz2, or zlib for compression.
(Note: The csv module is in the Python standard library, but not (as of Jython 2.2.1) in the Jython standard library.)
Read a CSV (comma separated values) file. (1) Print out a report of the contents of file with columns that are 10 characters wide. (2) Create a CSV file, add several lines to it, and save it to disk.
Hints: The Python standard library contains a csv module. Consider using my_str_variable.ljust(n) (or .rjust()) to align columns.
Read a .ini file. Print out a report of the contents of this file. Hint: The Python standard library contains the ConfigParser module.
Example data:
[general] title: The Python Programming Language version: 2.5.1 [details] location: http://python.org/download/ formats: gzipped-tar bzipped-tar ms-windows-installer
Now, write a function that extracts a value, given the section name and option name entered on the command line.
Write the following scripts:
(Note: Jython support for ElementTree is not there yet. Consider using dom4j instead: http://www.dom4j.org/ )
Use xml.etree.ElementTree to read and parse an XML file. (1) Print out all the tags in the file. (2) Now, try to indent your print-out to show level of nesting. (3) Add display of the attributes.
Sample data:
<?xml version="1.0" encoding="UTF-8"?> <vegetables version="1.0"> <tomato id="001"> <name>Tomato</name> <colors> <color>pink</color> <color>red</color> <color>purple</color> </colors> </tomato> <eggplant id="002"> <name>Eggplant</name> <colors> <color>purple</color> </colors> </eggplant> </vegetables>
Now, write code that does each of the following tasks:
Extract the "id" attribute of the eggplant element.
Extract the text (character data) in the eggplant/name element.
Add a "<recipe>" element in the eggplant with attribute "category" and value "main course" and with character data "ratatouille", that is:
<recipe category="main course">ratatouille</recipe>
Add a node to the XML tree, for example, add an additional vegetable.. (1) From the XML tree producea string. (2) Then write the string representation out to disk.
Expand the Vehicle/Truck example. Add a Automobile class. Give one of your subclasses a method that overrides and calls a method in its superclass.
Implement a tree data structure in which each node has a value and any number of child nodes. Your Node class should implement the following methods:
Write a function that walks the tree and "shows" each node.
Delegation -- (1) Define an interface using a class containing empty methods. (2) Define two classes that implement this interface. (3) Implement a class whose constructor takes an object that satisfies the interface and delegates operations to it.
Modify your solution to the word count exercise so that it can take a command line argument that is either a path on the file system or a URL, for example:
file:///path/to/file.txt
or:
http://en.wikipedia.org/wiki/Python_(programming_language)
Modify the solution to the previous exercise so that it responds to the following command line options:
Implement a class hierarchy different from but similar to the Vehicle/Truck class hierarchy. For example: