import asyncio
from random import randint
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackQueryHandler, ContextTypes
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
choices = ["камень", "ножницы", "бумага"]
scissors = InlineKeyboardButton("Ножницы", callback_data="Ножницы")
rock = InlineKeyboardButton("Камень", callback_data="Камень")
paper = InlineKeyboardButton("Бумага", callback_data="Бумага")
rockboard = InlineKeyboardMarkup([
[scissors, rock],
[paper]
])
TOKEN = ''
async def start_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
print(update.effective_user.first_name)
print("Получена команда /game")
await update.message.reply_text(f'Привет, 🎮\nДавай сыграем в Камень, Ножницы, Бумага! Выбери свой вариант ниже ⬇️"', reply_markup=rockboard)
async def handle_choice(update: Update, context: ContextTypes.DEFAULT_TYPE):
bot_choice = randint.choice(["Камень", "Ножницы", "Бумага"])
result = determine_winner(update.message.text, bot_choice)
await update.message.reply_text(f"Вы выбрали: {update.message.text} Бот выбрал: {bot_choice} Результат: {result}")
def determine_winner(user, bot):
if user == bot:
return "Ничья!"
elif (user == "камень" and bot == "ножницы") or \
(user == "ножницы" and bot == "бумага") or \
(user == "бумага" and bot == "камень"):
return "Ты выиграл!"
else:
return "Я выиграл!"
def main():
application = Application.builder().token(TOKEN).build()
application.add_handler(CommandHandler("game", start_cmd))
print("Бот запущен!")
application.run_polling()
if __name__ == '__main__':
main()
Филипп Шувалов
Asked:
2025-04-29 18:15:51 +0000 UTC
尝试在 CadQuery Python 中对螺栓进行建模:
import cadquery as cq
from math import sqrt, tan, radians
# Параметры модели
head_diameter = 10.0 # Диаметр по вершинам (описанная окружность)
head_height = 5.0 # Высота головки
shaft_diameter = 5.0 # Диаметр стержня
shaft_length = 20.0 # Длина стержня
# Расчетные параметры
R = head_diameter / 2 # Радиус описанной окружности
r = R * sqrt(3)/2 # Радиус вписанной окружности
chamfer_size = (R - r) / tan(45) # Размер фаски для угла 45°
#1. Создаем шестигранную головку
bolt_head = (
cq.Workplane("XY")
.polygon(6, 2*R) # Создаем шестигранник
.extrude(head_height) # Выдавливаем на высоту головки
.translate((0, 0, -1 * (head_height/2)))
)
bolt_head = bolt_head.edges("Z").chamfer(1)
# 2. Создаем стержень
bolt_shaft = (
cq.Workplane("XY")
.circle(shaft_diameter/2)
.extrude(-shaft_length)
)
# 3. Объединяем компоненты
bolt = bolt_head.union(bolt_shaft)
Лиза Кригер
Asked:
2025-04-29 14:14:48 +0000 UTC
电子表格文件每行包含七个自然数。确定表格行中满足以下条件的最小数字的总和:
- 一行中有两个数字,每个数字重复两次,另外三个数字不同;
- 最大行数不重复。
在你的回答中,只写下数字。
f = open("9")
cnt = 0
for s in f:
a = list(map(int, s.split()))
povt = [x for x in a if a.count(x) > 1]
ne_povt = [x for x in a if a.count(x) == 1]
if (len(ne_povt) == 3 and len(set(povt)) == 2) and max(ne_povt) == 1:
cnt += 1
print(cnt)
geo
Asked:
2025-04-28 18:28:02 +0000 UTC
为了在类中使用,我需要一组异常,我从 Exceptions 继承并将该组异常存储在模块中(在标题中),我将其构造如下:
class BaseUserError(Exception):
pass
class AccountError(BaseUserError):
pass
class DebitError(AccountError):
pass
class CreitError(AccountError):
pass
希望将它们移动到用作子类的类中(例如,Account 类、Client 类等等)。这样看来似乎更正确。谁存储在哪里以及为什么存储?
t1m013y
Asked:
2025-04-26 20:37:06 +0000 UTC
我正在创建一个 Python 应用程序,它允许我在某些行中使用变量。假设字符串和变量列表都是由用户直接提供的(在这种情况下,安全意味着防止 SSTI 等攻击),那么使用标准库对象string.Template
(https://docs.python.org/3/library/string.html#template-strings )是否安全?
换句话说,这样的代码是否安全:
import string
template_str = input("Введите строку: ")
variables = {}
while True:
name = input("Введите имя переменной (оставить пустым для отмены): ")
if not name.strip():
break
value = input("Введите значение переменной: ")
name, value = map(lambda s: s.strip(), [name, value])
if name in variables.keys():
print("Такая переменная уже существует")
else:
variables.update({name: value})
t = string.Template(template_str)
res = t.substitute(variables)
print(res)
注意:问题是如果用户可以控制字符串、变量名和值,使用过程是否安全,string.Template
而不是接下来字符串会发生什么。