Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Count Characters Words Lines

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Count Characters Words Lines. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Yugabyte tooling may need lightweight statistics for text returned by command-line diagnostics. Given a string of text, count its characters, words, and lines in a single pass.

A character is every Unicode code point in the input, including spaces, tabs, and newline characters. A word is a maximal consecutive sequence of non-whitespace characters. Whitespace is determined by Python's str.isspace() behavior. Lines are separated by the newline character . An empty string contains zero lines; otherwise, its line count is one plus the number of characters.

Formal Specification

Implement count_text_stats(text), where text is a Python string. Return a dictionary with exactly these keys:

  • characters: total number of characters
  • words: number of whitespace-delimited words
  • lines: number of lines

Constraints

  • 0 <= len(text) <= 10^6
  • Characters may include spaces, tabs, Unicode whitespace, and newline characters
  • A word is a maximal run of non-whitespace characters
  • Only the newline character \n separates lines
  • Do not use regular expressions or split the entire string into a list

Function Signature

def count_text_stats(text):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output