將此提示複製到我們的開發者控制台中,親自試試看!

內容
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(  # 默認為 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)