Text compressor doesn't compress the intended way
<p>For a school assignment I have to write a python program to compress a text and write a new file with the compressed text, conserving the original. For example, the text "heeeeeeellllooo" to "he7l4o3". So each character that is iterated subsequently has to be replaced by the character and has to be directly followed by the number of iterations, except if the number of iterations is 1 of course. However, in stead of getting the compressed text "he7l4o3", I get "hee2ll2oo2."</p>

<p>What am I doing wrong?</p>

<p>The code:</p>

<pre><code>inp =  open("hello.txt", "r")
out = open("compr.txt", "w")
kar=inp.read(1)
prevkar=''

def iterations(a,b):
    while a==b:
        re=1
        re+=1
        b = a
        a = inp.read(1)
    out.write(b + str(re))
    return

def no_iteration(a):
    out.write(a)
    return

while kar:
    if kar==prevkar:
        iterations(kar, prevkar)
        prevkar=kar
        kar=inp.read(1)
    else:
        no_iteration(kar)
        prevkar=kar
        kar=inp.read(1)

inp.close()
out.close()
</code></pre>

<p>Here's a correct solution:</p>

<pre><code>inp =  open("hello.txt", "r")
out = open("compr.txt", "w")
kar=inp.read(1)
prevkar=''

def iterations(a,b):
    re = 1
    while a==b:
        re+=1
        b = a
        a = inp.read(1)
    out.write(str(re))
    return a

def no_iteration(a):
    out.write(a)
    return

while kar:
    if kar==prevkar:
        prevkar=kar
        kar = iterations(kar, prevkar)
    else:
        no_iteration(kar)
        prevkar=kar
        kar=inp.read(1)

inp.close()
out.close()
</code></pre>

<p>the problem with wrong numbers was because you set <code>re</code> to be 1 every time you looped through letters, also <code>iterations(a, b)</code> did one <code>inp.read(1)</code> but did nothing with it, making <code>while kar:</code> loop skip one letter after each call to <code>iterations(a,b)</code></p>

python python-2.7 compression