Skip to content

Commit 403ac52

Browse files
committed
Add a function to avoid duplication.
1 parent 116b25e commit 403ac52

1 file changed

Lines changed: 29 additions & 39 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.py

Lines changed: 29 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -4,31 +4,14 @@
44
count_lines = "-l" in sys.argv
55
count_words = "-w" in sys.argv
66
count_bytes = "-c" in sys.argv
7+
78
filenames = []
89

910
for argument in sys.argv[1:]:
1011
if not argument.startswith("-"):
1112
filenames.append(argument)
1213

13-
total_lines = 0
14-
total_words = 0
15-
total_bytes = 0
16-
17-
for filename in filenames:
18-
file = open(filename)
19-
20-
line_count = 0
21-
word_count = 0
22-
23-
for line in file:
24-
line_count += 1
25-
word_count += len(line.split())
26-
byte_count = os.path.getsize(filename)
27-
28-
total_lines += line_count
29-
total_words += word_count
30-
total_bytes += byte_count
31-
14+
def format_counts(line_count, word_count, byte_count):
3215
output = []
3316

3417
if count_lines:
@@ -40,7 +23,6 @@
4023
if count_bytes:
4124
output.append(byte_count)
4225

43-
4426
if not count_lines and not count_words and not count_bytes:
4527
output.append(line_count)
4628
output.append(word_count)
@@ -51,27 +33,35 @@
5133
for number in output:
5234
formatted_output.append(f"{number:3}")
5335

54-
print(" ".join(formatted_output), filename)
36+
return " ".join(formatted_output)
5537

56-
if len(filenames) > 1:
57-
total_output = []
38+
total_lines = 0
39+
total_words = 0
40+
total_bytes = 0
5841

59-
if count_lines:
60-
total_output.append(total_lines)
42+
for filename in filenames:
43+
file = open(filename)
6144

62-
if count_words:
63-
total_output.append(total_words)
45+
line_count = 0
46+
word_count = 0
6447

65-
if count_bytes:
66-
total_output.append(total_bytes)
48+
for line in file:
49+
line_count += 1
50+
word_count += len(line.split())
6751

68-
if not count_lines and not count_words and not count_bytes:
69-
total_output.append(total_lines)
70-
total_output.append(total_words)
71-
total_output.append(total_bytes)
72-
73-
formatted_total = []
74-
75-
for number in total_output:
76-
formatted_total.append(f"{number:3}")
77-
print(" ".join(formatted_total), "total")
52+
byte_count = os.path.getsize(filename)
53+
54+
total_lines += line_count
55+
total_words += word_count
56+
total_bytes += byte_count
57+
58+
print(
59+
format_counts(line_count, word_count, byte_count),
60+
filename,
61+
)
62+
63+
if len(filenames) > 1:
64+
print(
65+
format_counts(total_lines, total_words, total_bytes),
66+
"total",
67+
)

0 commit comments

Comments
 (0)