1
1

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】~* を n 回出力、ただし w 個ごとに改行せよ~で見る効率化したコード例

Posted at

🎯 お題:* を n 回出力、ただし w 個ごとに改行せよ

n = int(input("nを何回にしますか?: "))
w = int(input("wをいくつにしますか?: "))

🙅‍♂️ 最初に書いたコード(Bad例)

for i in range(n):
    print("*", end="")
    if i % w == w - 1:
        print()
if n % w:
    print()

🔍 問題点

  • ループ回数:n 回(1文字ずつ出力)
  • 条件分岐:n + 1 回(ループ内で毎回if判定+最後にも1回)

→ 見た目が悪いわけじゃないけど、処理としてはちょっと冗長


✅ 改善したコード(Good例)

for _ in range(n // w):
    print("*" * w)
rest = n % w
if rest:
    print("*" * rest)

👍 改善ポイント

  • ループ回数:n // w 回(まとめて出力)
  • 条件分岐:1回だけ(余りがあるかどうか)

🧠 なぜこれが良いの?

  • print("*" * w) のように、繰り返しは計算に任せる
  • ループの中で毎回 if を書くのは、無駄な処理を増やす原因

✨ 実行例

n = 10, w = 3 のとき:

***
***
***
*

🎉 まとめ

項目 Bad Good
ループ回数 n回 n // w回
条件分岐 n+1回 1回
可読性 普通 スッキリ!
処理効率 やや遅い 高速でスマート
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?