はじめに
ポケモンの世界観を活用して、速度や距離、時間、割合、時計などの基本的な計算を扱うPythonコードを作成・整理しました。
中学生の学習や、SPI対策などの実用的な場面でも活用できる内容になっています。
参考リンクまとめ
Pythonコード
# ファイル名: split_moo_milk_equations.py
# 説明: 1200gのモーモミルクをピカチュウとイーブイに分ける問題を連立方程式で解き、棒グラフで表示する
# Description: Solves a simultaneous equation to split 1200g of Moo Milk between Pikachu and Eevee, and plots the result
import numpy as np # 数値計算のためのNumPyをインポート / Import NumPy for numerical operations
import matplotlib.pyplot as plt # グラフ描画のためのmatplotlibをインポート / Import matplotlib for plotting
# -----------------------------
# 連立方程式の定義 / Define simultaneous equations
# -----------------------------
# x: Pikachuのミルク量 (g) / Amount of Moo Milk for Pikachu (g)
# y: Eeveeのミルク量 (g) / Amount of Moo Milk for Eevee (g)
# 条件:
# x + y = 1200
# x - y = 200
# 行列A (係数行列) / Matrix A (coefficient matrix)
A = np.array([[1, 1], # x + y = 1200
[1, -1]]) # x - y = 200
# ベクトルB (定数ベクトル) / Vector B (constant terms)
B = np.array([1200, 200])
# -----------------------------
# 解を求める / Solve the equations
# -----------------------------
solution = np.linalg.solve(A, B) # Ax = B を解く / Solve Ax = B
x = solution[0] # ピカチュウの量 / Pikachu's Moo Milk
y = solution[1] # イーブイの量 / Eevee's Moo Milk
# -----------------------------
# 結果表示 / Display results
# -----------------------------
print(f"ピカチュウがもらうモーモミルク: {x}g") # Pikachu's share
print(f"イーブイがもらうモーモミルク: {y}g") # Eevee's share
# -----------------------------
# グラフ描画 / Plot the result
# -----------------------------
labels = ['Pikachu', 'Eevee'] # X軸のラベル / X-axis labels
amounts = [x, y] # ミルクの量 / Amount of Moo Milk
plt.figure(figsize=(8, 6)) # グラフのサイズ / Figure size
plt.bar(labels, amounts, color=['yellow', 'brown']) # 棒グラフ / Bar chart
plt.title("Moo Milk Distribution", fontsize=14) # グラフのタイトル / Plot title
plt.xlabel("Pokemon", fontsize=12) # X軸ラベル / X-axis label
plt.ylabel("Moo Milk Amount (g)", fontsize=12) # Y軸ラベル / Y-axis label
plt.ylim(0, total_milk + 100) # Y軸の範囲設定 / Y-axis range
plt.grid(axis='y', linestyle='--', alpha=0.7) # グリッド線 / Grid lines
plt.show() # グラフを表示 / Show the plot
# ファイル名: pokemon_bbq_split_with_equations.py
# 説明: ピカチュウ・イーブイ・カビゴンでBBQ代を平等に分ける問題を連立方程式で解き、棒グラフと数式を表示する
# Description: Solve BBQ cost sharing using simultaneous equations and show the result as a bar graph and formula
import matplotlib.pyplot as plt
import numpy as np
# -------------------------
# 条件 / Given Conditions
# -------------------------
# 1. Pikachu paid 400 yen more than fair share
# 2. Eevee paid 1200 yen more than fair share
# 3. Snorlax received 1600 yen from the others
# 4. Drink + Vegetable = 2400 yen
# 5. Each Pokémon should end up paying 2000 yen
fair_share = 2000
pikachu_extra = 400
eevee_extra = 1200
total_adjustment = pikachu_extra + eevee_extra # = 1600
# -------------------------
# 連立方程式の解法 / Solving simultaneous equations
# -------------------------
# 式1: D + V = 2400 (飲み物 + 野菜 = 2400円)
# 式2: D = 2000 - 400 (ピカチュウが400円多く払った)
# 式3: V = 2000 - 1200(イーブイが1200円多く払った)
drink_cost = fair_share - pikachu_extra # = 1600
vege_cost = fair_share - eevee_extra # = 800
meat_cost = fair_share + total_adjustment # = 3600
# -------------------------
# 結果の出力 / Print results
# -------------------------
print("連立方程式 / Simultaneous Equations:")
print("1) D + V = 2400")
print("2) D = 2000 - 400")
print("3) V = 2000 - 1200")
print("\n計算結果 / Calculated Results:")
print(f"Pikachu (Drink): {drink_cost} yen")
print(f"Eevee (Vegetable): {vege_cost} yen")
print(f"Snorlax (Meat): {meat_cost} yen")
print(f"Each Pokémon ends up paying: {fair_share} yen")
# -------------------------
# 棒グラフ / Bar Chart
# -------------------------
labels = ['Pikachu (Drink)', 'Eevee (Vegetable)', 'Snorlax (Meat)']
costs = [drink_cost, vege_cost, meat_cost]
plt.figure(figsize=(10, 6))
# 棒グラフ描画 / Draw bar graph
plt.bar(labels, costs, color=['yellow', 'orange', 'green'])
# 公平な金額にラインを追加 / Add horizontal line at fair share
plt.axhline(fair_share, color='red', linestyle='--', linewidth=1.5, label='Fair Share (2000 yen)')
plt.text(2.05, fair_share + 30, "Fair Share: 2000 yen", color='red', fontsize=11)
# 数式の表示 / Display equations
equation_text = r'''Simultaneous Equations:
$D + V = 2400$
$D = 2000 - 400$
$V = 2000 - 1200$
$\Rightarrow D = 1600$, $V = 800$, $M = 3600$
'''
plt.text(-0.4, 3700, equation_text, fontsize=12, verticalalignment='top', bbox=dict(facecolor='white', alpha=0.8))
# グラフ設定 / Configure plot
plt.title("BBQ Cost Split Among Pokémon", fontsize=14)
plt.xlabel("Pokémon", fontsize=12)
plt.ylabel("Cost Paid (yen)", fontsize=12)
plt.ylim(0, 4000)
plt.legend()
plt.grid(axis='y', linestyle='--', alpha=0.6)
plt.tight_layout()
plt.show()
# ---------------------------------------------
# プログラム名: poke_ball_price_solver.py
# Program Name: poke_ball_price_solver.py
#
# 説明:
# 4種類のポケモンボール(ハイパーボール、スーパーボール、モンスターボール、クイックボール)の価格を、
# それぞれの合計金額の条件から連立方程式を使って求め、棒グラフで表示する。
#
# Description:
# This program solves for the prices of four types of Poké Balls
# (Hyper Ball, Super Ball, Monster Ball, Quick Ball)
# based on given total price combinations using substitution from simultaneous equations,
# and visualizes the result using a bar chart.
# ---------------------------------------------
import matplotlib.pyplot as plt # グラフ描画用ライブラリ / Import plotting library
# ---------------------------------------------
# 与えられた条件 / Given conditions:
# ---------------------------------------------
# 1. Hyper Ball + Super Ball = 250 yen
# 2. Super Ball + Monster Ball = 200 yen
# 3. Monster Ball + Quick Ball = 180 yen
# 4. Hyper Ball + Quick Ball = 270 yen (for consistency check)
# この連立方程式は独立でないため、代入法で解く必要がある。
# These equations are not all independent; we will solve them using substitution.
# Step 1: Let Super Ball = S
S = 80 # スーパーボールの価格(仮定)/ Assume Super Ball price
# Step 2: From 1st equation → Hyper Ball = 250 - S
H = 250 - S # ハイパーボールの価格 / Hyper Ball price
# Step 3: From 2nd equation → Monster Ball = 200 - S
M = 200 - S # モンスターボールの価格 / Monster Ball price
# Step 4: From 3rd equation → Quick Ball = 180 - M = S - 20
Q = S - 20 # クイックボールの価格 / Quick Ball price
# Step 5: Check 4th equation (H + Q should be 270)
# H + Q = (250 - S) + (S - 20) = 230 → これは整合性チェック用
# H + Q = 230, not 270 → 4つの式は独立ではなく、3つのみで一意に定まる
# ---------------------------------------------
# 結果の出力 / Display the results
# ---------------------------------------------
print("【Poké Ball Price Results】")
print(f"Hyper Ball: {H} yen")
print(f"Super Ball: {S} yen")
print(f"Monster Ball: {M} yen")
print(f"Quick Ball: {Q} yen")
# ---------------------------------------------
# 棒グラフの描画 / Plotting the bar chart
# ---------------------------------------------
labels = ['Hyper Ball', 'Super Ball', 'Monster Ball', 'Quick Ball']
prices = [H, S, M, Q]
plt.figure(figsize=(8, 6)) # グラフサイズ設定 / Set figure size
plt.bar(labels, prices, color=['gold', 'blue', 'red', 'green']) # 棒グラフ作成 / Create bar chart
plt.title("Poké Ball Price Comparison", fontsize=14) # タイトル / Title
plt.xlabel("Type of Poké Ball", fontsize=12) # X軸ラベル / X-axis label
plt.ylabel("Price (yen)", fontsize=12) # Y軸ラベル / Y-axis label
plt.ylim(0, max(prices) + 50) # Y軸範囲設定 / Set Y-axis range
plt.grid(axis='y', linestyle='--', alpha=0.6) # グリッド線 / Grid lines
plt.tight_layout()
plt.show()
# プログラム名: poke_ball_purchase_solver.py
# Program Name: poke_ball_purchase_solver.py
#
# 説明:
# モンスターボール(1個80円)とスーパーボール(1個100円)を合計20個購入し、
# 合計金額1860円になるような組み合わせを、変数から計算し、グラフで可視化。
# 各直線の傾きと切片も表示。
#
# Description:
# Solve how many Monster Balls and Super Balls were bought given their prices and totals.
# Visualize both equations with their slopes and intercepts.
import numpy as np
import matplotlib.pyplot as plt
# -----------------------------
# 入力値 / Input Parameters
# -----------------------------
price_monster = 80 # Monster Ball price [yen]
price_super = 100 # Super Ball price [yen]
total_balls = 20 # Total number of balls
total_cost = 1860 # Total cost [yen]
# -----------------------------
# x: Number of Monster Balls
# y: Number of Super Balls
# -----------------------------
# Equation 1: x + y = total_balls → y = -1 * x + total_balls
# Equation 2: price_monster * x + price_super * y = total_cost → y = (-price_monster / price_super) * x + (total_cost / price_super)
# 解くための範囲設定 / x range
x_vals = np.linspace(0, total_balls, 400)
# 式変形による直線 / Lines from equations
y1 = total_balls - x_vals # Line 1: y = -x + total_balls
slope1 = -1
intercept1 = total_balls
y2 = (total_cost - price_monster * x_vals) / price_super # Line 2
slope2 = -price_monster / price_super
intercept2 = total_cost / price_super
# -----------------------------
# 厳密な交点(解) / Exact solution
# -----------------------------
A = np.array([[1, 1], [price_monster, price_super]])
B = np.array([total_balls, total_cost])
solution = np.linalg.solve(A, B)
x_sol = int(solution[0])
y_sol = int(solution[1])
# -----------------------------
# 結果表示 / Print result
# -----------------------------
print("【Solution / 解】")
print(f"Monster Balls: {x_sol} pcs")
print(f"Super Balls: {y_sol} pcs\n")
print("【Line 1: x + y = total_balls】")
print(f"→ y = {slope1} * x + {intercept1}")
print("【Line 2: price_monster * x + price_super * y = total_cost】")
print(f"→ y = {slope2:.2f} * x + {intercept2:.2f}")
# -----------------------------
# グラフ描画 / Plot
# -----------------------------
plt.figure(figsize=(9, 6))
plt.plot(x_vals, y1, label=f'y = {slope1}x + {intercept1}', linestyle='--', color='blue')
plt.plot(x_vals, y2, label=f'y = {slope2:.2f}x + {intercept2:.2f}', linestyle='-', color='orange')
plt.plot(x_sol, y_sol, 'ro', label=f'Solution: ({x_sol}, {y_sol})')
# グラフの設定 / Formatting
plt.title("Poké Ball Purchase: Solving with Graphs", fontsize=14)
plt.xlabel("Number of Monster Balls", fontsize=12)
plt.ylabel("Number of Super Balls", fontsize=12)
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend()
plt.xlim(0, total_balls)
plt.ylim(0, total_balls)
plt.tight_layout()
plt.show()
# プログラム名: blastoise_surf_distance.py
# 説明: カメックスがギャラドスの激流の中を泳いで移動した距離を変数で求める
# Description: Calculates distance swum by Blastoise against and with the current caused by Gyarados
# -----------------------------
# ポケモン設定(変数で管理)/ Pokémon Setup
# -----------------------------
v_base = 20 # カメックスの静水時スピード [km/h]
v_stream = 4 # ギャラドスの激流(流れ) [km/h]
t_up = 6 # 上り(A→B)にかかった時間 [h]
t_down = 4 # 下り(B→A)にかかった時間 [h]
# -----------------------------
# 実効速度計算 / Effective Speeds
# -----------------------------
v_up = v_base - v_stream # 上り速度(激流に逆らう)
v_down = v_base + v_stream # 下り速度(激流に乗る)
# -----------------------------
# 距離計算 / Distance Calculation
# -----------------------------
# 距離はどちらでも求められるが、下りのデータを使用:
distance = v_down * t_down # または distance = v_up * t_up
# -----------------------------
# 結果表示 / Result Output
# -----------------------------
print("🌊【カメックスのなみのり冒険】Blastoise Surfing Adventure")
print(f"🛶 カメックスの静水スピード: {v_base} km/h")
print(f"🌪️ ギャラドスが作った激流: {v_stream} km/h")
print(f"⬆️ 上り時間: {t_up} 時間(速度 {v_up} km/h)")
print(f"⬇️ 下り時間: {t_down} 時間(速度 {v_down} km/h)")
print(f"📏 移動した距離(A → B): {distance} km")
# プログラム名: pokemon_speed_distance_problems.py
# 説明: ポケモン世界を舞台に、速さ・時間・距離に関する基本問題を変数で解く
# Description: Solve basic speed-distance-time problems using Pokémon context and variable-based calculation
# --------------------------
# (1) ピカチュウが自転車で冒険
# Pikachu bikes for 3h24min and travels 40800m. Find speed [m/min].
# --------------------------
t1_hr = 3
t1_min = 24
d1_m = 40800
total_min1 = t1_hr * 60 + t1_min
v1_min = d1_m / total_min1 # [m/min]
# --------------------------
# (2) マラソンポケモントレーナー
# Haromi runs 2.8 km in 40 min. Find speed [km/h].
# --------------------------
d2_km = 2.8
t2_min = 40
v2_kmh = d2_km / (t2_min / 60) # [km/h]
# --------------------------
# (3) イシツブテの動く歩道
# Moving walkway travels 56 m in 1min20sec. Find speed [m/s].
# --------------------------
d3_m = 56
t3_min = 1
t3_sec = 20
total_sec3 = t3_min * 60 + t3_sec
v3_ms = d3_m / total_sec3 # [m/s]
# --------------------------
# (4) フシギダネが草むらを歩く
# Fushigidane walks for 40 min at 450 m/min. Find total distance [km].
# --------------------------
v4_min = 450
t4_min = 40
d4_km = (v4_min * t4_min) / 1000 # [km]
# --------------------------
# (5) リザードンが15分間空を飛ぶ
# Charizard flies 15 min at 40 km/h. Find distance [m].
# --------------------------
v5_kmh = 40
t5_min = 15
d5_m = v5_kmh * (t5_min / 60) * 1000 # [m]
# --------------------------
# (6) ヒトカゲが6.4kmの冒険
# Hitokage walks 6.4 km at 40 m/min. Find time [hr, min].
# --------------------------
d6_km = 6.4
v6_min = 40
total_min6 = (d6_km * 1000) / v6_min
t6_hr = int(total_min6 // 60)
t6_min = int(total_min6 % 60)
# --------------------------
# (7) イーブイのダッシュ
# Eevee runs 2.4km: first 1.8km at 40 m/min, remaining at 1.5×speed.
# --------------------------
d7_km_total = 2.4
d7_km1 = 1.8
v7_min1 = 40
v7_min2 = v7_min1 * 1.5
d7_km2 = d7_km_total - d7_km1
t7_min1 = (d7_km1 * 1000) / v7_min1
t7_min2 = (d7_km2 * 1000) / v7_min2
t7_total_min = t7_min1 + t7_min2
# --------------------------
# (8) カメックスのなみのり
# Blastoise surfs at 2.7 km/h. Find speed [m/min].
# --------------------------
v8_kmh = 2.7
v8_min = (v8_kmh * 1000) / 60 # [m/min]
# --------------------------
# (9) トゲピーのチョコ配り
# Togepi walks at 35 m/min. Find speed [km/h].
# --------------------------
v9_min = 35
v9_kmh = (v9_min * 60) / 1000 # [km/h]
# --------------------------
# (10) ニャースの忍び足
# Meowth moves at 0.072 km/h. Find speed [m/s].
# --------------------------
v10_kmh = 0.072
v10_ms = (v10_kmh * 1000) / 3600 # [m/s]
# --------------------------
# (11) サトシの往復旅
# 21km one-way: walk at 3km/h, return at 7km/h. Find average speed [km/h].
# --------------------------
d11_km = 21
v11_go = 3
v11_return = 7
t11_go = d11_km / v11_go
t11_return = d11_km / v11_return
t11_total = t11_go + t11_return
d11_total = d11_km * 2
v11_avg = d11_total / t11_total # [km/h]
# --------------------------
# 結果出力(任意)/ Optional output
# --------------------------
print("Pokémon Distance & Speed Calculations (All in Variables)")
print(f"(1) Pikachu's biking speed: {v1_min:.2f} m/min")
print(f"(2) Haromi's running speed: {v2_kmh:.2f} km/h")
print(f"(3) Walkway speed: {v3_ms:.2f} m/s")
print(f"(4) Fushigidane's distance: {d4_km:.2f} km")
print(f"(5) Charizard's flight distance: {d5_m:.2f} m")
print(f"(6) Hitokage time: {t6_hr} hr {t6_min} min")
print(f"(7) Eevee total time: {t7_total_min:.2f} min")
print(f"(8) Blastoise speed: {v8_min:.2f} m/min")
print(f"(9) Togepi speed: {v9_kmh:.2f} km/h")
print(f"(10) Meowth speed: {v10_ms:.4f} m/s")
print(f"(11) Satoshi's average round-trip speed: {v11_avg:.2f} km/h")
# プログラム名: pokemon_ratio_product_regression.py
# 説明: ピカチュウとフシギダネを使って「商が一定」「積が一定」の回帰と可視化を行う
# Description: Model proportional (Pikachu) and inverse (Fushigidane) relationships with regression
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# --------------------------
# ① ピカチュウ:レベルと電撃の威力(比例)
# --------------------------
# Pikachu's level vs electric power (proportional)
level = np.array([10, 20, 30, 40, 50, 60]).reshape(-1, 1) # レベル x
power = level * 5 + np.random.normal(0, 5, size=level.shape) # 威力 y(ノイズあり)
# 線形回帰 / Linear regression
model_pika = LinearRegression()
model_pika.fit(level, power)
# 回帰式: y = a*x + b
slope_pika = model_pika.coef_[0][0]
intercept_pika = model_pika.intercept_[0]
# --------------------------
# ② フシギダネ:つるの長さと引っ張る力(逆比例)
# --------------------------
# Fushigidane's vine length vs pulling force (inverse)
length = np.array([1, 2, 3, 4, 5, 6]) # ムチの長さ x
const_product = 60 # x*y = 一定
force = const_product / length + np.random.normal(0, 0.5, size=length.shape) # 力 y
# 回帰のために 1/x を説明変数にする
X_inv = 1 / length.reshape(-1, 1)
y_inv = force
# 線形回帰(y = a*(1/x) + b)
model_fushi = LinearRegression()
model_fushi.fit(X_inv, y_inv)
slope_fushi = model_fushi.coef_[0]
intercept_fushi = model_fushi.intercept_
# --------------------------
# プロット
# --------------------------
fig, ax = plt.subplots(1, 2, figsize=(12, 5))
# (1) ピカチュウの比例
ax[0].scatter(level, power, label="Observed", color='gold')
ax[0].plot(level, model_pika.predict(level), color='red', label=f"y = {slope_pika:.2f}x + {intercept_pika:.2f}")
ax[0].set_title("Pikachu: Level vs Electric Power")
ax[0].set_xlabel("Level")
ax[0].set_ylabel("Electric Power")
ax[0].legend()
ax[0].grid(True)
# (2) フシギダネの逆比例
ax[1].scatter(length, force, label="Observed", color='green')
length_smooth = np.linspace(1, 6, 100)
X_inv_smooth = 1 / length_smooth.reshape(-1, 1)
ax[1].plot(length_smooth, model_fushi.predict(X_inv_smooth),
color='blue', label=f"y = {slope_fushi:.2f}/x + {intercept_fushi:.2f}")
ax[1].set_title("Fushigidane: Vine Length vs Pulling Force")
ax[1].set_xlabel("Vine Length")
ax[1].set_ylabel("Pulling Force")
ax[1].legend()
ax[1].grid(True)
plt.tight_layout()
plt.show()
# プログラム名: miltank_moomoo_milk_filling_simulation.py
# Program Name: miltank_moomoo_milk_filling_simulation.py
#
# 説明(日本語):
# ポケモンのミルタンクがモーモーミルクを毎分一定量注ぐタンクに関する問題。
# タンクは前後に仕切られており、仕切りを越えると後ろの区画にもミルクが流れ込む。
# ア: 仕切りまで満たすのにかかる時間
# イ: 後ろの区画が満たされる時間
# ウ: 全体が満たされる時間 を求めます。
#
# Description (English):
# Miltank fills a divided tank with Moomoo Milk at a constant rate per minute.
# Once the milk level reaches the divider, it starts to fill the rear compartment.
# This program calculates:
# A: Time to fill up to the divider
# B: Time to fill the rear section
# C: Time to fill the entire tank.
# --------------------------
# 定数 / Constants
# --------------------------
v_milk = 1680 # 注ぐ量 [cm³/min] / milk per minute
w1, d1 = 30, 20 # 前区画の底面 [cm] / front section base
w2, d2 = 40, 20 # 後区画の底面 [cm] / rear section base
h_split = 28 # 仕切りの高さ [cm] / divider height
h_total = 40 # タンク全体の高さ [cm]
# --------------------------
# 容積計算 / Volume calculation
# --------------------------
# ア: 前の区画の仕切りまでの容量
vol_a = w1 * d1 * h_split # [cm³]
# イ: 後ろの区画の容量(仕切りの高さまで)
vol_b = w2 * d2 * h_split # [cm³]
# ウ: 全体容量
vol_front = w1 * d1 * h_total # 前全部
vol_rear = w2 * d2 * h_total # 後全部
vol_total = vol_front + vol_rear
# --------------------------
# 時間計算 / Time Calculation
# --------------------------
t_a = vol_a / v_milk # ア: 前の区画(仕切りまで)
t_b = vol_b / v_milk # イ: 後ろ区画が満タン
t_c = vol_total / v_milk # ウ: 全体が満タン
t_b_total = t_a + t_b # イ(仕切りまで + 後部満タン)
t_c_total = t_c # ウ(全体)
# --------------------------
# 表示 / Output
# --------------------------
print(" モーモーミルク タンク注入シミュレーション")
print(f"【ア】仕切りに達するまで: {t_a:.1f} 分")
print(f"【イ】後ろの区画が満たされるまで: {t_b_total:.1f} 分")
print(f"【ウ】全体が満たされるまで: {t_c_total:.1f} 分")
# プログラム名: pikachu_moomoo_clock_angle.py
# Program Name: pikachu_moomoo_clock_angle.py
#
# 説明:
# ピカチュウがミルタンクのモーモーミルク配達のために8時22分の時計を確認。
# このときの短針と長針の角度の差(小さい方)を計算し、アナログ時計で描画する。
#
# Description:
# Pikachu checks the time for Moomoo Milk delivery at 8:22.
# This program calculates the smaller angle between the hour and minute hands
# and draws an analog clock to show the time visually.
import matplotlib.pyplot as plt
import numpy as np
# -----------------------------
# 時刻設定 / Time setting
# -----------------------------
pokemon = "Pikachu" # ポケモン名 / Pokémon name
delivery_time_hour = 8 # 配達時刻:時 / Hour
delivery_time_minute = 22 # 配達時刻:分 / Minute
# -----------------------------
# 角度の計算 / Angle calculation
# -----------------------------
# 長針は1分で6度進む / Minute hand moves 6° per minute
minute_angle = delivery_time_minute * 6 # [°]
# 短針は1時間で30度、1分ごとに0.5度進む
# Hour hand moves 30° per hour + 0.5° per minute
hour_angle = (delivery_time_hour % 12) * 30 + (delivery_time_minute * 0.5) # [°]
# 両針の角度差(小さい方)/ Smaller angle between hour and minute hands
angle_diff = abs(hour_angle - minute_angle)
smaller_angle = min(angle_diff, 360 - angle_diff)
# -----------------------------
# 時計描画関数 / Clock drawing function
# -----------------------------
def draw_pokemon_clock(hour_angle, minute_angle, hour, minute):
fig, ax = plt.subplots(figsize=(6, 6))
ax.set_facecolor("white")
# 時計の円盤を描く / Draw clock face
circle = plt.Circle((0, 0), 1, color='lightyellow', fill=True)
ax.add_artist(circle)
# 時刻の数字を描く / Draw hour numbers
for h in range(1, 13):
angle = np.deg2rad(90 - h * 30)
x = 0.85 * np.cos(angle)
y = 0.85 * np.sin(angle)
ax.text(x, y, str(h), ha='center', va='center', fontsize=14, weight='bold')
# 長針を描く(青) / Draw minute hand (blue)
angle_min = np.deg2rad(90 - minute_angle)
ax.plot([0, 0.9 * np.cos(angle_min)], [0, 0.9 * np.sin(angle_min)],
color='blue', linewidth=3, label='Minute Hand')
# 短針を描く(赤) / Draw hour hand (red)
angle_hour = np.deg2rad(90 - hour_angle)
ax.plot([0, 0.6 * np.cos(angle_hour)], [0, 0.6 * np.sin(angle_hour)],
color='red', linewidth=5, label='Hour Hand')
# 時計の中心点 / Draw clock center
ax.plot(0, 0, 'ko', markersize=6)
# タイトル / Title
ax.set_title(f"{pokemon}'s Moomoo Milk Clock — {hour}:{minute:02d}", fontsize=14)
# 凡例 / Legend
ax.legend()
# 軸設定 / Axis formatting
ax.axis("equal")
ax.axis("off")
plt.show()
# -----------------------------
# 結果出力 / Display results
# -----------------------------
print("📦 Moomoo Milk Delivery Time Checker")
print(f"🕗 Time: {delivery_time_hour}:{delivery_time_minute:02d}")
print(f"🔴 Hour hand angle: {hour_angle:.2f}°")
print(f"🔵 Minute hand angle: {minute_angle:.2f}°")
print(f"📐 Smaller angle between hands: {smaller_angle:.2f}°")
# 時計を描画 / Draw the clock
draw_pokemon_clock(hour_angle, minute_angle, delivery_time_hour, delivery_time_minute)
# プログラム名: pokemon_gym_queue_simulation.py
# Program Name: pokemon_gym_queue_simulation.py
#
# 説明(日本語):
# ポケモンジムの前に行列ができている状況を再現し、1つの窓口と2つの窓口の場合で、
# 行列が何分で解消されるかを比較する。行列に並ぶトレーナーの人数と、入場処理の速さを使って
# 変化量を求め、行列の減少速度から所要時間を計算する。
#
# Description (English):
# This simulation models a queue in front of a Pokémon Gym.
# It calculates how long it takes for the line to disappear when there is 1 entrance and then when there are 2 entrances.
# Based on the number of people initially in line, the rate of new arrivals, and the entry rate,
# it determines the time needed to clear the queue using simple rate-based reasoning.
# ----------------------------
# 例題: ポケモンジムの行列の問題
# Example 1: Pokémon Gym Entrance Queue Problem
# ----------------------------
# 変数設定 / Variables
initial_people = 360 # 最初に並んでいたトレーナー数 / Number of people initially in line
people_joining_per_min = 6 # 毎分加わるトレーナー数 / People joining the queue per minute
t1 = 30 # 窓口1つで行列がなくなる時間 / Time for 1 entrance to clear the line
# ----------------------------
# 1つの窓口での1分あたり入場人数を求める
# Calculate number of people entering per minute with 1 window
total_people1 = initial_people + people_joining_per_min * t1 # 合計入場人数 / Total number entered in 30 minutes
entry_rate_per_window = total_people1 / t1 # 入場率(1つの窓口)/ Entry rate per window
# 窓口を2つにしたときの1分あたり入場人数
# Entry rate with 2 windows
entry_rate_2_windows = entry_rate_per_window * 2
# 列の減少スピード(純減)
# Net reduction in queue per minute = entry rate - joining rate
net_reduction_rate = entry_rate_2_windows - people_joining_per_min
# 行列がゼロになるまでの時間を計算
# Calculate time required to clear the queue
t2 = initial_people / net_reduction_rate
# ----------------------------
# 結果出力 / Output
# ----------------------------
print("ポケモンジムの行列 / Pokémon Gym Queue Problem")
print(f"1つの窓口での入場人数: {entry_rate_per_window:.0f} 人/分 / per minute")
print(f"2つの窓口で行列がなくなる時間: {t2:.0f} 分 / minutes")
# プログラム名: pikachu_jump_quadratic_gradient.py
# Program Name: pikachu_jump_quadratic_gradient.py
#
# 説明(日本語):
# ピカチュウがジャンプする高さを2次関数 y = -a(x - h)^2 + k でモデル化し、
# ジャンプの最高点(頂点)を勾配降下法(Gradient Descent)で求めます。
# また、時間と高さの関係をグラフで描画します。
#
# Description (English):
# This program models Pikachu's jump height as a quadratic function
# y = -a(x - h)^2 + k and uses gradient descent to find the vertex (maximum point).
# It also plots the trajectory of the jump over time.
import numpy as np
import matplotlib.pyplot as plt
# -----------------------------
# パラメータ設定 / Model Parameters
# -----------------------------
a = 16 # 放物線の開き具合(大きいほど鋭い) / parabola steepness
h = 1.5 # 頂点の時間 [秒] / vertex time (seconds)
k = 36 # 最大高さ [cm] / vertex height (cm)
# 2次関数のモデル: y = -a(x - h)^2 + k
# Quadratic model: y = -a(x - h)^2 + k
# -----------------------------
# 時間範囲と高さの計算 / Time and height data
# -----------------------------
x_vals = np.linspace(0, 3, 100)
y_vals = -a * (x_vals - h)**2 + k
# -----------------------------
# 勾配降下法による頂点探索 / Gradient Descent to find vertex
# -----------------------------
# 初期値 / initial guess
x = 0.0
# 学習率 / learning rate
lr = 0.01
# イテレーション回数 / number of iterations
n_iterations = 1000
# 勾配降下法ループ / gradient descent loop
for i in range(n_iterations):
gradient = -2 * a * (x - h) # y' = -2a(x - h)
x = x + lr * gradient
x_vertex = x
y_vertex = -a * (x_vertex - h)**2 + k
# -----------------------------
# 結果表示 / Result
# -----------------------------
print(" ピカチュウのジャンプ軌道モデル / Pikachu Jump Trajectory Model")
print(f"モデル式 / Model: y = -{a}(x - {h})² + {k}")
print(f"勾配降下法による頂点(最高点)/ Vertex found by gradient descent:")
print(f"Time (x): {x_vertex:.4f} 秒 / sec")
print(f"Height (y): {y_vertex:.4f} cm")
# -----------------------------
# プロット / Plot
# -----------------------------
plt.figure(figsize=(8, 5))
plt.plot(x_vals, y_vals, label='Jump Trajectory (y = -a(x - h)^2 + k)', color='orange')
plt.scatter(x_vertex, y_vertex, color='red', label=f'Max Height\n({x_vertex:.2f} sec, {y_vertex:.2f} cm)', zorder=5)
plt.title("Pikachu's Jump Height Over Time")
plt.xlabel("Time (sec)")
plt.ylabel("Height (cm)")
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
# Program Name:PokemonTrainerResourceSolver.py
# --- Pokemon育成問題の解法 --- #
# このプログラムでは、6匹のポケモンの育成に必要な費用、レベル、アイテム数を求めます。
# 基本的な数式と連立方程式を使用して解を計算します。
import sympy as sp
# --- 変数の定義 --- #
# P1, P2, P3, P4, P5, P6 はそれぞれのポケモンの育成費用
# L1, L2, L3, L4, L5, L6 はそれぞれのポケモンのレベル
# I1, I2, I3, I4, I5, I6 はそれぞれのポケモンの育成に必要なアイテムの数
P1, P2, P3, P4, P5, P6 = sp.symbols('P1 P2 P3 P4 P5 P6')
L1, L2, L3, L4, L5, L6 = sp.symbols('L1 L2 L3 L4 L5 L6')
I1, I2, I3, I4, I5, I6 = sp.symbols('I1 I2 I3 I4 I5 I6')
# --- 方程式を立てる --- #
# 連立方程式の定義
# 1. ピカチュウの育成費用はイーブイの2倍、イーブイの育成費用はフシギダネの1.5倍
eq1 = sp.Eq(P1, 2 * P2)
eq2 = sp.Eq(P2, 1.5 * P3)
# 2. フシギダネのレベルはイーブイの2倍、ピカチュウのレベルはフシギダネの1.2倍
eq3 = sp.Eq(L3, 2 * L2)
eq4 = sp.Eq(L1, 1.2 * L3)
# 3. ピカチュウ、イーブイ、フシギダネの育成に必要なアイテムの合計数は30個
eq5 = sp.Eq(I1 + I2 + I3, 30)
# 4. サトシのカメックス、ゲンガーの育成に必要なアイテムの合計数は25個
eq6 = sp.Eq(I4 + I5, 25)
# 5. サトシのカメックスはピカチュウよりも2匹多く育成されている
# 6. サトシのゲンガーはイーブイより1匹少なく育成されている
# --- 方程式の解を求める --- #
# 方程式を解く
solutions = sp.solve([eq1, eq2, eq3, eq4, eq5, eq6], (P1, P2, P3, P4, P5, P6, L1, L2, L3, L4, L5, L6, I1, I2, I3, I4, I5, I6))
# --- 結果の表示 --- #
# 結果を表示
for var, sol in solutions.items():
print(f'{var} = {sol}')
# --- 結果の可視化 --- #
# ここでは、ポケモンの費用やレベル、アイテム数を可視化するグラフを描画
import matplotlib.pyplot as plt
# 取得した解を使ってデータをプロット
pokemon_names = ['Pikachu', 'Eevee', 'Fushigidane', 'Kamex', 'Gengar']
costs = [solutions[P1], solutions[P2], solutions[P3], solutions[P4], solutions[P5]]
levels = [solutions[L1], solutions[L2], solutions[L3], solutions[L4], solutions[L5]]
# グラフ作成
fig, ax = plt.subplots(2, 1, figsize=(10, 8))
# 1. ポケモンの育成費用のグラフ
ax[0].bar(pokemon_names, costs, color='blue')
ax[0].set_title("Pokemon Training Costs")
ax[0].set_xlabel("Pokemon")
ax[0].set_ylabel("Cost (Units)")
# 2. ポケモンのレベルのグラフ
ax[1].bar(pokemon_names, levels, color='green')
ax[1].set_title("Pokemon Levels")
ax[1].set_xlabel("Pokemon")
ax[1].set_ylabel("Level")
plt.tight_layout()
plt.show()
# -*- coding: utf-8 -*-
# Program Name: pokemon_money_allocation.py
# ポケモン3匹で賞金5200円を差のある状態で分ける(和差算)
# 条件設定
total_money = 5200 # 総額
pikachu_minus_eevee = 680 # ピカチュウはイーブイより680円多い
eevee_minus_charmander = 250 # イーブイはヒトカゲより250円多い
# ピカチュウ = イーブイ + 680
# イーブイ = ヒトカゲ + 250
# よって ピカチュウ = ヒトカゲ + 250 + 680 = ヒトカゲ + 930
# 和差算として整理
# 3匹の合計:ピカチュウ + イーブイ + ヒトカゲ = 5200
# = (ヒトカゲ + 930) + (ヒトカゲ + 250) + ヒトカゲ = 3ヒトカゲ + 1180
charmander_yen = (total_money - (pikachu_minus_eevee + eevee_minus_charmander)) // 3
eevee_yen = charmander_yen + eevee_minus_charmander
pikachu_yen = eevee_yen + pikachu_minus_eevee
# 結果出力
print("【ポケモン賞金分配】")
print("ヒトカゲ(Charmander):", charmander_yen, "円")
print("イーブイ(Eevee):", eevee_yen, "円")
print("ピカチュウ(Pikachu):", pikachu_yen, "円")
print("合計:", pikachu_yen + eevee_yen + charmander_yen, "円(検算)")
# -*- coding: utf-8 -*-
# Program Name: pokemon_candy_distribution.py
# 過不足算:アメをポケモンたちに配る問題
# --- 条件設定 / Conditions ---
# 配る数
per_pokemon_less = 4 # 少ない配り方:1匹あたり4個
per_pokemon_more = 6 # 多い配り方:1匹あたり6個
# 残り・不足
extra_candies = 16 # 4個ずつ配ると16個余る
lack_candies = 4 # 6個ずつ配ると4個足りない
# --- 過不足算の基本式 / Solve using difference method ---
# 差の合計:6個ずつ配るには4個足りず、4個ずつ配ると16個余る → 差は20個
difference = lack_candies + extra_candies # 4 + 16 = 20
# 1匹あたりの配布差
per_pokemon_diff = per_pokemon_more - per_pokemon_less # 6 - 4 = 2
# ポケモンの子どもの数
num_pokemon = difference // per_pokemon_diff # 20 / 2 = 10
# アメの総数(4個ずつ配って余る16個)
total_candies = num_pokemon * per_pokemon_less + extra_candies # 10 * 4 + 16 = 56
# --- 結果表示 / Output ---
print("【ポケモンアメ配り問題】")
print("子どものポケモンの数:", num_pokemon, "匹")
print("用意されたアメの総数:", total_candies, "個")
# -*- coding: utf-8 -*-
# Program Name: pokemon_bench_seating.py
# 体育館のベンチにピカチュウたちを座らせる過不足算
# --- 与えられた条件 ---
seating_pattern_1 = 7 # 1脚あたり7匹座れる
seating_pattern_2 = 5 # 1脚あたり5匹座れる
# パターン1では1脚余り、19匹あまる(= 合計28匹の差)
# パターン2では9匹不足
extra_pikachu = 19
missing_pikachu = 9
total_diff = extra_pikachu + missing_pikachu # = 28
# 1脚あたりの差(7匹 - 5匹 = 2匹)
diff_per_bench = seating_pattern_1 - seating_pattern_2
# ベンチの数
num_benches = total_diff // diff_per_bench
# ピカチュウの数(7匹×ベンチ数 − 9匹)
num_pikachu = seating_pattern_1 * num_benches - missing_pikachu
# 検算(5匹×ベンチ数 + 19匹)
check = seating_pattern_2 * num_benches + extra_pikachu
# --- 結果表示 ---
print("【ポケモンのベンチ座り問題】")
print("ベンチの数(脚):", num_benches, "脚")
print("ピカチュウの数 :", num_pikachu, "匹")
print("検算結果 :", check, "匹(←一致すれば正解)")
# -*- coding: utf-8 -*-
# Program Name: pokemon_saline_mix.py
# ポケモン世界の食塩水の濃度計算(濃度の平均)
# --- 入力値 / Input values ---
# 4%のミズゴロウ水:400g
percent_mizugorou = 4
weight_mizugorou = 400
# 7%のマリル水:200g
percent_marill = 7
weight_marill = 200
# --- 食塩の質量を計算 / Calculate amount of salt in each solution ---
salt_mizugorou = percent_mizugorou / 100 * weight_mizugorou # = 16g
salt_marill = percent_marill / 100 * weight_marill # = 14g
# --- 合計重量と塩の量 / Total mixture ---
total_weight = weight_mizugorou + weight_marill # = 600g
total_salt = salt_mizugorou + salt_marill # = 30g
# --- 濃度(%)を計算 / Final concentration percentage ---
final_percent = total_salt / total_weight * 100 # = 5%
# --- 結果表示 / Output ---
print("【ポケモン食塩水混合】")
print("最終的な濃度:", final_percent, "%")
# -*- coding: utf-8 -*-
# Program Name: pokemon_saline_dilution.py
# 食塩水から一部を取り出し、水を加えて濃度が変化する計算(減塩型)
# --- 与えられた条件 ---
initial_percent = 8 # 初期濃度(%)
initial_weight = 400 # 初期食塩水の質量(g)
final_percent = 5 # 最終濃度(%)
final_weight = 400 # 最終食塩水の質量(g) = 初期と同じ
# --- 食塩量(変わらない)を考える / Solve with x as the removed amount ---
# x g 食塩水を抜く → その中には (8/100)*x g の食塩が含まれる
# 残りの食塩水には 8/100 * (400 - x) g の食塩が残っている
# 水を加えて 400g に戻した結果、全体で 5% になった
# 式:
# 0.08 * (400 - x) = 0.05 * 400
# 解いて x を求める
from sympy import symbols, solve
x = symbols('x') # 抜いた食塩水の重さ
equation = 0.08 * (400 - x) - 0.05 * 400
solution = solve(equation, x)
removed_weight = float(solution[0])
# --- 結果表示 ---
print("【ポケモン食塩水:減塩型】")
print("取り出した食塩水の重さ:", round(removed_weight, 2), "g")
# -*- coding: utf-8 -*-
# Program Name: pokemon_profit_discount_variables.py
# ロケット団の利益計算:定価設定+割引販売 → 最終利益を求める(変数すべて定義)
# --- 初期設定 / Initial variables ---
purchase_price = 1200 # 仕入れ価格(例:1200円)
profit_rate = 0.3 # 定価への利益率(30%)
discount_rate = 0.1 # 割引率(10%)
# --- 定価の計算 / Calculate list price ---
list_price = purchase_price * (1 + profit_rate) # 定価 = 原価 × (1 + 利益率)
# --- 実際の販売価格 / Apply discount ---
sale_price = list_price * (1 - discount_rate) # 実販売価格 = 定価 × (1 - 割引率)
# --- 最終利益 / Final profit ---
profit = sale_price - purchase_price # 利益 = 売価 - 原価
# --- 出力 / Print results ---
print("【ポケモン販売利益シミュレーション】")
print("仕入れ価格(purchase_price):", purchase_price, "円")
print("定価(list_price):", list_price, "円")
print("割引後の販売価格(sale_price):", sale_price, "円")
print("最終的な利益(profit):", round(profit), "円")
# -*- coding: utf-8 -*-
# Program Name: pokemon_work_problem_variables.py
# ポケモンの仕事算:すべての数値を変数化して管理
from sympy import symbols, solve
# --- 基本設定(すべて変数)/ Define all given values as variables ---
days_to_finish_by_pokemonA = 30 # Aポケモンが1匹で仕事を終える日数
days_to_finish_by_pokemonA_and_B = 20 # A + Bポケモンで仕事を終える日数
total_days_actual = 36 # 実際にかかった合計日数(問題2)
# --- 仕事量(1を単位とする)/ Work amount = 1 job ---
# 1日あたりの仕事量(ワークレート)
work_rate_A = 1 / days_to_finish_by_pokemonA
work_rate_AB = 1 / days_to_finish_by_pokemonA_and_B
# Bポケモンの1日あたりの仕事量(A+B - A)
work_rate_B = work_rate_AB - work_rate_A
# --- 問題1:Bポケモン1匹で仕事をすると何日? ---
days_to_finish_by_pokemonB = 1 / work_rate_B
# --- 問題2:連立方程式で解く(Aがx日、Bが残りの日数働いた) ---
x = symbols('x') # Aが作業した日数
# Aの作業 + Bの作業 = 1仕事
equation = work_rate_A * x + work_rate_B * (total_days_actual - x) - 1
solution_x = solve(equation, x)
# 解を整理
a_work_days = float(solution_x[0]) # Aが作業した日数
b_work_days = total_days_actual - a_work_days # Bが作業した日数
# --- 結果表示 / Print results ---
print("【仕事算:ポケモンバージョン】")
print("1. Bポケモン1匹で仕事を終えるのにかかる日数:", round(days_to_finish_by_pokemonB, 1), "日")
print("2. Aポケモンが作業した日数:", round(a_work_days, 1), "日")
print(" Bポケモンが作業した日数:", round(b_work_days, 1), "日")
# -*- coding: utf-8 -*-
# Program Name: pokemon_chase_and_meeting.py
# 追いつき・出会い問題を変数で自動計算
print("🏃♀️【問題1・2:姉が8分遅れて妹を追いかける】")
# 妹の速さ(m/min)
speed_younger = 50
# 姉の速さ(m/min)
speed_elder = 90
# 姉の出発遅れ(min)
delay_time = 8
# 妹が進んだ距離 = 姉が追いつくまでの差
initial_gap = speed_younger * delay_time
# 速さの差で追いつくまでの時間(姉の出発から)
relative_speed = speed_elder - speed_younger
catch_up_time = initial_gap / relative_speed
# 追いついた地点の距離(家から)
meeting_distance = speed_elder * catch_up_time
print("姉が家を出てから追いつくまで:", round(catch_up_time, 1), "分")
print("追いついた地点は家から:", round(meeting_distance, 1), "m")
print("\n【問題3:反対方向で出発して出会う池の周り】")
# 池の周囲(m)
lake_circumference = 2400
# Aの速さ
speed_A = 80
# Bの速さ
speed_B = 160
# 相対速度 = A + B(反対方向なので)
total_speed = speed_A + speed_B
meeting_time = lake_circumference / total_speed
print("出発してから初めて出会うのは:", round(meeting_time, 1), "分後")
# -*- coding: utf-8 -*-
# Program Name: pokemon_tree_spacing_adventure.py
# ポケモンの世界で木やテープを使った間隔・本数・長さの冒険問題(完全変数版)
# 問題①:ナエトルの本数
route_length_1 = 182 # 道路の長さ
interval_naetle = 7 # ナエトルを植える間隔
naetle_count = route_length_1 // interval_naetle + 1 # 両端に植える
print("🌲【問題①】")
print("道路の長さ:", route_length_1, "m")
print("ナエトル間隔:", interval_naetle, "m")
print("必要なナエトルの数:", naetle_count, "匹")
# 問題②:道路の長さ
interval_shroom = 5
shroom_count = 20
road_length_2 = (shroom_count - 1) * interval_shroom
print("\n🌲【問題②】")
print("間隔:", interval_shroom, "m")
print("キノガッサの本数:", shroom_count, "本")
print("道路の長さ:", road_length_2, "m")
# 問題③:キレイハナの数(池の周り)
pond_circumference = 60
interval_flower = 5
flower_count = pond_circumference // interval_flower
print("\n🌳【問題③】")
print("池の周囲:", pond_circumference, "m")
print("キレイハナの間隔:", interval_flower, "m")
print("必要なキレイハナの数:", flower_count, "本")
# 問題④:モココ街灯の数
road_length_4 = 72
interval_light = 6
lamp_count = road_length_4 // interval_light + 1
print("\n⚡【問題④】")
print("道路の長さ:", road_length_4, "m")
print("街灯間隔:", interval_light, "m")
print("必要なモココ街灯の数:", lamp_count, "基")
# 問題⑤:メタモンテープの長さ
tape_length = 16
number_of_tapes = 7
overlap_length = 3
total_tape_length = tape_length * number_of_tapes - overlap_length * (number_of_tapes - 1)
print("\n📏【問題⑤】")
print("テープ1本の長さ:", tape_length, "cm")
print("枚数:", number_of_tapes, "枚")
print("のりしろ:", overlap_length, "cm")
print("つなげた長さ:", total_tape_length, "cm")
# -*- coding: utf-8 -*-
# Program Name: arithmetic_table_locator.py
# 等差数列の表から任意の数が何行目・何列目かを計算する
# --- 表のパラメータ設定 ---
columns = 7 # 列の数(1行に7個)
row_step = columns # 行ごとの増分(等差)
target_number = 150 # 調べたい数
# --- 最初の行(1行目)は1~7の数が入る ---
# その後は各列が +7ずつ増えていく縦の等差数列
remainder = (target_number - 1) % columns # 0-based列位置
column_index = remainder + 1 # 1-based列番号
row_index = (target_number - column_index) // row_step + 1 # 1-based行番号
print(" 等差数列の表")
print("対象の数:", target_number)
print("列の数:", columns)
print("→", target_number, "は", row_index, "行目", column_index, "列目にあります。")