Run Length Encoding in python
<p>i got homework to do "Run Length Encoding" in python and i wrote a code but it is print somthing else that i dont want. it prints just the string(just like he was written) but i want that it prints the string and if threre are any characthers more than one time in this string it will print the character just one time and near it the number of time that she appeard in the string. how can i do this? </p>

<p>For example:</p>

<p>the string : 'lelamfaf"</p>

<p>the result : 'l2ea2mf2</p>

<pre><code>def encode(input_string):
        count = 1
        prev = ''
        lst = []
        for character in input_string:
            if character != prev:
                if prev:
                    entry = (prev, count)
                    lst.append(entry)
                    #print lst
                count = 1
                prev = character
            else:
                count += 1
        else:
            entry = (character, count)
            lst.append(entry)
        return lst    


def decode(lst):
        q = ""
        for character, count in lst:
            q += character * count
        return q    


def main():
        s = 'emanuelshmuel'
        print decode(encode(s))    

if __name__ == "__main__":
        main()
</code></pre>

<p>Three remarks:</p>

<ol>
<li>You should use the existing method <code>str.count</code> for the <code>encode</code> function.</li>
<li>The <code>decode</code> function will print <code>count</code> times a character, not the character and its counter.</li>
<li>Actually the <code>decode(encode(string))</code> combination is a coding function since you do not retrieve the starting string from the encoding result.</li>
</ol>

<p>Here is a working code:</p>

<pre><code>def encode(input_string):
    characters = []
    result = ''
    for character in input_string:
        # End loop if all characters were counted
        if set(characters) == set(input_string):
            break
        if character not in characters:
            characters.append(character)
            count = input_string.count(character)
            result += character
            if count &gt; 1:
                result += str(count)
    return result

def main():
        s = 'emanuelshmuel'
        print encode(s)
        assert(encode(s) == 'e3m2anu2l2sh')
        s = 'lelamfaf'
        print encode(s)
        assert(encode(s) == 'l2ea2mf2')

if __name__ == "__main__":
        main()
</code></pre>

python