Advertisement
Guest User

Arithmetc

a guest
Apr 7th, 2020
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. from fractions import Fraction
  2.  
  3. def CalFreq(string):
  4.     freq = {}
  5.     prob = {}
  6.     #check evey characters' frequency in the string
  7.     for char in string:
  8.         #if this character has already in the dict, then the frequecny add one
  9.         if char in freq:    
  10.             freq[char] += 1
  11.         #else, this character's frequency = 1
  12.         else:  
  13.             freq[char] = 1
  14.     #sort them in the desending order, reverse=True means desending order
  15.     freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
  16.  
  17.     temp = freq
  18.     sum = 0
  19.  
  20.     for i in range(len(temp)):
  21.         prob[temp[i][0]] = (temp[i][1], sum/len(string), (sum+temp[i][1])/len(string))
  22.         sum = sum + temp[i][1]
  23.     print(prob)
  24.     #prob{} is to record all the upper-bound and lower-bound for every character
  25.     return prob
  26.  
  27. def Arithmeticencoding(probability, string):
  28.     Range = 1
  29.     lower = 0
  30.     upper = 1
  31.  
  32.     for i in range(len(string)):
  33.         #print(probability[text[i]])
  34.         lower = lower + Range * probability[string[i]][1]
  35.         #print(lower)
  36.         Range = Range * (probability[string[i]][2]-probability[string[i]][1])
  37.         upper = lower + Range
  38.         #print(upper)
  39.    
  40.     return lower, upper
  41.  
  42. if __name__ == '__main__':
  43.     #input string
  44.     string = input("Enter a sequence to encode: ")
  45.    
  46.     #calculate every characters' frequency and probability
  47.     char_freq = CalFreq(string)
  48.  
  49.     #Do the Arithmetc Encoding
  50.     lower, upper = Arithmeticencoding(char_freq, string)
  51.     print("Arithmetic Encoding final tag: ")
  52.     print((lower+upper)/2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement