Skip to main content

Section 1.13 HW7

Exercises Exercises

1. Swap List Ends.

The function swap_list_ends takes one parameter, L, which is a list. The function then swaps the first and last items in L and returns the object None.Β  Notice that since L is mutable, the changes the function makes to L are visible back in the calling program.
SPECIAL CASE: If the list L has length less than 2, then the function does nothing to L and returns None.
For example:
Test Result
swap_list_ends([1, 3, 9, 2])
[2, 3, 9, 1]
swap_list_ends(['super', 'awesome', 'excellent'])
['excellent', 'awesome', 'super']
swap_list_ends([True, False])
[False, True]

2. Make List Items Uppercase 2.

Define the function make_uppercase(mylist), which takes a list parameter mylist (a list of strings), mutates the list by uppercasing each string in mylist. The function returns None.
For example, if mylist is ['cat', 'Dog', 'frOG'], then the mutated list shouldΒ  be ['CAT', 'DOG', 'FROG'].
For example:
Test Result
make_uppercase(['cat', 'Dog', 'frOG'])
['CAT', 'DOG', 'FROG']
make_uppercase(['baNanas', 'appLes', 'pEAches', 'PEArs'])
['BANANAS', 'APPLES', 'PEACHES', 'PEARS']

3. Square Nums 2.

Define the function square_nums_2 which takes a list of numbers, L, and mutates L so that each original item is now squared. For example, if L is [2, -5, 9] then, after calling square_nums_2(L), L == [4, 25, 81].
Nothing is printed and None is returned.
For example:
Test Result
square_nums_2([0, 1, 2, 3])
[0, 1, 4, 9]
square_nums_2([5])
[25]
square_nums_2([])

4. Hyphenated Pairs with Nested Loop.

Define the function get_pairs, which takes a list L of strings, such as
L = ['r', 'g']
and returns a list of all the hyphenated pairs of strings from the list (returns a list of strings, such as ['r-r', 'r-g', 'g-r', 'g-g'])
Use a double for loop or list comprehension to accumulate the result.
For example:
Test Result
get_pairs(['yes', 'no', 'maybe'])
['yes-yes', 'yes-no', 'yes-maybe',
 'no-yes', 'no-no', 'no-maybe',
 'maybe-yes', 'maybe-no', 'maybe-maybe']
get_pairs(["X", "x"])
['X-X', 'X-x', 'x-X', 'x-x']
get_pairs([])

5. Print Grid of Asterisks with a Nested Loop.

Define a function print_star_grid(rows, cols), which takes two positive integers as parameters and prints a rectangular grid of asterisks in response. rows indicates the number of rows to be printed, and cols indicates the number of columns (i.e., the length of each row).
After each "*", print a space (to match the examples).
Hints:
  • For each r in range(rows), for each c in range(cols), print "*Β  " (a star followed by a space).
  • To prevent going to a new line each time, include keyword argument:end ="" inΒ  your print call.
  • Make a call to print() with no arguments each time the inner loop finishes (to make the end of a row).
Note: This function does NOT explicitly return a value.
For example:
Test Result
print_star_grid(2,3)
* * *
* * *
print_star_grid(1,1)
print_star_grid(5,5)
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

6. Print X’s and O’s in a Grid with a Nested Loop.

Define a function print_XO_grid(rows, cols), which takes two positive integers as parameters and prints a rectangular grid of X’s and O’s in response. rows indicates the number of rows to be printed, and cols indicates the number of columns (i.e., the length of each row).
After each "X" or "O", print a space (to match the examples).
Hints:
  • For each r in range(rows), for each c in range(cols), print "X " if r + c is even; otherwise, print "O ".
  • To prevent going to a new line each time, include keyword argument:end = "" inΒ  your print call.
  • Make a call to print() with no arguments each time the inner loop finishes (to make the end of a row).
Note: This function does NOT explicitly return a value.
For example:
Test Result
print_XO_grid(2,3)
X O X
O X O
print_XO_grid(3,2)
X O
O X
X O

7. Sum of Nested List Items.

Define the function sum_nested(L), which takes parameter L (a list of lists of integers) and returns the sum of all the elements of all the inner lists of L.
For example, if L = [[1, 2], [3, 3, 2], [7, -6]], then sum_nested(L) would return 1 + 2 + 3 + 3 + 2 + 7 + (-6) = 12.
TO DO:
Write a double for loop to accumulate the sum.
For example:
Test Result
sum_nested([[5]])
sum_nested([[1,2],[8,7,6]])
sum_nested([])

8. Triplets.

The function gen_triples takes one parameter, L, a list of characters (i.e., strings of length one). The function returns a list of all possible 3-character strings that can be made from the characters in L.
For example, if L = ['n', 'o'], then gen_triples(L) should return the list:
['nnn', 'nno', 'non', 'noo', 'onn', 'ono', 'oon', 'ooo']
If L is empty, gen_triplesΒ returns an empty list.
Hint: Use a triplenested for loop or a list comprehension to accumulate the list of triples.
For example:
Test Result
gen_triples(['n', 'o'])
['nnn', 'nno', 'non', 'noo',
 'onn', 'ono', 'oon', 'ooo']
gen_triples(['?'])
['???']
gen_triples([])

9. Add Entry.

The function add_entry takes a dictionary D and two additional parameters, new_key and new_val. The function adds new_key to the dictionary, using new_val for the value of D[new_key].
Hint: add_entry prints nothing and returns nothing; it simply mutates (i.e., changes the value of) D by adding a new key-value pair.
For example:
Test Result
D = {
    'Hitting Percent': 0.174,
    'Blocks': 5.0,
    'Digs': 47,
    'Aces': 7
}
add_entry(D, 'Spikes', 42)
correctly added Spikes:42
D = {'wins': 9, 'losses': 2}
add_entry(D, 'ties', 1)
correctly added ties:1

