- 1
Eb-b-b!!!!!!!!!!!!!!!!!!!!!
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−1
Eb-b-b!!!!!!!!!!!!!!!!!!!!!
Хрюк-хрюк-хрюк-хрюк
0
def make_coffie(water_amount: int = 0) -> object:
class Coffie_Constructor:
def __init__(self, beans_amount: int = 0):
self.water_amount = water_amount
self.beans_amount = beans_amount
def __call__(self, milk_amount: int = 0) -> int:
return self.water_amount + self.beans_amount + milk_amount
def __repr__(self) -> str:
return 'Not enought call brakets were given'
return Coffie_Constructor
print(make_coffie(120)(50)(50))
0
#Ввод пользователем шахматной клетки
chess_cell = input("Введите шахматную клетку ")
horizontal_chess = chess_cell[0] #присовение в переменную буквы клетки
vertical_chess = int (chess_cell[1]) #присовение в переменную цифры клетки
#Вычисление условий для определения цвета ячейки
if vertical_chess > 8:
print ("Число клетки не может быть больше 8! ") #Условие ограничивающее количество клеток по вертикали
elif horizontal_chess != "a" and horizontal_chess != "A" and horizontal_chess != "b" and horizontal_chess != "B"\
and horizontal_chess != "c" and horizontal_chess != "C" and horizontal_chess != "d" and horizontal_chess != "D"\
and horizontal_chess != "e" and horizontal_chess != "E" and horizontal_chess != "f" and horizontal_chess != "F"\
and horizontal_chess != "g" and horizontal_chess != "G" and horizontal_chess != "h" and horizontal_chess != "H":
print ("такой буквы ячейки не существует!") #Условие ограничивающее количество букв по горизонтали
elif horizontal_chess == "a" or horizontal_chess == "A" or horizontal_chess == "c" or horizontal_chess == "C"\
or horizontal_chess == "e" or horizontal_chess == "E" or horizontal_chess == "g" or horizontal_chess == "G":
if vertical_chess%2 == 1:
print ("ячейка черная ")
else:
print ("ячейка белая") #определение цвета клеток в вертикали А, C, E, G
elif horizontal_chess == "b" or horizontal_chess == "B"or horizontal_chess == "d" or horizontal_chess == "D"\
or horizontal_chess == "f" or horizontal_chess == "F" or horizontal_chess == "h" or horizontal_chess == "H":
if vertical_chess%2 == 0:
print ("ячейка черная ")
else:
print ("ячейка белая") #определение цвета клеток в вертикали B, D, F, H
Определение цвета ячейки шахматной доски. Перевести букву в число с помощью ord()? Не, это мы не проходили.
+1
#!/usr/bin/env python3
# -*- coding: UTF8 -*-
from datetime import date
from os import environ, mkdir, system
from os.path import dirname, exists, join as path_join
from time import time
def check_verbose():
return environ.get("DEBUG") in ("true", "True", "TRUE", True, "yes", "Yes", "YES")
class Timer:
def __init__(self):
"""
Объект добавляет в начале текста временные метки
"""
self.start_epoch = self.last_call = time()
@staticmethod
def __fully_scope(timer: int or str) -> str:
"""
Преобразует однозначные значения в двузначные.
:param timer: Время
:return: Двузначное значение
"""
if len(str(timer)) == 2:
return str(timer)
elif len(str(timer)) == 1:
return "0" + str(timer)
elif len(str(timer)) <= 0:
return "00"
elif len(str(timer)) >= 2:
return str(timer)[:2]
def __formatter(self, timestep: float) -> str:
"""
Форматирует время
:return: время hh:mm:ss
"""
_hours = int(timestep // 3600), int(timestep % 3600)
_minute = int(_hours[1] // 60), int(_hours[1] % 60)
_current_epoch = f"{self.__fully_scope(_minute[0])}:{self.__fully_scope(_minute[1])}"
if _hours[0] > 0:
_current_epoch = f"{_hours[0]}:" + _current_epoch
return _current_epoch
def __call__(self, fix_call: bool = True) -> str:
"""
Считает время с начала сценария + с последнего шага
:return: время hh:mm:ss(+hh:mm:ss)
"""
current_epoch = self.__formatter(time() - self.start_epoch)
timedelta_epoch = self.__formatter(time() - self.last_call)
if fix_call:
self.last_call = time()
return f"{current_epoch}(+{timedelta_epoch})"
def __bool__(self):
return True
class Logger:
def __init__(self, name: str):
self.start_time = time()
self.name = name.upper()
self.timer = Timer()
self.log_file = path_join(environ["RESULT_DIR"], name, f"{name}_{date.today().isoformat()}.log")
def check_file(self):
if not exists(self.log_file):
if not exists(dirname(self.log_file)):
mkdir(dirname(self.log_file))
system(f"echo {date.today().isoformat()}> {self.log_file}")
def save_log(self, msg: str):
self.check_file()
with open(self.log_file, "a+") as _log_file:
_log_file.write(msg + "\n")
def massage(self, msg: str):
print(f"{self.timer()}::{self.name}::{msg}")
self.check_file()
self.save_log(f"{self.timer()}::{self.name}::{msg}")
def multi_msg(self, level: str, msg: any):
if isinstance(msg, (str, int, float, bool)):
self.massage(f"{level.upper()}::{msg}")
elif isinstance(msg, (tuple, list, set)):
for _msg in msg:
self.multi_msg(level, _msg)
elif isinstance(msg, dict):
for _msg_key in msg:
Ну собственно самописный логгер, потому что "библиатечный логгер переусложнен НИНАДА!"
−1
words = ['Broom', 'Being', 'Boring', 'Breeding', 'Dreaming', 'Doing', 'Dancing', 'Drinking',
'Freezing', 'Falling', 'Flooding', 'Fearing', 'Saying', 'Sleeping', 'Standing',
'Screaming', 'Running', 'Reading', 'Rolling', 'Rushing', 'Twerking', 'Telling']
def make_rows(row_size: int) -> list:
row_size = abs(int(row_size)); index = 0; amount = len(words)
# Найти кол-во групп / Calculate the amount of sublists
if row_size>amount: row_size=amount
if row_size > 0:
subs = (amount // row_size) + 1 if amount % row_size > 0 else amount // row_size
print(f'Слов: {len(words)} | | Ячеек: {subs}\n')
# Создать найденное кол-во групп / Create the found amount of sublists
rows = [[] for i in range(subs)]
for x in range(amount):
rows[index].append(words[x])
if len(rows[index]) == row_size: index += 1
return rows
else: return words
print(make_rows(2))
+1
class FileCheckError(Exception):
def __init__(self, check, file):
self.check = check
self.file = file
self.exceptions = ['не является файлом',
'не является .wav файлом',
'не находится в списке требуемых сэмплов',]
def __str__(self):
return f'{self.file} {self.exceptions[self.check]}'
def validate_pack(pack) -> list:
"""
Checks for invalid files in a pack folder
Makes a list of invalid files if found any or
makes a list of accepted samples
"""
accepted_samples = []
found_errors = []
for sample in listdir(pack):
checks = [isfile(join(pack, sample)),
fnmatch(sample, '*.wav'),
Path(pack / sample).stem in required_samples, ]
try:
for check in range(len(checks)):
if not checks[check]:
raise FileCheckError(check=check, file=sample)
except FileCheckError as E:
found_errors.append(str(E))
continue
accepted_samples.append(sample)
if len(found_errors) != 0:
return found_errors
else:
return accepted_samples
result = validate_pack(Path('drumpacks/rock'))
print(result, sep='\n')
−4
a = float(input())
b = float(input())
operation = input()
if operation == '+':
print(a + b)
elif operation == '-':
print(a-b)
elif operation == '*':
print(a*b)
elif operation == '/':
print (a /b)
elif operation == 'mod':
print(a%b)
if b == 0:
print ("Деление на 0!")
elif operation == 'div':
print(a//b)
elif operation == 'pow':
print(a**b)
Шикарный калькулятор
0
>>> import math
>>> n = math.factorial(1559)
>>> n
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Exceeds the limit (4300) for integer string conversion
https://github.com/sympy/sympy/issues/24033
Какой багфикс )))
0
def decode_flag(event_states: str) -> bool:
flag = 1 if int(event_states, 16) & 10_000_000_000_000_000 else 0
return bool(flag)
Кусок из реального коммерческого проекта
Есть стринга из 8 символов - флагов (0 или 1), но нас интересует только 4 символ в ней
+2
from datetime import datetime, date, time, timedelta
date= datetime.now().date()
e = datetime.now().date()-timedelta(days=1)
ee = date
delta = e-ee
for i in range(0, delta.days+1):
dfa = ee+timedelta(days=i)
dfa = dfa.strftime('%Y-%m-%d')
print(dfa)
Кусок кода с реального промышленного решения. Попросили глянуть почему не работает...лол