0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

配列のサイズの変更・重複要素の削除 Python3編

Posted at

N,n = map(int,input().split())
A = [int(input()) for _ in range(N)]
B = [0] * n
for i in range(n):
    if i < N:
        B[i] = A[i]
        
print(*B, sep='\n')

指示のとおりにやっていれば難しくはなかった。
if文はちょっと不等号に気をつけないとだめだね。。。

次!

こいつはちょっと難しかった。
スマートな書き方ではないが
フラグを使い、Aの要素がBの配列にあるかループで調べ、
なければ追加する形。

N = int(input())
A = [int(input()) for _ in range(N)]
B = []
for i in range(len(A)):
    if i == 0:
        B.append(A[i])
    else:
        flag = False
        for j in range(len(B)):
            if B[j] == A[i]:
                flag = True
                break

        if flag == False:
           B.append(A[i])
           
print(*B,sep="\n")

答えを見るともっと簡単な書き方があり
Bの配列にAの要素がなければの部分は
not in で探すことが可能

for i in range(len(A)):
    if A[i] not in B:
        B.append(A[i])
0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?