10. Delete Entry.

The function delete_entry takes a parameter D (a dictionary)Β and a parameter k (aΒ supposed key in D).
  • The function removesthe entry whose key is k and returns the value that was associated with k.
  • However, if k is nota key in D, the function leaves D unchanged and returns the value None.
Hint: D.pop(k) is helpful here, but first you need to handle the case where k is not a key in D. You can search online to learn more, using search string: python dictionary delete item
For example:
Test Result
D = {
    'Hitting Percent': 0.174,
    'Blocks': 5.0,
    'Digs': 47,
    'Aces': 7
}
delete_entry(D, 'Digs')
D = {'wins': 9, 'losses': 2}
delete_entry(D, 'ties')
None

11. Has Key.

The function has_key takes two parameters: D and k, where D is a dictionary and k is a possible key in D.Β The function returns True if k is a key in the dictionary D and False otherwise.
Hint:Read up on using the in operatorΒ with dictionaries.
For example:
Test Result
D = {
    'Hitting Percent': 0.174,
    'Blocks': 5.0,
    'Digs': 47,
    'Aces': 7
}
has_key(D, 'Blocks')
True
D = {
    'Hitting Percent': 0.174,
    'Blocks': 5.0,
    'Digs': 47,
    'Aces': 7
}
has_key(D, 'Spikes')
False

12. Has Value.

The function has_value takes two parameters: a dictionary D and a number num. The function returns True if num is a value in dictionary D; otherwise, it returns False.
Hint:Remind yourself about the various operators and methods for dictionaries.
For example:
Test Result
D = {
    'Hitting Percent': 0.174,
    'Blocks': 5.0,
    'Digs': 47,
    'Aces': 7
}
has_value(D, 47)
True
D = {
    'Hitting Percent': 0.174,
    'Blocks': 5.0,
    'Digs': 47,
    'Aces': 7
}
has_value(D, 3047)
False

13. Get Num Pairs.

The function get_num_pairs takes one parameter, D, which is a dictionary. The function returns the numberof key-value pairs in D.
For example:
Test Result
D = {'Hitting Percent': 0.174, 'Blocks': 5.0, 'Digs': 47, 'Aces': 7}
get_num_pairs(D)
D = {'wins': 9, 'losses': 2}
get_num_pairs(D)

14. Build Dictionary.

Define the function build_dictionary which takes two parameters, key_list and value_list.Β  The function returns a dictionary.
  • Both lists have the same length.
  • The two lists are organized such that each item in key_list can be matched up with the item at the corresponding index in value_list to form a key-value pair for a dictionary.
  • For example, if key_list is ['a', 'b', 'c'] and value_listis ['yes', 'no', 'maybe'], then the new dictionary should contain these pairs: 'a':'yes', 'b':'no', 'c':'maybe'
Implement the function so that it accumulates a new dictionary.
  1. Initialize D to an empty dictionary, {}
  2. Iterate k over an appropriate range of indices
  3. Inside the loop, update D by giving D a new pair, using key_list[k] and value_list[k]
For example:
Test Result
key_list = ['Blocks', 'Digs', 'Aces']
value_list = [5.0, 47, 7]
build_dictionary(key_list, value_list)
{'Blocks': 5.0, 'Digs': 47, 'Aces': 7}
key_list = ['wins', 'losses']
value_list = [9, 2]
build_dictionary(key_list, value_list)
{'wins': 9, 'losses': 2}

15. Accumulate Frequencies Dictionary.

The function get_freq_dict(L) takes a list of integers and returnsa dictionary D such that for each number x in L, D[x] is the frequency of x in L.
TO DO: Accumulate D as explained in your textbook. Read up on how to generate a frequency table using a dictionary if the following hint leaves you puzzled.
Hint: Use the accumulator pattern.
  1. Initialize D to be an empty dictionary: DΒ  = {}
  2. For each x in L:
    • if x is already a key in D, update the frequencyΒ  of x: D[x] = D[x] + 1
    • else, make x:1 a new pair in D
  3. When the loop has finished, return D.
For example:
Test Result
get_freq_dict([1, 5, 25, 5, 1])
{1: 2, 5: 2, 25: 1}
get_freq_dict([17])
{17: 1}
get_freq_dict([1, 1, 1, 1, 2, 2, 2, 3, 3, 4])
{1: 4, 2: 3, 3: 2, 4: 1}

16. Calculate Mode of List (using a dictionary).

The function get_mode(L) takes one parameter, L, a list of integers. get_mode builds a dictionary of frequencies to determine how often each number in the list occurs. Then it returns the mode of the list, that is, the number in L which occurs with the highest frequency.
For example, get_mode([3, 8, 5, 5, 8, 8]) would determine that
BecauseΒ  8 has the highest frequency, get_mode would return 8Β  for this example.
Note: You may assume that L will not be empty and there will be a single mode in L (no ties for most frequent).
Tip: Suppose D is a dictionary with integer values. The following code will determine the maximum value in D: max_value = max(D.values())
For example:
Test Result
get_mode([3, 8, 5, 5, 8, 8])
get_mode([3, 8, 5, 5, 8, 8, 3, 3, 5, 3, 3])

17. Counting by k.

Write a 6-line Python script (not a function definition). The purpose of the program is to read a positive integer n from standard input and then show how to "count by k" for k = 0, 1, 2, ..., n.
Hint: Use a nested for loop.
For example:
Input Result
Counting by: 0
0 0 0 0 0 0 0
Counting by: 1
0 1 2 3 4 5 6
Counting by: 2
0 2 4 6 8 10 12
Counting by: 3
0 3 6 9 12 15 18
You have attempted of activities on this page.