filmov
tv
Run-Length Encode Numeric String – Count Consecutive Digits #RunLengthEncoding #Python

Показать описание
Perform run-length encoding on a numeric string by collapsing each maximal run of the same digit into a pair (count, digit). Read the input string S consisting solely of digits 0–9. Traverse S once, tracking consecutive identical characters. Each time the current run ends (or at the end of the string), output a token formatted as (v count v, v digit v). Separate tokens by a single space.
Key Steps:
Initialize prev = S[0], count = 1.
Iterate over S[1:]:
If ch == prev, increment count.
Otherwise, emit the token for (count, prev), then reset prev = ch, count = 1.
Emit the final run after the loop.
Print all tokens joined by spaces.
This runs in O(n) time, O(1) extra space (excluding output). No regex, no external libraries—just straightforward iteration.
Long Version:
# Read input string S
S = input().strip()
# Edge case: empty string
if not S:
print()
else:
prev = S[0]
count = 1
tokens = []
# Process from the second character onward
for ch in S[1:]:
if ch == prev:
count += 1
else:
# End of current run: record and reset
prev = ch
count = 1
# Emit the final run
# Print tokens separated by spaces
print(" ".join(tokens))
Compact One-Liner
import itertools
print(" ".join(
f"({sum(1 for _ in group)}, {digit})"
))
Key Steps:
Initialize prev = S[0], count = 1.
Iterate over S[1:]:
If ch == prev, increment count.
Otherwise, emit the token for (count, prev), then reset prev = ch, count = 1.
Emit the final run after the loop.
Print all tokens joined by spaces.
This runs in O(n) time, O(1) extra space (excluding output). No regex, no external libraries—just straightforward iteration.
Long Version:
# Read input string S
S = input().strip()
# Edge case: empty string
if not S:
print()
else:
prev = S[0]
count = 1
tokens = []
# Process from the second character onward
for ch in S[1:]:
if ch == prev:
count += 1
else:
# End of current run: record and reset
prev = ch
count = 1
# Emit the final run
# Print tokens separated by spaces
print(" ".join(tokens))
Compact One-Liner
import itertools
print(" ".join(
f"({sum(1 for _ in group)}, {digit})"
))