LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 1 year has passed since last update.

enumerate()ってはやかったりするのかな??

Posted at

この記事はAizu Advent Calendar 2021の7日目の記事です。遅刻してごめんなさい

enumerateって?

Pythonの組み込み関数

>>> language = ['C', 'C++', 'C#', 'Rust']
>>> A = enumerate(language)
>>> A
<enumerate object at 0x7f43000f5180>
>>> list(A)
[(0, 'C'), (1, 'C++'), (2, 'C#'), (3, 'Rust')]

値とカウントをタプルにして返す

 A = [x**2 for x in range(5)]
 for i, val in enumerate(A):
    print(str(i)+'**2='+str(val))

これを実行すると

 0**2=0
 1**2=1
 2**2=4
 3**2=9
 4**2=16

となった

はやいの?

普通にfor使うのとどっちがはやいのかな?

AtCoderのコードテストで色々見てみた

Pypy3で実行した
これ試していた時時間なかったから10回しかやってないです。もっと試行回数重ねるべきですね。

 for i, val in enumerate(range(5000000000)): #5.0 * 10^9 python3でこの回数回すとTLEになる
        pass

これで時間(ms)(メモリ)は
6046 (31236)
5986 (25380)
5983 (25360)
5983 (25376)
5982 (25488)
5980 (25448)
6057 (38932) #?!
5989 (25504)
5978 (25496)
5979 (25372)

じゃあenumerate()を使わないでやってみよう

 count = int
 for i in range(5000000000): #5.0 * 10^9    (Pypyは両者ともに1.0 * 10^10 でTLE)
    count += 1
    pass

そして時間(メモリ)は
6056 (25220)
6143 (25232)
6225 (25296)
6032 (25324)
5922 (25216)
5905 (25228)
5932 (25300)
5923 (25224)
5925 (25340)
5954 (25224)

結論と感想

あんまかわらない?
正確性に欠ける記事なので限定共有投稿にします
そもそも灰コーダーが書く記事じゃないね

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