Predict the output
Does the round-trip property hold for 500 random strings of a and b?
import random
def encode(s: str) -> str:
out, i = [], 0
while i < len(s):
j = i
while j < len(s) and s[j] == s[i]:
j += 1
out.append(f"{j - i}{s[i]}")
i = j
return "".join(out)
def decode(s: str) -> str:
out, num = [], ""
for ch in s:
if ch.isdigit():
num += ch
else:
out.append(ch * int(num))
num = ""
return "".join(out)
rng = random.Random(1)
samples = [
"".join(rng.choice("ab") for _ in range(rng.randrange(30)))
for _ in range(500)
]
ok = all(decode(encode(t)) == t for t in samples)
print(ok)Hint 1 of 1
What does a seeded Random do?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A True
Correct. Run-length encoding then decoding returns the original for these inputs.
A property test checks a rule over many generated inputs instead of a few examples. decode(encode(s)) == s holds for all 500 seeded strings, including the empty one.
Why not the others?
- B
False. Every run is encoded with its count and decoded back. - C A ValueError on the empty string. encode('') returns '' and decode('') returns ''.
- D It depends on the run. The generator is seeded with 1.