61

Re: Кодофлуд, або флудокод

Зацініть оформлення коду

rem='';/* <script>     /*
@node "%~f0" %* & goto :eof
  :mode=html:         */                 from210={/*
 
 Система запису з основою 210. Кожний 210-ковий розряд
 складається з десятків (позначаються латинськими буквами,
 крім I, L, O, V, Y, які не використовуються)
 та одиниць (позначаються арабськими цифрами, крім 0),
 у кожному розряді десятки йдуть перед одиницями.
 
       Одиницi:              Десятки:
        (0 не пишеться)                    */
        1: 1,               A: 10, M:110,
        2: 2,               B: 20, N:120,
        3: 3,               C: 30, P:130,
        4: 4,               D: 40, Q:140,
        5: 5,               E: 50, R:150,
        6: 6,               F: 60, S:160,
        7: 7,               G: 70, T:170,
        8: 8,               H: 80, U:180,
        9: 9,               J: 90, W:190,
                            K:100, X:200,
                                 Z:0            /*
 Z не пишеться:
    - між двома арабськими цифрами
    - на початку числа перед арабською цифрою
       (лише число нуль починається з Z)        */};

to210={};
for(i in from210)
    to210[from210[i]]=i;
    
function intTo210(n)
    {
    if(n==0)return 'Z';
    var res='',
        b, d, u;
    while(n>0)
        {
        b=n%210; n=(n-b)/210;
        u=b%10;  d=b-u;
        res=to210[d]+(u||'')+res;
        }
    return res.replace(/([1-9])Z([1-9])/g, '$1$2').
                replace(/([1-9])Z([1-9])/g, '$1$2').
                replace(/^Z/,'');
    }
function base210ToInt(s)
    {
    s='Z'+s.replace(/([1-9])([1-9])/g, '$1Z$2').
            replace(/([1-9])([1-9])/g, '$1Z$2').
            toUpperCase();
    var res=0, i;
    for(i in s)
        {
        if (s[i]>='A' && s[i]<='Z') res*=210;
        res+=from210[s[i]];
        }
    return res;
    }
// </script> :) <!--    
var convertfn=function(n)
    {return intTo210(n)+'[sub]210[/sub]';};
process.argv.forEach(function (val, index, array)
    {
    if(index>1)
        if(val=='-i' || val=='--invert')
            convertfn=base210ToInt;
        else if(val=='-d' || val=='--direct')
            convertfn=intTo210;
        else console.log(convertfn(val));
    }); /* -->
<script>document.body.innerHTML='';</script>
<form>
<input id=base10><sub>10</sub> = <input id=base210><sub>210</sub>
</form>
<script>
//document.write('12345');
base10 =document.getElementById('base10');
base210=document.getElementById('base210');
base10.onchange=function()
    {
    base210.value=intTo210(+base10.value);
    }
base210.onchange=function()
    {
    base10.value=base210ToInt(base210.value);
    }
</script>
    
    <!-- */ // -->
Подякували: 221VOLT1

62

Re: Кодофлуд, або флудокод

def int2str(n, base=10):
    if n<0:
        return '-'+int2str(-n, base)
    a=[n]
    while a[0]>=base:
        a[:1]=divmod(a[0],base)
    if base<=36:
        return ''.join((chr(i+(ord('0') if i<10 else ord('A')-10)) for i in a))
    else:
        return ':'.join((str(int(i)) for i in a))

from functools import reduce
def str2int(s, base=10):
    if s[0]=='-':
        return -str2int(s[1:], base)
    if base<=36:
        return int(s, base)
    else:
        return reduce(lambda x,y: base*x+y, map(int, s.split(':')))

Для чого це взагалі треба: python'івський конструктор int з двома параметрами дозволяє конвертувати рядок у число, використовуючи системи числення з довільною основою від 2 до 36 (використовуючи літери для додаткових цифр) — проте, зворотнє перетворення доводиться робити руками (що й робить перша функція). Також ці дві функції дозволяють перетворювати рядок<->число, використовуючи основу 37 і більше — в цьому випадку, розряди записуються десятковими числами, розділеними двокрапками.

63

Re: Кодофлуд, або флудокод

(lambda l,r=lambda a:range(3,a,2):[*filter(lambda i:all(map(i.__mod__,r(-~int(i**.5)))),r(l))])(100)
#[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Подякували: P.Y., 221VOLT2

64

Re: Кодофлуд, або флудокод

Зацініть еталонний код на пітончику

#!usr/bin/env python3
# -*- coding: utf-8 -*-

import dash
import dash_core_components as dcc
import dash_html_components as html

class VisualForDash():

    external_stylesheets = ['plotlydash.css']
    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

    colors = {
                'background': '#111111',
                'text': '#7FDBFF'
             }

    app.layout = html.Div(
                            [
                                html.Div(
                                            style={'backgroundColor': colors['background']},
                                            children=html.H1(
                                                                id='header',
                                                                children='OLX PARSER',
                                                                style={
                                                                        'textAlign': 'center',
                                                                        'color': colors['text']
                                                                      }
                                                                )
                                        ),

                                html.Div(
                                            html.Label(id='section', children='Розділ', ),
                                        ),
                                dcc.Dropdown(
                                                            options=[
                                                            {'label': 'Всі розділи', 'value': 'list/'},
                                                            {'label': 'Дитячий світ', 'value': 'detskiy-mir/'},
                                                            {'label': 'Нерухомість', 'value':'nedvizhimost/'},
                                                            {'label': 'Транспорт', 'value': 'transport/'},
                                                            {'label': 'Запчастини для транспорту', 'value': 'zapchasti-dlya-transporta/'},
                                                            {'label': 'Робота', 'value': 'rabota/'},
                                                            {'label': 'Тварини', 'value': 'zhivotnye/'},
                                                            {'label': 'Дім і сад', 'value': 'dom-i-sad/'},
                                                            {'label': 'Електроніка', 'value': 'elektronika/'},
                                                            {'label': 'Бізнес та послуги', 'value': 'uslugi/'},
                                                            {'label': 'Мода і стиль', 'value': 'moda-i-stil/'},
                                                            {'label': 'Хобі і відпочинок', 'value': 'hobbi-otdyh-i-sport/'},
                                                            {'label': 'Віддам безкоштовно', 'value': 'otdam-darom/'},
                                                            {'label': 'Обмін', 'value': 'obmen-barter/'}
                                                            ],
                                                            value='list/', id='section_dropbox'
                                                        ),

                                html.Div(
                                            html.Label(id='sub_section', children='Підрозділ', ),
                                        )
                                dcc.Dropdown(
                                                options=[
                                                            {'label':'Все в розділі', 'value':''}

                                                        ],
                                                value='', id='sub_section_dropbox'
                                            ),
                                html.Label(children='Введіть місцевість в форматі назва населеного пункту, область ,район ',id='label-adress'),
                                dcc.Input(value='',id='input-adress', type='text', ),
                                html.Label(id='radius', children='+км', ),
                                dcc.Dropdown(
                                                options=[
                                                            {'label': '+0', 'value': '0'},
                                                            {'label': '+2', 'value': '2'},
                                                            {'label': '+5', 'value':'5'},
                                                            {'label': '+10', 'value': '10'},
                                                            {'label': '+15', 'value': '15'},
                                                            {'label': '+30', 'value': '30'},
                                                            {'label': '+50', 'value': '50'},
                                                            {'label': '+75', 'value': '75'},
                                                            {'label': '+100', 'value': '100'},
                                                        ],
                                                value='0', id='radius_dropbox'
                                            ),
                                               html.Label(children='Виберіть валюту відображення', id='label-change valute'),
                                dcc.Dropdown(
                                                options = [{'label':'UAH','value':'UAH'},
                                                           {'label':'USD','value':'USD'},
                                                           {'label':'EUR','value':'EUR'}],
                                                value = 'UAH', id = 'change-valute-dropbox'
                                            ),

                                html.Label(children='Введіть мінімальну ціну',id='label-min-cost'),
                                dcc.Input(value='',id='input-min-cost', type='text', ),

                                html.Label(children='Введіть максимальну ціну',id='label-max-cost'),
                                dcc.Input(value='',id='input-max-cost', type='text', ),


                                html.Div(
                                            html.Label(style={'display':'none'},id='advanced_search_label', children='Розширений пошук'),

                                        ),

                            html.Div(html.Label(style={'display':'none'}, id=            'new-secondhand', children= 'Стан'),
                                    ),





                                html.Label(children='Введіть характеристику для пошуку:  ',id='label-input'),
                                dcc.Input(value='',id='input-box', type='text', ),
                                html.Button(children ='Пошук', id='button'),

                            ]
                        )
Подякували: /KIT\1

65

Re: Кодофлуд, або флудокод

У продовження дискусії.

<meta charset=utf-8 />
<h3>Чи враховується синтаксис скриптової мови (JS) HTML-парсером?</h3>
<script>
document.write(/*
</script>
Ні — тому ви бачите цей текст
<script>
*/ "Так — тому ви бачите цей програмний вивід");
</script>

Мій ФФ каже, що ні :(

Подякували: NaharD, leofun01, 221VOLT3

66 Востаннє редагувалося plusxx (01.03.2020 07:29:15)

Re: Кодофлуд, або флудокод

Получає всі повідомлення за сьогоднішній день з "replace.org.ua".

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from requests import request
from _selectors import Selectors as sel #css селектори
class ReplaceParser():

    def __init__(self, page):
        self. page = page
        self.active_t = request('GET',page ).text
        self.soup = BeautifulSoup(self.active_t, 'lxml')

    def number_all_links(self):
        return(len(self.soup.find_all('li', class_='info-lastpost')))

    def active_temes(self):#Повертає масив з даними останніх редагованих тем
        topic_mas = []
        for number in range(self.number_all_links()):
            line_mas = []
            time = str(self.soup.select(sel.find_today_elelments(number)))[-13:-5]
            url = str(self.soup.select(sel.find_today_elelments(number)))[10:-24]
            title = self.return_title(number)
            autor = str(self.soup.select(sel.find_last_autor_name(number)))[11:-8]
            if str(self.soup.select(sel.find_today_elelments(number)))[-22:-14] == "Сьогодні":
                line_mas.append(title)
                line_mas.append(time)
                line_mas.append(autor)
                line_mas.append(url)
                print(line_mas)
                topic_mas.append(line_mas)
        return(topic_mas)


    def return_title(self, number):
        title_line= str(self.soup.select(sel.find_active_temes_url(number)))[:-5]
        title=''
        for liter in title_line[::-1]:
            if liter == ">":
                return (title[::-1])
                break
            title += liter
        return(title[::-1])

if __name__ == "__main__":
    rp = ReplaceParser("https://replace.org.ua/search/recent/")
    print(rp.active_temes())
Подякували: /KIT\, P.Y., 221VOLT3

67

Re: Кодофлуд, або флудокод

>>> for i in range(1,30):
...     file_name = os.listdir(f"images/{str(i)}/1")[0]
...     os.rename(f"images/{str(i)}/1/{file_name}",f"images/{str(i)}/1/001.jpg")

Як швидко перейменувати файли в різних папках якщо в тебе назвами папок служать цифри без пошуку додаткових інструментів

68

Re: Кодофлуд, або флудокод

Календар на поточний місяць (користі -> 0, але ... )
SQL

MySQL 8.x
WITH RECURSIVE cte (d, w, dw, dm) AS (
    SELECT
        d,
        WEEK(d, 1),
        DAYOFWEEK(d),
        DAY(d) 
    FROM
        (SELECT DATE_ADD(CURDATE(), INTERVAL 1 - DAY(CURDATE()) DAY) AS d) AS temp 
        UNION ALL
    SELECT
        DATE_ADD(d, INTERVAL 1 DAY),
        WEEK(DATE_ADD(d, INTERVAL 1 DAY), 1),
        DAYOFWEEK(DATE_ADD(d, INTERVAL 1 DAY)),
        DAY(DATE_ADD(d, INTERVAL 1 DAY)) 
    FROM
        cte 
    WHERE
        d < LAST_DAY(CURDATE()) 
) 
SELECT
    SUM(CASE dw WHEN 2 THEN dm END) AS `ПН`,
    SUM(CASE dw WHEN 3 THEN dm END) AS `ВТ`,
    SUM(CASE dw WHEN 4 THEN dm END) AS `СР`,
    SUM(CASE dw WHEN 5 THEN dm END) AS `ЧТ`,
    SUM(CASE dw WHEN 6 THEN dm END) AS `ПТ`,
    SUM(CASE dw WHEN 7 THEN dm END) AS `СБ`,
    SUM(CASE dw WHEN 1 THEN dm END) AS `НД` 
FROM
    cte 
GROUP BY
    w;

https://replace.org.ua/uploads/images/3603/2492c34adeee568319bedd679fc7d302.png

Подякували: leofun01, Betterthanyou2

69

Re: Кодофлуд, або флудокод

Пишу код для зламу японського косинця

⎕←⊃(
'           /|'
'     c×√2 / |'
'         /  |b'
'        /___|'
'      β°  a')
cols←{⊃¨↓⍺h1⍴(↓⍵),' '⍴⍨-h-⍺×h1←⌈⍺÷⍨h←↑⍴⍵}
dms←{,/,⍉⊃(,∘⍕¨360 60 60⊤⌊.5+3600×180÷○÷⍵)'°′″'}
⎕←,∘('║'∘,)/4 cols ⊃ {⍵,(.5⋆⍨2÷⍨+/⍵⋆2),dms¯3○÷÷/⍵}¨{⍵[⍒⊃÷/¨⍵]}{({(⌊=⊢).5⋆⍨2÷⍨+/2⋆⍨⍵}¨⍵)/⍵}{(>/¨⍵)/⍵},1+⍳,⍨100

⎕←⊃(
'           /|'
'        c / |'
'         /  |b'
'        /___|'
'      β° a×√2')
⎕←{⍺,'║',⍵}/4 cols ⊃ {⍵,(.5⋆⍨+/2 1×⍵⋆2),dms¯3○÷(2⋆÷2)×÷/⍵}¨{⍵[⍒⊃÷/¨⍵]}{({(⌊=⊢).5⋆⍨+/2 1×⍵⋆2}¨⍵)/⍵},1+⍳,⍨100
результат роботи
           /|
     c×√2 / |
         /  |b
        /___|
      β°  a
41 1 29  1°23′50″  ║ 63  9 45  8°7′48″    ║ 69 21 51  16°55′39″  ║ 62 34 50  28°44′23″
82 2 58  1°23′50″  ║ 70 10 50  8°7′48″    ║ 92 28 68  16°55′39″  ║ 93 51 75  28°44′23″
 7 1  5  8°7′48″   ║ 77 11 55  8°7′48″    ║ 17  7 13  22°22′48″  ║ 79 47 65  30°45′0″
14 2 10  8°7′48″   ║ 84 12 60  8°7′48″    ║ 34 14 26  22°22′48″  ║ 49 31 41  32°19′11″
21 3 15  8°7′48″   ║ 91 13 65  8°7′48″    ║ 51 21 39  22°22′48″  ║ 98 62 82  32°19′11″
28 4 20  8°7′48″   ║ 98 14 70  8°7′48″    ║ 68 28 52  22°22′48″  ║ 71 49 61  34°36′40″
35 5 25  8°7′48″   ║ 73 17 53  13°6′33″   ║ 85 35 65  22°22′48″  ║ 97 71 85  36°12′9″
42 6 30  8°7′48″   ║ 89 23 65  14°29′23″  ║ 47 23 37  26°4′31″   ║
49 7 35  8°7′48″   ║ 23  7 17  16°55′39″  ║ 94 46 74  26°4′31″   ║
56 8 40  8°7′48″   ║ 46 14 34  16°55′39″  ║ 31 17 25  28°44′23″  ║
           /|
        c / |
         /  |b
        /___|
      β° a×√2
70  1  99  0°34′44″   ║  36 18  54  19°28′16″  ║  42 31  67  27°33′38″  ║ 12 21  27  51°3′27″
12  1  17  3°22′20″   ║  38 19  57  19°28′16″  ║  84 62 134  27°33′38″  ║ 16 28  36  51°3′27″
24  2  34  3°22′20″   ║  40 20  60  19°28′16″  ║  60 47  97  28°58′55″  ║ 20 35  45  51°3′27″
36  3  51  3°22′20″   ║  42 21  63  19°28′16″  ║  20 17  33  31°0′27″   ║ 24 42  54  51°3′27″
48  4  68  3°22′20″   ║  44 22  66  19°28′16″  ║  40 34  66  31°0′27″   ║ 28 49  63  51°3′27″
60  5  85  3°22′20″   ║  46 23  69  19°28′16″  ║  60 51  99  31°0′27″   ║ 32 56  72  51°3′27″
72  6 102  3°22′20″   ║  48 24  72  19°28′16″  ║  80 68 132  31°0′27″   ║ 36 63  81  51°3′27″
84  7 119  3°22′20″   ║  50 25  75  19°28′16″  ║ 100 85 165  31°0′27″   ║ 40 70  90  51°3′27″
96  8 136  3°22′20″   ║  52 26  78  19°28′16″  ║  24 23  41  34°7′24″   ║ 44 77  99  51°3′27″
40  7  57  7°3′15″    ║  54 27  81  19°28′16″  ║  48 46  82  34°7′24″   ║ 48 84 108  51°3′27″
80 14 114  7°3′15″    ║  56 28  84  19°28′16″  ║  72 69 123  34°7′24″   ║ 52 91 117  51°3′27″
30  7  43  9°22′8″    ║  58 29  87  19°28′16″  ║  96 92 164  34°7′24″   ║ 56 98 126  51°3′27″
60 14  86  9°22′8″    ║  60 30  90  19°28′16″  ║  88 89 153  35°34′13″  ║ 36 73  89  55°6′26″
90 21 129  9°22′8″    ║  62 31  93  19°28′16″  ║  70 73 123  36°24′20″  ║ 42 89 107  56°16′54″
84 23 121  10°57′27″  ║  64 32  96  19°28′16″  ║   6  7  11  39°31′16″  ║ 10 23  27  58°24′49″
56 17  81  12°6′54″   ║  66 33  99  19°28′16″  ║  12 14  22  39°31′16″  ║ 20 46  54  58°24′49″
90 31 131  13°41′18″  ║  68 34 102  19°28′16″  ║  18 21  33  39°31′16″  ║ 30 69  81  58°24′49″
 2  1   3  19°28′16″  ║  70 35 105  19°28′16″  ║  24 28  44  39°31′16″  ║ 40 92 108  58°24′49″
 4  2   6  19°28′16″  ║  72 36 108  19°28′16″  ║  30 35  55  39°31′16″  ║  6 17  19  63°28′29″
 6  3   9  19°28′16″  ║  74 37 111  19°28′16″  ║  36 42  66  39°31′16″  ║ 12 34  38  63°28′29″
 8  4  12  19°28′16″  ║  76 38 114  19°28′16″  ║  42 49  77  39°31′16″  ║ 18 51  57  63°28′29″
10  5  15  19°28′16″  ║  78 39 117  19°28′16″  ║  48 56  88  39°31′16″  ║ 24 68  76  63°28′29″
12  6  18  19°28′16″  ║  80 40 120  19°28′16″  ║  54 63  99  39°31′16″  ║ 30 85  95  63°28′29″
14  7  21  19°28′16″  ║  82 41 123  19°28′16″  ║  60 70 110  39°31′16″  ║ 14 47  51  67°9′23″
16  8  24  19°28′16″  ║  84 42 126  19°28′16″  ║  66 77 121  39°31′16″  ║ 28 94 102  67°9′23″
18  9  27  19°28′16″  ║  86 43 129  19°28′16″  ║  72 84 132  39°31′16″  ║  8 31  33  69°57′0″
20 10  30  19°28′16″  ║  88 44 132  19°28′16″  ║  78 91 143  39°31′16″  ║ 16 62  66  69°57′0″
22 11  33  19°28′16″  ║  90 45 135  19°28′16″  ║  84 98 154  39°31′16″  ║ 24 93  99  69°57′0″
24 12  36  19°28′16″  ║  92 46 138  19°28′16″  ║  30 41  59  44°1′14″   ║ 18 79  83  72°8′23″
26 13  39  19°28′16″  ║  94 47 141  19°28′16″  ║  60 82 118  44°1′14″   ║ 10 49  51  73°54′4″
28 14  42  19°28′16″  ║  96 48 144  19°28′16″  ║  28 41  57  45°59′48″  ║ 20 98 102  73°54′4″
30 15  45  19°28′16″  ║  98 49 147  19°28′16″  ║  56 82 114  45°59′48″  ║ 12 71  73  76°33′26″
32 16  48  19°28′16″  ║ 100 50 150  19°28′16″  ║   4  7   9  51°3′27″   ║ 14 97  99  78°27′49″

Як відомо, японські кутники та косинці мають додаткову шкалу гіпотенуз, поділки якої в √2 разів більші за поділки основної шкали:
https://i.stack.imgur.com/TCkoF.jpg
Пряме її призначення — полегшити роботу з рівнобедреним прямокутним трикутником, що має кут 45°: відкладаючи одне й те ж значення для катетів на основній шкалі та для гіпотенузи на шкалі гіпотенуз, можна легко отримати такий трикутник. Проте, існують і інші прямокутні трикутники, які можливо побудувати, комбінуючи цілочисельні значення з цих двох шкал. Саме їх і шукає ця програма — використовуючи шкалу гіпотенуз для гіпотенузи або для одного з катетів.

Подякували: plusxx, Tarpan872

70

Re: Кодофлуд, або флудокод

>>> def seei():
...  i=999
...  def i_of_def():return i
...  a=[(i, i_of_def()) for i in range(3)]
...  return a+[i]
...
>>> seei()
[(0, 999), (1, 999), (2, 999), 999]
>>> def seei2():
...  i=999
...  def i_of_def():return i
...  a=[]
...  for i in range(3):a+=[(i, i_of_def())]
...  return a+[i]
...
>>> seei2()
[(0, 0), (1, 1), (2, 2), 2]

Здавалось би, в чому різниця між for i for...

71

Re: Кодофлуд, або флудокод

А тепер спробуйте seei() на другому пітоні запустити...

Подякували: P.Y.1

72 Востаннє редагувалося P.Y. (01.09.2021 15:05:24)

Re: Кодофлуд, або флудокод

JavaBASIC.bat:

@(echo public class %~n0 /* 
@type "%~f0" )|gcc -E - -o -|sed "sI^#I//I"> %~n0.java
::type %~n0.java&goto :eof
@javac %~n0.java
@java  %~n0
@goto :eof
  :mode=java:             */
{
#define TWO Math.pow(Math.sin(Math.PI/4), -2)
#define PRINT(S) System.out.println(S)
#define GOTO_ON go_to:for(int go_to=0;;) switch(go_to){\
    default: PRINT("Bad label!"); System.exit(1);\
    case 0:
#define GOTO_OFF break go_to;}
#define L case
#define GOTO(label) do{go_to=label; continue go_to;}while(0<0)
public static void main (String argv[])
    {
    int i=0;
    GOTO_ON
L 5:    PRINT("I have "+TWO+" reasons to do it..."); GOTO(30);
L 10:    PRINT("  I. BASIC programmer can write BASIC programs in any language.");GOTO(40);
L 20:    PRINT("  II. C macros are good in any C-like language.");
L 30:    PRINT(i);
L 40:    if(i++ == 2) GOTO(10);
L 45:    if(i==8) GOTO(20);
L 50:    if(i<10) GOTO(30);
    GOTO_OFF
    }
}

Схрещування пройшло успішно. Я ФРАНКЕНШТЕЙН!!! *YAHOO*

Подякували: ch0r_t1

73

Re: Кодофлуд, або флудокод

Періодичні десяткові дроби

from fractions import Fraction as fr


def period2frac(s):
    '''
    "1.234..."   => 1 + fr(234, 999)
    "1.2 34..."  => fr(12,10) + fr(34,990)
    "1.2.34...", "1.2_34..." — аналогічно
    "12.34"      => fr(1234, 100)
    '''
    s=s.strip()
    if s.endswith('...'):
        s=s[:-3].replace('_', '.').replace(' ','.')
        np,p=s.rsplit('.', 1)
        p+='/'+len(p)*'9'
        if '.' in np:
            p+=len(np.split('.')[1])*'0'
        return fr(np)+fr(p)
    else: return fr(s)
    
def period2float(s):
    return float(period2frac(s))

def frac2period(n):
    n,d=fr(n).as_integer_ratio()
    # винести степені 10, 2, 5 за межі досліджуваного знаменника:
    d10=1
    while d%2==0: d10<<=1; d>>=1
    while d%5==0: d10*=5;  d//=5
    #підібрати такий період, щоб знаменник його дробового представлення ділився на знаменник аргумента:
    # (знаменник періодичного дробу може бути 9, 99, 999,...)
    p10=0
    while d10%10==0:
        d10//=10
        p10+=1
    while d10%5==0:
        d10//=5
        n<<=1
        p10+=1
    while d10%2==0:
        d10//=2
        n*=5
        p10+=1
    d9=9 if d>1 else 1
    while d9%d: d9=(d9+1)*10-1
    n*=d9//d; d=d9
    ni,nf=map(str, divmod(n, d))
    nf=(len(str(d))-len(nf))*'0' + nf #add leading zeros to nf if needed
    if len(ni)<=p10: ni='0'*(p10-len(ni)+1)+ni
    if p10:
        return ni[:-p10]+'.'+ni[-p10:]+'_'+nf+'...'
    else:
        return ni+'.'+nf+'...'

Приклад використання:

>>> frac2period('1/7')
'0.142857...'
>>> period2frac('0.142857...')
Fraction(1, 7)
>>> period2float('0.142857...')
0.14285714285714285
>>> 1/7
0.14285714285714285
>>> period2frac('12.34_56...')
Fraction(61111, 4950)
>>> frac2period('61111/4950')
'12.34_56...'
>>> 61111/4950
12.345656565656565

74

Re: Кодофлуд, або флудокод

>>> x='0';[*map(lambda c:x:=c, 'qwerty')]
  File "<stdin>", line 1
SyntaxError: cannot use assignment expressions with lambda
>>> x='0';[*map(lambda c:(x:=c), 'qwerty')]
['q', 'w', 'e', 'r', 't', 'y']
>>> x
'0'
>>> y=['0'];[*map(lambda c:(y[0]:=c), 'qwerty')]
  File "<stdin>", line 1
SyntaxError: cannot use assignment expressions with subscript
>>> y=['0'];[*map(lambda c:y.__setitem__(0,c) or c, 'qwerty')]
['q', 'w', 'e', 'r', 't', 'y']
>>> y
['y']

75

Re: Кодофлуд, або флудокод

C:\Users\py\Desktop\try\ebcdic>chcp 866
Active code page: 866

C:\Users\py\Desktop\try\ebcdic>echo ::KKKnХдУ@ЄnPёPЕГИЦKPЕГИЦ@╔@ИБеЕ@БХ@┼┬├─╔├k@ВБВЕKPЩЕФ@>tryhead2.bat

C:\Users\py\Desktop\try\ebcdic>echo @echo Sorry, I do not speak ASCII>>tryhead2.bat

C:\Users\py\Desktop\try\ebcdic>type tryhead2.bat
::KKKnХдУ@ЄnPёPЕГИЦKPЕГИЦ@╔@ИБеЕ@БХ@┼┬├─╔├k@ВБВЕKPЩЕФ@
@echo Sorry, I do not speak ASCII

C:\Users\py\Desktop\try\ebcdic>chcp 37&cmd/q/c tryhead2
Active code page: 37

I have an EBCDIC, babe.

C:\Users\py\Desktop\try\ebcdic>chcp 855&cmd/q/c tryhead2
Active code page: 855
Sorry, I do not speak ASCII

76

Re: Кодофлуд, або флудокод

Увага! Код містить сцени GOTO в особливо збоченій формі! Справжнім програмістам не дивитись!
C:\Users\py\Desktop\try>chcp 21866
Active code page: 21866

C:\Users\py\Desktop\try>type gotocp.bat
@goto І
:О
@echo This encoding is for perverts&goto :eof
:і
@echo KOI8-U/KOI8-RU&goto :eof
:І
@goto :Р
:С
@goto Ь
:Ы
@echo What I see! Ukrainian DOS! How can it be possible?!&goto :eof
:Ь
@echo DOS Cyrillic&goto :eof
:р
@goto Ъ
:ъ
@goto ё
:Ё
@echo KOI8-R (use another KOI pls.)&goto :eof
:ё
@echo Windows Cyrillic&goto :eof
:Я
@echo What the Cyrillic hell are U using?&goto :eof
:Р
:Ъ
@echo De kupu/)u4HI 6ykBu?!

C:\Users\py\Desktop\try> gotocp
KOI8-U/KOI8-RU


C:\Users\py\Desktop\try>chcp 855&cmd/c gotocp
Active code page: 855
What the Cyrillic hell are U using?

C:\Users\py\Desktop\try>chcp 850&cmd/c gotocp
Active code page: 850
De kupu/)u4HI 6ykBu?!

77

Re: Кодофлуд, або флудокод

Конфіг від бота (це справжні відповіді живої людини, які я зібрав в одному місці), який випадково відповідає на повідомлення в чаті:

Уривок конфігу з матюками
  { type = "text", content = "Вбивати..."},
  { type = "text", content = "Йобу дали"},
  { type = "text", content = "Я тебе сама зараз з чату видалю"},
  { type = "text", content = "З одного боку ЧОМУ ТИ НЕ БУВ У ПІДВАЛІ!"},
  { type = "text", content = "Топ тянка"},  
  { type = "text", content = "Я зараз і тобі бан пропишу"},
  { type = "text", content = "Сuм"},
  { type = "text", content = "Нагадуєш мені моїх колишніх, тільки один на мотоцику хтів розбитись , а другий в ванні з феном купатися"},
  { type = "text", content = "АХВЗВХВХВХВХВХВ БЛЯТЬ ЧОМУ ЦЕ ТАК ДИБІЛЬНО"},
  { type = "text", content = "Блін ай донт андестент"},
  { type = "text", content = "Ого ого ого"},
  { type = "text", content = "Все заїбісь"},
  { type = "text", content = "Не їбу"},
  { type = "text", content = "Смішно."},
  { type = "text", content = "Це пізда повна"},
  { type = "text", content = "Йой це конф.інфа."},
  { type = "text", content = "Виходь за мене заміж"},
  { type = "text", content = "Головка від хуя , вимбачте хтось мусив це сказати."},
  { type = "text", content = "Без порнухи."},
  { type = "text", content = "Я емо , панк гьорл"},
  { type = "text", content = "Ти щей сліпе"},
  { type = "text", content = "Бо це Україна крихітко"},
  { type = "text", content = "Я ТЕБЕ СЬОГОДНІ ВИЇБУ"},
  { type = "text", content = "Та це рофл"},
  { type = "text", content = "Тоді це база , фундамент"},
  { type = "text", content = "Він уйобок"},
  { type = "text", content = "Що за крінж"},
  { type = "text", content = "Я ходячий пісюн"},
  { type = "text", content = "Мені за тебе страшно"},
  { type = "text", content = "Чисто зараз був вумен момент"},
  { type = "text", content = "Не соромся"},
  { type = "text", content = "Джаст крінге"},
  { type = "text", content = "Секксу не було і тепер не буде"},
  { type = "text", content = "Стули пельку"},
  { type = "text", content = "Не вмирай , тобі ще постер дит будинку який я стоворюю потрібно подивитися"},
  { type = "text", content = "Зіграй в песюн"},
  { type = "text", content = "Павер кам"},
  { type = "text", content = "Почалось імпотенське гей порно"},
  { type = "text", content = "Зіграй в песюн"},
  { type = "text", content = "Тут охуїла навіть я"},
  { type = "text", content = "СЕКССС"},
  { type = "text", content = "Е ВІДДАЙ САЛО"},
  { type = "text", content = "Ви їбанулись?"},
  { type = "text", content = "Я вже:)) це був дабл оргазм"},
  { type = "text", content = "Ти після заводу?"},
  { type = "text", content = "Зараз вопше все нахуй видалю"},
  { type = "text", content = "АТБ їбе?"},
  { type = "text", content = "НЕ РУХАЙ МІЙ ПЕСЮН"},
  { type = "text", content = "ХУЙОРНІ ТИ БЛЯТЬ, ТА ХОЧ САНГВІНІК, СУКА НЕ СПРОМОЖНА ТИ НІ НАЩО ЛЮДИНА , СТУЛИ ТИ СУКА ПАШЧЕКУ А ТО РЕАЛЬНО ПО ПИСКУ ПАТЕЛЬНЬОЮ ДІСТАНЕШ"},
  { type = "text", content = "КУРЧА ЛЯГА ЄДРИТЬ ТВОЮ МАТІР А НАЙ ТЕБЕ КАЧЕА КОПНЕ СУКИН СИНУ Я ТВОЮ МАМКУ ЄБАЛА ТИ КУРВА В МЕНЕ БУДЕШ НА ТРОЬХ РОБОТАХ ПАХАНИ ГРЬОБАНА ТИ ХВОЙДА"},
  { type = "text", content = "СУЧИЙ СИНУ ТИ"},
  { type = "text", content = "Ти їбанувся?"},
  { type = "text", content = "Ахуй"},
  { type = "text", content = "У мене немає терпцю"},
  { type = "text", content = "Та ти заїбеш"},
  { type = "text", content = "Я хочаб не тік токер"},
  { type = "text", content = "Прикрий писок"},
  { type = "text", content = "І шо це за хуйня?"},
  { type = "text", content = "Газом їбануть?"},
  { type = "text", content = "Як це іронічно"},
  { type = "text", content = "Хочеш я до тебе зайду?"},
  { type = "text", content = "Надихає"},
  { type = "text", content = "Блять мене купили"},
  { type = "text", content = "скидай нюдси а то ляшок моїх більше не побачиш"},
  { type = "text", content = "Я чекаю на твої нюдси"},
  { type = "text", content = "Ноу алкохол - ноу проблем"},
  { type = "text", content = "Я і тебе відпизджу"},
  { type = "text", content = "Мовчи слейвв"},
  { type = "text", content = "Ем  ти що натурал?"},
  { type = "text", content = "Ти доводиш мене до сліз"},  
  { type = "text", content = "То якось важко"},
  { type = "text", content = "Хуйня , хочу лям гривень"},  
  { type = "text", content = "Біднятко, ходи обійму"},
  { type = "text", content = "Відсмокчеш мій ледачий хер"},
  { type = "text", content = "Сука я тебе зараз виїбу"},
  { type = "text", content = "Гей ти шкіряний чоловіче здається ти помилився дверима шкіряний клуб на поверх нижче"},  
  { type = "text", content = "Ніхуя ти вумний"},

78 Востаннє редагувалося P.Y. (01.05.2023 00:35:44)

Re: Кодофлуд, або флудокод

Їх би ранжувати трохи за градусом ефективності, спершу подавати щось більш доброзичливе, і лише коли користувач наговорить зайвого, переходити до відвертої агресії. Щоб користувача затягувало поступово. Якщо все зробити правильно, наприкінці розмови користувач вважатиме неадекватом не бота, а себе, і його продовжуватиме тягнути в це місце...

79

Re: Кодофлуд, або флудокод

:: gotoHanoi.bat - batch file for Windows' CMD.EXE
:: Hanoi towers. Recursive alg. No CALL, just GOTO.
@setlocal
@set n=%1
@if not defined n set/p n=How many disks in Hanoi tower? 
@set a[1]=1&set b[1]=2&set c[1]=3&set ret[1]=999
@set i=1
:1
@set/a j=i+1 >nul
@if %i%==%n% goto 2
    ::a=>c:
    @set/a ret[%j%]=2 >nul
    @set/a a[%j%]=a[%i%] >nul
    @set/a b[%j%]=c[%i%] >nul
    @set/a c[%j%]=b[%i%] >nul
    @set/a i=j >nul
    @goto 1
:2
@set/a a=a[%i%] >nul
@set/a b=b[%i%] >nul
@echo  %a%=^>%b%

@if %i%==%n% goto 3
    ::c=>b:
    @set/a ret[%j%]=3 >nul
    @set/a a[%j%]=c[%i%] >nul
    @set/a b[%j%]=b[%i%] >nul
    @set/a c[%j%]=a[%i%] >nul
    @set/a i=j >nul
    @goto 1
    
:3
::return:
@set/a ret=ret[%i%] >nul
@set/a j=i >nul
@set/a i=i-1 >nul
@goto %ret%

:999
@pause
Подякували: leofun011