Pythonで解決するプログラミング課題:距離計算、降水量分析、硬貨の組み合わせ

プログラミング

プログラミングの課題に取り組む際、与えられた問題を順を追って解決することが重要です。この記事では、Pythonを使った3つの課題の解法を実例を交えて解説します。

⑴ 原点からの距離と差の計算

2つの点の座標を入力し、原点からの距離を計算し、どちらの点が遠いかを判定する問題です。ユークリッド距離を計算して、どの点が原点から遠いかを出力します。

以下のPythonコードを使って解決できます。

import math

# ユーザーから座標を入力
x1, y1 = map(float, input('点1の座標を入力(x1 y1): ').split())
x2, y2 = map(float, input('点2の座標を入力(x2 y2): ').split())

# 原点からの距離を計算
distance1 = math.sqrt(x1**2 + y1**2)
distance2 = math.sqrt(x2**2 + y2**2)

# 距離を比較
if distance1 > distance2:
    print(f'点1は点2より{distance1 - distance2}だけ遠いです。')
elif distance1 < distance2:
    print(f'点2は点1より{distance2 - distance1}だけ遠いです。')
else:
    print('点1と点2は同じ距離です。')

⑵ 八王子市の降水量の分析

1927年から2024年までの90年間の八王子市の降水量データを分析し、平均降水量、最大・最小の年を求めます。データリストをもとに降水量の分析を行います。

以下のPythonコードを参考にしてください。

# 降水量データ(例)
precipitation = [1200, 1300, 1400, 1250, 1100, 900, 950, 1000, 980, 1050, 1150, 1200, 1300] # 1927-2024年のデータ

# 降水量の平均を計算
average_precipitation = sum(precipitation) / len(precipitation)

# 最大・最小の降水量と年を求める
max_precipitation = max(precipitation)
min_precipitation = min(precipitation)
max_year = precipitation.index(max_precipitation) + 1927
min_year = precipitation.index(min_precipitation) + 1927

# 結果を表示
print(f'平均降水量: {average_precipitation} mm')
print(f'最大降水量: {max_precipitation} mm({max_year}年)')
print(f'最小降水量: {min_precipitation} mm({min_year}年)')

⑶ 硬貨の組み合わせ

3000円未満の買い物をした際、現金で支払うために500円、100円、50円、10円、5円、1円の硬貨をどのように使うかを求める問題です。ここでは、額面の大きい硬貨を優先的に使用する方法を示します。

以下のPythonコードで解決できます。

# 現金で支払う金額
amount = 2500  # 例: 2500円

# 硬貨の種類
coins = [500, 100, 50, 10, 5, 1]

# 必要な硬貨の枚数を求める
coin_count = {}
for coin in coins:
    coin_count[coin] = amount // coin  # その硬貨で支払える枚数
    amount %= coin  # 残りの金額を更新

# 結果を表示
for coin, count in coin_count.items():
    print(f'{coin}円硬貨: {count}枚')

まとめ

プログラミング課題に取り組む際には、問題を順を追って解決することが重要です。今回の3つの課題では、Pythonを使って距離計算、降水量の分析、硬貨の組み合わせ問題を効率的に解決する方法を学びました。これらのサンプルコードを参考に、実践的なプログラミングスキルを身につけましょう。

コメント

タイトルとURLをコピーしました