Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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). If there are disproportinate number of substance then some of substances mixed together but a very low amount. 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 |
- ----------------------
- Such as:
- [['W', 'A', 'A', 'W', 'W', 'W', 'O', 'W', 'W', 'A'],
- ['A', 'H', 'O', 'O', 'H', 'O', 'H', 'A', 'H', 'W'],
- ['A', 'H', 'H', 'H', 'H', 'O', 'W', 'W', 'A', 'W'],
- ['H', 'A', 'A', 'H', 'O', 'A', 'H', 'W', 'O', 'A'],
- ['H', 'W', 'H', 'A', 'W', 'W', 'A', 'H', 'A', 'O'],
- ['A', 'W', 'H', 'W', 'H', 'O', 'A', 'A', 'A', 'W'],
- ['A', 'H', 'O', 'H', 'H', 'H', 'O', 'W', 'A', 'H'],
- ['A', 'W', 'W', 'H', 'H', 'W', 'A', 'A', 'A', 'A']]
- =====================================================
- ||
- ||
- \/
- ===================================================
- [['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'],
- ['O', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'],
- ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'],
- ['A', 'A', 'A', 'A', 'A', 'A', 'W', 'W', 'W', 'W'],
- ['W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W'],
- ['W', 'W', 'W', 'W', 'W', 'W', 'W', 'H', 'H', 'H'],
- ['H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H'],
- ['H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H', 'H']]
- #Solution using bubble sort
- def separate_liquids(glass):
- if not glass: #if empty glass is given, return empty array
- return []
- glass2=glass
- glass2=sum(glass2,[])
- #replace the list item with int for sorting
- for n,i in enumerate(glass2):
- if i=='A':
- glass2[n]=0.87
- elif i=='H':
- glass2[n]=1.36
- elif i=='W':
- glass2[n]=1.00
- else:
- glass2[n]=0.80
- #bubble sort
- for i in range(len(glass2)-1,0,-1):
- for j in range(i):
- if glass2[j] > glass2[j + 1]:
- temp = glass2[j]
- glass2[j] = glass2[j + 1]
- glass2[j + 1] = temp
- char={1.36:'H',1.00:'W',0.87:'A',0.80:'O'}
- glass3=[char.get(x,x) for x in glass2]
- result = [glass3[x:x + len(glass[0])] for x in range(0, len(glass3), len(glass[0]))][:len(glass)]
- return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement