gustavo.andriotti
BAN USERIn python:
def revert_by_n(in_lst, n):
result = []
ndx = 0
lst_ndx = min(len(in_lst), ndx + n)
while ndx < len(in_lst):
for i in xrange(lst_ndx, ndx, -1):
result.append(in_lst[i - 1])
if lst_ndx >= len(in_lst) + 1:
break
ndx += n
lst_ndx = min(len(in_lst), lst_ndx + n)
return result
Test:
tst = [
([1,2,3,4,5,6,7,8,9], 3, [3,2,1,6,5,4,9,8,7]),
([1,2,3,4,5,6,7,8], 3, [3,2,1,6,5,4,8,7]),
([1, 2, 3], 2, [2, 1, 3]),
([1, 2, 3], 4, [3, 2, 1]),
([1, 2, 3], 1, [1, 2, 3]),
]
for in_lst, n, exp in tst:
res = revert_by_n(in_lst, n)
assert res == exp, 'in: {}, n: {} -> {} != {}'.format(in_lst, n, res, exp)
print '{}: {} -> {}'.format(in_lst, n, res)
In python:
def encode_str(in_str):
result = ''
ndx = 0
while ndx < len(in_str):
if ndx + 1 > len(in_str):
result += in_str[ndx]
else:
count = 1
while len(in_str) > (ndx + 1) and in_str[ndx + 1] == in_str[ndx]:
count +=1
ndx += 1
if count > 1:
result += '{}x{}'.format(count, in_str[ndx])
else:
if in_str[ndx] == 'x':
result += '1xx'
else:
result += in_str[ndx]
ndx += 1
return result
Testing:
str1 = 'p14akkkkkkkkpq'
exp1 = 'p14a8xkpq'
str2 = 'x'
exp2 = '1xx'
str3 = '8x'
exp3 = '81xx'
str4 = '8'
exp4 = '8'
tests = [(str1, exp1), (str2, exp2), (str3, exp3), (str4, exp4)]
for s,e in tests:
r = encode_str(s)
assert e == r, '{} -> {} != {}'.format(s, r, e)
print r
In python:
Test:
- gustavo.andriotti May 23, 2016