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?

数字当てゲーム

Last updated at Posted at 2025-10-31

【追記・リファクタリング版】(2025/11/01)

この記事の公開後、Qiitaコミュニティの方(あるいはAI)から、より効率的でPythonicなコードについて貴重なフィードバックを頂きました。

特に、

  1. forループを使わずにリスト内包表記で書く方法
  2. zip()関数を使って2つのリストを同時に処理する方法
  3. same()関数に含まれていた「ヒット」もカウントしてしまうロジックバグ
    について学ぶことができ、コードを全面的にリファクタリングしました。

以下が、フィードバックを反映させた新しいコードです。

from random import randint
def comp(a, b):
    return sum(x == y for x, y in zip(a, b))
def same(a, b):
    return len(set(a) & set(b))
print("数当てゲームを始めます。3桁の数を当ててください!")
answer = [randint(0, 9) for n in range(3)]
while True:
    prediction = [int(input(f"{m + 1}桁目の予想を入力(0~9)")) for m in range(3)]
    hit = comp(answer, prediction)
    blow = same(answer, prediction) - hit
    print(f"{hit}ヒット!{blow}ブロー!")
    if hit == 3:
        print("正解です")
        break
    if input("続けますか?1:続ける2:終了>>") == "2":
        print(f"正解は{answer}")
        break

フィードバックありがとうございました。
改めてリファクタリングの大切さを学びました。

以下は編集前の記事です。

AIは人間の才能を引き出すツールであると感じ、一か月前からPython言語を勉強し始めました。今回は初めて作成した簡単な「数当てゲーム」を作成しましたので紹介します。これは"スッキリわかるPython入門"の演習課題で与えられていたものです。
この「数当てゲーム」は簡単なコードではありますが初心者が知っておくべき最低限の"繰り返し"や"関数"、"モジュール"と言った知識が必要になっていました。

最初にfrom random import randintという指定した範囲でランダムな整数を返す関数をインポートしています。

def comp(a,b):
    count = 0
    for x in range(3):
        if a[x] == b[x]:
            count += 1
        else:
            continue
    return count

また、ここではcop(a,b)という関数を自分で定義しています。引数に渡されたリストをforを使って一つずつ同じ値が同じリストのインデックスにあるかどうか調べ、一致している値の個数を返すというもの。

シンプルですが、とても学び概のあるコードでした。

1
0
1

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?