Python 繰り返し処理の実践演習

1. 数値のピラミッドを表示する

以下の形式の数値ピラミッドを表示するプログラムを作成してください。各段は2のべき乗とその半分を表示します。

lines = int(input("行数を入力してください: "))
spaces = lines + 30

for row in range(1, lines + 1):
    # スペースを出力
    for space_counter in range(1, spaces):
        print(" ", end="")
    spaces -= 2

    current_value = 1
    # 増加する2のべき乗を出力
    for num_counter in range(1, row + 1):
        print(current_value, end=" ")
        current_value *= 2

    # 減少する2のべき乗を出力
    current_value //= 2
    for num_counter in range(row - 2, 0, -1):
        current_value //= 2
        print(current_value, end=" ")
    print()

2. 2から1000までの素数を表示する

2から1000まで(両端を含む)の素数を表示し、各行に8個の素数が表示されるようにしてください。

prime_count = 0
for num in range(2, 1001):
    is_prime = True
    for divisor in range(2, int(num ** 0.5) + 1):
        if num % divisor == 0:
            is_prime = False
            break
    if is_prime:
        print(num, end=" ")
        prime_count += 1
        if prime_count % 8 == 0:
            print()

3. 円周率Πの近似値を計算する

指定された数式を使用して、i=10000, 20000, ..., 1000000の各ステップで円周率Πの近似値を計算し、表示してください。

for terms in range(10000, 100001, 10000):
    pi_approx = 0.0
    for term_index in range(1, terms + 1):
        pi_approx += ((-1) ** (term_index + 1)) / (2 * term_index - 1)
    print(f"{terms}項でのΠの近似値: {4 * pi_approx}")

4. 自然対数の底eの近似値を計算する

指定された数式を使用して、i=10000, 20000, ..., 1000000の各ステップで自然対数の底eの近似値を計算し、表示してください。

e_approx = 1.0
factorial = 1

for term_number in range(1, 100001):
    factorial *= term_number
    term_value = 1 / factorial
    e_approx += term_value
    if term_number % 10000 == 0:
        print(f"{term_number}項でのeの近似値: {e_approx}")

5. 10000未満の完全数を求める

10000未満の完全数をすべて見つけて表示してください。

for candidate in range(2, 10000):
    divisor_sum = 1  # 1は常に約数
    for divisor in range(2, candidate // 2 + 1):
        if candidate % divisor == 0:
            divisor_sum += divisor
    if divisor_sum == candidate:
        print(candidate)

6. ジャンケンゲーム

コンピュータとじゃんけんをするゲームを作成してください。先に2勝したプレイヤーが勝者となります。

import random

player_score = 0
computer_score = 0
choices = ["グー", "チョキ", "パー"]

while player_score < 2 and computer_score < 2:
    computer_choice = random.randint(0, 2)
    player_choice = int(input("グー (0), チョキ (1), パー (2): "))

    print(f"コンピュータ: {choices[computer_choice]}, プレイヤー: {choices[player_choice]}")

    # 勝敗判定
    if (computer_choice == 0 and player_choice == 1) or \
       (computer_choice == 1 and player_choice == 2) or \
       (computer_choice == 2 and player_choice == 0):
        computer_score += 1
        print("コンピュータの勝ち!")
    elif computer_choice == player_choice:
        print("あいこです")
    else:
        player_score += 1
        print("あなたの勝ち!")

print("ゲーム終了!" + ("あなたの勝利!" if player_score == 2 else "コンピュータの勝利!"))

7. 最大値とその出現回数を求める

複数の整数を入力し(0を入力すると終了)、その中の最大値とその出現回数を求めて表示してください。

max_value = None
frequency = {}

while True:
    input_num = int(input("整数を入力してください(0で終了): "))
    if input_num == 0:
        break

    # 頻度を記録
    if input_num in frequency:
        frequency[input_num] += 1
    else:
        frequency[input_num] = 1

    # 最大値を更新
    if max_value is None or input_num > max_value:
        max_value = input_num

if max_value is not None:
    print(f"最大値は {max_value} で、出現回数は {frequency[max_value]} 回です。")

8. 十進数を二進数に変換する

十進数を入力として受け取り、その二進数表現を表示するプログラムを作成してください。

decimal_num = int(input("十進数を入力してください: "))
binary_digits = []

if decimal_num == 0:
    binary_digits.append(0)

while decimal_num > 0:
    binary_digits.append(decimal_num % 2)
    decimal_num //= 2

# リストを逆順にして文字列に結合
binary_str = ''.join(map(str, reversed(binary_digits)))
print(f"二進数表現: {binary_str}")

9. 十進数を十六進数に変換する

十進数を入力として受け取り、その十六進数表現を表示するプログラムを作成してください。

decimal_input = int(input("十進数を入力してください: "))
hex_digits = "0123456789ABCDEF"
hex_str = ""

if decimal_input == 0:
    hex_str = "0"

while decimal_input > 0:
    remainder = decimal_input % 16
    hex_str = hex_digits[remainder] + hex_str
    decimal_input //= 16

print(f"十六進数表現: {hex_str}")

10. モンテカルロ法による確率の推定

モンテカルロ法を使って、ランダムに生成した点が特定の領域(奇数領域)に落ちる確率を推定するプログラムを作成してください。

import random

hits = 0
iterations = 1000000

for _ in range(iterations):
    random_x = random.random()
    random_y = random.random()

    # 特定の領域の判定ロジック
    if (random_x < 0.5) or \
       (random_x > 0.5 and random_x + random_y < 1.5 and random_y > 0.5):
        hits += 1

probability = hits / iterations
print(f"100万回試行した結果、奇数領域に落ちる確率は: {probability:.6f}")

11. 2001年から2100年までの閏年を表示する

2001年から2100年までのすべての閏年を表示し、10個ずつ改行して表示してください。

leap_year_count = 0
for year in range(2001, 2101):
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        print(year, end=" ")
        leap_year_count += 1
        if leap_year_count % 10 == 0:
            print()

タグ: Python forループ whileループ 素数 円周率

8月6日 01:57 投稿