Exercises

Use IPython sessions for each exercise where practical.

  1. 5.1 (What’s Wrong with This Code?) What, if anything, is wrong with each of the following code segments?

    1. day, high_temperature = ('Monday', 87, 65)
    2. numbers = [1, 2, 3, 4, 5]
      numbers[10]
    3. name = 'amanda'
      name[0] = 'A'
    4. numbers = [1, 2, 3, 4, 5]
      numbers[3.4]
    5. student_tuple = ('Amanda', 'Blue', [98, 75, 87])
      student_tuple[0] = 'Ariana'
      
    6. ('Monday', 87, 65) + 'Tuesday'
    7. 'A' += ('B', 'C')
    8. x = 7
      del x
      print(x)
      
    9. numbers = [1, 2, 3, 4, 5]
      numbers.index(10)
    10. numbers = [1, 2, 3, 4, 5]
      numbers.extend(6, 7, 8)
    11. numbers = [1, 2, 3, 4, 5]
      numbers.remove(10)
    12. values = []
      values.pop()
  2. 5.2 (What’s Does This Code Do?) What does the following function do, based on the sequence it receives as an argument?

    def mystery(sequence):
        return sequence == sorted(sequence)
  3. 5.3 (Fill in the Missing Code) Replace the ***s in the following list comprehension and map function call, such that given a list of heights in inches, the code maps the list to a list of tuples containing the original height values and their corresponding values in meters. For example, if one element in the original list contains the height 69 inches, the corresponding element in the new list will contain the tuple (69, 1.7526), representing both the height in inches and the height in meters. There are 0.0254 meters per inch.

    [*** for x in [69, 77, 54]]
    list(map(lambda ***, [69, 77, 54]))
  4. 5.4 (Iteration Order) Create a 2-by-3 list, then use a nested loop to:

    1. Set each element’s value to an integer indicating the order in which it was processed by the nested loop.

    2. Display the elements in tabular format. Use the column indices as headings across the top, and the row indices to the left of each row.

  5. 5.5 (IPython Session: Slicing) Create a string called alphabet containing 'abcdefghijklmnopqrstuvwxyz', then perform the following separate slice operations to obtain:

    1. The first half of the string using starting and ending indices.

    2. The first half of the string using only the ending index.

    3. The second half of the string using starting and ending indices.

    4. The second half of the string using only the starting index.

    5. Every second letter in the string starting with 'a'.

    6. The entire string in reverse.

    7. Every third letter of the string in reverse starting with 'z'.

  6. 5.6 (Functions Returning Tuples) Define a function rotate that receives three arguments and returns a tuple in which the first argument is at index 1, the second argument is at index 2 and the third argument is at index 0. Define variables a, b and c containing 'Doug', 22 and 1984. Then call the function three times. For each call, unpack its result into a, b and c, then display their values.

  7. 5.7 (Duplicate Elimination) Create a function that receives a list and returns a (possibly shorter) list containing only the unique values in sorted order. Test your function with a list of numbers and a list of strings.

  8. 5.8 (Sieve of Eratosthenes) A prime number is an integer greater than 1 that’s evenly divisible only by itself and 1. The Sieve of Eratosthenes is an elegant, straightforward method of finding prime numbers. The process for finding all primes less than 1000 is:

    1. Create a 1000-element list primes with all elements initialized to True. List elements with prime indices (like 2, 3, 5, 7, 11, …) will remain True. All other list elements will eventually be set to False.

    2. Starting with index 2, if a given element is True iterate through the rest of the list and set to False every element in primes whose index is a multiple of the index for the element we’re currently processing. For list index 2, all elements beyond element 2 in the list that have indices which are multiples of 2 (i.e., 4, 6, 8, 10, …, 998) will be set to False.

    3. Repeat Step (b) for the next True element. For list index 3 (which was initialized to True), all elements beyond element 3 in the list that have indices which are multiples of 3 (i.e., 6, 9, 12, 15, …, 999) will be set to False; and so on. A subtle observation (think about why this is true): The square root of 999 is 31.6, you’ll need to test and set to False only all multiples of 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29 and 31. This will significantly improve the performance of your algorithm, especially if you decide to look for large prime numbers.

    When this process completes, the list elements that are still True indicate that the index is a prime number. These indices can be displayed. Use a list of 1000 elements to determine and display the prime numbers less than 1000. Ignore list elements 0 and 1. [As you work through the book, you’ll discover other Python capabilities that will enable you to cleverly reimplement this exercise.]

  9. 5.9 (Palindrome Tester) A string that’s spelled identically backward and forward, like 'radar', is a palindrome. Write a function is_palindrome that takes a string and returns True if it’s a palindrome and False otherwise. Use a stack (simulated with a list as we did in Section 5.11) to help determine whether a string is a palindrome. Your function should ignore case sensitivity (that is, 'a' and 'A' are the same), spaces and punctuation.

  10. 5.10 (Anagrams) An anagram of a string is another string formed by rearranging the letters in the first. Write a script that produces all possible anagrams of a given string using only techniques that you’ve seen to this point in the book. [The itertools module provides many functions, including one that produces permutations.]

  11. 5.11 (Summarizing Letters in a String) Write a function summarize_letters that receives a string and returns a list of tuples containing the unique letters and their frequencies in the string. Test your function and display each letter with its frequency. Your function should ignore case sensitivity (that is, 'a' and 'A' are the same) and ignore spaces and punctuation. When done, write a statement that says whether the string has all the letters of the alphabet.

  12. 5.12 (Telephone-Number Word Generator) You should find this exercise to be entertaining. Standard telephone keypads contain the digits zero through nine. The numbers two through nine each have three letters associated with them, as shown in the following table:

    A table shows telephone numbers 2 through 9 with corresponding three letters associated with each number. 2, A B C. 3 D E F. 4 G H I. 5 J K L. 6 M N O. 7 P R S. 8 T U V. 9 W X Y.

    Many people find it difficult to memorize phone numbers, so they use the correspondence between digits and letters to develop seven-letter words (or phrases) that correspond to their phone numbers. For example, a person whose telephone number is 686-2377 might use the correspondence indicated in the preceding table to develop the seven-letter word “NUMBERS.” Every seven-letter word or phrase corresponds to exactly one seven-digit telephone number. A budding data science entrepreneur might like to reserve the phone number 244-3282 (“BIGDATA”).

    Every seven-digit phone number without 0s or 1s corresponds to many different seven-letter words, but most of these words represent unrecognizable gibberish. A veterinarian with the phone number 738-2273 would be pleased to know that the number corresponds to the letters “PETCARE.”

    Write a script that, given a seven-digit number, generates every possible seven-letter word combination corresponding to that number. There are 2,187 (37) such combinations. Avoid phone numbers with the digits 0 and 1 (to which no letters correspond). See if your phone number corresponds to meaningful words.

  13. 5.13 (Word or Phrase to Phone-Number Generator) Just as people would enjoy knowing what word or phrase their phone number corresponds to, they might choose a word or phrase appropriate for their business and determine what phone numbers correspond to it. These are sometimes called vanity phone numbers, and various websites sell such phone numbers. Write a script similar to the one in the previous exercise that produces the possible phone number for the given seven-letter string.

  14. 5.14 (Is a Sequence Sorted?) Create a function is_ordered that receives a sequence and returns True if the elements are in sorted order. Test your function with sorted and unsorted lists, tuples and strings.

  15. 5.15 (Tuples Representing Invoices) When you purchase products or services from a company, you typically receive an invoice listing what you purchased and the total amount of money due. Use tuples to represent hardware store invoices that consist of four pieces of data—a part ID string, a part description string, an integer quantity of the item being purchased and, for simplicity, a float item price (in general, Decimal should be used for monetary amounts). Use the sample hardware data shown in the following table.

    A table shows lists and tuples sequences with four pieces of data, part number, part description, quantity and price.

    Perform the following tasks on a list of invoice tuples:

    1. Use function sorted with a key argument to sort the tuples by part description, then display the results. To specify the element of the tuple that should be used for sorting, first import the itemgetter function from the operator module as in

      from operator import itemgetter

      Then, for sorted’s key argument specify itemgetter( index ) where index specifies which element of the tuple should be used for sorting purposes.

    2. Use the sorted function with a key argument to sort the tuples by price, then display the results.

    3. Map each invoice tuple to a tuple containing the part description and quantity, sort the results by quantity, then display the results.

    4. Map each invoice tuple to a tuple containing the part description and the value of the invoice (the product of the quantity and the item price), sort the results by the invoice value, then display the results.

    5. Modify Part (d) to filter the results to invoice values in the range $200 to $500.

    6. Calculate the total of all the invoices.

  16. 5.16 (Sorting Letters and Removing Duplicates) Insert 20 random letters in the range 'a' through 'f' into a list. Perform the following tasks and display your results:

    1. Sort the list in ascending order.

    2. Sort the list in descending order.

    3. Get the unique values sort them in ascending order.

  17. 5.17 (Filter/Map Performance) With regard to the following code:

    numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
    
    list(map(lambda x: x ** 2,
        filter(lambda x: x % 2 != 0, numbers)))
    1. How many times does the filter operation call its lambda argument?

    2. How many times does the map operation call its lambda argument?

    3. If you reverse the filter and map operations, how many times does the map operation call its lambda argument?

    To help you answer the preceding questions, define functions that perform the same tasks as the lambdas. In each function, include a print statement so you can see each time the function is called. Finally, replace the lambdas in the preceding code with the names of your functions.

  18. 5.18 (Summing the Triples of the Even Integers from 2 through 10) Starting with a list containing 1 through 10, use filter, map and sum to calculate the total of the triples of the even integers from 2 through 10. Reimplement your code with list comprehensions rather than filter and map.

  19. 5.19 (Finding the People with a Specified Last Name) Create a list of tuples containing first and last names. Use filter to locate the tuples containing the last name Jones. Ensure that several tuples in your list have that last name.

  20. 5.20 (Display a Two-Dimensional List in Tabular Format) Define a function named display_table that receives a two-dimensional list and displays its contents in tabular format. List the column indices as headings across the top, and list the row indices at the left of each row.

  21. 5.21 (Computer-Assisted Instruction: Reducing Student Fatigue) Re-implement Exercise 4.15 to store the computer’s responses in lists. Use random-number generation to select responses using random list indices.

  22. 5.22 (Simulating a Queue with a List) In this chapter, you simulated a stack using a list. You also can simulate a queue collection with a list. Queues represent waiting lines similar to a checkout line in a supermarket. The cashier services the person at the front of the line first. Other customers enter the line only at the end and wait for service.

    In a queue, you insert items at the back (known as the tail) and delete items from the front (known as the head). For this reason, queues are first-in, first-out (FIFO) collections. The insert and remove operations are commonly known as enqueue and dequeue.

    Queues have many uses in computer systems, such as sharing CPUs among a potentially large number of competing applications and the operating system itself. Applications not currently being serviced sit in a queue until a CPU becomes available. The application at the front of the queue is the next to receive service. Each application gradually advances to the front as the applications before it receive service.

    Simulate a queue of integers using list methods append (to simulate enqueue) and pop with the argument 0 (to simulate dequeue). Enqueue the values 3, 2 and 1, then dequeue them to show that they’re removed in FIFO order.

  23. 5.23 (Functional-Style Programming: Order of filter and map Calls) When combining filter and map operations, the order in which they’re performed matters. Consider a list numbers containing 10, 3, 7, 1, 9, 4, 2, 8, 5, 6 and the following code:

    In [1]: numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
    
    In [2]: list(map(lambda x: x * 2,
       ...:          filter(lambda x: x % 2 == 0, numbers)))
       ...:
    Out[3]: [20, 8, 4, 16, 12]
    

    Reorder this code to call map first and filter second. What happens and why?

