Unary coding in Python

Last Updated : 13 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • For encoding: take an empty list then append N times 1 and 0 in the last then convert it into string and print the result.
  • For decoding: Take a given string and count number of 1's into it and then print the result.

Example 1: Unary representation of a natural number.

Python3
# 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.

Python3
# 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)


Next Article
Practice Tags :

Similar Reads