Created
September 28, 2018 10:26
-
-
Save HemantNegi/cfe6429c3ab8e1826d923b79f97b1545 to your computer and use it in GitHub Desktop.
Special elements in a matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Complete the countSpecialElements function below. | |
def countSpecialElements(matrix): | |
items = set() | |
for m, row in enumerate(matrix): | |
min_i, max_i, solution = min_max_in_list(row) | |
if not solution: | |
return -1 | |
# add as row_col | |
items.add('%d_%d' % (m, min_i)) | |
items.add('%d_%d' % (m, max_i)) | |
matrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))] | |
# print matrix | |
for n, col in enumerate(matrix): | |
min_i, max_i, solution = min_max_in_list(col) | |
if not solution: | |
return -1 | |
# add as row_col | |
items.add('%d_%d' % (min_i, n)) | |
items.add('%d_%d' % (max_i, n)) | |
print items | |
return len(items) | |
def min_max_in_list(lst): | |
""" | |
Return the index of min and max in the given list | |
""" | |
max = lst[0] | |
min = max | |
min_i, max_i = 0, 0 # index of min and max | |
for i in range(len(lst)): | |
if min > lst[i]: | |
min = lst[i] | |
min_i = i | |
if max < lst[i]: | |
max = lst[i] | |
max_i = i | |
if lst.count(max)>1 or lst.count(min)>1: | |
return 0, 0, false | |
return min_i, max_i, true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment