Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Keys and Locks by PythonLearner
from itertools import chain, dropwhile
from operator import eq
def rotate(matrix):
return list(zip(*matrix[::-1]))
def are_equal(matrix1, matrix2):
answer = False
if len(matrix1) == len(matrix2) and len(matrix1[0]) == len(matrix2[0]):
answer = all(map(eq, chain(*matrix1), chain(*matrix2)))
return answer
def cut(matrix):
emprty_cell_marker = '0'
def is_empty(row):
return all(cell == emprty_cell_marker for cell in row)
def horizontal_cut(matrix):
matrix = list(dropwhile(is_empty, matrix))
matrix = list(dropwhile(is_empty, matrix[::-1]))[::-1]
return matrix
matrix = horizontal_cut(matrix)
matrix = zip(*matrix)
matrix = horizontal_cut(matrix)
matrix = list(zip(*matrix))
return matrix
def keys_and_locks(lock, some_key):
lock_matrix = cut(lock.split())
key_matrix = cut(some_key.split())
does_key_fit = False
max_rotations_count = 4
rotations_count = 0
while not does_key_fit and rotations_count < max_rotations_count:
does_key_fit = are_equal(lock_matrix, key_matrix)
key_matrix = rotate(key_matrix)
rotations_count += 1
return does_key_fit
if __name__ == '__main__':
print("Example:")
print(keys_and_locks('''
0##0
0##0
00#0
00##
00##''',
'''
00000
000##
#####
##000
00000'''))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert keys_and_locks('''
0##0
0##0
00#0
00##
00##''',
'''
00000
000##
#####
##000
00000''') == True
assert keys_and_locks('''
###0
00#0''',
'''
00000
00000
#0000
###00
0#000
0#000''') == False
assert keys_and_locks('''
0##0
0#00
0000''',
'''
##000
#0000
00000
00000
00000''') == True
assert keys_and_locks('''
###0
0#00
0000''',
'''
##00
##00''') == False
print("Coding complete? Click 'Check' to earn cool rewards!")
Sept. 18, 2018
Comments: