0
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?

プログラミング習得ログ ジェネレーター式

Posted at

演習問題はこちら

def analyze_sales_data(sales_records):
    """
    売上データを分析する総合関数
    引数: [(商品名, 価格, 販売数), (商品名, 価格, 販売数), ...]
    戻り値: {
        "total_revenue": 総売上,
        "best_seller": (商品名, 販売数),
        "most_profitable": (商品名, 売上金額),
        "summary": (商品数, 総販売数, 平均単価)
    }
    """
    # ここにコードを書いてください
    pass

# 期待する動作
sales = [
    ("ノートPC", 80000, 5),
    ("マウス", 2000, 20),
    ("キーボード", 5000, 15),
    ("モニター", 30000, 8)
]

analysis = analyze_sales_data(sales)
print(f"総売上: {analysis['total_revenue']:,}")
print(f"最多販売: {analysis['best_seller'][0]} ({analysis['best_seller'][1]}個)")
print(f"最高売上: {analysis['most_profitable'][0]} ({analysis['most_profitable'][1]:,}円)")
print(f"サマリー: 商品{analysis['summary'][0]}種類, 総販売{analysis['summary'][1]}個, 平均単価{analysis['summary'][2]:,.0f}")

私の書いたコード(エラーがあり、要件も読み間違っている)

def analyze_sales_data(sales_records):
    """
    売上データを分析する総合関数
    引数: [(商品名, 価格, 販売数), (商品名, 価格, 販売数), ...]
    戻り値: {
        "total_revenue": 総売上,
        "best_seller": (商品名, 販売数),
        "most_profitable": (商品名, 売上金額),
        "summary": (商品数, 総販売数, 平均単価)
    }
    """
    total_revenue=0
    best_seller=()
    most_profitable=()
    summary=()

    for name,price,quantitysold in sales_records:
        total_revenue = total_revenue+price 
        best_seller =max(sales_records ,key=lambda x:x[2])
        most_profitable=max(sales_records,key=lambda x:x[1])
        summary=sum(len(sales_records),len(key=lambda x:x[2]),sum(key=lambda x:x[2])/len(sales_records))

    
    return {
            'total_revenue':total_revenue,
            'best_seller':best_seller,
            'most_profitable':most_profitable,
            'summary':summary
            }
# 期待する動作
sales = [
    ("ノートPC", 80000, 5),
    ("マウス", 2000, 20),
    ("キーボード", 5000, 15),
    ("モニター", 30000, 8)
]
analysis = analyze_sales_data(sales)
print(f"総売上: {analysis['total_revenue']:,}")
print(f"最多販売: {analysis['best_seller'][0]} ({analysis['best_seller'][1]}個)")
print(f"最高売上: {analysis['most_profitable'][0]} ({analysis['most_profitable'][1]:,}円)")
print(f"サマリー: 商品{analysis['summary'][0]}種類, 総販売{analysis['summary'][1]}個, 平均単価{analysis['summary'][2]:,.0f}")

正解版(1)

def analyze_sales_data(sales_records):
    """
    売上データを分析する総合関数
    """
    total_revenue = 0
    
    for name, price, quantity_sold in sales_records:
        total_revenue = total_revenue + (price * quantity_sold)  # 価格×数量
    
    # ループの外で計算
    best_seller = max(sales_records, key=lambda x: x[2])
    most_profitable = max(sales_records, key=lambda x: x[1] * x[2])  # 価格×数量で最高売上
    
    # summary の正しい計算
    item_count = len(sales_records)  # 商品数
    total_quantity = sum(x[2] for x in sales_records)  # 総販売数
    average_price = total_revenue / total_quantity  # 平均単価
    
    summary = (item_count, total_quantity, average_price)
    
    return {
        'total_revenue': total_revenue,
        'best_seller': (best_seller[0], best_seller[2]),  # (商品名, 販売数)
        'most_profitable': (most_profitable[0], most_profitable[1] * most_profitable[2]),  # (商品名, 売上金額)
        'summary': summary
    }

正解版(2)更に効率化

