Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

プロンプトエンジニアリング【新規コーディング編】例:Least-to-Most

0
Last updated at Posted at 2026-10-30

本記事は、プロンプトエンジニアリングについて【新規コーディング編】の記事で比較した「Least-to-Most」による、説明用のサンプル記事です。
以下はAIの回答結果です。構成案の妥当性を保証するものではありません。

入力プロンプト

以下の要件を満たすPythonプログラムを作成してください。

【作業依頼】
売上CSVファイルを読み込み、商品別の売上金額と全体の合計金額を表示するPythonプログラムを新規作成したい。

【機能要件】
・CSVにはdate、product、quantity、priceの列がある
・売上金額はquantity × priceで計算する
・商品別の売上金額を集計する
・全商品の売上合計を表示する
・商品はCSVに最初に登場した順番で表示する

【制約条件】
・Pythonの標準ライブラリのみを使用する
・CSVファイル名はsales.csvとする
・結果はコンソールに表示する

【実装方法(Least-to-Most)】
いきなり完成コードを生成せず、以下の小さな課題を順番に解決してください。

ステップ1:CSVファイルの読み込み
・標準ライブラリを使用してsales.csvを読み込む処理を実装する
・date、product、quantity、priceの各列を取得する

ステップ2:売上金額の計算
・ステップ1で取得したデータを使用する
・各行のquantity × priceを計算する

ステップ3:商品別の売上集計
・ステップ2の計算結果を使用する
・同じ商品の売上金額を合算する
・商品はCSVに最初に登場した順番を維持する

ステップ4:全商品の売上合計
・ステップ3の集計結果を使用する
・全商品の売上合計金額を計算する

ステップ5:コンソールへの出力
・ステップ3とステップ4の結果を使用する
・商品別の売上金額と全体の合計金額を表示する

【進め方】
・ステップ1から順番に取り組んでください
・各ステップでは、その時点までの処理を実装したコードを提示してください
・次のステップでは、前のステップで作成したコードを引き継いで拡張してください
・各ステップの実装内容を簡潔に説明してください
・すべてのステップが完了したら、最終的な完成コードを提示してください

【回答形式】
・ステップ1〜5の実装内容とコード
・最終的な完成コード
・コードの実行方法
・使用した標準ライブラリの説明

AIの回答(実行方法の説明を省略)

Python売上集計プログラムの作成(Least-to-Most)

指定されたLeast-to-Mostの手法に従い、CSVの読み込みから始めて、処理を段階的に追加していきます。

各ステップでは、前のステップのコードを引き継ぎながら機能を拡張し、最後に完成コードを提示します。

ステップ1:CSVファイルの読み込み

標準ライブラリのcsvを使用して、sales.csvを読み込みます。

csv.DictReaderを使用すると、CSVの列名をキーとして各データを取得できます。

import csv

with open("sales.csv", "r", encoding="utf-8-sig", newline="") as file:
    reader = csv.DictReader(file)

    for row in reader:
        date = row["date"]
        product = row["product"]
        quantity = int(row["quantity"])
        price = int(row["price"])

        print(date, product, quantity, price)

実装内容

  • csv.DictReaderでCSVを読み込む。
  • date、product、quantity、priceを取得する。
  • quantityとpriceを整数に変換する。
  • 読み込んだデータを確認用に表示する。

ステップ2:売上金額の計算

ステップ1のコードに、各行の売上金額を計算する処理を追加します。

売上金額はquantity × priceで計算します。

import csv

with open("sales.csv", "r", encoding="utf-8-sig", newline="") as file:
    reader = csv.DictReader(file)

    for row in reader:
        date = row["date"]
        product = row["product"]
        quantity = int(row["quantity"])
        price = int(row["price"])

        sales = quantity * price

        print(date, product, sales)

追加した処理

  • sales = quantity * priceで売上金額を計算する。
  • 各行の売上金額を表示する。

ステップ3:商品別の売上集計

ステップ2の計算結果を商品別に集計します。

辞書型dictを使用すると、商品名をキー、売上金額を値として管理できます。

Python 3.7以降の辞書はキーの挿入順序を保持するため、CSVに最初に登場した商品順で表示できます。

import csv

product_sales = {}

with open("sales.csv", "r", encoding="utf-8-sig", newline="") as file:
    reader = csv.DictReader(file)

    for row in reader:
        date = row["date"]
        product = row["product"]
        quantity = int(row["quantity"])
        price = int(row["price"])

        sales = quantity * price

        if product not in product_sales:
            product_sales[product] = 0

        product_sales[product] += sales

for product, sales in product_sales.items():
    print(f"{product}: {sales}円")

