Don't Drink the Water

Given a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom.

```
======================
|   Density Chart    |
======================
| Honey   | H | 1.36 |
| Water   | W | 1.00 |
| Alcohol | A | 0.87 |
| Oil     | O | 0.80 |
----------------------

[                            [
 ['H', 'H', 'W', 'O'],        ['O','O','O','O']
 ['W', 'W', 'O', 'W'],  =>    ['W','W','W','W']
 ['H', 'H', 'O', 'O']         ['H','H','H','H']
 ]                           ]
 
 ```
 
 The glass representation may be larger or smaller. If a liquid doesn't fill a row, it floats to the top and to the left.

Source: codewars | Difficulty: EASY
Tags: Sorting

Data structures

Starter code: def separate_liquids(glass):
	

Solutions:
DENSITY = {'H': 1.36, 'W': 1, 'A': 0.87, 'O': 0.8}

def separate_liquids(glass):
	if not glass:
		return []
	column = len(glass[0])
	liquids = sorted((b for a in glass for b in a), key=lambda c: DENSITY[c])
	return [liquids[d:d + column] for d in range(0, len(liquids), column)]


def separate_liquids(glass):
	chain = sorted(sum(glass, []), key='OAWH'.index)
	return [chain[len(level) * i:][:len(level)] for (i, level) in enumerate(glass)]


s = '| Honey   | H | 1.36 |\n| Water   | W | 1.00 |\n| Alcohol | A | 0.87 |\n| Oil     | O | 0.80 |'

def separate_liquids(glass):
	d = {}
	for x in s.split('\n'):
		res = x.split('|')
		(a, b) = [c.strip(' ') for (i, c) in enumerate(res) if i in (2, 3)]
		d[a] = float(b)
	l = []
	for x in glass:
		l.extend(x)
	result = iter(sorted(l, key=lambda x: d[x]))
	for x in range(len(glass)):
		for i in range(len(glass[-1])):
			glass[x][i] = next(result)
	return glass


def separate_liquids(glass):
	chain = sorted(sum(glass, []), key='HWAO'.index)
	return [[chain.pop() for c in ro] for ro in glass]


density_order = {key: i for (i, key) in enumerate(['O', 'A', 'W', 'H'])}

def separate_liquids(glass):
	lst_of_liquids = iter(sorted([liquid for row in glass for liquid in row], key=lambda d: density_order[d]))
	return [[next(lst_of_liquids) for j in range(0, len(glass[0]))] for i in range(0, len(glass))]


density = {'H': 4, 'W': 3, 'A': 2, 'O': 1}

def separate_liquids(glass):
	glass_ = sorted([x for i in glass for x in i], key=lambda elem: density.get(elem))
	for row in glass:
		for i in range(len(row)):
			row[i] = glass_.pop(0)
	return glass


def separate_liquids(glass):
	liquids = []
	comparing = {'H': 1.36, 'W': 1.0, 'A': 0.87, 'O': 0.8}
	for row in glass:
		liquids.extend(row)
	liquids.sort(key=lambda k: comparing[k], reverse=True)
	for i in range(len(glass)):
		for j in range(len(glass[0])):
			glass[i][j] = liquids.pop()
	return glass