from typing import Tuple
def four_squares(n: int) -> Tuple[int, int, int, int]:
for a in range(int(n**0.5) + 1):
a_sqr = a ** 2
for b in range(int((n - a_sqr)**0.5) + 1):
b_sqr = b ** 2
for c in range(int((n - a_sqr - b_sqr)**0.5) + 1):
c_sqr = c ** 2
d_sqr = n - a_sqr - b_sqr - c_sqr
d = int(d_sqr ** 0.5)
if a_sqr + b_sqr + c_sqr + d_sqr == n:
return a, b, c, d
return 0, 0, 0, 0
if __name__ == '__main__':
test_cases = [0, 1, 17, 33, 215, 333, 2**12-3, 1234567890, 106369249365575352836589875696130383747]
for i in test_cases:
a, b, c, d = four_squares(i)
squares = [a, b, c, d]
if not all(isinstance(s, int) for s in squares):
print(f"Error: squares are not of type int for n = {i}")
elif sum(s**2 for s in squares) != i:
print(f"Error: incorrect sum for n = {i}. Squares: {squares}")
else:
print(f"Solution accepted for n = {i}")
LOCATIONS = ["Chaes", "Kordon"]
def print_available_locations(locations):
print(f"Welcome to колхозный S.T.A.L.K.E.R ёпт\nДоступные локации:{locations}\n")
def create_monolit(n=20):
return [{"Name": "Monolit", "HP": 120, "Rang": "Master"} for i in range(n)]
def create_stalker(n=10):
return [{"Name": "Stalker", "HP": 100, "Rang": "Noob"} for i in range(n)]
def create_mutant(n=5):
return [{"Name": "Psevdosobaki", "HP": 90, "Rang": "None"} for i in range(n)]
def handle_location(location):
if location == "Chaes":
monolit = create_monolit()
for mon in monolit:
print(mon)
print("Уууууу ты нарвался на монолитов")
elif location == "Kordon":
stalker = create_stalker()
for st in stalker:
print(st)
mutant = create_mutant()
for mu in mutant:
print(mu)
print("Не мельтеши особо и трогать тебя не будут ")
else:
print("Некорректное название локации")
def main():
print_available_locations(LOCATIONS)
location = input("Введите локацию: Пример(Kordon)\n>")
print("==============================================================")
handle_location(location)
print("==============================================================")
input()
if __name__ == '__main__':
main()
import fitz
import nltk
import string
import pymorphy2
# загружаем словари и правила для pymorphy2
morph = pymorphy2.MorphAnalyzer()
# загружаем русский язык для NLTK
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('tagsets')
nltk.download('words')
nltk.download('maxent_ne_chunker')
nltk.download('stopwords')
# извлекаем текст из PDF-файла
with fitz.open('example.pdf') as doc:
text = ""
for page in doc:
text += page.getText()
# токенизируем текст и удаляем пунктуацию
tokens = nltk.word_tokenize(text)
tokens = [word for word in tokens if word.isalnum()]
# исправляем орфографические ошибки
corrected_tokens = []
for token in tokens:
parsed_token = morph.parse(token)[0]
if 'LATIN' in parsed_token.tag or 'PNCT' in parsed_token.tag:
corrected_tokens.append(token)
else:
corrected_tokens.append(parsed_token.normal_form)
# восстанавливаем пунктуацию
final_text = ""
for i, token in enumerate(corrected_tokens):
final_text += token
if i < len(corrected_tokens) - 1 and corrected_tokens[i+1] not in string.punctuation:
final_text += " "
elif i < len(corrected_tokens) - 1 and corrected_tokens[i+1] in string.punctuation:
final_text += corrected_tokens[i+1]
print(final_text)
import telebot
import config
import sounddevice as sd
from scipy.io.wavfile import write
bot = telebot.TeleBot(config.TOKEN)
fs = 44100 # Sample rate
seconds = 15 # Recording duration
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
sd.wait() # Wait for recording to finish
print("Recording finished")
write('minecraft.wav', fs, myrecording) # Save as WAV file
keyboard = telebot.types.ReplyKeyboardMarkup(True, False)
keyboard.row("GET")
@bot.message_handler(commands=["start"])
def start_message(message):
chat_id = message.chat.id
text = message.text.lower()
bot.send_message(chat_id, "Hi", reply_markup=keyboard)
@bot.message_handler(content_types=["text"])
def send_message(message):
chat_id = message.chat.id
text = message.text.lower()
print(text)
if text == "get":
bot.send_message(chat_id, "FILE")
bot.send_audio(chat_id, open("minecraft.wav", "rb"))
elif text == "bye":
bot.send_message(chat_id, "Bye!")
bot.polling()
import time
import config
import logging
from aiogram import Bot, Dispatcher, executor, types
logging.basicConfig(level=logging.INFO)
bot = Bot(token=config.token)
dp = Dispatcher(bot)
# A dictionary to map mutetype to corresponding time in seconds
MUTE_TYPE = {
"г": 3600,
"годин": 3600,
"h": 3600,
"хв": 60,
"хвилин": 60,
"m": 60,
"д": 86400,
"дней": 86400,
"день": 86400
}
@dp.message_handler(commands=['mute'], is_chat_admin=True)
async def mute(message):
name1 = message.from_user.get_mention(as_html=True)
if not message.reply_to_message:
await message.reply("Команда має бути відповідю!")
return
try:
mute_time, mute_type, *comment = message.text.split()
mute_time = int(mute_time)
comment = " ".join(comment)
except:
await message.reply('Не правильно написано!\nПриклад:\n/мут 1 ч причина')
return
mute_duration = 0
if mute_type == "ч":
mute_duration = mute_time * 3600
elif mute_type == "хв":
mute_duration = mute_time * 60
elif mute_type == "д":
mute_duration = mute_time * 86400
else:
await message.reply(f'Неправильний тип часу! Використовуйте: ч (часи), хв (хвилини), д (дні)')
return
await bot.restrict_chat_member(
message.chat.id, message.reply_to_message.from_user.id,
until_date=int(time.time()) + mute_duration
)
await message.answer(f' | <b>Решение было принято:</b> {name1}\n | <b>Нарушитель:</b> <a href="tg://user?id={message.reply_to_message.from_user.id}">{message.reply_to_message.from_user.first_name}</a>\n⏰ | <b>Срок наказания:</b> {mute_time} {mute_type}\n | <b>Причина:</b> {comment}', parse_mode='html')
def calculate():
"""
This function prompts the user to enter an operation and then performs the corresponding mathematical operation on the input numbers.
"""
#Prompt the user to enter the operation
operation = input("<Мега автор - @andron2105> \n "
"Введите операцию =+-*/^ ")
# Use a dictionary to map operation to corresponding function
operations = {
"+": (lambda x, y: x + y),
"-": (lambda x, y: x - y),
"=": (lambda x: x),
"*": (lambda x, y: x * y),
"/": (lambda x, y: x / y),
"^": (lambda x, y: x ** y)
}
# Use try-except block to handle ValueError
try:
n1 = int(input("Введите число: "))
n2 = int(input("Введите число: "))
except ValueError:
print("Неизвестные знаение")
else:
# Use the operator to perform the corresponding operation
if operation in operations:
result = operations[operation](n1, n2)
print(f"Результат {result}")
else:
print("Неизвестная операция!")
calculate()