Start learning free

LESSON 380 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: wc v4 — Mode Flag in Python

Practice

Combine the previous three versions of wc. Given a list of lines and a mode flag, return the requested count(s) as a string. This is our own simplified interface, not the real wc flags: the real tool combines flags (such as -lw) and pads its columns with spaces.

Function signature:

def wc(self, lines: List[str], mode: str) -> str:

Mode values:

  • "l" → line count, as a string.
  • "w" → word count (whitespace-separated tokens), as a string.
  • "c" → character count (lines only, no separating newlines), as a string.
  • "all" → lines, words, chars (in that order) joined with a tab character: f"{lines}\t{words}\t{chars}".

The "c" count is the one from v3 (the sum of the line lengths, no newlines). Any other mode value, for example "x" or "L" (modes are case-sensitive), gives the same result as "all". For an empty list, "l", "w" and "c" give "0" and "all" gives "0<TAB>0<TAB>0". The input is plain ASCII text.

Example:

Input: lines = ["hello", "world"], mode = "all"

Output: "2\t2\t10"

2 lines, 2 words (one per line), 10 characters total.


Compute all three counts upfront — even if you only return one. Then a simple chain of if statements selects which count(s) to return.

The function always returns a string — so str(numLines) for the single-mode cases, and an f-string for "all".
numLines = len(lines)
numWords = sum(len(line.split()) for line in lines)
numChars = sum(len(line) for line in lines)


The full solution:
class Solution:
    def wc(self, lines, mode):
        numLines = len(lines)
        numWords = sum(len(line.split()) for line in lines)
        numChars = sum(len(line) for line in lines)
        if mode == "l":
            return str(numLines)
        if mode == "w":
            return str(numWords)
        if mode == "c":
            return str(numChars)
        return f"{numLines}\t{numWords}\t{numChars}"

STEP 1 OF 7
    Ctrl + Enter to check

    Wc V4 in Python

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free