Motivation
---------

When compressing sequences of symbols, it is useful to have many equal symbols follow each other, because then they can be encoded with a run length encoding. For example, RLE encoding of `"aaaabbbbbbbbbbbcccccc"` would give something like `4a 11b 6c`.

(Look [here](http://www.codewars.com/kata/run-length-encoding/) for learning more about the run-length-encoding.)

Of course, RLE is interesting only if the string contains many identical consecutive characters. But what bout human readable text? Here comes the Burrows-Wheeler-Transformation.

Transformation
-------------
There even exists a transformation, which brings equal symbols closer together, it is called the **Burrows-Wheeler-Transformation**. The forward transformation works as follows: Let's say we have a sequence with length n, first write every shift of that string into a *n x n* matrix:
```
Input: "bananabar"

b a n a n a b a r
r b a n a n a b a
a r b a n a n a b
b a r b a n a n a
a b a r b a n a n
n a b a r b a n a
a n a b a r b a n
n a n a b a r b a
a n a n a b a r b
```
Then we sort that matrix by its rows. The output of the transformation then is the **last column** and the **row index** in which the original string is in:
```
               .-.
a b a r b a n a n
a n a b a r b a n
a n a n a b a r b
a r b a n a n a b
b a n a n a b a r <- 4
b a r b a n a n a
n a b a r b a n a
n a n a b a r b a
r b a n a n a b a
               '-'

Output: ("nnbbraaaa", 4)
```

```if:java
To handle the two kinds of output data, we will use the preloaded class `BWT`, whose contract is the following:

    public class BWT {
        
        public String s;
        public int n;
        
        public BWT(String s, int n)
        
        @Override public String  toString()
        @Override public boolean equals(Object o)
        @Override public int     hashCode()
    }

```

Of course we want to restore the original input, therefore you get the following hints:

1. The output contains the last matrix column.
2. The first column can be acquired by sorting the last column.
3. **For every row of the table:** Symbols in the first column follow on symbols in the last column, in the same way they do in the input string.
4. You don't need to reconstruct the whole table to get the input back.

Goal
----

The goal of this Kata is to write both, the `encode` and `decode` functions. Together they should work as the identity function on lists. (*Note:* For the empty input, the row number is ignored.)

Further studies
--------------
You may have noticed that symbols are not always consecutive, but just in proximity, after the transformation. If you're interested in how to deal with that, you should have a look at [this Kata](http://www.codewars.com/kata/move-to-front-encoding/).

Difficulty: MEDIUM
Tags: Data structures

Ad-hoc
Skill types: Data structures

Starter code:
def encode(s):
	

Solutions:
def encode(s):
	lst = sorted((s[i or len(s):] + s[:i or len(s)] for i in reversed(range(len(s)))))
	return (''.join((ss[-1] for ss in lst)), s and lst.index(s) or 0)

def decode(s, n):
	(out, lst) = ([], sorted(((c, i) for (i, c) in enumerate(s))))
	for _ in range(len(s)):
		(c, n) = lst[n]
		out.append(c)
	return ''.join(out)


def encode(s):
	try:
		arr = [s]
		for i in range(1, len(s)):
			arr.append(s[-i:] + s[:-i])
		arr.sort()
		res_str = ''
		for el in arr:
			res_str += el[-1]
		return (res_str, arr.index(s))
	except:
		return (s, len(s))

def decode(s, n):
	try:
		m = [''] * len(s)
		for i in range(len(s)):
			for j in range(len(s)):
				m[j] = s[j] + m[j]
			m.sort()
		return m[n]
	except:
		return ''


def encode(s):
	if not s:
		return ('', 0)
	l = sorted((s[-i:] + s[:-i] for i in range(len(s))))
	return (''.join((x[-1] for x in l)), l.index(s))

def decode(s, n):
	if not s:
		return s
	l = [''] * len(s)
	for _ in range(len(s)):
		l = sorted((s[i] + l[i] for i in range(len(s))))
	return l[n]


from bisect import bisect_left

def encode(s):
	if s == '':
		return ('', 0)
	string_array = list(s)
	matrix = []
	for _ in range(len(s)):
		head = string_array.pop(0)
		string_array.append(head)
		matrix.append(list(string_array))
	matrix.sort()
	lost_col_array = []
	for row in matrix:
		lost_col_array.append(row[-1])
	row_num = bisect_left(matrix, string_array)
	return (''.join(lost_col_array), row_num)

def decode(s, n):
	if s == '':
		return ''
	matrix = []
	for (index, char) in enumerate(s):
		matrix.append([char])
	matrix.sort()
	for _ in range(len(s) - 1):
		for (index, char) in enumerate(s):
			matrix[index].insert(0, char)
		matrix.sort()
	return ''.join(matrix[n])


def encode(s):
	if len(s) <= 1:
		return (s, 0)
	mas = sorted([s[-i:] + s[:-i] for i in range(0, len(s))])
	return (''.join([c[-1] for c in mas]), mas.index(s))

def decode(sn, n):
	if len(sn) <= 1:
		return sn
	table = [''] * len(sn)
	for j in range(len(sn)):
		table = sorted((sn[i] + table[i] for i in range(len(sn))))
	return table[n]


def encode(s):

	def shift(st, l):
		res = list(s)
		for i in range(l):
			res.insert(0, res.pop())
		return res
	matrix = []
	for i in range(len(s)):
		matrix.append(shift(s, i))
	matrix.sort()
	out = []
	number = 0
	for i in range(len(matrix)):
		out.append(matrix[i][-1])
		if matrix[i] == list(s):
			number = i
	return (''.join(out), number)

def decode(string, number):
	if string == '':
		return ''

	def AppenderAndSorter(matrix, arr):
		for i in range(len(arr)):
			matrix[i].insert(0, arr[i])
		matrix.sort()
	matrix = []
	for i in range(0, len(string)):
		matrix.append([string[i]])
	matrix.sort()
	for i in range(1, len(string)):
		AppenderAndSorter(matrix, string)
	out = ''.join(matrix[number])
	return ''.join(out)


def encode(s):
	if not s:
		return ('', 0)
	acc = []
	for i in range(len(s)):
		acc.append(s[-i:] + s[:-i])
	acc = sorted(acc)
	r = []
	for a in acc:
		r.append(a[-1])
	return (''.join(r), acc.index(s))

def decode(s, n):
	if not s:
		return ''
	res = [''] * len(s)
	for _ in range(len(s)):
		u = []
		for i in range(len(s)):
			u.append(s[i] + res[i])
		res = sorted(u)
	return res[n]


def shift(s):
	return sorted([s[-i:] + s[:-i] for i in range(len(s))])

def encode(s):
	if not s:
		return ('', 0)
	return (''.join([x[-1] for x in shift(s)]), shift(s).index(s))

def decode(s, n):
	if not s:
		return ''
	(first, last) = (sorted(s), list(s))
	res = ''
	i = n
	while len(res) < len(s):
		res += first[i]
		i = [k for k in range(len(s)) if last[k] == first[i]][[k for k in range(len(s)) if first[k] == first[i]].index(i)]
	return res


import numpy as np

def encode(s):
	if not s:
		return ('', 0)
	lol = [s[i:] + s[:i] for i in range(0, -len(s), -1)]
	order = np.argsort(lol)
	last_col = ''.join([seq[-1] for seq in [lol[o] for o in order]])
	original_col = np.where(order == 0)[0][0]
	return (last_col, original_col)

def decode(s, n):
	if not s:
		return ''
	lol = sorted(list(s))
	for i in range(1, len(s)):
		lol = sorted([''.join([s[i], lol[i]]) for i in range(0, len(s))])
	return lol[n]


def encode(s):
	if not s:
		return ('', 0)
	list_s = []
	for x in range(len(s)):
		list_s.append(s[x:] + s[:x])
	sort_list_s = sorted(list_s)
	final_word = ''
	for e in sort_list_s:
		final_word += e[-1]
	return (final_word, sort_list_s.index(s))

def decode(s, n):
	s_list = list(s)
	s_list.sort()
	s_list = ''.join(s_list)
	final_list = []
	count = 1
	if not s:
		return s
	else:
		while count < len(s):
			for i in range(len(s)):
				final_list.append(s[i] + s_list[i])
			count += 1
			s_list = sorted(final_list)
			final_list = []
	return s_list[n]