☰ 분류

Python 코드 감사 프롬프트

Python 코드를 넣으면 PEP 8, 최신 Python 3.10+ 문법, 타입 힌트, 오류 처리, 구조 개선을 검토하고 스페인어 설명과 리팩터링 코드를 제공합니다.

분류개발 › 코딩
태그검토교정첨삭개발자코드
프롬프트 (영어 본문 · 답은 한국어로 옵니다)
Act as a Senior Software Architect and Python expert. You are tasked with performing a comprehensive code audit and complete refactoring of the provided script.

Your instructions are as follows:

### Critical Mindset
- Be extremely critical of the code. Identify inefficiencies, poor practices, redundancies, and vulnerabilities.

### Adherence to Standards
- Rigorously apply PEP 8 standards. Ensure variable and function names are professional and semantic.

### Modernization
- Update any outdated syntax to leverage the latest Python features (3.10+) when beneficial, such as f-strings, type hints, dataclasses, and pattern matching.

### Beyond the Basics
- Research and apply more efficient libraries or better algorithms where applicable.

### Robustness
- Implement error handling (try/except) and ensure static typing (Type Hinting) in all functions.

### IMPORTANT: Output Language
- Although this prompt is in English, **you MUST provide the summary, explanations, and comments in SPANISH.**

### Output Format
1. **Bullet Points (in Spanish)**: Provide a concise list of the most critical changes made and the reasons for each.
2. **Refactored Code**: Present the complete, refactored code, ready for copying without interruptions.

Here is the code for review:

${codigo}

어떤 프롬프트인가

Python 스크립트를 강하게 비판하고 리팩터링할 때 쓰인다. 설명과 주석은 스페인어로 출력하도록 명시되어 있다.

모델 비교

ChatGPT가 정확성과 분량의 균형이 가장 좋다. Claude는 상세하지만 일부 과장됐고, Gemini는 구체적이나 지나치게 장황하다.

ChatGPT종합 1위
44/ 50

+ 핵심 문제를 정확하고 간결한 코드로 해결했다.

- 빈 이름·음수 나이 검증과 상세 감사가 부족하다.

Claude
39/ 50

+ 결함별 근거와 개선 코드를 구체적으로 연결했다.

- O(n³) 주장은 부정확하고 3.12 문법이 과하다.

Gemini
33/ 50

+ 감사 범위가 넓고 스페인어 설명도 충실하다.

- 과도하게 길며 bool 검증과 로깅 설계가 미흡하다.

기준ChatGPTClaudeGemini앞선 모델
지시 준수888동점
정확성976ChatGPT +29%
구체성899동점
구성·가독성997동점
분량 적정성1063ChatGPT +67%

gpt-5.6-sol가 모델 이름을 가린 채 1~10점으로 채점했습니다 (2026-09-24). 측정값이 아니라 AI 심사 결과입니다.

답 전문 보기

같은 입력을 세 모델에 넣어 받은 답을 그대로 옮겼습니다. 각 CLI(에이전트 하네스)에서 실행했습니다. ChatGPT·Claude 앱이나 웹에서는 답이 다를 수 있습니다.

넣은 입력
[붙여 넣은 자료]
import time

def procesar_usuarios(usuarios, resultado=[]):
    for u in usuarios:
        try:
            nombre = u["nombre"]
            edad = u["edad"]
            if edad > 18:
                resultado.append("%s es mayor de edad" % nombre)
            else:
                resultado.append("%s es menor de edad" % nombre)
        except:
            print("error con el usuario:", u)
    return resultado

def buscar_duplicados(lista):
    duplicados = []
    for i in range(len(lista)):
        for j in range(len(lista)):
            if i != j and lista[i] == lista[j] and lista[i] not in duplicados:
                duplicados.append(lista[i])
    return duplicados

usuarios = [
    {"nombre": "Carlos", "edad": 25},
    {"nombre": "Ana", "edad": 17},
    {"nombre": "Carlos", "edad": 25},
]

print(procesar_usuarios(usuarios))
print(buscar_duplicados([1, 2, 2, 3, 3, 3]))
gpt-5.6-luna (codex CLI · 에이전트 하네스) · 실행일 2026-09-24
  • resultado=[]를 제거해 호출 간 데이터가 누적되는 문제를 해결했습니다.
  • except: 대신 구체적인 예외를 처리하고, 잘못된 사용자 데이터는 로그로 기록하도록 개선했습니다.
  • 모든 함수에 타입 힌트를 추가하고 입력값을 검증했습니다.
  • 중복 검색을 이중 반복문에서 Counter 기반의 O(n) 알고리즘으로 변경했습니다.
  • 실행 코드를 main()과 if __name__ == "__main__":으로 분리했습니다.
  • 문자열 포맷팅을 f-string으로 현대화하고, 성년 기준을 일반적인 18세 이상으로 수정했습니다.
from __future__ import annotations

import logging
from collections import Counter
from collections.abc import Hashable, Iterable, Mapping
from typing import TypeVar


T = TypeVar("T", bound=Hashable)

LOGGER = logging.getLogger(__name__)


def procesar_usuarios(
    usuarios: Iterable[Mapping[str, object]],
    resultado: list[str] | None = None,
) -> list[str]:
    """Procesa usuarios y genera mensajes según su edad."""
    mensajes = resultado if resultado is not None else []

    for usuario in usuarios:
        try:
            nombre = usuario["nombre"]
            edad = usuario["edad"]

            if not isinstance(nombre, str):
                raise TypeError("El nombre debe ser una cadena.")

            if isinstance(edad, bool) or not isinstance(edad, int):
                raise TypeError("La edad debe ser un entero.")

            estado = "mayor de edad" if edad >= 18 else "menor de edad"
            mensajes.append(f"{nombre} es {estado}")

        except (KeyError, TypeError, ValueError) as error:
            LOGGER.warning(
                "Error al procesar el usuario %r: %s",
                usuario,
                error,
            )

    return mensajes


def buscar_duplicados(valores: Iterable[T]) -> list[T]:
    """Devuelve los valores duplicados, conservando su orden original."""
    elementos = list(valores)
    frecuencias = Counter(elementos)

    return list(dict.fromkeys(
        valor for valor in elementos if frecuencias[valor] > 1
    ))


def main() -> None:
    """Ejecuta un ejemplo de uso del programa."""
    logging.basicConfig(level=logging.WARNING)

    usuarios: list[Mapping[str, object]] = [
        {"nombre": "Carlos", "edad": 25},
        {"nombre": "Ana", "edad": 17},
        {"nombre": "Carlos", "edad": 25},
    ]

    print(procesar_usuarios(usuarios))
    print(buscar_duplicados([1, 2, 2, 3, 3, 3]))


if __name__ == "__main__":
    main()

같은 분류의 프롬프트

방산 CV 12개월 로드맵 프롬프트
2046 퍼즐 게임 제작 프롬프트
React 컴포넌트 통합 프롬프트
3D 아바타 팩토리 요구 프롬프트
3D FPS 게임 개발 프롬프트