Open In App

Unary coding in Python

Unary code also sometimes called thermometer code is a type of entropy encoding. It is a lossless data compression technique with application in Golomb codes.

Unary representation of a natural number n is n ones followed by a zero. For example, unary code for 6 will be 6 ones followed by a zero which is 1111110



Example:

Input: 5
Output: 111110
result has 5 ones followed by a 0 

Input: 1
Output: 10
result has 1 one followed by a 0

Approach:



Example 1: Unary representation of a natural number.




# Unary code encoding
N = 8
A = []
 
for i in range(N):
    A.append(1)
     
A.append(0)
 
B = [str(k) for k in A]
 
C = "".join(B)
 
print("Unary code for", N,
      'is', C)

Output:

Unary code for 8 is 111111110

Time Complexity: O(n)
Auxiliary Space: O(n)

Example 2: Decimal representation of an unary code.




# Unary code decoding
 
code =  "111111110"
count = 0
 
for i in code:
    if i == "1":
        count += 1
         
print("decoded number is :", count)

Output:

decoded number is : 8

Time Complexity: O(n)
Auxiliary Space: O(1)


Article Tags :