Сравнение двух массивов с неполным совпадением
import itertools
_ = None # 0 or 1
A = [
[1, _, 1, _],
[0, 1, _, 0],
[_, 1, 1, 0],
[0, 0, 0, 0]
]
B = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[1, 1, 0, 0],
[0, 0, 0, 0]
]
P = [0, 1, 2, 3]
for p in itertools.permutations(P):
if [[B[p[i]][p[j]] for j in P] for i in P] == A: # ???
print(p)
break
Как остановить цикл при нахождении неполного совпадения?
Ответы (3 шт):
Автор решения: CrazyElf
→ Ссылка
Ну я вам сравнивалку написал, только ничего всё-равно не находится. Мне кажется, там как-то по-другому надо перебирать, но как - не соображу:
def my_compare(A, B):
for i in range(len(A)):
for j in range(len(A[0])):
a = A[i][j]
if not a == _ and not a == B[i][j]:
return False
return True
P = [0, 1, 2, 3]
for p in itertools.permutations(P):
if my_compare(A, [[B[p[i]][p[j]] for j in P] for i in P]):
print(p)
break
Автор решения: vp_arth
→ Ссылка
Сравнение двух массивов с неполным совпадением
def compareWithNones(A, B):
for i, row in enumerate(A):
for j, cell in enumerate(row):
b_cell = B[i][j]
if cell is not None and b_cell is not None and cell != b_cell:
return False
return True
_ = None # 0 or 1
A = [
[1, _, 1, _],
[0, 1, _, 0],
[_, 1, 1, 0],
[0, 0, 0, 0]
]
B = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[1, 1, 0, 0],
[0, 0, 0, 0]
]
C = [
[_, 1, 1, 0],
[0, 1, 0, 0],
[1, _, 1, 0],
[0, 0, _, 0]
]
print(compareWithNones(A, B)) # False
print(compareWithNones(A, C)) # True
Автор решения: splash58
→ Ссылка
можно воспользоваться генераторами и встроенными функциями
def compareWithNones(A, B):
return all(
all(cell1 is None
or cell2 is None
or not (cell1-cell2)
for cell1, cell2 in zip(row1, row2)
)
for row1,row2 in zip(A,B))
print(compareWithNones(A, B)) # False
print(compareWithNones(A, C)) # True