LoginSignup
0
0

More than 3 years have passed since last update.

行列から探してみよう

Posted at

こんばんは('Д')
いつも応援有難うございます m(_ _)m

アルゴリズムを色々書いてきましたが、
ちょっと小休止で行列で遊んでみたくなりました。
簡単な奴から行きます。

test.py
import numpy as np
Tarray = np.arange(12)
print(Tarray)
実行結果.py
[ 0  1  2  3  4  5  6  7  8  9 10 11]

これって、例えば 3行4列に変更できないのでしょうか?
はい、出来ます。

test.py
import numpy as np
Tarray = np.arange(12).reshape(3,4)
print(Tarray)
実行結果.py
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

なるほど~、面白い!!
ここから、特定の要素のみを print するには
どうすれば良いでしょうか?
こんな記述はどうでしょう。。

test.py
import numpy as np

Tarray = np.arange(12).reshape(3,4)

print(Tarray)
print()
print(f"Tarray[0,0] is {Tarray[0,0]}")
実行結果.py
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Tarray[0,0] is 0

なるほど。( ´ー`)y-~~
ここまで分かったら、
行列から、欲しい数字を探せるかも。
やってみましょう(≧▽≦)

例えば 2行10列の 1 行目からデータを
抜き取る場合、こんな記述になりませんか?

test.py
import numpy as np

Tarray = np.arange(20).reshape(2,10)
print(Tarray)
num = int(input(": "))

for i in range(10):
    if Tarray[0,i] == num:
        print(f"founded data is placed Tarray[0,{i}] ")
実行結果.py
[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]

: 6
founded data is placed Tarray[0,6] 

次は行をまたいで検索しましょう。
前述の Tarray[0,i] の 0 を変数に変えれば OK です。

test.py
import numpy as np

Tarray = np.arange(20).reshape(2,10)
print(Tarray)
num = int(input(": "))

for j in range(2):
    for i in range(10):
        if Tarray[j,i] == num:
            print(f"founded data is placed Tarray[{j},{i}] ")
実行結果.py
[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]

: 13
founded data is placed Tarray[1,3] 

ではでは、行、列すらも変数になったらどうなるでしょうか。
私はこんな風に書いてみました。

matrix_search.py
import numpy as np

M,N = map(int,input("enter M , N: ").split())
atest = np.arange(M*N).reshape(M,N)
print(atest)

num = int(input("find value: "))

for i in range(M):
    for j in range(N):
        if atest[i,j] == num:
            print(f"found value is placed at [{i},{j}]")
実行結果.py
enter M , N: 4 8
[[ 0  1  2  3  4  5  6  7]
 [ 8  9 10 11 12 13 14 15]
 [16 17 18 19 20 21 22 23]
 [24 25 26 27 28 29 30 31]]

find value: 20
found value is placed at [2,4]

位置表示が 0 行 0 列があるものとして構成しています。
無いですよね、そんなの(笑)

matrix_search.py
import numpy as np

M,N = map(int,input("enter M , N: ").split())
atest = np.arange(M*N).reshape(M,N)
print(atest)

num = int(input("find value: "))

for i in range(M):
    for j in range(N):
        if atest[i,j] == num:
            print(f"found value is placed at [{i+1},{j+1}]")
実行結果.py
enter M , N: 4 8
[[ 0  1  2  3  4  5  6  7]
 [ 8  9 10 11 12 13 14 15]
 [16 17 18 19 20 21 22 23]
 [24 25 26 27 28 29 30 31]]

find value: 20
found value is placed at [3,5]

はい、今度は大丈夫そうです。
ではまた ^^) _旦~~

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0