Skip to content

Commit 6da34b1

Browse files
committed
Merge pull request gregmalcolm#93 from knservis/Line_count_simplify
Simplify line counting
2 parents 075dfd4 + cceafc9 commit 6da34b1

File tree

2 files changed

+6
-24
lines changed

2 files changed

+6
-24
lines changed

python2/koans/about_with_statements.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,7 @@ def count_lines(self, file_name):
1515
try:
1616
f = open(file_name)
1717
try:
18-
count = 0
19-
for line in f.readlines():
20-
count += 1
21-
return count
18+
return len(f.readlines())
2219
finally:
2320
f.close()
2421
except IOError:
@@ -86,10 +83,7 @@ def __exit__(self, cls, value, tb):
8683

8784
def count_lines2(self, file_name):
8885
with self.FileContextManager(file_name) as f:
89-
count = 0
90-
for line in f.readlines():
91-
count += 1
92-
return count
86+
return len(f.readlines())
9387

9488
def test_counting_lines2(self):
9589
self.assertEqual(__, self.count_lines2("example_file.txt"))
@@ -108,10 +102,7 @@ def test_finding_lines2(self):
108102

109103
def count_lines3(self, file_name):
110104
with open(file_name) as f:
111-
count = 0
112-
for line in f.readlines():
113-
count += 1
114-
return count
105+
return len(f.readlines())
115106

116107
def test_open_already_has_its_own_built_in_context_manager(self):
117108
self.assertEqual(__, self.count_lines3("example_file.txt"))

python3/koans/about_with_statements.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ def count_lines(self, file_name):
1414
try:
1515
file = open(file_name)
1616
try:
17-
count = 0
18-
for line in file.readlines():
19-
count += 1
20-
return count
17+
return len(file.readlines())
2118
finally:
2219
file.close()
2320
except IOError:
@@ -85,10 +82,7 @@ def __exit__(self, cls, value, tb):
8582

8683
def count_lines2(self, file_name):
8784
with self.FileContextManager(file_name) as file:
88-
count = 0
89-
for line in file.readlines():
90-
count += 1
91-
return count
85+
return len(file.readlines())
9286

9387
def test_counting_lines2(self):
9488
self.assertEqual(__, self.count_lines2("example_file.txt"))
@@ -107,10 +101,7 @@ def test_finding_lines2(self):
107101

108102
def count_lines3(self, file_name):
109103
with open(file_name) as file:
110-
count = 0
111-
for line in file.readlines():
112-
count += 1
113-
return count
104+
return len(file.readlines())
114105

115106
def test_open_already_has_its_own_built_in_context_manager(self):
116107
self.assertEqual(__, self.count_lines3("example_file.txt"))

0 commit comments

Comments
 (0)