☰ Categories

Code Review Assistant

a Code Review Assistant. Your role is to provide a detailed assessment of the code provided by the user.

CategoryDevelopment › Coding
TagsAnalyzingReviewingDeveloperCode
Prompt
Act as a Code Review Assistant. Your role is to provide a detailed assessment of the code provided by the user. You will:

- Analyze the code for readability, maintainability, and style.
- Identify potential bugs or areas where the code may fail.
- Suggest improvements for better performance and efficiency.
- Highlight best practices and coding standards followed or violated.
- Ensure the code is aligned with industry standards.

Rules:
- Be constructive and provide explanations for each suggestion.
- Focus on the specific programming language and framework provided by the user.
- Use examples to clarify your points when applicable.

Response Format:
1. **Code Analysis:** Provide an overview of the code’s strengths and weaknesses.
2. **Specific Feedback:** Detail line-by-line or section-specific observations.
3. **Improvement Suggestions:** List actionable recommendations for the user to enhance their code.

Input Example:
"Please review the following Python function for finding prime numbers: \ndef find_primes(n):\n    primes = []\n    for num in range(2, n + 1):\n        for i in range(2, num):\n            if num % i == 0:\n                break\n        else:\n            primes.append(num)\n    return primes"

What this prompt does

This is useful for code feedback tied to a specific language and framework. It structures the response as code analysis, specific feedback, and improvement suggestions.

Model comparison

ChatGPT has the best balance of accuracy, structure, and length. Gemini is thorough but contains an inaccurate example and repetition, while [C] was not provided.

ChatGPTTop overall
48/ 50

+ Clearly covers the cause, validation, and rounding.

- Currency-specific policy is not parameterized.

Gemini
42/ 50

+ Offers rich payment-domain context and alternatives.

- Some numeric examples are inaccurate and verbose.

CriterionChatGPTGeminiLeader
Instruction following109ChatGPT +11%
Accuracy97ChatGPT +29%
Specificity1010Tie
Structure109ChatGPT +11%
Right length97ChatGPT +29%

Scored 1–10 by gpt-5.6-sol with model names hidden (2026-09-24). This is an AI review, not a measurement.

Read full answers

We gave three models the same input and copied their answers unedited. Each ran in its CLI (an agent harness), and answers in the ChatGPT or Claude apps or on the web may differ. Outputs are in Korean.

Input used
[Pasted material]
다음 Python 함수를 리뷰해주세요. 장바구니 총액에 할인율을 적용해 최종 결제 금액을 계산하는 함수인데, 가끔 소수점 이하 금액이 이상하게 나온다는 CS 문의가 들어왔습니다.

```python
def calculate_final_price(cart_items, discount_rate):
    total = 0
    for item in cart_items:
        total += item['price'] * item['quantity']
    discount = total * discount_rate
    final = total - discount
    return final
```
gpt-5.6-luna (codex CLI · 에이전트 하네스) · Run on 2026-09-24

1. 코드 분석

장바구니 상품별 금액을 합산한 뒤 할인액을 계산하는 구조는 단순하고 이해하기 쉽습니다. 반복문을 통해 여러 상품을 처리하며, 계산 단계도 total → discount → final로 명확합니다.

다만 금액 계산에 Python의 float 또는 일반 숫자 타입을 사용하면 이진 부동소수점 오차가 발생할 수 있습니다. 예를 들어 0.1 + 0.2가 정확히 0.3이 아닌 값으로 계산될 수 있어, 문의하신 “소수점 이하 금액이 이상하게 나오는 현상”의 주요 원인으로 보입니다.

또한 할인율의 단위와 반올림 정책이 명확하지 않고, 잘못된 입력값에 대한 검증도 없습니다.

2. 구체적인 피드백

total = 0

  • 초기값 자체는 문제가 없지만, item['price']가 실수형이면 이후 계산 전체에 부동소수점 오차가 전파될 수 있습니다.
  • 금액은 Decimal 또는 최소 화폐 단위인 정수(예: 원 단위)로 관리하는 것이 안전합니다.

item['price'] * item['quantity']

  • price, quantity 키가 없으면 KeyError가 발생합니다.
  • 가격이 음수이거나 수량이 0 또는 음수인 경우를 허용할지 정책이 필요합니다.
  • 수량이 실수나 문자열로 들어오면 의도하지 않은 계산이 될 수 있습니다.
  • item['price']가 float이면 금액 오차가 발생할 가능성이 높습니다.

discount = total * discount_rate

  • discount_rate가 0.1인지 10인지 불분명합니다. 호출자가 10을 전달하면 10배 할인액이 계산됩니다.
  • 할인율이 음수이거나 100%를 초과해도 현재 코드는 그대로 계산합니다.
  • total * 0.1과 같은 계산에서 부동소수점 오차가 발생할 수 있습니다.

final = total - discount

  • 최종 결과를 통화의 최소 단위에 맞게 반올림하지 않습니다.
  • 예를 들어 원 단위 결제라면 소수점 이하를 어떤 규칙으로 처리할지 정해야 합니다.
  • 결제 시스템에서는 일반적으로 반올림 방식(ROUND_HALF_UP 등)을 명시적으로 적용해야 합니다.

return final

  • 반환값의 타입과 정밀도가 명확하지 않습니다.
  • 호출하는 쪽에서 float인지 Decimal인지 일관되게 처리할 수 있도록 계약을 정하는 것이 좋습니다.

3. 개선 제안

Decimal을 사용하는 예시

금액과 할인율을 문자열 또는 Decimal로 변환해 계산하고, 최종 결과에서 명시적으로 반올림하는 방식이 적절합니다.

from decimal import Decimal, ROUND_HALF_UP


def calculate_final_price(cart_items, discount_rate):
    rate = Decimal(str(discount_rate))

    if not Decimal("0") <= rate <= Decimal("1"):
        raise ValueError("discount_rate must be between 0 and 1")

    total = Decimal("0")

    for item in cart_items:
        price = Decimal(str(item["price"]))
        quantity = item["quantity"]

        if price < 0:
            raise ValueError("price must not be negative")
        if not isinstance(quantity, int) or quantity < 0:
            raise ValueError("quantity must be a non-negative integer")

        total += price * quantity

    final = total * (Decimal("1") - rate)

    return final.quantize(Decimal("1"), rounding=ROUND_HALF_UP)

예를 들어 할인율 10%는 0.1로 전달해야 합니다.

calculate_final_price(
    [
        {"price": "1000", "quantity": 2},
        {"price": "500.50", "quantity": 1},
    ],
    "0.1",
)

추가로 다음 사항을 권장합니다.

  • 할인율 단위를 명확히 정의하고 함수명이나 문서에 명시합니다.
  • 상품 가격은 외부 입력 단계에서 검증합니다.
  • 통화별 소수점 자리 수를 고려합니다. 원화는 일반적으로 소수점 0자리, 달러는 2자리입니다.
  • 할인 계산 및 반올림 규칙에 대한 단위 테스트를 작성합니다.
  • 0.1 + 0.2, 100% 할인, 0% 할인, 빈 장바구니, 잘못된 가격과 수량을 테스트합니다.
  • 결제 시스템이라면 금액을 정수형 최소 단위로 저장하는 방식도 고려할 수 있습니다. 예를 들어 원화는 원 단위 정수로 저장하면 부동소수점 문제를 원천적으로 줄일 수 있습니다.

More in this category

12-Month AI and Computer Vision Roadmap for Defense Applications
2046 Puzzle Game Challenge
21st.dev component prompt
3D FACTORY
3D FPS Game