def analyze_sales_data(sales_records):
    """売上データを分析する総合関数"""
    total_revenue = 0
    max_quantity = 0
    max_revenue = 0
    best_seller_item = None
    most_profitable_item = None
    total_quantity = 0
    
    # 1回のループで全て計算
    for name, price, quantity_sold in sales_records:
        revenue = price * quantity_sold
        total_revenue += revenue
        total_quantity += quantity_sold
        
        # 最多販売をチェック
        if quantity_sold > max_quantity:
            max_quantity = quantity_sold
            best_seller_item = (name, quantity_sold)
        
        # 最高売上をチェック
        if revenue > max_revenue:
            max_revenue = revenue
            most_profitable_item = (name, revenue)
    
    # サマリー計算
    item_count = len(sales_records)
    average_price = total_revenue / total_quantity if total_quantity > 0 else 0
    summary = (item_count, total_quantity, average_price)
    
    return {
        'total_revenue': total_revenue,
        'best_seller': best_seller_item,
        'most_profitable': most_profitable_item,
        'summary': summary
    }

# テスト
sales = [
    ("ノートPC", 80000, 5),      # 売上: 400,000円
    ("マウス", 2000, 20),        # 売上: 40,000円 ← 最多販売
    ("キーボード", 5000, 15),    # 売上: 75,000円
    ("モニター", 30000, 8)       # 売上: 240,000円
]

analysis = analyze_sales_data(sales)
print(f"総売上: {analysis['total_revenue']:,}")  # 755,000円
print(f"最多販売: {analysis['best_seller'][0]} ({analysis['best_seller'][1]}個)")  # マウス (20個)
print(f"最高売上: {analysis['most_profitable'][0]} ({analysis['most_profitable'][1]:,}円)")  # ノートPC (400,000円)
print(f"サマリー: 商品{analysis['summary'][0]}種類, 総販売{analysis['summary'][1]}個, 平均単価{analysis['summary'][2]:,.0f}")

正解をみてから1日たって、自分で以下のように書いてみた。

   variation= len(sales_records)
    quantity= sum(x[2]for x in sales_records)
    average = total_revenue / quantity
    summary=(variation,quantity,average)

ジェネレーター式の基本構文

sum(x[2] for x in sales_records)
#   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#   これがジェネレータ式

基本パターン

関数( for 変数 in リスト)

forを使った従来の書き方

# 従来の書き方よりもジェネレーター式を使ったほうが効率的
total_quantity = 0
for x in sales_records:
    total_quantity += x[2]

覚えるべきパターン

# 合計
total = sum(x[インデックス] for x in リスト)

# 最大・最小
maximum = max(x[インデックス] for x in リスト)
minimum = min(x[インデックス] for x in リスト)

# 条件付き
filtered_sum = sum(x[インデックス] for x in リスト if 条件)

# 計算結果
calculated_sum = sum(x[1] * x[2] for x in リスト)  # 価格×数量など

この演習問題で最終的に私自身で書いたコード

def analyze_sales_data(sales_records):
    """
    売上データを分析する総合関数
    引数: [(商品名, 価格, 販売数), (商品名, 価格, 販売数), ...]
    戻り値: {
        "total_revenue": 総売上,
        "best_seller": (商品名, 販売数),
        "most_profitable": (商品名, 売上金額),
        "summary": (商品数, 総販売数, 平均単価)
    }
    """
    total_revenue=0
    best_seller=()
    most_profitable=()
    summary=()

    for name,price,quantitysold in sales_records:
        total_revenue = total_revenue+(price*quantitysold) 

    best_seller =max(sales_records ,key=lambda x:x[2])
    most_profitable=max(sales_records,key=lambda x:x[1]*x[2])

    variation= len(sales_records)
    quantity= sum(x[2]for x in sales_records)
    average = total_revenue / quantity
    summary=(variation,quantity,average)

    return {
            'total_revenue':total_revenue,
            'best_seller':best_seller,
            'most_profitable':most_profitable,
            'summary':summary
            }
# 期待する動作
sales = [
    ("ノートPC", 80000, 5),
    ("マウス", 2000, 20),
    ("キーボード", 5000, 15),
    ("モニター", 30000, 8)
]
analysis = analyze_sales_data(sales)
print(f"総売上: {analysis['total_revenue']:,}")
print(f"最多販売: {analysis['best_seller'][0]} ({analysis['best_seller'][1]}個)")
print(f"最高売上: {analysis['most_profitable'][0]} ({analysis['most_profitable'][1]:,}円)")
print(f"サマリー: 商品{analysis['summary'][0]}種類, 総販売{analysis['summary'][1]}個, 平均単価{analysis['summary'][2]:,.0f}")
0
0
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
0
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?