Workout 7. Functional Programming with Comprehensions Flashcards

(9 cards)

1
Q

Produce a list of squared numbers for each number in an iterable range(5).

A
[x*x for x in range(5)]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Produce a dictionary with keys from an iterable, with key-value pairs of the form (k,2k).

A
{x : 2*x for x in range(5)}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Produce a set of squared numbers for each number in an iterable range(5).

A
{x*x for x in range(5)}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

For loop vs List Comprehension:
If your goal is to execute something once for each element in an iterable, throwing away or ignoring any return value, then a _ is the preferred way.
However, if you are interested in transformed output of each element in an iterable, then a _ is the preferred way.

A
  1. for loop
  2. list comprehension
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Write a function (join_numbers) that takes a range of integers.
The function should return those numbers as a string, with commas between the
numbers.
That is, given range(15) as input, the function should return this string:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

nested list comprehensions:
return list of all visited cities, given the dictionary of (country, [cities]) pairs:

all_places_dict = {'USA': ['Philadelphia', 'New York', 'Cleveland', 'San Jose',
'San Francisco'],
'China': ['Beijing', 'Shanghai', 'Guangzhou'],
'UK': ['London'],
'India': ['Hyderabad']}
A
def visited_cities(all_places_dict):
  return [city for (_,cities) in all_places_dict.items() for city in cities]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Which of the following runs faster?
1. sum([x*x for x in range(100000)])
2. sum((x*x for x in range(100000)))

A

Second: since it uses generator expression

The generator returns one element at a time, waiting for sum to request the next item in line.
In this way, we’re only consuming one integer’s worth of memory at a time, rather than a huge list of integers’ memory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

produce a list of tuples: (x,y) from range(numrange) where x is odd and y is even.
1. with list comprehension
2. with for loop

print(odd_even_tuples(5))

A

with list comprehension:

def odd_even_tuples(numrange):
  return [(x,y) for x in range(1, numrange) if x%2 for y in range(1, numrange) if not y%2]

with for loop:

def odd_even_tuples_via_loop(numrange):
  output = []
  for x in range(1, numrange):
    if x%2:
      for y in range(1, numrange):
        if not y%2:
          output.append((x,y))
  return output
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly