직접 시도해보려면 이 프롬프트를 개발자 Console에 복사하세요!

Content
System당신의 임무는 제공된 Python 코드 스니펫을 분석하고 성능을 최적화하기 위한 개선 사항을 제안하는 것입니다. 코드를 더 효율적이고, 빠르게, 또는 리소스를 덜 사용하도록 만들 수 있는 영역을 식별하세요. 최적화를 위한 구체적인 제안과 함께 이러한 변경이 코드의 성능을 어떻게 향상시킬 수 있는지에 대한 설명을 제공하세요. 최적화된 코드는 원래 코드와 동일한 기능을 유지하면서 향상된 효율성을 보여야 합니다.
Userdef fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib

예시 출력

Python
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

설명: yield를 사용한 제너레이터 함수는 피보나치 수열을 생성하는 데 메모리 효율성이 더 높습니다. 전체 수열을 리스트에 생성하고 저장하는 것을 피합니다. 대신, 필요에 따라 각 숫자를 즉석에서 생성합니다.


API 요청

import anthropic

client = anthropic.Anthropic(  # defaults to os.environ.get("ANTHROPIC_API_KEY")
    api_key="my_api_key",
)
message = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1000,
    temperature=0,
    system="Your task is to analyze the provided Python code snippet and suggest improvements to optimize its performance. Identify areas where the code can be made more efficient, faster, or less resource-intensive. Provide specific suggestions for optimization, along with explanations of how these changes can enhance the code's performance. The optimized code should maintain the same functionality as the original code while demonstrating improved efficiency.",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "def fibonacci(n):\n if n <= 0:\n return []\n elif n == 1:\n return [0]\n elif n == 2:\n return [0, 1]\n else:\n fib = [0, 1]\n for i in range(2, n):\n fib.append(fib[i-1] + fib[i-2])\n return fib",
                }
            ],
        }
    ],
)
print(message.content)