Section 7.12. Exercises


7.12. Exercises

7-1.

Dictionary Methods. What dictionary method would we use to combine two dictionaries together?

7-2.

Dictionary Keys. We know that dictionary values can be arbitrary Python objects, but what about the keys? Try using different types of objects as the key other than numbers or strings. What worked for you and what didn't? As for the failures, why do you think they didn't succeed?

7-3.

Dictionary and List Methods.

  1. Create a dictionary and display its keys alphabetically.

  2. Now display both the keys and values sorted in alphabetical order by the key.

  3. Same as part (b), but sorted in alphabetical order by the value. (Note: This has no practical purpose in dictionaries or hash tables in general because most access and ordering [if any] is based on the keys. This is merely an exercise.)

7-4.

Creating Dictionaries. Given a pair of identically sized lists, say, [1, 2, 3,...], and ['abc', 'def', 'ghi',...], process all that list data into a single dictionary that looks like: { 1:'abc', 2:'def', 3:'ghi',...}.

7-5.

userpw2.py. The following problems deal with the program in Example 7.1, a manager of a database of name-password key-value pairs.

  1. Update the script so that a timestamp (see the time module) is also kept with the password indicating date and time of last login. This interface should prompt for login and password and indicate a successful or failed login as before, but if successful, it should update the last login timestamp. If the login occurs within four hours of the last login, tell the user, "You already logged in at: <last_ login_timestamp>."

  2. Add an "administration" menu to include the following two menu options: (1) remove a user and (2) display a list of all users in the system and their passwords

  3. The passwords are currently not encrypted. Add password-encryption if so desired (see the crypt, rotor, or other cryptographic modules).

  4. *Add a GUI interface, i.e., Tkinter, on top of this application.

  5. Allow usernames to be case-insensitive.

  6. Restrict usernames by not allowing symbols or whitespace.

  7. Merge the "new user" and "old user" options together. If a new user tries to log in with a nonexistent username, prompt if they are new and if so, do the proper setup. Otherwise, they are an existing user so log in as normal.

7-6.

Lists and Dictionaries. Create a crude stock portfolio database system. There should be at least four data columns: stock ticker symbol, number of shares, purchase price, and current priceyou can add more if you wish, such as percentage gain(loss), 52-week high/low, beta, etc.

Have the user input values for each column to create a single row. Each row should be created as list. Another all-encompassing list will hold all these rows. Once the data is entered, prompt the user for one column to use as the sort metric. Extract the data values of that column into a dictionary as keys, with their corresponding values being the row that contains that key. Be mindful that the sort metric must have non-coincidental keys or else you will lose a row because dictionaries are not allowed to have more than one value with the same key. You may also choose to have additional calculated output, such as percentage gain/loss, current portfolio values, etc.

7-7.

Inverting Dictionaries. Take a dictionary as input and return one as output, but the values are now the keys and vice versa.

7-8.

Human Resources. Create a simple name and employee number dictionary application. Have the user enter a list of names and employee numbers. Your interface should allow a sorted output (sorted by name) that displays employee names followed by their employee numbers. Extra credit: Come up with an additional feature that allows for output to be sorted by employee numbers.

7-9.

Translations.

  1. Create a character translator (that works similar to the Unix tr command). This function, which we will call TR(), takes three strings as arguments: source, destination, and base strings, and has the following declaration:

    def tr(srcstr, dststr, string)

    srcstr contains the set of characters you want "translated," dststr contains the set of characters to translate to, and string is the string to perform the translation on. For example, if srcstr == 'abc', dststr == 'mno', and string == 'abcdef', then tr() would output'mnodef'. Note that len(srcstr) == len(dststr). For this exercise, you can use the chr() and ord() BIFs, but they are not necessary to arrive at a solution.

  2. Add a new flag argument to this function to perform case-insensitive translations.

  3. Update your solution so that it can process character deletions. Any extra characters in srcstr that are beyond those that could be mapped to characters in dststr should be filtered. In other words, these characters are mapped to no characters in dststr, and are thus filtered from the modified string that is returned. For example, if srcstr =='abcdef', dststr == 'mno', and string == 'abcdefghi', then tr() would output 'mnoghi'. Note now that len(srcstr) >= len(dststr).

7-10.

Encryption. Using your solution to the previous problem, and create a "rot13" translator. "rot13" is an old and fairly simplistic encryption routine whereby each letter of the alphabet is rotated 13 characters. Letters in the first half of the alphabet will be rotated to the equivalent letter in the second half and vice versa, retaining case. For example, a goes to n and X goes to K. Obviously, numbers and symbols are immune from translation.

(b) Add an application on top of your solution to prompt the user for strings to encrypt (and decrypt on reapplication of the algorithm), as in the following examples:

    % rot13.py     Enter string to rot13: This is a short sentence.     Your string to en/decrypt was: [This is a short     sentence.].     The rot13 string is: [Guvf vf n fubeg fragrapr.].     %     % rot13.py     Enter string to rot13: Guvf vf n fubeg fragrapr.     Your string to en/decrypt was: [Guvf vf n fubeg     fragrapr.].     The rot13 string is: [This is a short sentence.].


7-11.

Definitions. What constitutes valid dictionary keys? Give examples of valid and invalid dictionary keys.

7-12.

Definitions. (a) What is a set in the mathematical sense? (b) What is a set type as it relates to Python?

7-13.

Random Numbers. The next problems use a customization of Exercise 5-17: use randint() or randrange() in the random module to generate a set of numbers: generate between 1 to 10 random numbers numbered randomly between 0 and 9 (inclusive). These values constitute a set A (A can be mutable or otherwise). Create another random set B in a similar manner. Display A | B and A & B each time sets A and B are generated.

7-14.

User Validation. Alter the previous problem where instead of displaying A | B and A & B, ask the user to input solutions to A | B and A & B, and let the user know if his or her solution was right or wrong. If it is not correct, give the user the ability to correct and revalidate his or her answers. Display the correct results if three incorrect answers are submitted. Extra credit: Use your knowledge of sets to generate potential subsets and ask the user whether they are indeed subsets (or not), and provide corrections and answers as necessary as in the main part of this problem.

7-15.

Set Calculator. This exercise is inspired by Exercise 12.2 in the free online Java textbook located at http://math.hws.edu/javanotes. Create an application that allows users to input a pair of sets, A and B, and allow users to give an operation symbol, i.e., in, not in, &, |, ^, <, <=, >, >=, ==, !=, etc. (For sets, you define the input syntaxthey do not have to be enclosed in brackets as the Java example.) Parse the entire input string and execute the operation on the input sets as requested by the user. Your solution should require fewer lines of Python than the one in Java.



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