itertools.combinations()の使い方に注意が必要.
考え方
$A$のどの行・列を残すかを全通り試せば良い.回答例
itertools.combinations()を使えば簡単だが,2回使う場合には注意が必要.こうするとダメ.
r = combinations(range(H1), H2) c = combinations(range(W1), W2)
入力例 1で試すと,以下のようになるため.
r = combinations(range(H1), H2) print(list(r)) # [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] c = combinations(range(W1), W2) print(list(r)) # [] print(list(c)) # [(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
以下のようにリストにするか,
from itertools import combinations H1, W1 = map(int, input().split()) A = [list(map(int, input().split())) for _ in range(H1)] H2, W2 = map(int, input().split()) B = [list(map(int, input().split())) for _ in range(H2)] r = list(combinations(range(H1), H2)) c = list(combinations(range(W1), W2)) for rr in r: for cc in c: flag = True for ib, ia in enumerate(rr): for jb, ja in enumerate(cc): if A[ia][ja] != B[ib][jb]: flag = False break if not flag: break if flag: exit(print('Yes')) print('No')
次のように,生成後に上書きされても問題ないようにする(代入しない).
from itertools import combinations H1, W1 = map(int, input().split()) A = [list(map(int, input().split())) for _ in range(H1)] H2, W2 = map(int, input().split()) B = [list(map(int, input().split())) for _ in range(H2)] for rr in combinations(range(H1), H2): for cc in combinations(range(W1), W2): flag = True for ib, ia in enumerate(rr): for jb, ja in enumerate(cc): if A[ia][ja] != B[ib][jb]: flag = False break if not flag: break if flag: exit(print('Yes')) print('No')