tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
29
Task/Run-length-encoding/Python/run-length-encoding-1.py
Normal file
29
Task/Run-length-encoding/Python/run-length-encoding-1.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
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
|
||||
|
||||
#Method call
|
||||
encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa")
|
||||
decode([('a', 5), ('h', 6), ('m', 7), ('u', 1), ('i', 7), ('a', 6)])
|
||||
9
Task/Run-length-encoding/Python/run-length-encoding-2.py
Normal file
9
Task/Run-length-encoding/Python/run-length-encoding-2.py
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
from itertools import groupby
|
||||
def encode(input_string):
|
||||
return [(len(list(g)), k) for k,g in groupby(input_string)]
|
||||
|
||||
def decode(lst):
|
||||
return ''.join(c * n for n,c in lst)
|
||||
|
||||
encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa")
|
||||
decode([(5, 'a'), (6, 'h'), (7, 'm'), (1, 'u'), (7, 'i'), (6, 'a')])
|
||||
22
Task/Run-length-encoding/Python/run-length-encoding-3.py
Normal file
22
Task/Run-length-encoding/Python/run-length-encoding-3.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
from re import sub
|
||||
|
||||
def encode(text):
|
||||
'''
|
||||
Doctest:
|
||||
>>> encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW')
|
||||
'12W1B12W3B24W1B14W'
|
||||
'''
|
||||
return sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1),
|
||||
text)
|
||||
|
||||
def decode(text):
|
||||
'''
|
||||
Doctest:
|
||||
>>> decode('12W1B12W3B24W1B14W')
|
||||
'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'
|
||||
'''
|
||||
return sub(r'(\d+)(\D)', lambda m: m.group(2) * int(m.group(1)),
|
||||
text)
|
||||
|
||||
textin = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
|
||||
assert decode(encode(textin)) == textin
|
||||
Loading…
Add table
Add a link
Reference in a new issue