Exercises

In Chapter 1, the exercises were short enough to be typed into IDLE. From now on we recommend that you type your solutions into a file with a .py extension, and add some test calls at the end. For example, you might write a file with this structure:

#!/usr/bin/env python def mysolution(arg0, argl):

pass # Whatever code is needed mysolution(1, 2) # Call with one set of parameters mysolution("a", "b") # Call with another set of parameters # Additional calls to make sure all boundary cases are tested

If you are using Windows, make sure that you run your test programs inside a console window; similarly, Mac OS X users should use a Terminal. You may also need to include print statements so that you can see the results. (Exercises involving GUI applications begin in Part II.)

If you look at the book's source code, including this chapter's answers.py file, you will find that the code often has long docstrings, in many cases occupying far more lines than the code itself. This is because the docstrings usually include usage examples which do double duty as unit tests, as we will see in Chapter 3's "Using the doctest Module" subsection.

1. Write a function with signature:

valid(text, chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

The function should return a (possibly empty) string which is a copy of text that only contains characters in chars. For example:

valid("Barking!") # Returns "B"

valid("KL754", "0123456789") # Returns "754"

valid("BEAN", "abcdefghijklmnopqrstuvwxyz") # Returns ""

It can be done in half a dozen lines, using a for loop and an if statement, not counting the docstring, which should also be written.

2. Write a function with signature:

charcount(text)

This should return a dictionary with 28 keys, "a", "b", ..., "z", plus "whitespace" and "others". For every lowercase character in text, if the character is alphabetic, increment the corresponding key; if the character is whitespace, increment the "whitespace" key; otherwise, increment the "others" key. For example, the call:

stats = charcount("Exceedingly Edible")

will mean that stats is a dictionary with the following contents:

{'whitespace': 1, 'others': 0, 'a': 0, 'c': 1, 'b': 1, 'e': 5,

d'

2,

'g'

1, 'f'

0, 'i'

2,

'h'

0, 'k': 0, 'j':

), 'm

I'

2,

'o'

0, 'n'

1, 'q'

0,

'p'

0, 's': 0, 'r':

), 'u

t'

0,

'w'

0, 'v'

0, 'y'

1,

'x'

1, 'z': 0}

Using a dictionary and a for loop, it can be done in slightly more than a dozen lines of code.

3. Create a function with signature: integer(number)

The number parameter is either a number or a string that can be converted to a number. The function should return the number as type int, rounding it if the number passed in is a float. If the conversion fails, catch the ValueError exception, and return 0. Make sure it works for both strings and literal numbers, such as 4.5,32, "23", and "-15.1", and that it correctly returns zero for invalid numbers like "tonsils". This can be done in half a dozen lines. (Hint: To work with all the cases you'll always need to convert to type float first, that is, by calling float() on the input.)

4. Now write a function with signature:

incrementString(text="AAAA")

The function must "increment" the given string. Here are some examples:

incrementString(

'A")

#

Returns

'B"

incrementString(

■Z")

#

Returns

■AA"

incrementString(

'AM")

#

Returns

'AN"

incrementString(

'AZ")

#

Returns

'BA"

incrementString(

■BA")

#

Returns

■BB"

incrementString(

■BZ")

#

Returns

"CA"

incrementString(

'ZZA")

#

Returns

'ZZB"

incrementString(

■ZZZ")

#

Returns

'AAAA"

incrementString(

'AAAA")

#

Returns

'AAAB"

incrementString(

'AAAZ")

#

Returns

"AABA"

incrementString(

'ABC2")

#

Raises a

ValueError

The characters in text must be A-Z (or a-z, in which case the function must upper-case them); otherwise the function should raise a ValueError exception.

This is a bit more challenging than the previous exercises. The code can be written in less than 20 lines if you use a couple of list comprehensions, although it can also be written without them. It is a bit tricky to get right. (Hint: The reversed() function returns a sequence in reverse order.)

5. If you read the section on function generators, try writing a generator with signature:

leapyears(yearlist)

The yearlist parameter is a sequence of year numbers—for example, [1600, 1604, 1700, 1704, 1800, 1900, 1996, 2000, 2004]. Given this input, the output would be the years 1600,1604,1704,1996,2000, and 2004, one at a time. This can be done in about half a dozen lines. (Hint: Leap years are divisible by 4, but if they are divisible by 100, must also be divisible by 400.)

Model answers for this chapter's exercises are in the file chap02/answers.py.

Creating Instances Methods and Special Methods Inheritance and Polymorphism Modules and Multifile Applications

Was this article helpful?

+1 0
Tuberminator

Tuberminator

The main focus of this report is to show how to get involved in video marketing on the run, how to rank quickly on YouTube and Google using FREE semi-automatic tools and services. QUICKLY AND FREE. I will show methods and techniques I use to rank my videos, as well as free resources and tools to make video clips, to get backlinks and free traffic.

Get My Free Ebook


Post a comment