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?

Python基礎学習②数をカウントする際に配列を使う実装は相応しくないという学び

Posted at

Pythonで次の問題を解いた時の学びをシェアします。

1000未満の「3と7の倍数」の5番目に大きい数を出力

最初の自分の回答

multiples_of_3_and_7_number = []
for n in range(1, 1000):
    if n % 3 == 0 and n % 7 == 0:
       multiples_of_3_and_7_number.append(num)
print(sorted(multiples_of_3_and_7_number)[-5])

出力結果
903 

リストを使って出力しました。
一見、これでいいように思えたのですが、リストに値を入れていくとメモリを消費します。
もし何千万もループするような処理ですと、メモリオーバーでエラーになるかもしれません。
なので、数をカウントする際にリストを使う実装は相応しくありません。

修正したコードが以下です。

count = 0
for n in range(1000, 1, -1):
    if n % 3 == 0 and n % 7 == 0:
       count += 1
       if count == 5:
          print(n)

出力結果
903 

1000から順にnに代入していき、条件を通過したらcountに+1する。もし、countが5なら、その時のnを出力する。
この方法であれば、メモリを消費せずに実装できました。

1000未満と聞くと1から1000と考えがちですが、1000から数えていく方法もあるんですね。

とても勉強になりましたので、シェアさせていただきます。

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?