This repository has been archived by the owner on Sep 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
read_util.py
107 lines (94 loc) · 2.54 KB
/
read_util.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
from bisect import insort
def parse_integers(read_file):
for line in read_file:
yield int(line)
def test_parse_integers():
with open('./inputs/test-0I.txt') as given:
assert next(parse_integers(given)) == 35
assert [line for line in parse_integers(given)] == [
20,
15,
25,
47,
40,
62,
55,
65,
95,
102,
117,
150,
182,
127,
219,
299,
277,
309,
576
]
def readlines_batch(read_file, sep = '\n'):
batch = ''
for line in read_file:
if line is sep:
yield batch
batch = ''
else:
batch += line
yield batch
def test_readlines_batch():
with open('./inputs/test-0F.txt') as given:
assert next(readlines_batch(given)) == 'abc\n', "Cannot read single line"
assert next(readlines_batch(given)) == 'a\nb\nc\n', "Cannot collect multiple lines"
assert [batch for batch in readlines_batch(given)] == ['ab\nac\n', 'a\na\na\na\n', 'b'], "Cannot be comprehended into a list"
def readlines_sort(read_file):
sorted = []
for line in read_file:
insort(sorted, line)
return sorted
def test_readlines_sort():
with open('./inputs/test-0J.txt') as given:
assert readlines_sort(given) == [
'1\n',
'10\n',
'11\n',
'12\n',
'15\n',
'16\n',
'19\n',
'4',
'5\n',
'6\n',
'7\n'
], 'Cannot sort strings'
given.seek(0)
assert readlines_sort(parse_integers(given)) == [
1,
4,
5,
6,
7,
10,
11,
12,
15,
16,
19
], 'Cannot sort integers'
def strip_lines(read_file):
for line in read_file:
yield line.strip()
def test_strip_lines():
with open('./inputs/test-0C.txt') as given:
assert next(strip_lines(given)) == '..##.......', "Cannot strip new-lines"
assert [line for line in strip_lines(given)] == [
'#...#...#..',
'.#....#..#.',
'..#.#...#.#',
'.#...##..#.',
'..#.##.....',
'.#.#.#....#',
'.#........#',
'#.##...#...',
'#...##....#',
'.#..#...#.#'
], "Cannot be comrehended into a list"