Counting available seats

It's important during booking to know how many seats are available. To this end we'll write a num_available_seats() method. This uses two nested generator expressions. The outer expression filters for all rows which are not None to exclude our dummy first row. The value of each item in the outer expression is the sum of the number of None values in each row. This inner expression iterates over values of the dictionary and adds 1 for each None found:

def num_available_seats(self):
return sum( sum(1 for s in row.values() if s is None)
for row in self._seating
if row is not None )

Notice how we have split the outer expression over three lines to improve readability.

>>> from airtravel import make_flight
>>> f = make_flight()
>>> f.num_available_seats()
127

A quick check shows that our new calculation is correct:

>>> 6 * 22 - 5
127
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset