List Exercises
Contents
List Exercises#
Table of Contents
Hand of Cards#
(Hand of Cards)
Make a list of cards like:
cards = ["7H", "QC", "2S", "AD", "3C"]
Iterate over the list and print each card symbol with a space after it.
Hint: To print without adding a newline useprint(... end="")
OUTPUT
Your hand: 7H QC 2S AD 3C
Make a table of contents#
(Make a table of contents)
Make a list of chapters like:
chapters = [
"The Setup",
"A Good First Program",
"Comments And Pound Characters",
"Numbers And Math"
]
Use the
enumerate()
function to iterate over the list and print each chapter number and title.
OUTPUT
Table of Contents
Chapter 1: The Setup
Chapter 2: A Good First Program
Chapter 3: Comments And Pound Characters
Chapter 4: Numbers And Math
Running Calculator#
(Running Calculator)
Make a list of numbers.
Iterate over the list. For each element:
Add the element value to the running total.
Print the value and the balance.
OUTPUT
= 0
+ 8 = 8
+ 5 = 13
Reformat Contact from CSV#
(Reformat Contact from CSV)
Start with the string:
"smith,john,415-555-5555"
Split it into a list on
,
Hint: To split on a different delimiter usestr.split(<delim>)
Print the full name capitalized, then the phone number.
Hint: Access list elements withvarname[<index-number>]
OUTPUT
John Smith: 415-555-5555
Column lengths#
(Column lengths Exercise)
This exercise is to calculate the length of the longest value in each column.
Write a function that takes one argument table
that should be a list of
equally sized lists. Each child list is a “row”.
It should return a list the same size as the child rows, where each element is length of the longest value (once converted to a string) in all rows in the same position.
Example Usage
>>> max_lengths([["a", "bb", "ccc"]])
[1, 2, 3]
>>> max_lengths([[628, 4, 82], [140, 59, 23]])
[3, 2, 2]
>>> max_lengths([['lend', 'job', 'when'], ['mail', 'walk', 'prove']])
[4, 4, 5]
Solution template
def max_lengths(table):
"""Return a list of the longest length of columns
(when converted to strings)
Arguments:
table (list): list of equal length lists
>>> max_lengths([["a", "bb", "ccc"]])
[1, 2, 3]
>>> max_lengths([[628, 4, 82], [140, 59, 23]])
[3, 2, 2]
>>> max_lengths([['lend', 'job', 'when'], ['mail', 'walk', 'prove']])
[4, 4, 5]
"""
pass
Solution to Exercise 124 (Column lengths Exercise)
1def max_lengths(table):
2 """Return a list of the longest length of columns
3 (when converted to strings)
4
5 Arguments:
6 table (list): list of equal length lists
7
8 >>> max_lengths([["a", "bb", "ccc"]]) == [1, 2, 3]
9 >>> max_lengths([[628, 4, 82], [140, 59, 23]]) == [3, 2, 2]
10 >>> words = [['lend', 'job', 'when'], ['mail', 'walk', 'prove']]
11 >>> max_lengths(words) == [4, 4, 5]
12 """
13 # in case of empty list, return an empty list
14 if not table:
15 return []
16
17 # initialize lengths to all zeros, same size as the first row
18 lengths = [0] * len(table[0])
19
20 # iterate over each child list
21 for row in table:
22
23 # iterate over each value
24 for i, value in enumerate(row):
25
26 # handle weird values
27 # None should be an empty string (not "None")
28 # and convert everything else to a string
29 if value is None:
30 value = ""
31 else:
32 value = str(value)
33
34 # the length of the value
35 size = len(value)
36
37 # if its longer than the current longest
38 # then replace it
39 if size > lengths[i]:
40 lengths[i] = size
41
42 # return the list of lengths
43 return lengths
Columnize#
(Columnize)
This exercise is to format align a data into columns.
Write a function that takes one argument table
that should be a list of
equally sized lists. Each child list is a “row”. It should return a string
where each line contains the text in one row, and the columns are aligned.
Note: This depends on the max_lengths()
function from the
Column lengths exercise.
Example Usage
>>> scores = [['Joe', 82], ['Billy', 59], ['Mary', 77]]
>>> text = columnize(scores)
>>> text
'Joe 82\nBilly 59\nMary 77'
>>> print(text)
Joe 82
Billy 59
Mary 77
Solution template
def columnize(table):
"""Return a string of aligned columns of text
Arguments:
table (list): list of equal length lists
>>> columnize([['Joe', 82], ['Billy', 59], ['Mary', 77]])
'Joe 82\\nBilly 59\\nMary 77'
"""
# your code here
Solution to Exercise 125 (Columnize)
1from pythonclass.exercises.max_lengths import max_lengths
2
3def columnize(table):
4 """Return a string of aligned columns of text
5
6 Arguments:
7 table (list): list of equal length lists
8
9 >>> columnize([['Joe', 82], ['Billy', 59], ['Mary', 77]])
10 'Joe 82\\nBilly 59\\nMary 77'
11 """
12
13 # create empty lines list for formatted strings, and set seperator to be two spaces
14 lines, sep = [], " " * 2
15
16 # get the column widths
17 sizes = max_lengths(table)
18
19 for row in table:
20 # an empty list for justified strings
21 line = []
22
23 for i, value in enumerate(row):
24 # None should be an empty string (not "None")
25 if value is None:
26 value = ""
27
28 # left justify value to this column size
29 value = str(value).ljust(sizes[i])
30
31 # add value line list
32 line.append(value)
33
34 # join justified strings with seperator
35 text = sep.join(line)
36
37 # add to lines list
38 lines.append(text)
39
40 # join lines with newline character and return
41 return "\n".join(lines)