|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +from runner.koan import * |
| 5 | + |
| 6 | + |
| 7 | +class AboutComprehension(Koan): |
| 8 | + |
| 9 | + |
| 10 | + def test_creating_lists_with_list_comprehensions(self): |
| 11 | + feast = ['lambs', 'sloths', 'orangutans', 'breakfast cereals', |
| 12 | + 'fruit bats'] |
| 13 | + |
| 14 | + comprehension = [delicacy.capitalize() for delicacy in feast] |
| 15 | + |
| 16 | + #self.assertEqual(__, comprehension[0]) |
| 17 | + #self.assertEqual(__, comprehension[2]) |
| 18 | + |
| 19 | + def test_filtering_lists_with_list_comprehensions(self): |
| 20 | + feast = ['spam', 'sloths', 'orangutans', 'breakfast cereals', |
| 21 | + 'fruit bats'] |
| 22 | + |
| 23 | + comprehension = [delicacy for delicacy in feast if len(delicacy) > 6] |
| 24 | + |
| 25 | + self.assertEqual(__, len(feast)) |
| 26 | + self.assertEqual(__, len(comprehension)) |
| 27 | + |
| 28 | + def test_unpacking_tuples_in_list_comprehensions(self): |
| 29 | + list_of_tuples = [(1, 'lumberjack'), (2, 'inquisition'), (4, 'spam')] |
| 30 | + comprehension = [ skit * number for number, skit in list_of_tuples ] |
| 31 | + |
| 32 | + self.assertEqual(__, comprehension[0]) |
| 33 | + self.assertEqual(__, len(comprehension[2])) |
| 34 | + |
| 35 | + def test_double_list_comprehention(self): |
| 36 | + list_of_eggs = ['poached egg', 'fried egg'] |
| 37 | + list_of_meats = ['lite spam', 'ham spam', 'fried spam'] |
| 38 | + |
| 39 | + |
| 40 | + comprehension = [ '{0} and {1}'.format(egg, meat) for egg in list_of_eggs for meat in list_of_meats] |
| 41 | + |
| 42 | + |
| 43 | + self.assertEqual(__, len(comprehension)) |
| 44 | + self.assertEqual(__, comprehension[0]) |
| 45 | + |
| 46 | + def test_creating_a_set_with_set_comprehention(self): |
| 47 | + comprehension = { x for x in 'aabbbcccc'} |
| 48 | + |
| 49 | + self.assertequal(__, len(comprehension)) # remeber that set members are unique |
| 50 | + |
| 51 | + def test_creating_a_dictionary_with_dictionary_comprehention(self): |
| 52 | + dict_of_weapons = {'first': 'fear', 'second': 'surprise', |
| 53 | + 'third':'ruthless efficiency', 'forth':'fanatical devotion', 'fifth': None} |
| 54 | + |
| 55 | + dict_comprehention = { k.upper(): weapon for k, weapon in dict_of_weapons.iteritems() if weapon} |
| 56 | + |
| 57 | + self.assertEqual(__, 'first' in dict_comprehention) |
| 58 | + self.assertEqual(__, 'FIRST' in dict_comprehention) |
| 59 | + self.assertEqual(__, len(dict_of_weapons)) |
| 60 | + self.assertEqual(__, len(dict_comprehention)) |
0 commit comments