1
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?

More than 3 years have passed since last update.

【学習記録】入力の配列による保持 (paizaランク D 相当)

Last updated at Posted at 2021-10-05

目次

  • 問題文
  • 書いたコード
  • 解答例
  • 学んだこと
  • 振り返り

背伸びしてチャレンジしたらBランクの問題が解けた…!!
のですが、時間かけすぎて?ランク認定されず。
悔しいのと、基本的な型や関数の理解がボロボロ抜けてるいうことが分かったので、スキルチェックではなく解答例が見れるpaizaラーニングでもう少し基礎を固めます。

問題文

詳細はコチラ

整数 n と n 個の数 a_1, ..., a_n が改行区切りで与えられます。与えられた a_1, ..., a_n の中で最も大きい数を出力してください。

入力値
n
a_1
...
a_n

解答例
3
20
19
2

出力例
20

要約すると、n個整数が与えられてその中から大きい値を出力せよ、という問題。

書いたコード

main.py
count = int(input())
ans = 0

while count > 0:
    b = int(input())
    if b > ans:
        ans = b
    count -= 1
print(ans)

whileループの中で受けた値を一つ一つ評価している形。

解答例

main.py
n = int(input())

A = [0] * n

for i in range(n):
    a = int(input())
    A[i] = a

print(max(A))

Aには何が…?

受け取った a_1, ..., a_n をひとつのリストで保持したいので、最初に A = [0]*n として、長さ n のリストを作っています。[0]*n は「0 が n 個並んだリスト」を作るときの書き方です。

なるほど、n = 2であれば [0, 0]の形でリストを作ってるんですね。
forループ内で上書きして、max関数で最大値を抜き出す…と。

学んだこと

  1. [i] * n でリストが作れること
  2. max関数の存在

一言

ポートフォリオでも今回同様、ループ内で評価する、という書き方をしていたのでリファクタリングのチャンス。
実行時間も毎回評価するより、max関数で一発で見た方が早くなりそうな印象。
Pythonは簡単に実行時間確認できたはずなのでそちらも調べてみたいと思います。

1
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
1
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?