Open the context
Choose the project folder and name the files or behavior involved.
Assign canonical binary prefix codes from symbol lengths between 1 and 16 for at most 256 symbols. Check empty and incomplete tables, sort equal lengths by the original Unicode strings and reject oversubscribed or invalid lengths without normalizing symbols.
Choose the project folder and name the files or behavior involved.
Describe the input, expected output and boundaries that must stay intact.
Review the proposed edits and any commands before relying on their result.
Compare actual behavior with the expected result. If a check fails, investigate it before applying more changes.
def canonical_codes(lengths):
if type(lengths) is not dict or len(lengths) > 256:
raise ValueError("codes.input")
if any(type(s) is not str or not s or type(n) is not int or
not 1 <= n <= 16 for s,n in lengths.items()):
raise ValueError("codes.length")
result, code, previous = {}, 0, 0
for symbol, length in sorted(lengths.items(), key=lambda p:(p[1],p[0])):
code <<= length-previous
if code >= 1 << length:
raise ValueError("codes.oversubscribed")
result[symbol] = format(code, f"0{length}b")
code += 1
previous = length
return resultThe example is a starting point for a real project, not a claim that generated code is already tested. Adjust paths, dependencies and expected behavior to match your application.