# Task
 Sorting is one of the most basic computational devices used in Computer Science. 
 Given a sequence (length ≤ 1000) of 3 different key values (7, 8, 9), your task is to find the minimum number of exchange operations necessary to make the sequence sorted. 
 One operation is the switching of 2 key values in the sequence.
# Example
 For `sequence = [7, 7, 8, 8, 9, 9]`, the result should be `0`.
 It's already a sorted sequence.
 For `sequence = [9, 7, 8, 8, 9, 7]`, the result should be `1`.
 We can switching `sequence[0]` and `sequence[5]`.
 For `sequence = [8, 8, 7, 9, 9, 9, 8, 9, 7]`, the result should be `4`.
 We can:
```
 [8, 8, 7, 9, 9, 9, 8, 9, 7] 
 switching sequence[0] and sequence[3]
 --> [9, 8, 7, 8, 9, 9, 8, 9, 7]
 switching sequence[0] and sequence[8]
 --> [7, 8, 7, 8, 9, 9, 8, 9, 9]
 switching sequence[1] and sequence[2]
 --> [7, 7, 8, 8, 9, 9, 8, 9, 9]
 switching sequence[5] and sequence[7]
 --> [7, 7, 8, 8, 8, 9, 9, 9, 9] 
```
So `4` is the minimum number of operations for the sequence to become sorted.
# Input/Output
 - `[input]` integer array `sequence`
  The Sequence.
 - `[output]` an integer
  the minimum number of operations.
def exchange_sort(sequence):
    print(sequence)
    # Reduce the sequence into its useful data
    counts = [sequence.count(n) for n in [7, 8, 9]]
    dividers = [0] + [sum(counts[:i]) for i in range(1,4)]
    groupings = [[sequence[dividers[i]:dividers[i+1]].count(n) for n in [7, 8, 9]] for i in range(3)]
    # Perform swaps en masse until done
    n = 0
    def swap(t0, t1, n0, n1):
        swappable = min(groupings[t0][n1], groupings[t1][n0])
        groupings[t0][n0] += swappable
        groupings[t0][n1] -= swappable
        groupings[t1][n1] += swappable
        groupings[t1][n0] -= swappable
        return swappable
    for a, b in [(0, 1), (0, 2), (1, 2)]:
        n += swap(a, b, a, b)
    for a, b, c in [(0, 1, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0), (1, 0, 2), (0, 2, 1)]:
        n += swap(a, b, a, c)
    for a, b in [(0, 1), (0, 2), (1, 2)]:
        n += swap(a, b, a, b)
    return n
def exchange_sort(sequence):
    print(sequence)
    # Reduce the sequence into its useful data
    counts = [sequence.count(n) for n in [7, 8, 9]]
    dividers = [0] + [sum(counts[:i]) for i in range(1,4)]
    groupings = [[sequence[dividers[i]:dividers[i+1]].count(n) for n in [7, 8, 9]] for i in range(3)]
    # Perform swaps en masse until done
    n = 0
    def swap(t0, t1, n0, n1):
        swappable = min(groupings[t0][n1], groupings[t1][n0])
        groupings[t0][n0] += swappable
        groupings[t0][n1] -= swappable
        groupings[t1][n1] += swappable
        groupings[t1][n0] -= swappable
        return swappable
    for a, b in [(0, 1), (0, 2), (1, 2)]:
        n += swap(a, b, a, b)
    for a, b, c in [(0, 1, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0), (1, 0, 2), (0, 2, 1)]:
        n += swap(a, b, a, c)
    for a, b in [(0, 1), (0, 2), (1, 2)]:
        n += swap(a, b, a, b)
    return n