Section 6.22. Exercises


6.22. Exercises

6-1.

Strings. Are there any string methods or functions in the string module that will help me determine if a string is part of a larger string?

6-2.

String Identifiers. Modify the idcheck.py script in Example 6-1 such that it will determine the validity of identifiers of length 1 as well as be able to detect if an identifier is a keyword. For the latter part of the exercise, you may use the keyword module (specifically the keyword.kwlist list) to aid in your cause.

6-3.

Sorting.

  1. Enter a list of numbers and sort the values in largest-to-smallest order.

  2. Do the same thing, but for strings and in reverse alphabetical (largest-to-smallest lexicographic) order.

6-4.

Arithmetic. Update your solution to the test score exercise in the previous chapter such that the test scores are entered into a list. Your code should also be able to come up with an average score. See Exercises 2-9 and 5-3.

6-5.

Strings.

  1. Update your solution to Exercise 2-7 so that you display a string one character at a time forward and backward.

  2. Determine if two strings match (without using comparison operators or the cmp() built-in function) by scanning each string. Extra credit: Add case-insensitivity to your solution.

  3. Determine if a string is palindromic (the same backward as it is forward). Extra credit: Add code to suppress symbols and whitespace if you want to process anything other than strict palindromes.

  4. Take a string and append a backward copy of that string, making a palindrome.

6-6.

Strings. Create the equivalent to string.strip(): Take a string and remove all leading and trailing whitespace. (Use of string.*strip() defeats the purpose of this exercise.)

6-7.

Debugging. Take a look at the code we present in Example 6.4 (buggy.py).

  1. Study the code and describe what this program does. Add a comment to every place you see a comment sign ( # ). Run the program.

  2. This problem has a big bug in it. It fails on inputs of 6, 12, 20, 30, etc., not to mention any even number in general. What is wrong with this program?

  3. Fix the bug in (b).

6-8.

Lists. Given an integer value, return a string with the equivalent English text of each digit. For example, an input of 89 results in "eight-nine" being returned. Extra credit: Return English text with proper usage, i.e., "eighty-nine." For this part of the exercise, restrict values to be between 0 and 1,000.

6-9.

Conversion. Create a sister function to your solution for Exercise 5.13 to take the total number of minutes and return the same time interval in hours and minutes, maximizing on the total number of hours.

6-10.

Strings. Create a function that will return another string similar to the input string, but with its case inverted. For example, input of "Mr. Ed" will result in "mR. eD" as the output string.

Example 6.4. Buggy Program (buggy.py)

This is the program listing for Exercise 6-7. You will determine what this program does, add comments where you see "#"s, determine what is wrong with it, and provide a fix for it.

1  #!/usr/bin/env python 2 3  # 4  num_str = raw_input('Enter a number: ') 5 6  # 7  num_num = int(num_str) 8 9  # 10 fac_list = range(1, num_num+1) 11 print "BEFORE:", 'fac_list' 12 13 # 14 i = 0 15 16 # 17 while i < len(fac_list): 18 19     # 20     if num_num % fac_list[i] == 0: 21         del fac_list[i] 22     # 23     i = i + 1 25 26 # 27 print "AFTER:", 'fac_list'

6-11.

Conversion.

  1. Create a program that will convert from an integer to an Internet Protocol (IP) address in the four-octet format of WWW.XXX.YYY.ZZZ.

  2. Update your program to be able to do the vice versa of the above.

6-12.

Strings.

  1. Create a function called findchr(), with the following declaration:

    def findchr(string, char)

    findchr() will look for character char in string and return the index of the first occurrence of char, or -1 if that char is not part of string. You cannot use string.*find() or string.*index() functions or methods.

  2. Create another function called rfindchr() that will find the last occurrence of a character in a string. Naturally this works similarly to findchr(), but it starts its search from the end of the input string.

  3. Create a third function called subchr() with the following declaration:

    def subchr(string, origchar, newchar)

    subchr() is similar to findchr() except that whenever origchar is found, it is replaced by newchar. The modified string is the return value.

6-13.

Strings. The string module contains three functions, atoi(), atol(), and atof(), that convert strings to integers, long integers, and floating point numbers, respectively. As of Python 1.5, the Python built-in functions int(), long(), and float() can also perform the same tasks, in addition to complex(), which can turn a string into a complex number. (Prior to 1.5, however, those built-in functions converted only between numeric types.)

An atoc() was never implemented in the string module, so that is your task here. atoc() takes a single string as input, a string representation of a complex number, e.g., '-1.23e+4-5.67j', and returns the equivalent complex number object with the given value. You cannot use eval(), but complex() is available. However, you can only use complex() with the following restricted syntax: complex(real, imag) where real and imag are floating point values.

6-14.

*Random Numbers. Design a "rock, paper, scissors" game, sometimes called "Rochambeau," a game you may have played as a kid. Here are the rules. At the same time, using specified hand motions, both you and your opponent have to pick from one of the following: rock, paper, or scissors. The winner is determined by these rules, which form somewhat of a fun paradox:

  1. the paper covers the rock,

  2. the rock breaks the scissors,

  3. the scissors cut the paper. In your computerized version, the user enters his/her guess, the computer randomly chooses, and your program should indicate a winner or draw/tie. Note: The most algorithmic solutions use the fewest number of if statements.

6-15.

Conversion.

  1. Given a pair of dates in some recognizable standard format such as MM/DD/YY or DD/MM/YY, determine the total number of days that fall between both dates.

  2. Given a person's birth date, determine the total number of days that person has been alive, including all leap days.

  3. Armed with the same information from (b) above, determine the number of days remaining until that person's next birthday.

6-16.

Matrices. Process the addition and multiplication of a pair of M by N matrices.

6-17.

Methods. Implement a function called myPop(), which is similar to the list pop() method. Take a list as input, remove the last object from the list and return it.

6-18.

In the zip() example of Section 6.12.2, what does zip(fn, ln) return?

6-19.

Multi-Column Output. Given any number of items in a sequence or other container, display them in equally-distributed number of columns. Let the caller provide the data and the output format. For example, if you pass in a list of 100 items destined for three columns, display the data in the requested format. In this case, two columns would have 33 items while the last would have 34. You can also let the user choose horizontal or vertical sorting.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net