Python3関連のことを調べてみた2022年11月22日

Python3関連のことを調べてみた2022年11月22日

[Python]timeitで処理時間を計測してみた

# はじめに
– 今回はPython標準ライブラリのtimeitモジュールを使って、プログラムの処理時間を計測してみたいと思います。
– 動作環境
– Python 3.11.0
– macOS Ventura

# timeitとは
timeitはPython標準ライブラリのモジュールで、小さなコードの計測に便利です。

timeitモジュールは、コードの一部を指定した回数だけ実行することで、その処理速度を計測して、平均処理時間を計測できます。また、デフォルトでは計測中、一時的にガベージコレクションを無効にすることで、個々の計測結果がより比較しやすくなります。

timeitを使って以下の3つのやり方で処理時間を計測してみます。
– pyファイル内で計測
– コマンドラインで計測
– 対話モードで計測

※処理時間は実行するマシンの性能によって異なる場合があります。

# pyファイル内で計測
## timeit.timeit()
“`python
import timeit

timeit.timeit(stmt=’pass’, setup=’pass’, tim

元記事を表示

paizaラーニング「積の最小化 Python3編」

https://paiza.jp/works/mondai/conditions_branch/conditions_branch__complex_boss
私の回答
“`
a,b=[int(x) for x in input().split()]
if a<0 and b<0: print(b*b) elif a<0 and b>0:
print(a*b)
elif a==0 or b==0:
print(0)
elif a>0 and b>0:
print(a*a)
“`
模範回答
“`
a, b = [int(x) for x in input().split()]

if a <= 0 and b >= 0:
# a から b の間に 0 が含まれる
print(a * b)
elif a > 0:
# a と b が両方とも正の数
print(a * a)
else:
# a と b が両方とも負の数
print(b * b)
“`

元記事を表示

paizaラーニング「タイルの敷き詰め Python3編」

https://paiza.jp/works/mondai/conditions_branch/conditions_branch__complex_step8
私の回答
最初値が0のときを想定せず、何度もトライしました。
“`
h, w = [int(x) for x in input().split()]

if h==0 and w==0:
print(“NO”)
elif h==0 or w==0:
print(“NO”)
elif h%2==0 and w%2==0:
print(“YES”)
else:
print(“NO”)
“`
模範回答
“`
h, w = [int(x) for x in input().split()]

if h == 0 or w == 0:
print(“NO”)
elif h % 2 == 0 and w % 2 == 0:
print(“YES”)
else:
print(“NO”)
“`
– 1 つだけ注意点があります。本問は「この箱を 1 つ以上の高さ 2 、幅 2 の四

元記事を表示

paizaラーニング「池の周回 Python3編」

https://paiza.jp/works/mondai/conditions_branch/conditions_branch__complex_step6
私の回答
“`
n,k,t=[int(x) for x in input().split()]
if (k*t)%n==0:
print(“YES”)
else:
print(“NO”)
“`
模範回答
“`
n, k, t = [int(x) for x in input().split()]

if k * t % n == 0:
print(“YES”)
else:
print(“NO”)
“`
今回は模範解答と私の回答がほぼ同じでした!!

元記事を表示

paizaラーニング「終了判定 2 Python3編」

https://paiza.jp/works/mondai/conditions_branch/conditions_branch__complex_step5
私の回答
whileとbreakを同時に使う必要がなかったようでした。
長い回答にしてしまいました。
“`
n,k=map(int,input().split())
count=0
while (n<=k): if n>=k:
break
n=n*2
count=count+1
print(count)
“`

模範回答
“`
n, k = [int(x) for x in input().split()]

m = 0
while n < k: n *= 2 m += 1 print(m) ```

元記事を表示

paizaラーニング 「終了判定 Python3編」

https://paiza.jp/works/mondai/conditions_branch/conditions_branch__complex_step4
私の回答
“`
n=int(input())
array=list(map(int,input().split()))
sum=0
for i in range(n):
if array[i]%2!=0:
break
sum=sum+array[i]
print(sum)
“`

模範回答
“`
n = int(input())
a = [int(x) for x in input().split()]

ans = 0
for ele in a:
if ele % 2 == 1:
break

ans += ele

print(ans)
“`

元記事を表示

Atlassian API を利用して、 Confluence にページを作成する

OTHERカテゴリの最新記事