Skip to content

Commit dfaa6ea

Browse files
committed
update code in wc.py to remove duplication
1 parent ac8c2de commit dfaa6ea

File tree

1 file changed

+19
-20
lines changed
  • implement-shell-tools/wc

1 file changed

+19
-20
lines changed

implement-shell-tools/wc/wc.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,22 @@
1919

2020
multiple_files = len(args.files) > 1 # to store totals if muliple files
2121

22+
# Helper function to print counts in wc style
23+
def print_counts(lines, words, bytes_, filename):
24+
output = []
25+
if args.l:
26+
output.append(str(lines))
27+
if args.w:
28+
output.append(str(words))
29+
if args.c:
30+
output.append(str(bytes_))
31+
32+
# If no flags are given, print all three counts
33+
if not output:
34+
output = [f"{lines:>7}", f"{words:>7}", f"{bytes_:>7}"]
35+
36+
print(" ".join(output), filename)
37+
2238
for file in args.files:
2339
if not os.path.isfile(file):
2440
print(f"wc: {file}: No such file or directory")
@@ -31,33 +47,16 @@
3147
tbytes = os.path.getsize(file)
3248

3349

34-
3550
total_lines += lines
3651
total_words += words
3752
total_bytes += tbytes
3853

39-
if args.l:
40-
print(f"{lines:} {file}")
41-
42-
elif args.w:
43-
print(f"{words:} {file}")
44-
45-
elif args.c:
46-
print(f"{tbytes:} {file}")
47-
48-
else:
49-
print(f"{lines:>3} {words:>3} {tbytes:>3} {file}") # to print data from per file
54+
# Print counts per file
55+
print_counts(lines, words, tbytes, file)
5056

5157
#to print total output
5258
if multiple_files:
53-
if args.l:
54-
print(f"{total_lines:} total")
55-
56-
elif args.w:
57-
print(f"{total_words:} total")
58-
59-
else:
60-
print(f"{total_lines:>3} {total_words:>3} {total_bytes:>3} total")
59+
print_counts(total_lines, total_words, total_bytes, "total")
6160

6261

6362

0 commit comments

Comments
 (0)