バイナリ行列で重複する行を見つけるPythonプログラムを作成する
バイナリ行列に0と1が含まれている場合、重複する行を見つけて印刷することがタスクです。
Pythonは、ここで使用されるCounter()メソッドを提供します。
例
Input: 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 Output: (1, 1, 1, 1) (0, 0, 0, 0)
アルゴリズム
Step 1: Create a binary matrix, only 0 and 1 elements are present. Step 2: Which will have rows as key and it’s frequency as value. Lists are mutable so first, we will cast each row (list) into a tuple. Step 3: Create a dictionary using the counter method. Step 4: Now traverse the dictionary completely. Step 5: Print all rows which have frequency greater than 1.
サンプルコード
# Function to find duplicate rows in a binary matrix
from collections import Counter
def binarymatrix(A):
A = map(tuple,A)
dic = Counter(A)
print("Duplicate rows of Binary Matrix ::>")
for (i,j) in dic.items():
if j>1:
print (i)
# Driver program
if __name__ == "__main__":
A=[]
n=int(input("Enter n for n x n matrix : ")) #3 here
#use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
print("Enter the element ::>")
for i in range(n):
row=[] #temporary list to store the row
for j in range(n):
row.append(int(input())) #add the input to row list
A.append(row) #add the row to the list
print(A)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(A[i][j], end=" ")
print()
binarymatrix(A) 出力
Enter n for n x n matrix : 4 Enter the element ::> 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 [[1, 1, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0]] Display Array In Matrix Form 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 Duplicate rows of Binary Matrix ::> (1, 1, 1, 1) (0, 0, 0, 0)
-
Pythonプログラムで行列の転置を見つける
この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −行列が与えられたので、行列の転置を表示する必要があります。 行列の転置は、A[i][j]に存在する値をA[j][i]に置き換えることによって得られます。 それでは、以下の実装の概念を見てみましょう- アプローチ1:入力行列の転置を格納するための新しい行列を作成する 例 def transpose(A,B): for i in range(M): for j in range(N):
-
行列の転置を見つけるPythonプログラム
この記事では、特定の問題ステートメントを解決するための解決策とアプローチについて学習します。 問題の説明 行列が与えられた場合、転置を同じ行列に格納して表示する必要があります。 行列の転置は、行を列に、列を行に変更することで得られます。つまり、A行列の転置はA[i][j]をA[j][i]に変更することで得られます。 以下に示す実装を見てみましょう- 例 N = 4 def transpose(A): for i in range(N): for j in range(i+1, N): &nbs