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>Came up with this quickly, maybe there's room for optimization (for example, if the strings are too large and there's enough memory, it would be better to use a set of the letters of the original string for look ups rather than the list of characters itself). But, does the job fairly efficiently:</p>

<pre><code>text = 'lelamfaf'
counts = {s:text.count(s) for s in text}

char_lst = []
for l in text:
    if l not in char_lst:
        char_lst.append(l)
        if counts[l] &gt; 1:
            char_lst.append(str(counts[l]))

encoded_str = ''.join(char_lst)
print encoded_str
</code></pre>

python