Repository navigation
Expand file tree
/
Copy pathfunctional.po
More file actions
2088 lines (1836 loc) · 111 KB
/
Copy pathfunctional.po
File metadata and controls
2088 lines (1836 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SOME DESCRIPTIVE TITLE.
# Copyright (C) 2001-2025, Python Software Foundation
# This file is distributed under the same license as the Python package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
# Translators:
# Dmytro Kazanzhy, 2022
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Python 3.13\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-04-18 14:18+0000\n"
"PO-Revision-Date: 2021-06-28 00:53+0000\n"
"Last-Translator: Dmytro Kazanzhy, 2022\n"
"Language-Team: Ukrainian (https://app.transifex.com/python-doc/teams/5390/"
"uk/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: uk\n"
"Plural-Forms: nplurals=4; plural=(n % 1 == 0 && n % 10 == 1 && n % 100 != "
"11 ? 0 : n % 1 == 0 && n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % "
"100 > 14) ? 1 : n % 1 == 0 && (n % 10 ==0 || (n % 10 >=5 && n % 10 <=9) || "
"(n % 100 >=11 && n % 100 <=14 )) ? 2: 3);\n"
msgid "Functional Programming HOWTO"
msgstr "Функціональне програмування HOWTO"
msgid "Author"
msgstr "Автор"
msgid "A. M. Kuchling"
msgstr "A. M. Kuchling"
msgid "Release"
msgstr "Реліз"
msgid "0.32"
msgstr "0,32"
msgid ""
"In this document, we'll take a tour of Python's features suitable for "
"implementing programs in a functional style. After an introduction to the "
"concepts of functional programming, we'll look at language features such as :"
"term:`iterator`\\s and :term:`generator`\\s and relevant library modules "
"such as :mod:`itertools` and :mod:`functools`."
msgstr ""
"У цьому документі ми ознайомимося з функціями Python, придатними для "
"реалізації програм у функціональному стилі. Після вступу до концепцій "
"функціонального програмування ми розглянемо функції мови, такі як :term:"
"`iterator`\\s і :term:`generator`\\s, а також відповідні бібліотечні модулі, "
"такі як :mod:`itertools` і :mod:`functools`."
msgid "Introduction"
msgstr "вступ"
msgid ""
"This section explains the basic concept of functional programming; if you're "
"just interested in learning about Python language features, skip to the next "
"section on :ref:`functional-howto-iterators`."
msgstr ""
"У цьому розділі пояснюється основна концепція функціонального програмування; "
"якщо вам просто цікаво дізнатися про функції мови Python, перейдіть до "
"наступного розділу :ref:`functional-howto-iterators`."
msgid ""
"Programming languages support decomposing problems in several different ways:"
msgstr ""
"Мови програмування підтримують декомпозицію проблем кількома різними "
"способами:"
msgid ""
"Most programming languages are **procedural**: programs are lists of "
"instructions that tell the computer what to do with the program's input. C, "
"Pascal, and even Unix shells are procedural languages."
msgstr ""
"Більшість мов програмування є **процедурними**: програми — це списки "
"інструкцій, які вказують комп’ютеру, що робити з вхідними даними програми. "
"C, Pascal і навіть оболонки Unix є процедурними мовами."
msgid ""
"In **declarative** languages, you write a specification that describes the "
"problem to be solved, and the language implementation figures out how to "
"perform the computation efficiently. SQL is the declarative language you're "
"most likely to be familiar with; a SQL query describes the data set you want "
"to retrieve, and the SQL engine decides whether to scan tables or use "
"indexes, which subclauses should be performed first, etc."
msgstr ""
"У **декларативних** мовах ви пишете специфікацію, яка описує проблему, яку "
"потрібно вирішити, а реалізація мови визначає, як виконати обчислення "
"ефективно. SQL — це декларативна мова, з якою ви, швидше за все, знайомі; "
"SQL-запит описує набір даних, який ви хочете отримати, і механізм SQL "
"вирішує, сканувати таблиці чи використовувати індекси, які підпункти слід "
"виконати першими тощо."
msgid ""
"**Object-oriented** programs manipulate collections of objects. Objects "
"have internal state and support methods that query or modify this internal "
"state in some way. Smalltalk and Java are object-oriented languages. C++ "
"and Python are languages that support object-oriented programming, but don't "
"force the use of object-oriented features."
msgstr ""
"**Об’єктно-орієнтовані** програми маніпулюють колекціями об’єктів. Об’єкти "
"мають внутрішній стан і підтримують методи, які певним чином запитують або "
"змінюють цей внутрішній стан. Smalltalk і Java є об'єктно-орієнтованими "
"мовами. C++ і Python — це мови, які підтримують об’єктно-орієнтоване "
"програмування, але не примусово використовують об’єктно-орієнтовані функції."
msgid ""
"**Functional** programming decomposes a problem into a set of functions. "
"Ideally, functions only take inputs and produce outputs, and don't have any "
"internal state that affects the output produced for a given input. Well-"
"known functional languages include the ML family (Standard ML, OCaml, and "
"other variants) and Haskell."
msgstr ""
"**Функціональне** програмування розкладає проблему на набір функцій. В "
"ідеалі функції лише приймають вхідні дані та виробляють виходи, і не мають "
"жодного внутрішнього стану, який впливає на вихідні дані, отримані для "
"даного вхідного елемента. Добре відомі функціональні мови включають "
"сімейство ML (Standard ML, OCaml та інші варіанти) і Haskell."
msgid ""
"The designers of some computer languages choose to emphasize one particular "
"approach to programming. This often makes it difficult to write programs "
"that use a different approach. Other languages are multi-paradigm languages "
"that support several different approaches. Lisp, C++, and Python are multi-"
"paradigm; you can write programs or libraries that are largely procedural, "
"object-oriented, or functional in all of these languages. In a large "
"program, different sections might be written using different approaches; the "
"GUI might be object-oriented while the processing logic is procedural or "
"functional, for example."
msgstr ""
"Розробники деяких комп’ютерних мов вирішують наголосити на одному "
"конкретному підході до програмування. Це часто ускладнює написання програм, "
"які використовують інший підхід. Інші мови є мовами з кількома парадигмами, "
"які підтримують кілька різних підходів. Lisp, C++ і Python є "
"мультипарадигмальними; ви можете писати програми або бібліотеки, які в "
"основному є процедурними, об'єктно-орієнтованими або функціональними на всіх "
"цих мовах. У великій програмі різні розділи можуть бути написані з "
"використанням різних підходів; GUI може бути об'єктно-орієнтованим, тоді як "
"логіка обробки є процедурною або функціональною, наприклад."
msgid ""
"In a functional program, input flows through a set of functions. Each "
"function operates on its input and produces some output. Functional style "
"discourages functions with side effects that modify internal state or make "
"other changes that aren't visible in the function's return value. Functions "
"that have no side effects at all are called **purely functional**. Avoiding "
"side effects means not using data structures that get updated as a program "
"runs; every function's output must only depend on its input."
msgstr ""
"У функціональній програмі введення проходить через набір функцій. Кожна "
"функція працює зі своїм входом і видає певний результат. Функціональний "
"стиль не заохочує функції з побічними ефектами, які змінюють внутрішній стан "
"або вносять інші зміни, які не видно у значенні, що повертається функцією. "
"Функції, які взагалі не мають побічних ефектів, називаються **чисто "
"функціональними**. Уникати побічних ефектів означає не використовувати "
"структури даних, які оновлюються під час виконання програми; кожен вихід "
"функції повинен залежати лише від її входу."
msgid ""
"Some languages are very strict about purity and don't even have assignment "
"statements such as ``a=3`` or ``c = a + b``, but it's difficult to avoid all "
"side effects, such as printing to the screen or writing to a disk file. "
"Another example is a call to the :func:`print` or :func:`time.sleep` "
"function, neither of which returns a useful value. Both are called only for "
"their side effects of sending some text to the screen or pausing execution "
"for a second."
msgstr ""
"Деякі мови дуже суворі щодо чистоти й навіть не мають операторів присвоєння, "
"таких як ``a=3`` або ``c = a + b``, але важко уникнути всіх побічних "
"ефектів, таких як друк на екрані або запис у файл диска. Іншим прикладом є "
"виклик функції :func:`print` або :func:`time.sleep`, жодна з яких не "
"повертає корисне значення. Обидва викликаються лише через побічні ефекти "
"надсилання тексту на екран або призупинення виконання на секунду."
msgid ""
"Python programs written in functional style usually won't go to the extreme "
"of avoiding all I/O or all assignments; instead, they'll provide a "
"functional-appearing interface but will use non-functional features "
"internally. For example, the implementation of a function will still use "
"assignments to local variables, but won't modify global variables or have "
"other side effects."
msgstr ""
"Програми на Python, написані у функціональному стилі, зазвичай не йдуть до "
"крайнощів, щоб уникнути всього вводу-виводу або всіх призначень; замість "
"цього вони забезпечуватимуть функціональний інтерфейс, але "
"використовуватимуть нефункціональні функції всередині. Наприклад, реалізація "
"функції все одно використовуватиме призначення локальним змінним, але не "
"змінюватиме глобальні змінні чи матиме інші побічні ефекти."
msgid ""
"Functional programming can be considered the opposite of object-oriented "
"programming. Objects are little capsules containing some internal state "
"along with a collection of method calls that let you modify this state, and "
"programs consist of making the right set of state changes. Functional "
"programming wants to avoid state changes as much as possible and works with "
"data flowing between functions. In Python you might combine the two "
"approaches by writing functions that take and return instances representing "
"objects in your application (e-mail messages, transactions, etc.)."
msgstr ""
"Функціональне програмування можна вважати протилежністю об'єктно-"
"орієнтованого програмування. Об’єкти — це маленькі капсули, що містять "
"певний внутрішній стан разом із набором викликів методів, які дозволяють "
"змінювати цей стан, а програми складаються із внесення правильних змін "
"стану. Функціональне програмування хоче якомога більше уникати змін стану та "
"працює з потоком даних між функціями. У Python ви можете поєднати два "
"підходи, написавши функції, які приймають і повертають екземпляри, що "
"представляють об’єкти у вашій програмі (повідомлення електронної пошти, "
"транзакції тощо)."
msgid ""
"Functional design may seem like an odd constraint to work under. Why should "
"you avoid objects and side effects? There are theoretical and practical "
"advantages to the functional style:"
msgstr ""
"Функціональний дизайн може здатися дивним обмеженням для роботи. Чому слід "
"уникати предметів і побічних ефектів? Існують теоретичні та практичні "
"переваги функціонального стилю:"
msgid "Formal provability."
msgstr "Формальна доказовість."
msgid "Modularity."
msgstr "Модульність."
msgid "Composability."
msgstr "Композиційність."
msgid "Ease of debugging and testing."
msgstr "Простота налагодження та тестування."
msgid "Formal provability"
msgstr "Формальна доказовість"
msgid ""
"A theoretical benefit is that it's easier to construct a mathematical proof "
"that a functional program is correct."
msgstr ""
"Теоретична перевага полягає в тому, що легше побудувати математичний доказ "
"правильності функціональної програми."
msgid ""
"For a long time researchers have been interested in finding ways to "
"mathematically prove programs correct. This is different from testing a "
"program on numerous inputs and concluding that its output is usually "
"correct, or reading a program's source code and concluding that the code "
"looks right; the goal is instead a rigorous proof that a program produces "
"the right result for all possible inputs."
msgstr ""
"Довгий час дослідники були зацікавлені в пошуку способів математичної "
"перевірки правильності програм. Це відрізняється від тестування програми на "
"численних вхідних даних і висновку, що її вихід зазвичай правильний, або "
"читання вихідного коду програми та висновку, що код виглядає правильно; "
"натомість метою є суворий доказ того, що програма дає правильний результат "
"для всіх можливих вхідних даних."
msgid ""
"The technique used to prove programs correct is to write down "
"**invariants**, properties of the input data and of the program's variables "
"that are always true. For each line of code, you then show that if "
"invariants X and Y are true **before** the line is executed, the slightly "
"different invariants X' and Y' are true **after** the line is executed. "
"This continues until you reach the end of the program, at which point the "
"invariants should match the desired conditions on the program's output."
msgstr ""
"Техніка, яка використовується для підтвердження правильності програм, "
"полягає в записі **інваріантів**, властивостей вхідних даних і змінних "
"програми, які завжди є істинними. Для кожного рядка коду ви потім показуєте, "
"що якщо інваріанти X і Y істинні **до** виконання рядка, дещо інші "
"інваріанти X' і Y' є істинними **після** виконання рядка. Це продовжується, "
"доки ви не досягнете кінця програми, після чого інваріанти повинні "
"відповідати бажаним умовам на виході програми."
msgid ""
"Functional programming's avoidance of assignments arose because assignments "
"are difficult to handle with this technique; assignments can break "
"invariants that were true before the assignment without producing any new "
"invariants that can be propagated onward."
msgstr ""
"Уникання присвоєння у функціональному програмуванні виникло тому, що "
"присвоєння важко обробляти за допомогою цієї техніки; призначення можуть "
"порушувати інваріанти, які були істинними до призначення, не створюючи "
"жодних нових інваріантів, які можна поширювати далі."
msgid ""
"Unfortunately, proving programs correct is largely impractical and not "
"relevant to Python software. Even trivial programs require proofs that are "
"several pages long; the proof of correctness for a moderately complicated "
"program would be enormous, and few or none of the programs you use daily "
"(the Python interpreter, your XML parser, your web browser) could be proven "
"correct. Even if you wrote down or generated a proof, there would then be "
"the question of verifying the proof; maybe there's an error in it, and you "
"wrongly believe you've proved the program correct."
msgstr ""
"На жаль, перевірка правильності програм в основному непрактична і не "
"стосується програмного забезпечення Python. Навіть тривіальні програми "
"вимагають доказів довжиною кілька сторінок; докази правильності для помірно "
"складної програми були б величезними, і мало або жодна з програм, якими ви "
"користуєтеся щодня (інтерпретатор Python, ваш аналізатор XML, ваш веб-"
"браузер), може бути доведена правильною. Навіть якщо ви записали або "
"згенерували доказ, тоді виникне питання перевірки доказу; можливо, у ньому є "
"помилка, і ви помилково вважаєте, що довели правильність програми."
msgid "Modularity"
msgstr "Модульність"
msgid ""
"A more practical benefit of functional programming is that it forces you to "
"break apart your problem into small pieces. Programs are more modular as a "
"result. It's easier to specify and write a small function that does one "
"thing than a large function that performs a complicated transformation. "
"Small functions are also easier to read and to check for errors."
msgstr ""
"Більш практична перевага функціонального програмування полягає в тому, що "
"воно змушує вас розбивати проблему на дрібні частини. В результаті програми "
"стають більш модульними. Простіше вказати та написати невелику функцію, яка "
"виконує щось одне, ніж велику функцію, яка виконує складне перетворення. "
"Невеликі функції також легше читати та перевіряти на наявність помилок."
msgid "Ease of debugging and testing"
msgstr "Простота налагодження та тестування"
msgid "Testing and debugging a functional-style program is easier."
msgstr "Тестування та налагодження програми у функціональному стилі легше."
msgid ""
"Debugging is simplified because functions are generally small and clearly "
"specified. When a program doesn't work, each function is an interface point "
"where you can check that the data are correct. You can look at the "
"intermediate inputs and outputs to quickly isolate the function that's "
"responsible for a bug."
msgstr ""
"Налагодження спрощене, оскільки функції, як правило, невеликі та чітко "
"визначені. Коли програма не працює, кожна функція є точкою інтерфейсу, де "
"можна перевірити правильність даних. Ви можете переглянути проміжні входи та "
"виходи, щоб швидко виділити функцію, яка є відповідальною за помилку."
msgid ""
"Testing is easier because each function is a potential subject for a unit "
"test. Functions don't depend on system state that needs to be replicated "
"before running a test; instead you only have to synthesize the right input "
"and then check that the output matches expectations."
msgstr ""
"Тестування легше, тому що кожна функція є потенційним предметом модульного "
"тесту. Функції не залежать від стану системи, який потрібно відтворити перед "
"виконанням тесту; натомість вам потрібно лише синтезувати правильні вхідні "
"дані, а потім перевірити, чи результат відповідає очікуванням."
msgid "Composability"
msgstr "Композиційність"
msgid ""
"As you work on a functional-style program, you'll write a number of "
"functions with varying inputs and outputs. Some of these functions will be "
"unavoidably specialized to a particular application, but others will be "
"useful in a wide variety of programs. For example, a function that takes a "
"directory path and returns all the XML files in the directory, or a function "
"that takes a filename and returns its contents, can be applied to many "
"different situations."
msgstr ""
"Працюючи над програмою функціонального стилю, ви напишете ряд функцій із "
"різними входами та виходами. Деякі з цих функцій неминуче будуть "
"спеціалізовані для конкретної програми, але інші будуть корисні в широкому "
"спектрі програм. Наприклад, функцію, яка приймає шлях до каталогу та "
"повертає всі файли XML у каталозі, або функцію, яка приймає ім’я файлу та "
"повертає його вміст, можна застосувати до багатьох різних ситуацій."
msgid ""
"Over time you'll form a personal library of utilities. Often you'll "
"assemble new programs by arranging existing functions in a new configuration "
"and writing a few functions specialized for the current task."
msgstr ""
"З часом ви сформуєте особисту бібліотеку утиліт. Часто ви збираєте нові "
"програми, організовуючи існуючі функції в новій конфігурації та написавши "
"кілька функцій, спеціалізованих для поточного завдання."
msgid "Iterators"
msgstr "Ітератори"
msgid ""
"I'll start by looking at a Python language feature that's an important "
"foundation for writing functional-style programs: iterators."
msgstr ""
"Я почну з вивчення функції мови Python, яка є важливою основою для написання "
"програм у функціональному стилі: ітератори."
msgid ""
"An iterator is an object representing a stream of data; this object returns "
"the data one element at a time. A Python iterator must support a method "
"called :meth:`~iterator.__next__` that takes no arguments and always returns "
"the next element of the stream. If there are no more elements in the "
"stream, :meth:`~iterator.__next__` must raise the :exc:`StopIteration` "
"exception. Iterators don't have to be finite, though; it's perfectly "
"reasonable to write an iterator that produces an infinite stream of data."
msgstr ""
"Ітератор - це об'єкт, що представляє потік даних; цей об’єкт повертає дані "
"по одному елементу за раз. Ітератор Python має підтримувати метод під "
"назвою :meth:`~iterator.__next__`, який не приймає аргументів і завжди "
"повертає наступний елемент потоку. Якщо в потоці більше немає елементів, :"
"meth:`~iterator.__next__` має викликати виняток :exc:`StopIteration`. Проте "
"ітератори не обов’язково мають бути кінцевими; цілком розумно написати "
"ітератор, який створює нескінченний потік даних."
msgid ""
"The built-in :func:`iter` function takes an arbitrary object and tries to "
"return an iterator that will return the object's contents or elements, "
"raising :exc:`TypeError` if the object doesn't support iteration. Several "
"of Python's built-in data types support iteration, the most common being "
"lists and dictionaries. An object is called :term:`iterable` if you can get "
"an iterator for it."
msgstr ""
"Вбудована функція :func:`iter` приймає довільний об’єкт і намагається "
"повернути ітератор, який повертатиме вміст або елементи об’єкта, викликаючи :"
"exc:`TypeError`, якщо об’єкт не підтримує ітерацію. Кілька вбудованих типів "
"даних Python підтримують ітерацію, найпоширенішими з яких є списки та "
"словники. Об’єкт називається :term:`iterable`, якщо ви можете отримати для "
"нього ітератор."
msgid "You can experiment with the iteration interface manually:"
msgstr "Ви можете експериментувати з інтерфейсом ітерації вручну:"
msgid ""
"Python expects iterable objects in several different contexts, the most "
"important being the :keyword:`for` statement. In the statement ``for X in "
"Y``, Y must be an iterator or some object for which :func:`iter` can create "
"an iterator. These two statements are equivalent::"
msgstr ""
"Python очікує ітерованих об’єктів у кількох різних контекстах, найважливішим "
"з яких є оператор :keyword:`for`. У операторі ``для X в Y`` Y має бути "
"ітератором або деяким об’єктом, для якого :func:`iter` може створити "
"ітератор. Ці два твердження еквівалентні:"
msgid ""
"for i in iter(obj):\n"
" print(i)\n"
"\n"
"for i in obj:\n"
" print(i)"
msgstr ""
msgid ""
"Iterators can be materialized as lists or tuples by using the :func:`list` "
"or :func:`tuple` constructor functions:"
msgstr ""
"Ітератори можна матеріалізувати як списки або кортежі за допомогою функцій "
"конструктора :func:`list` або :func:`tuple`:"
msgid ""
"Sequence unpacking also supports iterators: if you know an iterator will "
"return N elements, you can unpack them into an N-tuple:"
msgstr ""
"Розпакування послідовності також підтримує ітератори: якщо ви знаєте, що "
"ітератор поверне N елементів, ви можете розпакувати їх у N-кортеж:"
msgid ""
"Built-in functions such as :func:`max` and :func:`min` can take a single "
"iterator argument and will return the largest or smallest element. The "
"``\"in\"`` and ``\"not in\"`` operators also support iterators: ``X in "
"iterator`` is true if X is found in the stream returned by the iterator. "
"You'll run into obvious problems if the iterator is infinite; :func:`max`, :"
"func:`min` will never return, and if the element X never appears in the "
"stream, the ``\"in\"`` and ``\"not in\"`` operators won't return either."
msgstr ""
"Вбудовані функції, такі як :func:`max` і :func:`min`, можуть приймати один "
"аргумент ітератора та повертати найбільший або найменший елемент. Оператори "
"``\"in\"`` і ``\"not in\"`` також підтримують ітератори: ``X в ітераторі`` є "
"істинним, якщо X знайдено в потоці, повернутому ітератором. Ви зіткнетеся з "
"очевидними проблемами, якщо ітератор нескінченний; :func:`max`, :func:`min` "
"ніколи не повертаються, а якщо елемент X ніколи не з’являється в потоці, "
"оператори ``\"in\"`` і ``\"not in\"`` не повертаються або."
msgid ""
"Note that you can only go forward in an iterator; there's no way to get the "
"previous element, reset the iterator, or make a copy of it. Iterator "
"objects can optionally provide these additional capabilities, but the "
"iterator protocol only specifies the :meth:`~iterator.__next__` method. "
"Functions may therefore consume all of the iterator's output, and if you "
"need to do something different with the same stream, you'll have to create a "
"new iterator."
msgstr ""
"Зауважте, що в ітераторі можна рухатися лише вперед; немає способу отримати "
"попередній елемент, скинути ітератор або зробити його копію. Об’єкти-"
"ітератори можуть додатково надавати ці додаткові можливості, але протокол "
"ітераторів визначає лише метод :meth:`~iterator.__next__`. Тому функції "
"можуть споживати весь вихід ітератора, і якщо вам потрібно зробити щось інше "
"з тим самим потоком, вам доведеться створити новий ітератор."
msgid "Data Types That Support Iterators"
msgstr "Типи даних, які підтримують ітератори"
msgid ""
"We've already seen how lists and tuples support iterators. In fact, any "
"Python sequence type, such as strings, will automatically support creation "
"of an iterator."
msgstr ""
"Ми вже бачили, як списки та кортежі підтримують ітератори. Насправді будь-"
"який тип послідовності Python, наприклад рядки, автоматично підтримуватиме "
"створення ітератора."
msgid ""
"Calling :func:`iter` on a dictionary returns an iterator that will loop over "
"the dictionary's keys::"
msgstr ""
"Виклик :func:`iter` для словника повертає ітератор, який перебиратиме ключі "
"словника::"
msgid ""
">>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,\n"
"... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}\n"
">>> for key in m:\n"
"... print(key, m[key])\n"
"Jan 1\n"
"Feb 2\n"
"Mar 3\n"
"Apr 4\n"
"May 5\n"
"Jun 6\n"
"Jul 7\n"
"Aug 8\n"
"Sep 9\n"
"Oct 10\n"
"Nov 11\n"
"Dec 12"
msgstr ""
msgid ""
"Note that starting with Python 3.7, dictionary iteration order is guaranteed "
"to be the same as the insertion order. In earlier versions, the behaviour "
"was unspecified and could vary between implementations."
msgstr ""
"Зауважте, що, починаючи з Python 3.7, порядок ітерацій словника гарантовано "
"збігається з порядком вставки. У попередніх версіях поведінка була "
"невизначеною та могла відрізнятися в різних реалізаціях."
msgid ""
"Applying :func:`iter` to a dictionary always loops over the keys, but "
"dictionaries have methods that return other iterators. If you want to "
"iterate over values or key/value pairs, you can explicitly call the :meth:"
"`~dict.values` or :meth:`~dict.items` methods to get an appropriate iterator."
msgstr ""
"Застосування :func:`iter` до словника завжди повторює ключі, але словники "
"мають методи, які повертають інші ітератори. Якщо ви хочете перебирати "
"значення або пари ключ/значення, ви можете явно викликати методи :meth:"
"`~dict.values` або :meth:`~dict.items`, щоб отримати відповідний ітератор."
msgid ""
"The :func:`dict` constructor can accept an iterator that returns a finite "
"stream of ``(key, value)`` tuples:"
msgstr ""
"Конструктор :func:`dict` може приймати ітератор, який повертає кінцевий "
"потік кортежів ``(ключ, значення)``:"
msgid ""
"Files also support iteration by calling the :meth:`~io.TextIOBase.readline` "
"method until there are no more lines in the file. This means you can read "
"each line of a file like this::"
msgstr ""
"Файли також підтримують ітерацію шляхом виклику методу :meth:`~io.TextIOBase."
"readline`, доки у файлі не залишиться рядків. Це означає, що ви можете "
"читати кожен рядок файлу таким чином:"
msgid ""
"for line in file:\n"
" # do something for each line\n"
" ..."
msgstr ""
msgid ""
"Sets can take their contents from an iterable and let you iterate over the "
"set's elements::"
msgstr ""
"Набори можуть брати свій вміст із ітерованого елемента й дозволяти вам "
"перебирати елементи набору:"
msgid ""
">>> S = {2, 3, 5, 7, 11, 13}\n"
">>> for i in S:\n"
"... print(i)\n"
"2\n"
"3\n"
"5\n"
"7\n"
"11\n"
"13"
msgstr ""
msgid "Generator expressions and list comprehensions"
msgstr "Генератор виразів і розуміння списків"
msgid ""
"Two common operations on an iterator's output are 1) performing some "
"operation for every element, 2) selecting a subset of elements that meet "
"some condition. For example, given a list of strings, you might want to "
"strip off trailing whitespace from each line or extract all the strings "
"containing a given substring."
msgstr ""
"Дві загальні операції на виході ітератора: 1) виконання певної операції для "
"кожного елемента, 2) вибір підмножини елементів, які відповідають певній "
"умові. Наприклад, маючи список рядків, ви можете видалити кінцеві пробіли з "
"кожного рядка або витягти всі рядки, що містять певний підрядок."
msgid ""
"List comprehensions and generator expressions (short form: \"listcomps\" and "
"\"genexps\") are a concise notation for such operations, borrowed from the "
"functional programming language Haskell (https://www.haskell.org/). You can "
"strip all the whitespace from a stream of strings with the following code::"
msgstr ""
"Розуміння списків і вирази генератора (скорочена форма: \"listcomps\" і "
"\"genexps\") є короткою нотацією для таких операцій, запозиченої з "
"функціональної мови програмування Haskell (https://www.haskell.org/). Ви "
"можете видалити всі пробіли з потоку рядків за допомогою такого коду::"
msgid ""
">>> line_list = [' line 1\\n', 'line 2 \\n', ' \\n', '']\n"
"\n"
">>> # Generator expression -- returns iterator\n"
">>> stripped_iter = (line.strip() for line in line_list)\n"
"\n"
">>> # List comprehension -- returns list\n"
">>> stripped_list = [line.strip() for line in line_list]"
msgstr ""
msgid ""
"You can select only certain elements by adding an ``\"if\"`` condition::"
msgstr "Ви можете вибрати лише певні елементи, додавши умову ``\"if\"``::"
msgid ""
">>> stripped_list = [line.strip() for line in line_list\n"
"... if line != \"\"]"
msgstr ""
msgid ""
"With a list comprehension, you get back a Python list; ``stripped_list`` is "
"a list containing the resulting lines, not an iterator. Generator "
"expressions return an iterator that computes the values as necessary, not "
"needing to materialize all the values at once. This means that list "
"comprehensions aren't useful if you're working with iterators that return an "
"infinite stream or a very large amount of data. Generator expressions are "
"preferable in these situations."
msgstr ""
"З розумінням списку ви отримуєте список Python; ``stripped_list`` – це "
"список, що містить отримані рядки, а не ітератор. Вирази генератора "
"повертають ітератор, який обчислює значення за потреби, не потребуючи "
"матеріалізації всіх значень одночасно. Це означає, що розуміння списку не є "
"корисним, якщо ви працюєте з ітераторами, які повертають нескінченний потік "
"або дуже великий обсяг даних. Вирази-генератори є кращими в цих ситуаціях."
msgid ""
"Generator expressions are surrounded by parentheses (\"()\") and list "
"comprehensions are surrounded by square brackets (\"[]\"). Generator "
"expressions have the form::"
msgstr ""
"Вирази генератора оточені дужками (\"()\"), а розуміння списків оточені "
"квадратними дужками (\"[]\"). Вирази генератора мають вигляд::"
msgid ""
"( expression for expr in sequence1\n"
" if condition1\n"
" for expr2 in sequence2\n"
" if condition2\n"
" for expr3 in sequence3\n"
" ...\n"
" if condition3\n"
" for exprN in sequenceN\n"
" if conditionN )"
msgstr ""
msgid ""
"Again, for a list comprehension only the outside brackets are different "
"(square brackets instead of parentheses)."
msgstr ""
"Знову ж таки, для розуміння списку відрізняються лише зовнішні дужки "
"(квадратні дужки замість дужок)."
msgid ""
"The elements of the generated output will be the successive values of "
"``expression``. The ``if`` clauses are all optional; if present, "
"``expression`` is only evaluated and added to the result when ``condition`` "
"is true."
msgstr ""
"Елементи згенерованого результату будуть послідовними значеннями ``виразу``. "
"Речення ``if`` є необов'язковими; якщо присутнє, ``вираз`` обчислюється та "
"додається до результату лише тоді, коли ``умова`` є істинною."
msgid ""
"Generator expressions always have to be written inside parentheses, but the "
"parentheses signalling a function call also count. If you want to create an "
"iterator that will be immediately passed to a function you can write::"
msgstr ""
"Вирази генератора завжди мають бути записані в дужках, але дужки, що "
"сигналізують про виклик функції, також враховуються. Якщо ви хочете створити "
"ітератор, який буде негайно передано функції, ви можете написати::"
msgid "obj_total = sum(obj.count for obj in list_all_objects())"
msgstr ""
msgid ""
"The ``for...in`` clauses contain the sequences to be iterated over. The "
"sequences do not have to be the same length, because they are iterated over "
"from left to right, **not** in parallel. For each element in ``sequence1``, "
"``sequence2`` is looped over from the beginning. ``sequence3`` is then "
"looped over for each resulting pair of elements from ``sequence1`` and "
"``sequence2``."
msgstr ""
"Речення ``for...in`` містять послідовності, які потрібно повторити. "
"Послідовності не обов’язково мають бути однакової довжини, оскільки вони "
"повторюються зліва направо, **не** паралельно. Для кожного елемента в "
"``sequence1`` ``sequence2`` повторюється з самого початку. Після цього "
"``sequence3`` виконується в циклі для кожної отриманої пари елементів з "
"``sequence1`` і ``sequence2``."
msgid ""
"To put it another way, a list comprehension or generator expression is "
"equivalent to the following Python code::"
msgstr ""
"Іншими словами, вираз розуміння списку або генератор еквівалентний такому "
"коду Python::"
msgid ""
"for expr1 in sequence1:\n"
" if not (condition1):\n"
" continue # Skip this element\n"
" for expr2 in sequence2:\n"
" if not (condition2):\n"
" continue # Skip this element\n"
" ...\n"
" for exprN in sequenceN:\n"
" if not (conditionN):\n"
" continue # Skip this element\n"
"\n"
" # Output the value of\n"
" # the expression."
msgstr ""
msgid ""
"This means that when there are multiple ``for...in`` clauses but no ``if`` "
"clauses, the length of the resulting output will be equal to the product of "
"the lengths of all the sequences. If you have two lists of length 3, the "
"output list is 9 elements long:"
msgstr ""
"Це означає, що коли є кілька пропозицій ``for...in``, але немає пропозицій "
"``if``, довжина результату буде дорівнювати добутку довжин усіх "
"послідовностей. Якщо у вас є два списки довжиною 3, вихідний список "
"складається з 9 елементів:"
msgid ""
"To avoid introducing an ambiguity into Python's grammar, if ``expression`` "
"is creating a tuple, it must be surrounded with parentheses. The first list "
"comprehension below is a syntax error, while the second one is correct::"
msgstr ""
"Щоб уникнути неоднозначності в граматиці Python, якщо ``вираз`` створює "
"кортеж, він повинен бути оточений дужками. Перше розуміння списку нижче є "
"синтаксичною помилкою, тоді як друге є правильним:"
msgid ""
"# Syntax error\n"
"[x, y for x in seq1 for y in seq2]\n"
"# Correct\n"
"[(x, y) for x in seq1 for y in seq2]"
msgstr ""
msgid "Generators"
msgstr "Генератори"
msgid ""
"Generators are a special class of functions that simplify the task of "
"writing iterators. Regular functions compute a value and return it, but "
"generators return an iterator that returns a stream of values."
msgstr ""
"Генератори — це спеціальний клас функцій, які спрощують завдання написання "
"ітераторів. Звичайні функції обчислюють значення та повертають його, але "
"генератори повертають ітератор, який повертає потік значень."
msgid ""
"You're doubtless familiar with how regular function calls work in Python or "
"C. When you call a function, it gets a private namespace where its local "
"variables are created. When the function reaches a ``return`` statement, "
"the local variables are destroyed and the value is returned to the caller. "
"A later call to the same function creates a new private namespace and a "
"fresh set of local variables. But, what if the local variables weren't "
"thrown away on exiting a function? What if you could later resume the "
"function where it left off? This is what generators provide; they can be "
"thought of as resumable functions."
msgstr ""
"Ви, безсумнівно, знайомі з тим, як працюють звичайні виклики функцій у "
"Python або C. Коли ви викликаєте функцію, вона отримує приватний простір "
"імен, де створюються її локальні змінні. Коли функція досягає оператора "
"``return``, локальні змінні знищуються, а значення повертається "
"викликаючому. Пізніший виклик тієї ж функції створює новий приватний простір "
"імен і новий набір локальних змінних. Але що, якби локальні змінні не були "
"викинуті під час виходу з функції? Що, якби ви могли пізніше відновити "
"функцію, де вона була зупинена? Це те, що забезпечують генератори; їх можна "
"розглядати як відновлювані функції."
msgid "Here's the simplest example of a generator function:"
msgstr "Ось найпростіший приклад функції генератора:"
msgid ""
"Any function containing a :keyword:`yield` keyword is a generator function; "
"this is detected by Python's :term:`bytecode` compiler which compiles the "
"function specially as a result."
msgstr ""
"Будь-яка функція, що містить ключове слово :keyword:`yield`, є функцією-"
"генератором; це виявляється компілятором :term:`bytecode` Python, який "
"спеціально компілює функцію в результаті."
msgid ""
"When you call a generator function, it doesn't return a single value; "
"instead it returns a generator object that supports the iterator protocol. "
"On executing the ``yield`` expression, the generator outputs the value of "
"``i``, similar to a ``return`` statement. The big difference between "
"``yield`` and a ``return`` statement is that on reaching a ``yield`` the "
"generator's state of execution is suspended and local variables are "
"preserved. On the next call to the generator's :meth:`~generator.__next__` "
"method, the function will resume executing."
msgstr ""
"Коли ви викликаєте функцію генератора, вона не повертає жодного значення; "
"замість цього він повертає об'єкт генератора, який підтримує протокол "
"ітератора. Під час виконання виразу ``yield`` генератор виводить значення "
"``i``, подібно до оператора ``return``. Велика різниця між оператором "
"``yield`` і оператором ``return`` полягає в тому, що після досягнення "
"``yield`` стан виконання генератора призупиняється, а локальні змінні "
"зберігаються. Під час наступного виклику методу генератора :meth:`~generator."
"__next__` функція відновить виконання."
msgid "Here's a sample usage of the ``generate_ints()`` generator:"
msgstr "Ось приклад використання генератора ``generate_ints()``:"
msgid ""
"You could equally write ``for i in generate_ints(5)``, or ``a, b, c = "
"generate_ints(3)``."
msgstr ""
"Так само можна написати ``для i в generate_ints(5)`` або ``a, b, c = "
"generate_ints(3)``."
msgid ""
"Inside a generator function, ``return value`` causes "
"``StopIteration(value)`` to be raised from the :meth:`~generator.__next__` "
"method. Once this happens, or the bottom of the function is reached, the "
"procession of values ends and the generator cannot yield any further values."
msgstr ""
"Усередині функції-генератора ``повернене значення`` викликає "
"``StopIteration(value)``, яке буде викликано з методу :meth:`~generator."
"__next__`. Як тільки це станеться, або коли функція досягне дна, обробка "
"значень закінчується, і генератор не зможе видавати жодних додаткових "
"значень."
msgid ""
"You could achieve the effect of generators manually by writing your own "
"class and storing all the local variables of the generator as instance "
"variables. For example, returning a list of integers could be done by "
"setting ``self.count`` to 0, and having the :meth:`~iterator.__next__` "
"method increment ``self.count`` and return it. However, for a moderately "
"complicated generator, writing a corresponding class can be much messier."
msgstr ""
"Ви можете досягти ефекту генераторів вручну, написавши власний клас і "
"зберігши всі локальні змінні генератора як змінні екземпляра. Наприклад, "
"повернути список цілих чисел можна, встановивши ``self.count`` на 0, і "
"дозволивши методу :meth:`~iterator.__next__` збільшити ``self.count`` і "
"повернути його. Однак для помірно складного генератора написання "
"відповідного класу може бути набагато складнішим."
msgid ""
"The test suite included with Python's library, :source:`Lib/test/"
"test_generators.py`, contains a number of more interesting examples. Here's "
"one generator that implements an in-order traversal of a tree using "
"generators recursively. ::"
msgstr ""
"Набір тестів, що входить до бібліотеки Python, :source:`Lib/test/"
"test_generators.py`, містить низку більш цікавих прикладів. Ось один "
"генератор, який реалізує рекурсивний обхід дерева за допомогою "
"генераторів. ::"
msgid ""
"# A recursive generator that generates Tree leaves in in-order.\n"
"def inorder(t):\n"
" if t:\n"
" for x in inorder(t.left):\n"
" yield x\n"
"\n"
" yield t.label\n"
"\n"
" for x in inorder(t.right):\n"
" yield x"
msgstr ""
msgid ""
"Two other examples in ``test_generators.py`` produce solutions for the N-"
"Queens problem (placing N queens on an NxN chess board so that no queen "
"threatens another) and the Knight's Tour (finding a route that takes a "
"knight to every square of an NxN chessboard without visiting any square "
"twice)."
msgstr ""
"Два інших приклади в ``test_generators.py`` створюють рішення для проблеми N-"
"Queens (розміщення N ферзів на NxN шахівниці так, щоб жодна королева не "
"загрожувала іншій) і Knight's Tour (пошук маршруту, який веде лицаря до "
"кожної клітинки). шахової дошки NxN, не відвідуючи жодного поля двічі)."
msgid "Passing values into a generator"
msgstr "Передача значень у генератор"
msgid ""
"In Python 2.4 and earlier, generators only produced output. Once a "
"generator's code was invoked to create an iterator, there was no way to pass "
"any new information into the function when its execution is resumed. You "
"could hack together this ability by making the generator look at a global "
"variable or by passing in some mutable object that callers then modify, but "
"these approaches are messy."
msgstr ""
"У Python 2.4 і раніших версіях генератори створювали лише вихідні дані. Як "
"тільки код генератора був викликаний для створення ітератора, не було "
"можливості передати будь-яку нову інформацію у функцію, коли її виконання "
"відновилося. Ви можете об’єднати цю здатність, змусивши генератор дивитися "
"на глобальну змінну або передавши якийсь змінний об’єкт, який потім змінюють "
"абоненти, але ці підходи є безладними."
msgid ""
"In Python 2.5 there's a simple way to pass values into a generator. :keyword:"
"`yield` became an expression, returning a value that can be assigned to a "
"variable or otherwise operated on::"
msgstr ""
"У Python 2.5 є простий спосіб передачі значень у генератор. :keyword:`yield` "
"став виразом, який повертає значення, яке можна присвоїти змінній або іншим "
"чином оперувати:"
msgid "val = (yield i)"
msgstr ""
msgid ""
"I recommend that you **always** put parentheses around a ``yield`` "
"expression when you're doing something with the returned value, as in the "
"above example. The parentheses aren't always necessary, but it's easier to "
"always add them instead of having to remember when they're needed."
msgstr ""
"Я рекомендую вам **завжди** брати дужки навколо виразу ``yield``, коли ви "
"робите щось із повернутим значенням, як у прикладі вище. Дужки не завжди "
"потрібні, але простіше завжди додавати їх замість того, щоб запам’ятовувати, "
"коли вони потрібні."
msgid ""
"(:pep:`342` explains the exact rules, which are that a ``yield``-expression "
"must always be parenthesized except when it occurs at the top-level "
"expression on the right-hand side of an assignment. This means you can "
"write ``val = yield i`` but have to use parentheses when there's an "
"operation, as in ``val = (yield i) + 12``.)"
msgstr ""
"(:pep:`342` пояснює точні правила, які полягають у тому, що вираз ``yield`` "
"завжди повинен бути взятий у дужки, за винятком випадків, коли він "
"зустрічається у виразі верхнього рівня в правій частині призначення. Це "
"означає, що ви можна написати ``val = yield i``, але потрібно "
"використовувати дужки, коли є операція, як у ``val = (yield i) + 12``.)"
msgid ""
"Values are sent into a generator by calling its :meth:`send(value) "
"<generator.send>` method. This method resumes the generator's code and the "
"``yield`` expression returns the specified value. If the regular :meth:"
"`~generator.__next__` method is called, the ``yield`` returns ``None``."
msgstr ""
"Значення надсилаються в генератор шляхом виклику його методу :meth:"
"`send(value) <generator.send>`. Цей метод відновлює код генератора, а вираз "
"``yield`` повертає вказане значення. Якщо викликається звичайний метод :meth:"
"`~generator.__next__`, ``yield`` повертає ``None``."
msgid ""
"Here's a simple counter that increments by 1 and allows changing the value "
"of the internal counter."
msgstr ""
"Ось простий лічильник, який збільшується на 1 і дозволяє змінювати значення "
"внутрішнього лічильника."
msgid ""
"def counter(maximum):\n"
" i = 0\n"
" while i < maximum:\n"
" val = (yield i)\n"
" # If value provided, change counter\n"
" if val is not None:\n"
" i = val\n"
" else:\n"
" i += 1"
msgstr ""
msgid "And here's an example of changing the counter:"
msgstr "А ось приклад зміни лічильника:"
msgid ""
"Because ``yield`` will often be returning ``None``, you should always check "
"for this case. Don't just use its value in expressions unless you're sure "
"that the :meth:`~generator.send` method will be the only method used to "
"resume your generator function."
msgstr ""
"Оскільки ``yield`` часто повертатиме ``None``, ви завжди повинні перевіряти "
"цей випадок. Не просто використовуйте його значення у виразах, якщо ви не "
"впевнені, що метод :meth:`~generator.send` буде єдиним методом, використаним "
"для відновлення вашої функції генератора."
msgid ""