Start learning free

LESSON 386 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v2 — Count Adjacent Runs in Python

Practice

Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.

Each output line is formatted as f"{count:>7} {value}": a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

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

Example:

Input: lines = ["a", "a", "b", "c", "c", "c"]

Output (when printed):
      2 a
      1 b
      3 c

The first run is two "a"s, then a single "b", then three "c"s — three output lines.


Track two pieces of state as you walk the input: prev (the value of the current run) and count (its length). When you see a NEW value or reach the end, "flush" the previous run by appending f"{count:>7} {prev}" and reset.

Don't forget to flush the LAST run after the loop ends — it doesn't get triggered by the "new value" branch.
if count > 0:
    result.append(f"{count:>7} {prev}")


The full solution:
class Solution:
    def uniqCount(self, lines):
        result = []
        count = 0
        prev = None
        for line in lines:
            if count > 0 and line == prev:
                count += 1
            else:
                if count > 0:
                    result.append(f"{count:>7} {prev}")
                prev = line
                count = 1
        if count > 0:
            result.append(f"{count:>7} {prev}")
        return "\n".join(result)

STEP 1 OF 13
    Ctrl + Enter to check

    Uniq V2 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