1414
1515from __future__ import annotations
1616
17+ from collections .abc import Callable
1718from math import log
1819
1920
@@ -50,46 +51,47 @@ def _unary(x: int) -> str:
5051 x: A positive integer.
5152
5253 Returns:
53- A unary-coded string (x-1 ones followed by a zero ).
54+ A unary-coded string (x-1 zeros followed by a one ).
5455 """
55- return (x - 1 ) * "1 " + "0 "
56+ return (x - 1 ) * "0 " + "1 "
5657
5758
5859def _elias_generic (
59- length_encoding : callable ,
60+ length_encoding : Callable [[ int ], str ] ,
6061 x : int ,
6162) -> str :
6263 """Generic Elias encoding using a pluggable length-encoding function.
6364
6465 Args:
6566 length_encoding: A function to encode the length prefix.
66- x: A non-negative integer to encode.
67+ x: A positive integer to encode.
6768
6869 Returns:
6970 The Elias-coded bit string.
7071 """
71- if x = = 0 :
72- return "0"
72+ if x < = 0 :
73+ raise ValueError ( "Elias coding is defined only for positive integers" )
7374
7475 first_part = 1 + int (_log2 (x ))
7576 remainder = x - 2 ** int (_log2 (x ))
7677 bit_count = int (_log2 (x ))
78+ suffix = _binary (remainder , bit_count ) if bit_count else ""
7779
78- return length_encoding (first_part ) + _binary ( remainder , bit_count )
80+ return length_encoding (first_part ) + suffix
7981
8082
8183def elias_gamma (x : int ) -> str :
8284 """Encode a positive integer using Elias gamma coding.
8385
8486 Args:
85- x: A non-negative integer.
87+ x: A positive integer.
8688
8789 Returns:
8890 The Elias gamma coded bit string.
8991
9092 Examples:
9193 >>> elias_gamma(1)
92- '0 '
94+ '1 '
9395 >>> elias_gamma(5)
9496 '00101'
9597 """
@@ -100,14 +102,14 @@ def elias_delta(x: int) -> str:
100102 """Encode a positive integer using Elias delta coding.
101103
102104 Args:
103- x: A non-negative integer.
105+ x: A positive integer.
104106
105107 Returns:
106108 The Elias delta coded bit string.
107109
108110 Examples:
109111 >>> elias_delta(1)
110- '0 '
112+ '1 '
111113 >>> elias_delta(5)
112114 '01101'
113115 """
0 commit comments