追加した処理

  • product_salesという辞書を作成する。
  • 商品が辞書に存在しない場合は、売上金額を0で初期化する。
  • 同じ商品の売上金額を加算する。
  • 商品の初登場順を維持して集計結果を表示する。

ステップ4:全商品の売上合計

ステップ3で作成した商品別売上の辞書を使用して、全商品の売上合計を計算します。

import csv

product_sales = {}

with open("sales.csv", "r", encoding="utf-8-sig", newline="") as file:
    reader = csv.DictReader(file)

    for row in reader:
        date = row["date"]
        product = row["product"]
        quantity = int(row["quantity"])
        price = int(row["price"])

        sales = quantity * price

        if product not in product_sales:
            product_sales[product] = 0

        product_sales[product] += sales

total_sales = sum(product_sales.values())

for product, sales in product_sales.items():
    print(f"{product}: {sales}円")

print(f"合計: {total_sales}円")

追加した処理

  • product_sales.values()で商品別の売上金額を取得する。
  • sum()を使用して全商品の売上合計を計算する。
  • 全商品の売上合計を表示する。

ステップ5:コンソールへの出力

ステップ4までに実装した処理を引き継ぎ、商品別売上と全体の合計金額を見やすい形式で表示します。

import csv

product_sales = {}

with open("sales.csv", "r", encoding="utf-8-sig", newline="") as file:
    reader = csv.DictReader(file)

    for row in reader:
        date = row["date"]
        product = row["product"]
        quantity = int(row["quantity"])
        price = int(row["price"])

        sales = quantity * price

        if product not in product_sales:
            product_sales[product] = 0

        product_sales[product] += sales

total_sales = sum(product_sales.values())

print("商品別売上金額")
print("--------------------")

for product, sales in product_sales.items():
    print(f"{product}: {sales:,}円")

print("--------------------")
print(f"全体の売上合計: {total_sales:,}円")

追加した処理

  • 商品別売上と全体の合計を区切り線で分ける。
  • :,を使用して金額を3桁区切りで表示する。
  • 商品の表示順序はそのまま維持する。

最終的な完成コード

ステップ1〜5を統合した完成コードです。

ファイル名:sales_summary.py

import csv

# 商品別売上を保存する辞書
product_sales = {}

# ステップ1:CSVファイルの読み込み
with open("sales.csv", "r", encoding="utf-8-sig", newline="") as file:
    reader = csv.DictReader(file)

    for row in reader:
        date = row["date"]
        product = row["product"]
        quantity = int(row["quantity"])
        price = int(row["price"])

        # ステップ2:各行の売上金額を計算
        sales = quantity * price

        # ステップ3:商品別に売上金額を集計
        if product not in product_sales:
            product_sales[product] = 0

        product_sales[product] += sales

# ステップ4:全商品の売上合計を計算
total_sales = sum(product_sales.values())

# ステップ5:集計結果をコンソールに表示
print("商品別売上金額")
print("--------------------")

for product, sales in product_sales.items():
    print(f"{product}: {sales:,}円")

print("--------------------")
print(f"全体の売上合計: {total_sales:,}円")

入出力例

入力ファイル(sales.csv):

date,product,quantity,price
2026-10-01,りんご,3,150
2026-10-01,みかん,5,100
2026-10-02,りんご,2,150
2026-10-02,バナナ,4,120
2026-10-03,みかん,3,100

実行結果:

商品別売上金額
--------------------
りんご: 750円
みかん: 800円
バナナ: 480円
--------------------
全体の売上合計: 2,030円

商品はCSVに最初に登場した「りんご → みかん → バナナ」の順番で表示されます。

使用した標準ライブラリの説明

ライブラリ・機能 用途
csv CSVファイルの読み込み
csv.DictReader 列名をキーとして各行のデータを取得
open() ファイルを開く
int() 文字列を整数に変換
dict 商品別の売上金額を管理
sum() 全商品の売上金額を合計
print() コンソールに結果を表示

csv以外はPythonの組み込み機能です。外部ライブラリのインストールは必要ありません。

Least-to-Mostによる実装のまとめ

ステップ	解決した課題	前ステップからの拡張
1	CSVの読み込み	基本処理を作成
2	売上金額の計算	quantity * priceを追加
3	商品別の売上集計	辞書による集計処理を追加
4	全商品の売上合計	sum()による合計計算を追加
5	コンソールへの出力	表示形式を整える

このように、小さな課題を順番に解決し、それまでの実装を再利用しながら完成コードへ発展させることで、Least-to-Mostの手法を適用しています。

なお、今回の実装はquantityとpriceが整数であることを前提としています。小数の単価、CSVの列不足、不正な数値、ファイル不存在などの例外処理は要件に含まれていないため、追加していません。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?