Start learning free

LESSON 612 OF 673 · PROJECTS: COMMAND-LINE TOOLS

wc with a Mode Flag in Python: Choosing What to Count

Practice Read the full explanation

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

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Wc V4 in Python, explained

    Problem overview

    This version combines the three earlier wc counts behind one method, wc(self, lines, mode). It receives a list of lines and a mode string, and always returns a string:

    • "l" gives the number of lines;
    • "w" gives the number of words;
    • "c" gives the number of characters (the sum of the line lengths, no newlines);
    • "all" gives all three, in that order, separated by tab characters.

    Any other mode, such as "x" or "L", behaves like "all". Modes are case-sensitive. For ["hello", "world"] with mode "all" the result is "2\t2\t10": 2 lines, 2 words, 10 characters. For an empty list, the single modes give "0" and "all" gives "0\t0\t0".

    Approach: count everything, then pick

    The simplest design computes all three numbers first and only then decides what to return. The input is small, the three counts are one line each, and the mode check becomes a plain chain of if statements with no counting logic mixed in.

    The counts are the ones from the previous versions, now written as one-liners:

    • lines: len(lines);
    • words: sum(len(line.split()) for line in lines), since split() with no argument ignores repeated whitespace;
    • characters: sum(len(line) for line in lines).

    The function returns text, never a number, so each count goes through str(). For "all", an f-string builds the combined line, and \t inside it is a tab.

    Step by step

    1. Store the line count in numLines. len of the list is enough, so no loop is needed.
    2. Store the word count in numWords: for each line, take the length of line.split() and add them all with sum.
    3. Store the character count in numChars the same way, using len(line).
    4. Return str(numLines) when mode is "l". The return goes on its own indented line under the if.
    5. Return str(numWords) when mode is "w".
    6. Return str(numChars) when mode is "c".
    7. Finish with the combined string. The last line has no if around it. A return above has already left the function when the mode was "l", "w" or "c", so this line runs for "all" and for every other value.

    The solution in Python

    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}"
    

    The chain uses separate if statements rather than elif. That works because each branch returns, so at most one of them can run. The fall-through at the end is what makes unknown modes behave like "all": there is no else to write and no error to raise.

    In a normal string or f-string, \t is one tab character. Printed in a terminal, the three numbers line up in tab columns; as a Python value it is a string with two tab characters in it.

    Complexity

    Time is O(n) in the total number of characters, because the word count and character count each read every line once. This is true for every mode, since all three counts are computed up front. Extra space is O(1) apart from the short words list that split() builds for one line at a time.

    Edge cases and common mistakes

    • Returning an int. return numLines gives 2, not "2", and a string is expected.
    • Case-sensitive modes. "L" is not "l", so it falls through to the combined result.
    • Counting newlines in "c". The character count is only the sum of the line lengths.
    • Typing spaces instead of \t. The separator must be a real tab character, written \t in the string.

    Testing

    With lines = ["hello", "world"], the five modes give:

    moderesult
    "l""2"
    "w""2"
    "c""10"
    "all""2\t2\t10"
    "x" or "L""2\t2\t10"

    With an empty list, "all" returns "0\t0\t0". With ["a b", "", "c d e"] it returns "3\t5\t9": three lines (the empty one counts as a line), five words, nine characters.

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