Exercises 5.24 through 5.26 are reasonably challenging. Once you’ve done them, you ought to be able to implement many popular card games.

  1. 5.24 (Card Shuffling and Dealing) In Exercises 5.24 through 5.26, you’ll use lists of tuples in scripts that simulate card shuffling and dealing. Each tuple represents one card in the deck and contains a face (e.g., 'Ace', 'Deuce', 'Three', …, 'Jack', 'Queen', 'King') and a suit (e.g., 'Hearts', 'Diamonds', 'Clubs', 'Spades'). Create an initialize_deck function to initialize the deck of card tuples with 'Ace' through 'King' of each suit, as in

    deck = [('Ace', 'Hearts'), …, ('King', 'Hearts'),
        ('Ace', 'Diamonds'), …, ('King', 'Diamonds'),
        ('Ace', 'Clubs'), …, ('King', 'Clubs'),
        ('Ace', 'Spades'), …, ('King', 'Spades')]
    

    Before returning the list, use the random module’s shuffle function to randomly order the list elements. Output the shuffled cards in the following four-column format:

    A screen shot of an image that shows the use of a random module’s shuffle function and the output of the shuffled cards in a 4 column format.
  2. 5.25 (Card Playing: Evaluating Poker Hands) Modify Exercise 5.24 to deal a five-card poker hand as a list of five card tuples. Then create functions (i.e., is_pair, is_two_pair, is_three_of_a_kind, …) that determine whether the hand they receive as an argument contains groups of cards, such as:

    1. one pair

    2. two pairs

    3. three of a kind (e.g., three jacks)

    4. a straight (i.e., five cards of consecutive face values)

    5. a flush (i.e., all five cards of the same suit)

    6. a full house (i.e., two cards of one face value and three cards of another)

    7. four of a kind (e.g., four aces)

    8. straight flush (i.e., a straight with all five cards of the same suit)

    9. … and others.

    See https://en.wikipedia.org/wiki/List_of_poker_hands for poker-hand types and how they rank with respect to one another. For example, three of a kind beats two pairs.

  3. 5.26 (Card Playing: Determining the Winning Hand) Use the methods developed in Exercise 5.25 to write a script that deals two five-card poker hands (i.e., two lists of five card tuples each), evaluates each hand and determines which wins. As each card is dealt, it should be removed from the list of tuples representing the deck.

  4. 5.27 (Intro to Data Science: Duplicate Elimination and Counting Frequencies) Use a list comprehension to create a list of 50 random values in the range 1 through 10. Use NumPy’s unique function to obtain the unique values and their frequencies. Display the results.

  5. 5.28 (Intro to Data Science: Survey Response Statistics) Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses in a list

    1, 2, 5, 4, 3, 5, 2, 1, 3, 3, 1, 4, 3, 3, 3, 2, 3, 3, 2, 5

    Determine and display the frequency of each rating. Use the built-in functions, statistics module functions and NumPy functions demonstrated in Section 5.17.2 to display the following response statistics: minimum, maximum, range, mean, median, mode, variance and standard deviation.

  6. 5.29 (Intro to Data Science: Visualizing Survey Response Statistics) Using the list in Exercise 5.28 and the techniques you learned in Section 5.17.2, display a bar chart showing the response frequencies and their percentages of the total responses.

  7. 5.30 (Intro to Data Science: Removing the Text Above the Bars) Modify the die-rolling simulation in Section 5.17.2 to omit displaying the frequencies and percentages above each bar. Try to minimize the number of lines of code.

  8. 5.31 (Intro to Data Science: Coin Tossing) Modify the die-rolling simulation in Section 5.17.2 to simulate the flipping a coin. Use randomly generated 1s and 2s to represent heads and tails, respectively. Initially, do not include the frequencies and percentages above the bars. Then modify your code to include the frequencies and percentages. Run simulations for 200, 20,000 and 200,000 coin flips. Do you get approximately 50% heads and 50% tails? Do you see the “law of large numbers” in operation here?

  9. 5.32 (Intro to Data Science: Rolling Two Dice) Modify the script RollDie.py that we provided with this chapter’s examples to simulate rolling two dice. Calculate the sum of the two values. Each die has a value from 1 to 6, so the sum of the values will vary from 2 to 12, with 7 being the most frequent sum, and 2 and 12 the least frequent. The following diagram shows the 36 equally likely possible combinations of the two dice and their corresponding sums:

    A diagram shows the 36 equally likely possible combinations of 2 dice and their corresponding sums.

    If you roll the dice 36,000 times:

    • The values 2 and 12 each occur 1/36th (2.778%) of the time, so you should expect about 1000 of each.

    • The values 3 and 11 each occur 2/36ths (5.556%) of the time, so you should expect about 2000 of each, and so on.

    Use a command-line argument to obtain the number of rolls. Display a bar plot summarizing the roll frequencies. The following screen captures show the final bar plots for sample executions of 360, 36,000 and 36,000,000 rolls. Use the Seaborn barplot function’s optional orient keyword argument to specify a horizontal bar plot.

    A set of 3 diagrams show the Seaborn bar plots for the dice rolls of 360, 36,000 and 36,000,000 rolls.
  10. 5.33 (Intro to Data Science Challenge: Analyzing the Dice Game Craps) In this exercise, you’ll modify Chapter 4’s script that simulates the dice game craps by using the techniques you learned in Section 5.17.2. The script should receive a command-line argument indicating the number of games of craps to execute and use two lists to track the total numbers of games won and lost on the first roll, second roll, third roll, etc. Summarize the results as follows:

    1. Display a horizontal bar plot indicating how many games are won and how many are lost on the first roll, second roll, third roll, etc. Since the game could continue indefinitely, you might track wins and losses through the first dozen rolls (of a pair of dice), then maintain two counters that keep track of wins and losses after 12 rolls—no matter how long the game gets. Create separate bars for wins and losses.

    2. What are the chances of winning at craps? [Note: You should discover that craps is one of the fairest casino games. What do you suppose this means?]

    3. What is the mean for the length of a game of craps? The median? The mode?

    4. Do the chances of winning improve with the length of the game?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.121.131