w3resource

Python: Create a list reflecting the modified run-length encoding

Python List: Exercise - 76 with Solution

Write a Python program to create a list reflecting the modified run-length encoding from a given list of integers or a given list of characters.

Sample Solution:

Python Code:

from itertools import groupby
def modified_encode(alist):
        def ctr_ele(el):
            if len(el)>1: return [len(el), el[0]]
            else: return el[0]
        return [ctr_ele(list(group)) for key, group in groupby(alist)]

n_list = [1,1,2,3,4,4,5, 1]
print("Original list:") 
print(n_list)
print("\nList reflecting the modified run-length encoding from the said list:")
print(modified_encode(n_list))

n_list = 'aabcddddadnss'
print("\nOriginal String:") 
print(n_list)
print("\nList reflecting the modified run-length encoding from the said string:")
print(modified_encode(n_list))


Sample Output:

Original list:
[1, 1, 2, 3, 4, 4, 5, 1]
List reflecting the modified run-length encoding from the said list:
[[2, 1], 2, 3, [2, 4], 5, 1]

Original String:
aabcddddadnss

List reflecting the modified run-length encoding from the said string:
[[2, 'a'], 'b', 'c', [4, 'd'], 'a', 'd', 'n', [2, 's']]

Flowchart:

Flowchart: Create a list reflecting the modified run-length encoding.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to create a list reflecting the run-length encoding from a given list of integers or a given list of characters.
Next: Write a Python program to decode a run-length encoded given list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Decapitalizes the first letter of a string:

Example:

def tips_decapitalize(s, upper_rest=False):
  return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])
print(tips_decapitalize('PythonTips'))
print(tips_decapitalize('PythonTips', True)) 

Output:

pythonTips
pYTHONTIPS

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook