Assessment Questions: Python List Comprehensions

Sep 6, 2013 • Leszek Tarkowski

Question 1 competence
What is an equivalent list comprehension for code:
``

result = []
for i in range(10):
    if i % 2:
        result.append(i ** 2)
print(result)

 

Answers:
a) print([x ** 2 for x in range(10) if x % 2])
b) print([x = x ** 2 for x in range(10) if x % 2])
c) print([for x in range(10) if x % 2 then x ** 2 ])
d) print([if x % 2 then x ** 2 for x in range(10)])

Question 2 Experts
This code sample:
sum(x for x in range(1,1000) if x % 5 == 0 or x % 3 == 0)
could be expressed using “functional” python by using:

Answers (select all that apply):
a) map() and filter():

map ( lambda x, y: x+y, filter(lambda x : x % 5 == 0 or x % 3 == 0, range(1,1000)) )

b) filter() and reduce():

reduce ( lambda x, y: x+y, filter(lambda x : x % 5 == 0 or x % 3 == 0, range(1,1000)) )

c) map() and reduce():

reduce ( lambda x, y: x+y, map(lambda x : x % 5 == 0 or x % 3 == 0, range(1,1000)) )

d) filter() and reduce():

def divby5and3(x):
    if x % 5 == 0 or x % 3 == 0:
        return True

def sum(x, y):
    return x + y

reduce ( sum, filter(divby5and3, range(1,1000)))