easy +10 pts

Snake case converter

Convert a given string into snake_case with a precise algorithm.

Write a function `to_snake_case(s: str) -> str` that converts an input string to snake_case. The conversion rules are: 1. Replace all spaces and hyphens (`-`) with underscores (`_`). 2. Insert an underscore between a lowercase/digit and an uppercase letter (e.g., `camelCase` → `camel_Case`). 3. Convert all letters to lowercase. 4. Ensure there are no leading or trailing underscores, and no consecutive underscores (collapse multiple underscores into one). Examples: - `"hello world"` → `"hello_world"` - `"camelCase"` → `"camel_case"` - `"foo-bar_baz"` → `"foo_bar_baz"` - `"Hello World"` → `"hello_world"` - `"getHTTPResponse"` → `"get_http_response"` (see rule 2: insert underscore before an uppercase that follows a lowercase/digit, and also before an uppercase that follows another uppercase? The rule is: an underscore is inserted between a lowercase/digit and an uppercase (`aA` → `a_A`) AND between an uppercase and an uppercase if the previous character is also uppercase? Actually, to handle sequences of uppercase letters correctly, use the common rule: insert underscore before an uppercase if the previous character is lowercase or digit, OR if the previous character is uppercase and the next character is lowercase. This matches converting `getHTTPResponse` to `get_http_response`.)

Constraints

Input string length between 0 and 1000. Characters are printable ASCII. The function must run in O(n) time.

Example

>>> to_snake_case("hello world")
'hello_world'
>>> to_snake_case("camelCase")
'camel_case'
>>> to_snake_case("foo-bar_baz")
'foo_bar_baz'
>>> to_snake_case("Hello World")
'hello_world'
>>> to_snake_case("getHTTPResponse")
'get_http_response'
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

First handle separators (spaces, hyphens) by replacing with underscores.
Process the string character by character to insert underscores before uppercase letters when needed.
After constructing, normalize by lowercase and collapsing multiple underscores.
Finally strip leading and trailing underscores.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.