Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions projects/006-run-length-decoding/python/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'''
Run-length encoding is a simple data compression technique that can be effective
when repeated values occur at adjacent positions within a list.

Compression is achieved by replacing groups of repeated values with one copy of the value,
followed by the number of times that it should be repeated.
For example, the list
`["A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B","B","A","A","A","A","A","A","B"]`
would be compressed as `["A",12,"B",4,"A",6,"B",1]`.

Decompression is performed by replicating each value in the list the number of times indicated.

Write a recursive function that decompresses a run-length encoded list.
Your recursive function will take a run-length compressed list as its only argument.
It will return the decompressed list as its only result.

Create a main program that displays a run-length encoded list and the result of decoding it.
'''

def decompression(array):
if len(array) == 0:
return []

value = array[0]
count = array[1]
finalvalue = [value] * count + decompression(array[2:])

return finalvalue

def main():
array = ["A", 12, "B", 4, "A", 6, "B", 1]
print(decompression(array))

if __name__ == "__main__":
main()
30 changes: 30 additions & 0 deletions projects/007-run-length-encoding/python/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'''
Write a recursive function that implements the run-length compression technique described in Run-Lenght Decoding Exercise.

Your function will take a list or a string as its only argu- ment. It should return the run-length compressed list as its only result.

Include a main program that reads a string from the user, compresses it, and displays the run-length
encoded result.

Hint: You may want to include a loop inside the body of your recursive function.
'''

def compression(array):
if len(array) == 0:
return []

value = array[0]
count = 1

while count < len(array) and array[count] == value:
count += 1

return [value, count] + compression(array[count:])

def main():
array = ["A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "A", "A", "A", "A", "A", "A", "B"]
compressed = compression(array)
print(compressed)

if __name__ == "__main__":
main()