Цена за 48 часов в ленте | 1000,00 |
Цена за 1 час закрепления | N/A |
Взаимопиар | Нет |
казино, букмекеры |
|
def calculate_area(length, width):
return length * width
# Использование функции
room_area = calculate_area(5, 4)
print(f"Площадь комнаты: {room_area} кв.м.")
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
return f"Новый баланс: {self.balance}"
# Использование метода
account = BankAccount(1000)
account.deposit(500) # Вызов метода через объект
import plotly.express as px
import pandas as pd
# Создаём тестовые данные
df = pd.DataFrame({
'Месяц': ['Янв', 'Фев', 'Март', 'Апр', 'Май'],
'Продажи': [100, 150, 200, 180, 250],
'Прибыль': [20, 30, 40, 35, 50]
})
# Создаём интерактивный график
fig = px.line(df, x='Месяц', y=['Продажи', 'Прибыль'],
title='Динамика продаж и прибыли',
template='plotly_dark')
# Добавляем hover-эффекты
fig.update_traces(mode='lines+markers', hovertemplate='%{y:,.0f}₽')
# Сохраняем как HTML или показываем в браузере
fig.write_html('sales_dashboard.html')
from bokeh.plotting import figure, show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, HoverTool
import numpy as np
# Создаём интерактивный scatter plot
x = np.random.normal(0, 1, 1000)
y = np.random.normal(0, 1, 1000)
source = ColumnDataSource(data=dict(
x=x,
y=y,
size=np.random.uniform(5, 15, 1000),
color=['#%06x' % np.random.randint(0, 0xFFFFFF) for _ in range(1000)]
))
p = figure(width=800, height=600, title='Интерактивный Scatter Plot')
p.scatter('x', 'y', size='size', color='color', alpha=0.6, source=source)
# Добавляем интерактивные подсказки
hover = HoverTool(tooltips=[
('X', '@x{0.000}'),
('Y', '@y{0.000}'),
('Размер', '@size{0.00}')
])
p.add_tools(hover)
show(p)
import plotly.graph_objects as go
fig = go.Figure(
data=[go.Scatter(x=[1, 2, 3], y=[1, 3, 2])],
layout=dict(
updatemenus=[dict(
type="buttons",
buttons=[dict(label="Play",
method="animate",
args=[None])]
)]
)
)
from bokeh.plotting import curdoc
from functools import partial
from tornado.ioloop import IOLoop
def update():
source.data['y'] = np.random.rand(100)
curdoc().add_periodic_callback(update, 100) # Обновление каждые 100мс
from dataclasses import dataclass
from typing import List
@dataclass
class DataPoint:
x: float
y: float
category: str
data_points: List[DataPoint] = [] # Эффективнее, чем DataFrame для больших данных
import torch
import torch.nn as nn
class SimpleNet(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = nn.Linear(784, 128)
self.relu = nn.ReLU()
self.layer2 = nn.Linear(128, 10)
def forward(self, x):
x = self.layer1(x)
x = self.relu(x)
return self.layer2(x)
Создаем модель одной строчкой! 🎯
model = SimpleNet().to('cuda' if torch.cuda.is_available() else 'cpu')
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(784,)),
tf.keras.layers.Dense(10)
])
# Компилируем модель
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# PyTorch стиль
optimizer = torch.optim.Adam(model.parameters())
criterion = nn.CrossEntropyLoss()
for epoch in range(10):
for batch_x, batch_y in dataloader:
optimizer.zero_grad()
outputs = model(batch_x)
loss = criterion(outputs, batch_y)
loss.backward()
optimizer.step()
# Разбиваем данные
from sklearn.model_selection import train_test_split
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Следим за метриками
val_loss = []
for epoch in range(epochs):
model.train()
# ... обучение ...
model.eval()
with torch.no_grad():
val_predictions = model(X_val)
v_loss = criterion(val_predictions, y_val)
val_loss.append(v_loss.item())
def test_sum():
assert sum([1, 2, 3]) == 6
assert sum([-1, 1]) == 0
from hypothesis import given
import hypothesis.strategies as st
@given(st.lists(st.integers()))
def test_sum_properties(numbers):
assert sum(numbers) == sum(reversed(numbers))
assert sum(numbers + [0]) == sum(numbers)
import click
@click.group()
def cli():
"""Утилита для работы с файлами"""
pass
@cli.command()
@click.argument('path')
@click.option('--lines', '-l', is_flag=True, help='Показать количество строк')
def analyze(path, lines):
"""Анализирует файл и выводит статистику"""
try:
with open(path) as f:
content = f.readlines()
if lines:
click.echo(f'Количество строк: {len(content)}')
except FileNotFoundError:
click.secho('Файл не найден! 😱', fg='red')
if __name__ == '__main__':
cli()
@cli.command()
@click.argument('path')
def process(path):
"""Обрабатывает файлы с прогресс-баром"""
files = os.listdir(path)
with click.progressbar(files, label='Обработка файлов') as bar:
for f in bar:
# что-то делаем с файлом
time.sleep(0.1)
click.secho('Внимание! 🚨', fg='yellow', bold=True)
click.secho('Ошибка! ❌', fg='red')
click.secho('Успех! ✅', fg='green')
if click.confirm('Уверены, что хотите удалить все файлы? 🤔'):
click.echo('Поехали! 🚀')
print(bool(-1)) # Результат: True
# Старый подход с os.path
import os.path
file_path = os.path.join('data', 'users', 'config.json')
parent_dir = os.path.dirname(file_path)
file_name = os.path.basename(file_path)
# Новый подход с pathlib
from pathlib import Path
file_path = Path('data') / 'users' / 'config.json'
parent_dir = file_path.parent
file_name = file_path.name
path = Path('config.json')
if path.exists():
print('Файл существует!')
Path('nested/directories/structure').mkdir(parents=True, exist_ok=True)
# Найти все .py файлы в текущей директории
python_files = list(Path('.').glob('*.py'))
path = Path('document.pdf')
print(path.suffix) # .pdf
print(path.stem) # document
config_path = (Path.home() / 'projects' / 'app' / 'config.json')
if config_path.exists():
data = json.loads(config_path.read_text())
with Path('log.txt').open('w') as f:
f.write('Logging started')