Introduction to Python

davidbpython.com




Project Warmup Exercise Solutions, Session 7



FUNCTIONS

 
Ex. 7.1 What is the correct way to call this function?
Suggested Solution:
def do(arg):
    darg = arg * 2
    return arg

dval = do(10)

  • The function takes one argument, so the call passes one argument.
  • The function returns one return value, so the call assigns to one variable.

 
Ex. 7.2 What is the correct way to call this function?
Suggested Solution:
import random

def do():
    num = random.randint(10)
    return num

val = do()

  • The function takes no argument, so the call passes no argument.
  • The function returns one return value, so the call assigns to one variable.

 
Ex. 7.3 What is the correct way to call this function?
Suggested Solution:
def do(arg, otherarg):
    svals = arg + otherarg
    return svals

dbld = do(5, 10)

  • The function takes two arguments, so the call passes two arguments.
  • The function returns one return value, so the call assigns to one variable.

 
Ex. 7.4 What is the correct way to call this function?
Suggested Solution:
def do(arg, otherarg):
    darg = arg * 2
    dotherarg = otherarg * 2
    return darg, dotherarg

a, b = do(5, 10)

  • The function takes two arguments, so the call passes two arguments.
  • The function returns two return values, so the call assigns to two variables.

 
Ex. 7.5 Write a function addme() that takes two arguments, adds them together and returns the two arguments added / concatenated.
def addme(arg1, arg2):
    adx = arg1 + arg2
    return adx

x = addme(4, 5)
print(x)

y = addme('hey', 'you')
print(y)
 

SET COMPARISONS

 
Ex. 7.6 Use the set .difference() method to show which of the submitted addresses is not on the whitelist.
whitelist = {'joe@me.com', 'marie@there.com'}
submitted = {'joe@me.com', 'dark@lord.au', 'marie@there.com'}
Suggested Solution:
diff = submitted.difference(whitelist)
print(diff)
 
Ex. 7.7 Use the set .intersection() method to show which of the submitted addresses is on the blacklist.
blacklist = ['dark@lord.au', 'skeevy@guy.ny', 'bad@news.eu']
submitted = ['joe@me.com', 'dark@lord.au', 'marie@there.com']
Suggested Solution:
diff = set(submitted).intersection(blacklist)
print(diff)

Since we're starting with two lists, the first must be converted to a set so we can call the intersection() method. The second list does not need to be converted as set methods can work with any iterable.

 
Ex. 7.8 Use the set .union() method to show the complete set of clients between the NE_clients and NW_clients list.
NE_clients = {'Alpha Industries', 'Beta Engrams, Inc.',
              'Gamma Products, Ltd.'}

NW_clients = {'Alpha Industries',  'Gamma Products, Ltd.',
              'Epsilon Publications'}

all_clients = NE_clients.union(NW_clients)
 

LIST COMPREHENSIONS

 
Ex. 7.9 Run the below code to see that the list comprehension returns a list of the items from the 'source list'.
x = [1, 2, 3, 4]

y = [ item for item in x ]

(No solution - demonstration exercise.)

 
Ex. 7.10 Modify the list comprehension to double each value in the source list.
Suggested Solution:
x = [1, 2, 3, 4]

y = [ item * 2 for item in x ]

print(y)
 
Ex. 7.11 Write a list comprehension that halves each value in the source list.
Suggested Solution:
x = [1, 2, 3, 4]

y = [ item / 2 for item in x ]
 
Ex. 7.12 Write a list comprehension that uppercases each string in the source list.
Suggested Solution:
x = ['hi', 'there', 'pythonistas']

y = [ item.upper() for item in x ]
 
Ex. 7.13 Write a list comprehension that builds a list of only positive values (greater than 0).
Suggested Solution:
x = [7, -2, 9, -1, 0, 1, -3, 9, 3]

y = [ item for item in x if item > 0 ]
 
Ex. 7.14 Write a list comprehension that builds a list of only names starting with underscore ('_').
Suggested Solution:
dirlist = [ '__str__', '__repr__', 'upper', 'lower' ]


magic = [ item for item in dirlist if item.startswith('_') ]
 
Ex. 7.15 This list comprehension iterates over each line in the file (line for line in fh). Apply .rstrip() to each line to produce a list of stripped lines.
Suggested Solution:
fh = open('../revenue.csv')

lines = [ line.rstrip() for line in fh ]

fh.close()
 
Ex. 7.16 Write a list comprehension that iterates over each line in the FF_tiny.txt file and slices out the year from each line.
Suggested Solution:
fh = open('../FF_tiny.txt')

lines = [ line[0:4] for line in fh ]

fh.close()
 
Ex. 7.17 Write a list comprehension that splits each line, producing a list for each line in the file.
Suggested Solution:
fh = open('../FF_tiny.txt')

lol = [ item.split() for item in fh ]

fh.close()
 
Ex. 7.18 Continuing with the solution from previous exercise, subscript the split() so that only one item from each list is passed to the resulting list.
Suggested Solution:
fh = open('../FF_tiny.txt')

lol = [ item.split()[0] for item in fh ]

fh.close()
 
Ex. 7.19 Given the code below, write a list comprehension that only returns words longer than 3 letters - print the resulting list.
words = [ 'Hello', 'my', 'dear', 'the', 'heart',
          'is', 'a', 'child.' ]
Suggested Solution:
words = [ 'Hello', 'my', 'dear', 'the', 'heart',
          'is', 'a', 'child.' ]

rlist = [ x for x in words if len(x) > 3 ]
print(rlist)
 
Ex. 7.20 Build on the previous exercise - modify the list comprehension so that the returned words are uppercased.
Suggested Solution:
words = [ 'Hello', 'my', 'dear', 'the', 'heart',
          'is', 'a', 'child.' ]

rlist = [ x.upper() for x in words if len(x) > 3 ]
print(rlist)
 
Ex. 7.21 Open ../student_db.txt. Use a list comprehension to open the file and load it into a list as we did in previous exercises. Print the resulting list. (Hint: a list comprehension loops through any iterable (object that can be looped or iterated through), so you can place the call to open() right in the list comprehension and it will loop over that (or rather, the file object returned from it.)
Suggested Solution:
lines = [ line for line in open('../student_db.txt') ]

print(lines)
 
Ex. 7.22 Continuing the above exercise, use the list comprehension to remove the newline from each line in the file. Print the resulting list - you should see each line of the file as before, but without the newline.
Suggested Solution:
lines = [ line.rstrip() for line in open('../student_db.txt') ]

print(lines)
 
Ex. 7.23 Continuing the previous exercise, exclude the 1st line (the header line) from the output. (Hint: file.readlines() returns a list of lines, and you can slice that list. But since we can't assign open() to a filehandle, we can simply treat open() as if it were the filehandle (because it returns it); thus we can call the readlines() method on open(), and we can slice any list returned form a method, so we can attach a slice directly to the call to readlines().
Suggested Solution:
lines = [ line.rstrip()
          for line in
          open('../student_db.txt').readlines()[1:] ]

print(lines)

Note also that we can't call .close() on the file object since we never assigned it to a variable. This should only be used if your program is running for a short time, and you are not opening many files this way during the run of a program.

 
[pr]