aboutsummaryrefslogtreecommitdiff
path: root/challenge-253/sgreen/python/ch-2.py
blob: aad97b55d0ac90b971a15cf7106c9b81e6f18e9f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python3

import json
import sys


def validate_matrix(matrix):
    # Calculate the size of the matrix
    rows = len(matrix)
    cols = len(matrix[0])

    for r in range(0, rows):
        # Check that all columns are of equal length
        if len(matrix[r]) != cols:
            raise ValueError(f'Row {r} has different number of columns')

        # Check all values are 0 or 1
        if any(True for i in matrix[r] if i not in (0, 1)):
            raise ValueError(f'Row {r} has a value other than 0 or 1')

        # Check there are no ones zeros after zero.
        if any(True for c in range(1, cols) if matrix[r][c-1] == 0 and matrix[r][c] == 1):
            raise ValueError(f'Row {r} has a 1 after 0')


def weakest_row(matrix):
    # Start by validating any issues with the input
    validate_matrix(matrix)

    # Sort by the rows with the most 1s, followed by a numerical sort
    return sorted(range(len(matrix)), key=lambda i: sum(matrix[i]))


def main(json_string):
    matrix = json.loads(json_string)
    result = weakest_row(matrix)
    print('(' + ', '.join(map(str, result)) + ')')


if __name__ == '__main__':
    main(sys.argv[1])