Библиотека промптов
Консультант по коду
Ресурсы
- Overview
- Быстрый старт
- Карточка модели Claude 3
- Системная карта Claude 3.7
- Статус системы
- Курсы Anthropic
- Библиотека промптов
- Библиотека промптов
- Космические клавиши
- Корпоративный ясновидящий
- Мастер создания веб-сайтов
- Эксперт по формулам Excel
- Разработчик скриптов Google Apps
- Отладчик Python
- Консультант по путешествиям во времени
- Помощник по сторителлингу
- Цитируйте свои источники
- SQL-волшебник
- Толкователь снов
- Каламбурщик
- Кулинарный создатель
- Поэт портманто
- Хэл - юмористический помощник
- LaTeX справочник
- Цветовой определитель настроения
- Git gud
- Мастер сравнений
- Навигатор по этическим дилеммам
- Протоколист совещаний
- Толкователь идиом
- Консультант по коду
- Создатель функций
- Создатель неологизмов
- Конвертер CSV
- Эмодзи-кодировщик
- Шлифовщик прозы
- Анализатор перспектив
- Генератор викторин
- Наставник по осознанности
- Упроститель для второклассников
- Инноватор фитнеса в VR
- Очиститель PII
- Мастер служебных записок
- Карьерный коуч
- Эксперт по оценке
- Скороговорки
- Составитель вопросов для собеседования
- Гений грамматики
- Загадай-ка мне загадку
- Пояснитель кода
- Инопланетный антрополог
- Организатор данных
- Создатель бренда
- Оценщик эффективности
- Классификатор отзывов
- Преобразователь указаний
- Мотивационная муза
- Извлечение email-адресов
- Мастер-модератор
- Планировщик уроков
- Сократический мудрец
- Алхимик аллитераций
- Футуристический консультант по моде
- Полиглот-суперсилы
- Профессионал по названиям продуктов
- Философские размышления
- Волшебник электронных таблиц
- Симулятор научно-фантастических сценариев
- Адаптивный редактор
- Вещание Вавилона
- Определитель тона твитов
- Анализатор кодов аэропортов
Библиотека промптов
Консультант по коду
Предлагает улучшения для оптимизации производительности кода Python.
Скопируйте этот промпт в нашу Консоль для разработчиков, чтобы попробовать его самостоятельно!
Content | |
---|---|
System | Ваша задача — проанализировать предоставленный фрагмент кода Python и предложить улучшения для оптимизации его производительности. Определите области, где код может быть сделан более эффективным, быстрым или менее ресурсоемким. Предоставьте конкретные предложения по оптимизации вместе с объяснениями того, как эти изменения могут улучшить производительность кода. Оптимизированный код должен сохранять ту же функциональность, что и оригинальный код, демонстрируя при этом повышенную эффективность. |
User | def 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)
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)
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: "my_api_key", // по умолчанию использует process.env["ANTHROPIC_API_KEY"]
});
const msg = await anthropic.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"
}
]
}
]
});
console.log(msg);
from anthropic import AnthropicBedrock
# См. https://docs.anthropic.com/claude/reference/claude-on-amazon-bedrock
# для вариантов аутентификации
client = AnthropicBedrock()
message = client.messages.create(
model="anthropic.claude-opus-4-20250514-v1:0",
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)
import AnthropicBedrock from "@anthropic-ai/bedrock-sdk";
// См. https://docs.anthropic.com/claude/reference/claude-on-amazon-bedrock
// для вариантов аутентификации
const client = new AnthropicBedrock();
const msg = await client.messages.create({
model: "anthropic.claude-opus-4-20250514-v1:0",
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"
}
]
}
]
});
console.log(msg);
from anthropic import AnthropicVertex
client = AnthropicVertex()
message = client.messages.create(
model="claude-3-7-sonnet-v1@20250219",
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)
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
// Считывает из переменных окружения `CLOUD_ML_REGION` и `ANTHROPIC_VERTEX_PROJECT_ID`.
// Дополнительно проходит через стандартный поток `google-auth-library`.
const client = new AnthropicVertex();
const msg = await client.messages.create({
model: "claude-3-7-sonnet-v1@20250219",
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"
}
]
}
]
});
console.log(msg);
Was this page helpful?
On this page