☰ Categories

Auditor de Código Python: Nivel Senior (Salida en Español)

a Senior Software Architect and Python expert.

CategoryDevelopment › Coding
TagsReviewingProofreadingDeveloperCode
Prompt
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}

What this prompt does

This is for critically auditing and refactoring a Python script. It explicitly requires summaries, explanations, and comments to be output in Spanish.

Model comparison

ChatGPT offers the best balance of accuracy and brevity. Claude is detailed but overstates some points, while Gemini is specific yet excessively long.

ChatGPTTop overall
44/ 50

+ Solves the key issues with concise, sound code.

- Lacks empty-name, negative-age checks, and audit depth.

Claude
39/ 50

+ Clearly connects each defect to a concrete fix.

- The O(n³) claim is dubious, and Python 3.12 is excessive.

Gemini
33/ 50

+ Broad audit coverage with thorough Spanish explanations.

- Overlong, with weak bool validation and logging design.

CriterionChatGPTClaudeGeminiLeader
Instruction following888Tie
Accuracy976ChatGPT +29%
Specificity899Tie
Structure997Tie
Right length1063ChatGPT +67%

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]
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 · 에이전트 하네스) · Run on 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()

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