forked from gregmalcolm/python_koans
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabout_comprehension.py
More file actions
61 lines (39 loc) · 2.18 KB
/
about_comprehension.py
File metadata and controls
61 lines (39 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutComprehension(Koan):
def test_creating_lists_with_list_comprehensions(self):
feast = ['lambs', 'sloths', 'orangutans', 'breakfast cereals',
'fruit bats']
comprehension = [delicacy.capitalize() for delicacy in feast]
self.assertEqual(__, comprehension[0])
self.assertEqual(__, comprehension[2])
def test_filtering_lists_with_list_comprehensions(self):
feast = ['spam', 'sloths', 'orangutans', 'breakfast cereals',
'fruit bats']
comprehension = [delicacy for delicacy in feast if len(delicacy) > 6]
self.assertEqual(__, len(feast))
self.assertEqual(__, len(comprehension))
def test_unpacking_tuples_in_list_comprehensions(self):
list_of_tuples = [(1, 'lumberjack'), (2, 'inquisition'), (4, 'spam')]
comprehension = [ skit * number for number, skit in list_of_tuples ]
self.assertEqual(__, comprehension[0])
self.assertEqual(__, comprehension[2])
def test_double_list_comprehension(self):
list_of_eggs = ['poached egg', 'fried egg']
list_of_meats = ['lite spam', 'ham spam', 'fried spam']
comprehension = [ '{0} and {1}'.format(egg, meat) for egg in list_of_eggs for meat in list_of_meats]
self.assertEqual(__, comprehension[0])
self.assertEqual(__, len(comprehension))
def test_creating_a_set_with_set_comprehension(self):
comprehension = { x for x in 'aabbbcccc'}
self.assertEqual(__, comprehension) # remember that set members are unique
def test_creating_a_dictionary_with_dictionary_comprehension(self):
dict_of_weapons = {'first': 'fear', 'second': 'surprise',
'third':'ruthless efficiency', 'fourth':'fanatical devotion',
'fifth': None}
dict_comprehension = { k.upper(): weapon for k, weapon in dict_of_weapons.items() if weapon}
self.assertEqual(__, 'first' in dict_comprehension)
self.assertEqual(__, 'FIRST' in dict_comprehension)
self.assertEqual(__, len(dict_of_weapons))
self.assertEqual(__, len(dict_comprehension))