arithmetic coding help

This is the place for queries that don't fit in any of the other categories.

arithmetic coding help

Postby diable.sombre » Sat Apr 19, 2014 9:19 pm

Hello everyone, I am new to this forum and new to python as well
I typed this code to work as an arithmetic encoder (data compression), but I don't know what is wrong, it always gives zeros for 'high' and 'low'
here is a link illustrating the algorithm: http://cis.cs.technion.ac.il/Done_Proje ... ode19.html

and here is my code:
Code: Select all
import math
text=raw_input("Type text here : ")
letters=list(text)
length=len(letters)
def prob(a):
    return float(letters.count(a))/length

prob_list=[]

for a in letters:
    prob_list=prob_list+[prob(a)]
print prob_list   

def high_range(n):
    del prob_list[n+1:]
    return math.fsum(prob_list)

def low_range(n):
    del prob_list[n:]
    return math.fsum(prob_list)


low = 0
high = 1
for n in range(0,length):
    code_range = high - low
    high = low + code_range * high_range(n)
    low = low + code_range * low_range(n)   

print 'high: ' , high
print 'low: ', low
Last edited by stranac on Sat Apr 19, 2014 10:46 pm, edited 1 time in total.
Reason: First post lock.
diable.sombre
 
Posts: 1
Joined: Sat Apr 19, 2014 9:14 pm

Re: arithmetic coding help

Postby micseydel » Mon Apr 21, 2014 11:33 pm

Could you provide some sample desired input and output, along with the current output for that input?

By the way, your code is very difficult to follow. Functions ideally do not have side effects, which you cause by modifying global variables. Using function parameters and return values tends to be much more clear. If you re-write your code to define several functions upfront, then have the logic which uses them (rather than mixing these two things) we'll have an easier time giving you feedback.

Also, the following
Code: Select all
prob_list=prob_list+[prob(a)]

would be better written as
Code: Select all
prob_list.append(prob(a))

and everything you do with your letters list, you can do directly with the string that it was formed from. No need to create the list.
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 1115
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 3 guests