From 51f77e4860fafa84817a93414e8ed7f58c69fe6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 12:42:22 +0300 Subject: [PATCH 01/44] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=D0=B0=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B2=D0=BE=D0=B3=D0=BE=20=D1=80=D0=B0=D0=B7=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blank/chap00.ipynb | 206 +++++++++++++++++++++++---------------------- 1 file changed, 104 insertions(+), 102 deletions(-) diff --git a/blank/chap00.ipynb b/blank/chap00.ipynb index 55b62c2..9a2b141 100644 --- a/blank/chap00.ipynb +++ b/blank/chap00.ipynb @@ -5,9 +5,11 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать печатную и электронную версии книги *Think Python 3e*\n", + "\n", + "на сайте [Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", + "\n", + "на [Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, { @@ -15,7 +17,7 @@ "id": "d9724920", "metadata": {}, "source": [ - "# Preface\n", + "# Предисловие\n", "\n" ] }, @@ -24,21 +26,21 @@ "id": "b76f38c6", "metadata": {}, "source": [ - "## Who Is This Book For?\n", + "## Для кого эта книга?\n", "\n", - "If you want to learn to program, you have come to the right place.\n", - "Python is one of the best programming languages for beginners -- and it is also one of the most in-demand skills.\n", + "Если вы хотите научиться программировать, вы обратились по адресу.\n", + "Python — один из лучших языков для новичков и одновременно один из самых востребованных навыков.\n", "\n", - "You have also come at the right time, because learning to program now is probably easier than ever.\n", - "With virtual assistants like ChatGPT, you don't have to learn alone.\n", - "Throughout this book, I'll suggest ways you can use these tools to accelerate your learning.\n", + "Вы также выбрали подходящее время: сейчас учиться программировать, пожалуй, проще, чем когда-либо.\n", + "С виртуальными помощниками вроде ChatGPT вам не обязательно учиться в одиночку.\n", + "На протяжении всей книги я буду предлагать способы использовать эти инструменты, чтобы ускорить обучение.\n", "\n", - "This book is primarily for people who have never programmed before and people who have some experience in another programming language.\n", - "If you have substantial experience in Python, you might find the first few chapters too slow.\n", + "Эта книга предназначена прежде всего для тех, кто никогда не программировал, и для людей с опытом в других языках.\n", + "Если у вас уже есть серьёзный опыт работы с Python, первые главы могут показаться слишком медленными.\n", "\n", - "One of the challenges of learning to program is that you have to learn *two* languages: one is the programming language itself; the other is the vocabulary we use to talk about programs.\n", - "If you learn only the programming language, you are likely to have problems when you need to interpret an error message, read documentation, talk to another person, or use virtual assistants.\n", - "If you have done some programming, but you have not also learned this second language, I hope you find this book helpful." + "Одна из трудностей обучения программированию состоит в том, что нужно изучить *два* языка: сам язык программирования и словарь терминов, которыми мы описываем программы.\n", + "Если вы выучите только сам язык, вам будет сложно разбираться в сообщениях об ошибках, читать документацию, общаться с другими людьми и пользоваться виртуальными помощниками.\n", + "Если вы уже немного программировали, но не освоили эту вторую терминологию, надеюсь, эта книга поможет вам." ] }, { @@ -46,21 +48,21 @@ "id": "b4dd57bc", "metadata": {}, "source": [ - "## Goals of the Book\n", + "## Цели книги\n", "\n", - "Writing this book, I tried to be careful with the vocabulary.\n", - "I define each term when it first appears.\n", - "And there is a glossary that the end of each chapter that reviews the terms that were introduced.\n", + "Пишя эту книгу, я старался аккуратно использовать терминологию.\n", + "Я даю определение каждому термину, когда он впервые появляется.\n", + "В конце каждой главы есть глоссарий, где перечислены введённые термины.\n", "\n", - "I also tried to be concise.\n", - "The less mental effort it takes to read the book, the more capacity you will have for programming.\n", + "Я также старался быть кратким.\n", + "Чем меньше усилий требуется для чтения книги, тем больше сил останется на программирование.\n", "\n", - "But you can't learn to program just by reading a book -- you have to practice.\n", - "For that reason, this book includes exercises at the end of every chapter where you can practice what you have learned.\n", + "Но научиться программировать только читая книгу невозможно — нужно практиковаться.\n", + "Поэтому в конце каждой главы есть упражнения, где вы можете потренироваться.\n", "\n", - "If you read carefully and work on exercises consistently, you will make progress.\n", - "But I'll warn you now -- learning to program is not easy, and even for experienced programmers it can be frustrating.\n", - "As we go, I will suggest strategies to help you write correct programs and fix incorrect ones." + "Если читать внимательно и регулярно выполнять упражнения, вы будете продвигаться вперёд.\n", + "Но предупреждаю заранее: учиться программированию непросто, и даже опытные программисты иногда испытывают разочарование.\n", + "По ходу дела я буду предлагать стратегии, помогающие писать правильные программы и исправлять ошибки." ] }, { @@ -68,31 +70,31 @@ "id": "6516d914", "metadata": {}, "source": [ - "## Navigating the Book\n", + "## Как работать с книгой\n", "\n", - "Each chapter in this book builds on the previous ones, so you should read them in order and take time to work on the exercises before you move on.\n", + "Каждая глава этой книги опирается на предыдущие, поэтому лучше читать их по порядку и не переходить далее, пока не выполните упражнения.\n", "\n", - "The first six chapters introduce basic elements like arithmetic, conditionals, and loops.\n", - "They also introduce the most important concept in programming, functions, and a powerful way to use them, recursion.\n", + "В первых шести главах рассматриваются базовые элементы: арифметика, условные операторы и циклы.\n", + "Также в них вводится важнейшая концепция программирования — функции, а также мощный способ их применения — рекурсия.\n", "\n", - "Chapters 7 and 8 introduce strings -- which can represent letter, words, and sentences -- and algorithms for working with them.\n", + "Седьмая и восьмая главы посвящены строкам — они могут представлять буквы, слова и предложения — и алгоритмам работы с ними.\n", "\n", - "Chapters 9 through 12 introduce Python's core data structures -- lists, dictionaries, and tuples -- which are powerful tools for writing efficient programs.\n", - "Chapter 12 presents algorithms for analyzing text and randomly generating new text.\n", - "Algorithms like these are at the core of large language models (LLMs), so this chapter will give you an idea of how tools like ChatGPT work.\n", + "Глава 9—12 знакомят с основными структурами данных Python — списками, словарями и кортежами, которые позволяют писать эффективные программы.\n", + "В 12-й главе описаны алгоритмы анализа текста и генерации нового текста.\n", + "Такие алгоритмы лежат в основе больших языковых моделей (LLM), поэтому эта глава даст вам представление о том, как работают инструменты вроде ChatGPT.\n", "\n", - "Chapter 13 is about ways to store data in long-term storage -- files and databases.\n", - "As an exercise, you can write a program that searches a file system and finds duplicate files.\n", + "Глава 13 рассказывает о способах долговременного хранения данных — файлах и базах данных.\n", + "В качестве упражнения вы сможете написать программу, которая ищет в файловой системе дубликаты файлов.\n", "\n", - "Chapters 14 through 17 introduce object-oriented programming (OOP), which is a way to organize programs and the data they work with.\n", - "Many Python libraries are written in object-oriented style, so these chapters will help you understand their design -- and define your own objects.\n", + "Главы 14–17 вводят объектно-ориентированное программирование (ООП) — способ организовывать программы и данные, с которыми они работают.\n", + "Многие библиотеки Python написаны в объектно-ориентированном стиле, поэтому эти главы помогут понять их устройство и создавать собственные объекты.\n", "\n", - "The goal of this book is not to cover the entire Python language.\n", - "Rather, I focus on a subset of the language that provides the greatest capability with the fewest concepts.\n", - "Nevertheless, Python has a lot of features you can use to solve common problems efficiently.\n", - "Chapter 18 presents some of these features.\n", + "Цель книги — не покрыть весь язык Python полностью.\n", + "Я сосредоточился на той части языка, которая дает наибольшие возможности при минимальном наборе концепций.\n", + "Тем не менее в Python есть много возможностей, которые помогут эффективно решать типовые задачи.\n", + "Некоторые из них рассматриваются в главе 18.\n", "\n", - "Finally, Chapter 19 presents my parting thoughts and suggestions for continuing your programming journey." + "Наконец, в главе 19 я делюсь завершающими мыслями и советами по продолжению изучения программирования." ] }, { @@ -100,38 +102,38 @@ "id": "23013838", "metadata": {}, "source": [ - "## What's new in the third edition?\n", + "## Что нового в третьем издании?\n", "\n", - "The biggest changes in this edition were driven by two new technologies -- Jupyter notebooks and virtual assistants.\n", + "Наибольшие изменения в этом издании связаны с двумя новыми технологиями — Jupyter‑ноутбуками и виртуальными ассистентами.\n", "\n", - "Each chapter of this book is a Jupyter notebook, which is a document that contains both ordinary text and code.\n", - "For me, that makes it easier to write the code, test it, and keep it consistent with the text.\n", - "For you, it means you can run the code, modify it, and work on the exercises, all in one place.\n", - "Instructions for working with the notebooks are in the first chapter.\n", + "Каждая глава этой книги представляет собой Jupyter‑ноутбук — документ, содержащий и обычный текст, и код.\n", + "Мне это упрощает написание кода, его тестирование и поддержание согласованности с текстом.\n", + "Для вас это означает возможность запускать код, изменять его и выполнять упражнения прямо в одном месте.\n", + "Инструкции по работе с ноутбуками приведены в первой главе.\n", "\n", - "The other big change is that I've added advice for working with virtual assistants like ChatGPT and using them to accelerate your learning.\n", - "When the previous edition of this book was published in 2016, the predecessors of these tools were far less useful and most people were unaware of them. \n", - "Now they are a standard tool for software engineering, and I think they will be a transformational tool for learning to program -- and learning a lot of other things, too.\n", + "Другое важное нововведение — советы по работе с виртуальными помощниками вроде ChatGPT и использованию их для ускорения обучения.\n", + "Когда предыдущее издание вышло в 2016 году, предшественники этих инструментов были гораздо менее полезны, и большинство людей о них не знало.\n", + "Теперь же они стали стандартным инструментом разработки ПО, и я думаю, что они окажут революционное влияние на обучение программированию и многим другим вещам.\n", "\n", - "The other changes in the book were motivated by my regrets about the second edition.\n", + "Остальные изменения книги вызваны моими сожалениями по поводу второго издания.\n", "\n", - "The first is that I did not emphasize software testing.\n", - "That was already a regrettable omission in 2016, but with the advent of virtual assistants, automated testing has become even more important.\n", - "So this edition presents Python's most widely-used testing tools, `doctest` and `unittest`, and includes several exercises where you can practice working with them.\n", + "Прежде всего я недостаточно уделил внимания тестированию программного обеспечения.\n", + "Это и тогда было досадным упущением, а с появлением виртуальных ассистентов автоматическое тестирование стало ещё важнее.\n", + "Поэтому в этом издании представлены наиболее популярные средства тестирования Python — `doctest` и `unittest`, а также несколько упражнений для их практики.\n", "\n", - "My other regret is that the exercises in the second edition were uneven -- some were more interesting than others and some were too hard.\n", - "Moving to Jupyter notebooks helped me develop and test a more engaging and effective sequence of exercises.\n", + "Моё другое сожаление заключалось в том, что упражнения во втором издании были неравноценными: одни интереснее других, а некоторые слишком сложны.\n", + "Переход на Jupyter‑ноутбуки помог мне разработать и проверить более увлекательную и эффективную последовательность упражнений.\n", "\n", - "In this revision, the sequence of topics is almost the same, but I rearranged a few of the chapters and compressed two short chapters into one.\n", - "Also, I expanded the coverage of strings to include regular expressions.\n", + "В этой редакции последовательность тем почти та же, но я переставил несколько глав и объединил две короткие главы в одну.\n", + "Кроме того, я расширил раздел о строках, добавив регулярные выражения.\n", "\n", - "A few chapters use turtle graphics.\n", - "In previous editions, I used Python's `turtle` module, but unfortunately it doesn't work in Jupyter notebooks.\n", - "So I replaced it with a new turtle module that should be easier to use.\n", + "Несколько глав используют черепашью графику.\n", + "В предыдущих изданиях я применял модуль `turtle` из Python, но, к сожалению, он не работает в Jupyter‑ноутбуках.\n", + "Поэтому я заменил его новым модулем черепахи, пользоваться которым должно быть проще.\n", "\n", - "Finally, I rewrote a substantial fraction of the text, clarifying places that needed it and cutting back in places where I was not as concise as I could be.\n", + "Наконец, я переписал значительную часть текста, прояснив одни места и сократив другие, где мог быть лаконичнее.\n", "\n", - "I am very proud of this new edition -- I hope you like it!" + "Я очень горжусь этим новым изданием — надеюсь, оно вам понравится!" ] }, { @@ -139,27 +141,27 @@ "id": "bfb779bb", "metadata": {}, "source": [ - "## Getting started\n", + "## Начало работы\n", "\n", - "For most programming languages, including Python, there are many tools you can use to write and run programs. \n", - "These tools are called integrated development environments (IDEs).\n", - "In general, there are two kinds of IDEs:\n", + "Для большинства языков программирования, включая Python, существует множество инструментов для написания и запуска программ.\n", + "Эти инструменты называют интегрированными средами разработки (IDE).\n", + "В общем случае IDE бывают двух видов:\n", "\n", - "* Some work with files that contain code, so they provide tools for editing and running these files.\n", + "* Одни работают с файлами, содержащими код, и предоставляют средства для их редактирования и запуска.\n", "\n", - "* Others work primarily with notebooks, which are documents that contain text and code.\n", + "* Другие ориентированы на работу с ноутбуками — документами, в которых есть текст и код.\n", "\n", - "For beginners, I recommend starting with a notebook development environment like Jupyter.\n", + "Новичкам я рекомендую начать с среды для работы с ноутбуками, такой как Jupyter.\n", "\n", - "The notebooks for this book are available from an online repository at .\n", + "Ноутбуки из этой книги доступны в онлайн‑репозитории .\n", "\n", - "There are two ways to use them:\n", + "Есть два способа их использовать:\n", "\n", - "* You can download the notebooks and run them on your own computer. In that case, you have to install Python and Jupyter, which is not hard, but if you want to learn Python, it can be frustrating to spend a lot of time installing software.\n", + "* Вы можете скачать ноутбуки и запускать их на своём компьютере. Для этого нужно установить Python и Jupyter — это несложно, но если вы только начинаете изучать Python, может расстраивать трата времени на установку ПО.\n", "\n", - "* An alternative is to run the notebooks on Colab, which is a Jupyter environment that runs in a web browser, so you don't have to install anything. Colab is operated by Google, and it is free to use.\n", + "* Другой вариант — работать с ноутбуками в Colab. Это среда Jupyter, которая запускается в браузере, поэтому ничего не нужно устанавливать. Colab управляется Google и бесплатен.\n", "\n", - "If you are just getting started, I strongly recommend you start with Colab." + "Если вы только начинаете, настоятельно советую начинать с Colab." ] }, { @@ -167,17 +169,17 @@ "id": "2ebd2412", "metadata": {}, "source": [ - "## Resources for Teachers\n", + "## Ресурсы для преподавателей\n", "\n", - "If you are teaching with this book, here are some resources you might find useful.\n", + "Если вы преподаёте по этой книге, вот несколько полезных материалов.\n", "\n", - "* You can find notebooks with solutions to the exercises from , along with links to the additional resources below.\n", + "* Ноутбуки с решениями упражнений можно найти на , там же есть ссылки на дополнительные ресурсы.\n", "\n", - "* Quizzes for each chapter, and a summative quiz for the whole book, are available from [COMING SOON]\n", + "* Тесты к каждой главе и итоговый тест по всей книге будут доступны по ссылке [СКОРО]\n", "\n", - "* *Teaching and Learning with Jupyter* is an online book with suggestions for using Jupyter effectively in the classroom. You can read the book at \n", + "* Онлайн‑книга *Teaching and Learning with Jupyter* содержит советы по эффективному использованию Jupyter на занятиях. Её можно прочитать на сайте \n", "\n", - "* One of the best ways to use notebooks is live coding, where an instructor writes code and students follow along in their own notebooks. To learn about live coding -- and get other great advice about teaching programming -- I recommend the instructor training provided by The Carpentries, at " + "* Один из лучших способов работать с ноутбуками — «живое кодирование», когда преподаватель пишет код, а студенты повторяют у себя в тетрадях. Чтобы узнать больше о живом кодировании и получить другие полезные советы по преподаванию программирования, рекомендую пройти курс для инструкторов от The Carpentries: " ] }, { @@ -185,29 +187,29 @@ "id": "28e7de55", "metadata": {}, "source": [ - "## Acknowledgments\n", + "## Благодарности\n", "\n", - "Many thanks to Jeff Elkner, who translated my Java book into Python,\n", - "which got this project started and introduced me to what has turned out\n", - "to be my favorite language.\n", - "Thanks also to Chris Meyers, who contributed several sections to *How to Think Like a Computer Scientist*.\n", + "Большое спасибо Джеффу Элкнеру, который перевёл мою книгу по Java на Python,\n", + "что послужило началом этого проекта и познакомило меня с языком,\n", + "который стал моим любимым.\n", + "Благодарю также Криса Мейерса, который написал несколько разделов для *How to Think Like a Computer Scientist*.\n", "\n", - "Thanks to the Free Software Foundation for developing the GNU Free Documentation License, which helped make my collaboration with Jeff and Chris possible, and thanks to the Creative Commons for the license I am using now.\n", + "Благодарю Фонд свободного ПО за разработку лицензии GNU FDL, которая сделала возможным наше сотрудничество с Джеффом и Крисом, а также Creative Commons за лицензию, которую я использую сейчас.\n", "\n", - "Thanks to the developers and maintainers of the Python language and the libraries I used, including the Turtle graphics module; the tools I used to develop the book, including Jupyter and JupyterBook; and the services I used, including ChatGPT, Copilot, Colab and GitHub.\n", + "Спасибо разработчикам и сопровождающим язык Python и использованные библиотеки, включая модуль графики Turtle; а также инструменты, с помощью которых создавалась эта книга, в том числе Jupyter и JupyterBook; и сервисы, которыми я пользовался: ChatGPT, Copilot, Colab и GitHub.\n", "\n", - "Thanks to the editors at Lulu who worked on *How to Think Like a Computer Scientist* and the editors at O'Reilly Media who worked on *Think Python*.\n", + "Благодарю редакторов Lulu, работавших над *How to Think Like a Computer Scientist*, и редакторов O'Reilly Media, работавших над *Think Python*.\n", "\n", - "Special thanks to the technical reviewers for the second edition, Melissa Lewis and Luciano Ramalho, and for the third edition, Sam Lau and Luciano Ramalho (again!).\n", - "I am also grateful to Luciano for developing the turtle graphics module I use in several chapters, called `jupyturtle`.\n", + "Особая благодарность техническим редакторам второго издания Мелиссе Льюис и Лусиано Рамалью, а также рецензентам третьего издания — Сэму Лау и вновь Лусиано Рамалью.\n", + "Я также признателен Лусиано за разработку модуля `jupyturtle`, который используется в нескольких главах.\n", "\n", - "Thanks to all the students who worked with earlier versions of this book and all the contributors who sent in corrections and suggestions.\n", - "More than 100 sharp-eyed and thoughtful readers have sent in suggestions and corrections over the past few years. Their contributions, and enthusiasm for this project, have been a huge help.\n", + "Благодарю всех студентов, работавших с ранними версиями этой книги, и всех, кто присылал исправления и предложения.\n", + "Более сотни внимательных и неравнодушных читателей за последние годы прислали замечания и исправления. Их вклад и интерес к проекту очень помогли.\n", "\n", - "If you have a suggestion or correction, please send email to `feedback@thinkpython.com`.\n", - "If you include at least part of the sentence the error appears in, that\n", - "makes it easy for me to search. Page and section numbers are fine, too,\n", - "but not quite as easy to work with. Thanks!" + "Если у вас есть предложение или исправление, пожалуйста, пишите на `feedback@thinkpython.com`.\n", + "Если вы приведёте хотя бы часть предложения, в котором обнаружена ошибка,\n", + "мне будет проще её найти. Номера страниц и разделов тоже подходят,\n", + "но работать с ними не так удобно. Спасибо!" ] }, { @@ -229,9 +231,9 @@ "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -256,4 +258,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 6ba2b225e1b01caff0a5a7d365a06e17bdecd5b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 12:43:47 +0300 Subject: [PATCH 02/44] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=D0=BE=D0=B2=D1=8B=D1=85?= =?UTF-8?q?=20=D1=8F=D1=87=D0=B5=D0=B5=D0=BA=20=D0=B3=D0=BB=D0=B0=D0=B2?= =?UTF-8?q?=D1=8B=201?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blank/chap01.ipynb | 379 ++++++++------------------------------------- 1 file changed, 61 insertions(+), 318 deletions(-) diff --git a/blank/chap01.ipynb b/blank/chap01.ipynb index 7b758f0..3010a4c 100644 --- a/blank/chap01.ipynb +++ b/blank/chap01.ipynb @@ -5,9 +5,7 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать печатные и электронные версии *Think Python 3e*\n[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n[Amazon] (https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc&camp=1789&creative=9325)." ] }, { @@ -17,14 +15,7 @@ "tags": [] }, "source": [ - "# Welcome\n", - "\n", - "This is the Jupyter notebook for Chapter 1 of [*Think Python*, 3rd edition](https://greenteapress.com/wp/think-python-3rd-edition), by Allen B. Downey.\n", - "\n", - "If you are not familiar with Jupyter notebooks,\n", - "[click here for a short introduction](https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/jupyter_intro.ipynb).\n", - "\n", - "Then, if you are not already running this notebook on Colab, [click here to run this notebook on Colab](https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/chap01.ipynb)." + "Добро пожаловать\n\nЭто ноутбук Jupyter для главы 1 [*Think Python*, 3-е издание] (https://greenteapress.com/wp/think-python-3rd-edition), Аллена Б. Дауни.\n\nЕсли вы не знакомы с ноутбуками Jupyter,\n[нажмите здесь для краткого введения] (https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/jupyter_intro.ipynb).\n\nЗатем, если вы еще не запустили эту записную книжку на Colab, [нажмите здесь, чтобы запустить эту записную книжку на Colab] (https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/chap01.ipynb)." ] }, { @@ -34,9 +25,7 @@ "tags": [] }, "source": [ - "The following cell downloads a file and runs some code that is used specifically for this book.\n", - "You don't have to understand this code yet, but you should run it before you do anything else in this notebook.\n", - "Remember that you can run the code by selecting the cell and pressing the play button (a triangle in a circle) or hold down `Shift` and press `Enter`." + "Следующая ячейка загружает файл и запускает некоторый код, который используется специально для этой книги.\nВам еще не нужно понимать этот код, но вы должны запустить его, прежде чем делать что-либо еще в этом блокноте.\nПомните, что вы можете запустить код, выбрав ячейку и нажав кнопку воспроизведения (треугольник в круге) или удерживайте «Shift» и нажмите «Enter»." ] }, { @@ -71,21 +60,7 @@ "tags": [] }, "source": [ - "# Programming as a way of thinking\n", - "\n", - "The first goal of this book is to teach you how to program in Python.\n", - "But learning to program means learning a new way to think, so the second goal of this book is to help you think like a computer scientist.\n", - "This way of thinking combines some of the best features of mathematics, engineering, and natural science.\n", - "Like mathematicians, computer scientists use formal languages to denote ideas -- specifically computations.\n", - "Like engineers, they design things, assembling components into systems and evaluating trade-offs among alternatives.\n", - "Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.\n", - "\n", - "We will start with the most basic elements of programming and work our way up.\n", - "In this chapter, we'll see how Python represents numbers, letters, and words.\n", - "And you'll learn to perform arithmetic operations.\n", - "\n", - "You will also start to learn the vocabulary of programming, including terms like operator, expression, value, and type.\n", - "This vocabulary is important -- you will need it to understand the rest of the book, to communicate with other programmers, and to use and understand virtual assistants." + "# Программирование как способ мышления\n\nПервая цель этой книги — научить вас программировать на Python.\nНо обучение программированию означает изучение нового способа мышления, поэтому вторая цель этой книги — помочь вам думать как компьютерный ученый.\nЭтот способ мышления сочетает в себе некоторые из лучших особенностей математики, инженерии и естественных наук.\nКак и математики, компьютерные ученые используют формальные языки для обозначения идей, в частности вычислений.\nКак и инженеры, они проектируют вещи, собирают компоненты в системы и оценивают компромиссы между альтернативами.\nКак и ученые, они наблюдают за поведением сложных систем, формируют гипотезы и проверяют прогнозы.\n\nМы начнем с самых основных элементов программирования и проложим себе путь.\nВ этой главе мы увидим, как Python представляет числа, буквы и слова.\nИ вы научитесь выполнять арифметические операции.\n\nВы также начнете изучать словарь программирования, включая такие термины, как оператор, выражение, значение и тип.\nЭтот словарный запас важен — вам понадобится, чтобы понять остальную часть книги, общаться с другими программистами, а также использовать и понимать виртуальных помощников." ] }, { @@ -93,9 +68,7 @@ "id": "a371aea3", "metadata": {}, "source": [ - "## Arithmetic operators\n", - "\n", - "An **arithmetic operator** is a symbol that represents an arithmetic computation. For example, the plus sign, `+`, performs addition." + "## Арифметические операторы\n\n**арифметический оператор** является символом, представляющим арифметические вычисления. Например, знак «+» выполняет сложение." ] }, { @@ -111,7 +84,7 @@ "id": "fc0e7ce8", "metadata": {}, "source": [ - "The minus sign, `-`, is the operator that performs subtraction." + "Знак минус, '-', является оператором, который выполняет вычитание." ] }, { @@ -127,7 +100,7 @@ "id": "63e4e780", "metadata": {}, "source": [ - "The asterisk, `*`, performs multiplication." + "Звёздочка «*» выполняет умножение." ] }, { @@ -143,7 +116,7 @@ "id": "a6192d13", "metadata": {}, "source": [ - "And the forward slash, `/`, performs division:" + "А передний слэш, '/', выполняет деление:" ] }, { @@ -159,16 +132,7 @@ "id": "641ad233", "metadata": {}, "source": [ - "Notice that the result of the division is `42.0` rather than `42`. That's because there are two types of numbers in Python: \n", - "\n", - "* **integers**, which represent numbers with no fractional or decimal part, and \n", - "\n", - "* **floating-point numbers**, which represent integers and numbers with a decimal point.\n", - "\n", - "If you add, subtract, or multiply two integers, the result is an integer.\n", - "But if you divide two integers, the result is a floating-point number.\n", - "Python provides another operator, `//`, that performs **integer division**.\n", - "The result of integer division is always an integer." + "Обратите внимание, что результатом деления является «42.0», а не «42». Это потому, что в Python есть два типа чисел:\n\n** интегралы**, которые представляют собой числа без дробной или десятичной части, и\n\n*** числа с плавающей точкой**, которые представляют собой целые числа и числа с десятичной точкой.\n\nЕсли вы добавляете, вычитаете или умножаете два целых числа, результатом будет целое число.\nНо если разделить два целых числа, то получится число с плавающей точкой.\nPython предоставляет другого оператора, '//', который выполняет **целое деление **.\nРезультатом целого деления всегда является целое число." ] }, { @@ -184,7 +148,7 @@ "id": "b2a620ab", "metadata": {}, "source": [ - "Integer division is also called \"floor division\" because it always rounds down (toward the \"floor\"). " + "Целое деление также называют «половым делением», потому что оно всегда округляется вниз (к «полу»)." ] }, { @@ -200,8 +164,7 @@ "id": "41e2886a", "metadata": {}, "source": [ - "Finally, the operator `**` performs exponentiation; that is, it raises a\n", - "number to a power:" + "Наконец, оператор «**» выполняет экспоненциацию, то есть поднимает\nНомер для мощности:" ] }, { @@ -217,9 +180,7 @@ "id": "b2502fb6", "metadata": {}, "source": [ - "In some other languages, the caret, `^`, is used for exponentiation, but in Python\n", - "it is a bitwise operator called XOR.\n", - "If you are not familiar with bitwise operators, the result might be unexpected:" + "В некоторых других языках, забота, '^', используется для экспоненциации, но в Python.\nЭто небольшой оператор под названием XOR.\nЕсли вы не знакомы с операторами, результат может быть неожиданным:" ] }, { @@ -235,8 +196,7 @@ "id": "30078370", "metadata": {}, "source": [ - "I won't cover bitwise operators in this book, but you can read about\n", - "them at ." + "В этой книге я не буду освещать операторов по битам, но вы можете прочитать о\nОни расположены по адресу: http://wiki.python.org/moin/BitwiseOperators." ] }, { @@ -244,11 +204,7 @@ "id": "0f5b7e97", "metadata": {}, "source": [ - "## Expressions\n", - "\n", - "A collection of operators and numbers is called an **expression**.\n", - "An expression can contain any number of operators and numbers.\n", - "For example, here's an expression that contains two operators." + "## Выражения\n\nСовокупность операторов и чисел называется выражением **.\nВыражение может содержать любое количество операторов и чисел.\nНапример, вот выражение, которое содержит два оператора." ] }, { @@ -264,10 +220,7 @@ "id": "8e95039c", "metadata": {}, "source": [ - "Notice that exponentiation happens before addition.\n", - "Python follows the order of operations you might have learned in a math class: exponentiation happens before multiplication and division, which happen before addition and subtraction.\n", - "\n", - "In the following example, multiplication happens before addition." + "Обратите внимание, что экспоненциация происходит до добавления.\nPython следует порядку операций, который вы могли бы изучить в математическом классе: экспоненциация происходит до умножения и деления, что происходит до сложения и вычитания.\n\nВ следующем примере умножение происходит до сложения." ] }, { @@ -283,7 +236,7 @@ "id": "914a60d8", "metadata": {}, "source": [ - "If you want the addition to happen first, you can use parentheses." + "Если вы хотите, чтобы добавление произошло первым, вы можете использовать скобки." ] }, { @@ -299,8 +252,7 @@ "id": "67ae0ae9", "metadata": {}, "source": [ - "Every expression has a **value**.\n", - "For example, the expression `6 * 7` has the value `42`." + "Каждое выражение имеет значение ***.\nНапример, выражение \"6*7\" имеет значение \"42\"." ] }, { @@ -308,10 +260,7 @@ "id": "caebaa51", "metadata": {}, "source": [ - "## Arithmetic functions\n", - "\n", - "In addition to the arithmetic operators, Python provides a few **functions** that work with numbers.\n", - "For example, the `round` function takes a floating-point number and rounds it off to the nearest integer." + "##Арифметические функции\n\nВ дополнение к арифметическим операторам Python предоставляет несколько функций, которые работают с числами.\nНапример, функция «круглый» принимает число с плавающей точкой и округляет его до ближайшего целого числа." ] }, { @@ -335,8 +284,7 @@ "id": "f5738b4b", "metadata": {}, "source": [ - "The `abs` function computes the absolute value of a number.\n", - "For a positive number, the absolute value is the number itself." + "Функция «abs» вычисляет абсолютное значение числа.\nДля положительного числа абсолютным значением является само число." ] }, { @@ -352,7 +300,7 @@ "id": "e518494a", "metadata": {}, "source": [ - "For a negative number, the absolute value is positive." + "Для отрицательного числа абсолютное значение является положительным." ] }, { @@ -368,11 +316,7 @@ "id": "6969ce45", "metadata": {}, "source": [ - "When we use a function like this, we say we're **calling** the function.\n", - "An expression that calls a function is a **function call**.\n", - "\n", - "When you call a function, the parentheses are required.\n", - "If you leave them out, you get an error message." + "Когда мы используем такую функцию, мы говорим, что мы называем эту функцию.\nВыражение, которое вызывает функцию, является вызовом функции.\n\nПри вызове функции требуются скобки.\nЕсли вы оставите их, вы получите сообщение об ошибке." ] }, { @@ -382,8 +326,7 @@ "tags": [] }, "source": [ - "NOTE: The following cell uses `%%expect`, which is a Jupyter \"magic command\" that means we expect the code in this cell to produce an error. For more on this topic, see the\n", - "[Jupyter notebook introduction](https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/jupyter_intro.ipynb)." + "ПРИМЕЧАНИЕ: Следующая ячейка использует «%%-ожидание», которое является «магической командой» Jupyter, что означает, что мы ожидаем, что код в этой ячейке вызовет ошибку. Подробнее на эту тему см.\n[Введение ноутбука Юпитера] (https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/jupyter_intro.ipynb)." ] }, { @@ -401,13 +344,7 @@ "id": "7d356f1b", "metadata": {}, "source": [ - "You can ignore the first line of this message; it doesn't contain any information we need to understand right now.\n", - "The second line is the code that contains the error, with a caret (`^`) beneath it to indicate where the error was discovered.\n", - "\n", - "The last line indicates that this is a **syntax error**, which means that there is something wrong with the structure of the expression.\n", - "In this example, the problem is that a function call requires parentheses.\n", - "\n", - "Let's see what happens if you leave out the parentheses *and* the value." + "Вы можете проигнорировать первую строку этого сообщения; оно не содержит никакой информации, которую мы должны понять прямо сейчас.\nВторая строка — это код, содержащий ошибку, с аккуратностью («^») под ней, чтобы указать, где была обнаружена ошибка.\n\nПоследняя строка указывает, что это ошибка **syntax**, что означает, что со структурой выражения что-то не так.\nВ этом примере проблема заключается в том, что вызов функции требует скобок.\n\nДавайте посмотрим, что произойдет, если вы оставите скобки и значение." ] }, { @@ -423,8 +360,7 @@ "id": "94478885", "metadata": {}, "source": [ - "A function name all by itself is a legal expression that has a value.\n", - "When it's displayed, the value indicates that `abs` is a function, and it includes some additional information I'll explain later." + "Название функции само по себе является юридическим выражением, которое имеет значение.\nКогда он отображается, значение указывает, что «abs» является функцией, и оно включает в себя некоторую дополнительную информацию, которую я объясню позже." ] }, { @@ -432,10 +368,7 @@ "id": "31a85d17", "metadata": {}, "source": [ - "## Strings\n", - "\n", - "In addition to numbers, Python can also represent sequences of letters, which are called **strings** because the letters are strung together like beads on a necklace.\n", - "To write a string, we can put a sequence of letters inside straight quotation marks." + "## Струны\n\nВ дополнение к числам, Python также может представлять последовательности букв, которые называются струнами, потому что буквы нанизаны вместе, как бусины на ожерелье.\nЧтобы написать строку, мы можем поместить последовательность букв в прямые кавычки." ] }, { @@ -451,7 +384,7 @@ "id": "d20050d8", "metadata": {}, "source": [ - "It is also legal to use double quotation marks." + "Также законно использовать двойные кавычки." ] }, { @@ -467,7 +400,7 @@ "id": "76f5edb7", "metadata": {}, "source": [ - "Double quotes make it easy to write a string that contains an apostrophe, which is the same symbol as a straight quote." + "Двойные цитаты позволяют легко написать строку, содержащую апостроф, который является тем же символом, что и прямая цитата." ] }, { @@ -483,7 +416,7 @@ "id": "d62d4b1c", "metadata": {}, "source": [ - "Strings can also contain spaces, punctuation, and digits." + "Струны также могут содержать пробелы, пунктуации и цифры." ] }, { @@ -499,7 +432,7 @@ "id": "9ad47f7a", "metadata": {}, "source": [ - "The `+` operator works with strings; it joins two strings into a single string, which is called **concatenation**" + "Оператор «+» работает со строками; он соединяет две строки в одну строку, которая называется **concatenation* *" ] }, { @@ -515,7 +448,7 @@ "id": "0ad969a3", "metadata": {}, "source": [ - "The `*` operator also works with strings; it makes multiple copies of a string and concatenates them." + "Оператор «*» также работает со струнами; он делает несколько копий струны и объединяет их." ] }, { @@ -531,9 +464,7 @@ "id": "dfba16a5", "metadata": {}, "source": [ - "The other arithmetic operators don't work with strings.\n", - "\n", - "Python provides a function called `len` that computes the length of a string." + "Другие арифметические операторы не работают со строками.\n\nPython предоставляет функцию под названием «len», которая вычисляет длину строки." ] }, { @@ -549,10 +480,7 @@ "id": "d91e00b3", "metadata": {}, "source": [ - "Notice that `len` counts the letters between the quotes, but not the quotes.\n", - "\n", - "When you create a string, be sure to use straight quotes.\n", - "The back quote, also known as a backtick, causes a syntax error." + "Обратите внимание, что «len» подсчитывает буквы между цитатами, но не цитаты.\n\nКогда вы создаете строку, обязательно используйте прямые цитаты.\nЗадняя цитата, также известная как обратная, вызывает ошибку синтаксиса." ] }, { @@ -570,7 +498,7 @@ "id": "40d893d1", "metadata": {}, "source": [ - "Smart quotes, also known as curly quotes, are also illegal." + "Умные цитаты, также известные как кудрявые цитаты, также являются незаконными." ] }, { @@ -588,21 +516,7 @@ "id": "5471d4f8", "metadata": {}, "source": [ - "## Values and types\n", - "\n", - "So far we've seen three kinds of values:\n", - "\n", - "* `2` is an integer,\n", - "\n", - "* `42.0` is a floating-point number, and \n", - "\n", - "* `'Hello'` is a string.\n", - "\n", - "A kind of value is called a **type**.\n", - "Every value has a type -- or we sometimes say it \"belongs to\" a type.\n", - "\n", - "Python provides a function called `type` that tells you the type of any value.\n", - "The type of an integer is `int`." + "##Ценности и типы\n\nДо сих пор мы видели три типа ценностей:\n\n* '2' является целым числом,\n\n* '42.0' - число с плавающей точкой, и\n\n\"Привет\" - это строка.\n\nСвоеобразная величина называется **типом**.\nКаждая ценность имеет тип, или мы иногда говорим, что она принадлежит типу.\n\nPython предоставляет функцию под названием «тип», которая сообщает вам тип любого значения.\nТип целого числа — «int»." ] }, { @@ -618,7 +532,7 @@ "id": "b137814c", "metadata": {}, "source": [ - "The type of a floating-point number is `float`." + "Тип числа с плавающей точкой — «плавающий»." ] }, { @@ -634,7 +548,7 @@ "id": "266dea4e", "metadata": {}, "source": [ - "And the type of a string is `str`." + "Тип струны — «str»." ] }, { @@ -650,8 +564,7 @@ "id": "76d216ed", "metadata": {}, "source": [ - "The types `int`, `float`, and `str` can be used as functions.\n", - "For example, `int` can take a floating-point number and convert it to an integer (always rounding down)." + "В качестве функций могут использоваться типы «int», «float» и «str».\nНапример, «int» может взять число с плавающей точкой и преобразовать его в целое число (всегда округляя вниз)." ] }, { @@ -667,7 +580,7 @@ "id": "dcd8d114", "metadata": {}, "source": [ - "And `float` can convert an integer to a floating-point value." + "И «плавающий» может преобразовать целое число в значение с плавающей точкой." ] }, { @@ -683,8 +596,7 @@ "id": "eda70b61", "metadata": {}, "source": [ - "Now, here's something that can be confusing.\n", - "What do you get if you put a sequence of digits in quotes?" + "Вот кое-что, что может запутать.\nЧто вы получите, если поместите последовательность цифр в цитаты?" ] }, { @@ -700,7 +612,7 @@ "id": "fdded653", "metadata": {}, "source": [ - "It looks like a number, but it is actually a string." + "Это похоже на число, но на самом деле это строка." ] }, { @@ -716,7 +628,7 @@ "id": "2683ac35", "metadata": {}, "source": [ - "If you try to use it like a number, you might get an error." + "Если вы попытаетесь использовать его как число, вы можете получить ошибку." ] }, { @@ -734,10 +646,7 @@ "id": "32c11cc4", "metadata": {}, "source": [ - "This example generates a `TypeError`, which means that the values in the expression, which are called **operands**, have the wrong type.\n", - "The error message indicates that the `/` operator does not support the types of these values, which are `str` and `int`.\n", - "\n", - "If you have a string that contains digits, you can use `int` to convert it to an integer." + "Этот пример порождает «ошибку типа», что означает, что значения в выражении, которые называются **operands**, имеют неправильный тип.\nСообщение об ошибке указывает, что оператор \"/\" не поддерживает типы этих значений, которые являются \"str\" и \"int\".\n\nЕсли у вас есть строка, содержащая цифры, вы можете использовать «int» для преобразования ее в целое число." ] }, { @@ -753,7 +662,7 @@ "id": "86935d56", "metadata": {}, "source": [ - "If you have a string that contains digits and a decimal point, you can use `float` to convert it to a floating-point number." + "Если у вас есть строка, которая содержит цифры и десятичную точку, вы можете использовать «плавающий» для преобразования его в число с плавающей точкой." ] }, { @@ -769,9 +678,7 @@ "id": "03103ef4", "metadata": {}, "source": [ - "When you write a large integer, you might be tempted to use commas\n", - "between groups of digits, as in `1,000,000`.\n", - "This is a legal expression in Python, but the result is not an integer." + "Когда вы пишете большое целое число, у вас может возникнуть соблазн использовать запятые.\nмежду группами цифр, как в «1 000 000».\nЭто юридическое выражение в Python, но результат не целое число." ] }, { @@ -787,10 +694,7 @@ "id": "3d24af71", "metadata": {}, "source": [ - "Python interprets `1,000,000` as a comma-separated sequence of integers.\n", - "We'll learn more about this kind of sequence later.\n", - "\n", - "You can use underscores to make large numbers easier to read." + "Python интерпретирует «1,000,000» как последовательность целых чисел.\nМы узнаем больше об этой последовательности позже.\n\nВы можете использовать подчеркивания, чтобы упростить чтение больших чисел." ] }, { @@ -806,13 +710,7 @@ "id": "1761cbac", "metadata": {}, "source": [ - "## Formal and natural languages\n", - "\n", - "**Natural languages** are the languages people speak, like English, Spanish, and French. They were not designed by people; they evolved naturally.\n", - "\n", - "**Formal languages** are languages that are designed by people for specific applications. \n", - "For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols.\n", - "Similarly, programming languages are formal languages that have been designed to express computations." + "## Официальные и естественные языки\n\nЕстественные языки - это языки, на которых говорят люди, такие как английский, испанский и французский. Они не были созданы людьми, они развивались естественно.\n\n**Формальные языки - это языки, разработанные людьми для конкретных приложений.\nНапример, нотация, которую используют математики, является формальным языком, который особенно хорошо обозначает отношения между числами и символами.\nТочно так же языки программирования являются формальными языками, которые были разработаны для выражения вычислений." ] }, { @@ -820,19 +718,7 @@ "id": "1bf3d2dc", "metadata": {}, "source": [ - "Although formal and natural languages have some features in\n", - "common there are important differences:\n", - "\n", - "* Ambiguity: Natural languages are full of ambiguity, which people deal with by\n", - " using contextual clues and other information. Formal languages are\n", - " designed to be nearly or completely unambiguous, which means that\n", - " any program has exactly one meaning, regardless of context.\n", - "\n", - "* Redundancy: In order to make up for ambiguity and reduce misunderstandings,\n", - " natural languages use redundancy. As a result, they are\n", - " often verbose. Formal languages are less redundant and more concise.\n", - "\n", - "* Literalness: Natural languages are full of idiom and metaphor. Formal languages mean exactly what they say." + "Хотя формальные и естественные языки имеют некоторые особенности.\nОбщими являются важные различия:\n\nЕстественные языки полны двусмысленности, с которой люди имеют дело.\nиспользование контекстных ключей и другой информации. Формальные языки являются\nОн должен быть почти или полностью однозначным, что означает, что\nЛюбая программа имеет одно значение, независимо от контекста.\n\n* Увольнение: чтобы компенсировать двусмысленность и уменьшить недоразумения;\nВ естественных языках используется избыточность. В результате они являются\nЧасто глаголы. Формальные языки менее избыточны и более лаконичны.\n\n* Натуральные языки полны идиом и метафор. Формальные языки означают именно то, что они говорят." ] }, { @@ -840,12 +726,7 @@ "id": "78a1cec8", "metadata": {}, "source": [ - "Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages.\n", - "Formal languages are more dense than natural languages, so it takes longer to read them.\n", - "Also, the structure is important, so it is not always best to read from top to bottom, left to right.\n", - "Finally, the details matter. Small errors in spelling and\n", - "punctuation, which you can get away with in natural languages, can make\n", - "a big difference in a formal language." + "Поскольку мы все взрослеем, говоря на естественных языках, иногда трудно приспособиться к формальным языкам.\nФормальные языки более плотные, чем естественные, поэтому их чтение занимает больше времени.\nТакже важна структура, поэтому не всегда лучше читать сверху вниз, слева направо.\nНаконец, важны детали. Небольшие ошибки в орфографии и\nпунктуация, с которой можно обойтись на естественных языках, может\nБольшая разница в формальном языке." ] }, { @@ -853,17 +734,7 @@ "id": "4358fa9a", "metadata": {}, "source": [ - "## Debugging\n", - "\n", - "Programmers make mistakes. For whimsical reasons, programming errors are called **bugs** and the process of tracking them down is called **debugging**.\n", - "\n", - "Programming, and especially debugging, sometimes brings out strong emotions. If you are struggling with a difficult bug, you might feel angry, sad, or embarrassed.\n", - "\n", - "Preparing for these reactions might help you deal with them. One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture.\n", - "\n", - "Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses. And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.\n", - "\n", - "Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming. At the end of each chapter there is a section, like this one, with my suggestions for debugging. I hope they help!" + "## Отладка\n\nПрограммисты совершают ошибки. По причудливым причинам ошибки программирования называются **bugs**, а процесс их отслеживания называется **debugging**.\n\nПрограммирование, и особенно отладка, иногда вызывает сильные эмоции. Если вы боретесь с трудным жуком, вы можете чувствовать гнев, грусть или смущение.\n\nПодготовка к этим реакциям может помочь вам справиться с ними. Один из подходов заключается в том, чтобы думать о компьютере как о сотруднике с определенными сильными сторонами, такими как скорость и точность, и особыми недостатками, такими как отсутствие эмпатии и неспособность понять общую картину.\n\nВаша работа заключается в том, чтобы быть хорошим менеджером: находить способы использовать сильные стороны и смягчать слабые стороны. И найдите способы использовать свои эмоции для решения проблемы, не позволяя вашим реакциям мешать вашей способности эффективно работать.\n\nОбучение отладке может быть разочаровывающим, но это ценный навык, который полезен для многих видов деятельности, помимо программирования. В конце каждой главы есть раздел, подобный этому, с моими предложениями по отладке. Надеюсь, они помогут!" ] }, { @@ -871,62 +742,7 @@ "id": "33b8ad00", "metadata": {}, "source": [ - "## Glossary\n", - "\n", - "**arithmetic operator:**\n", - "A symbol, like `+` and `*`, that denotes an arithmetic operation like addition or multiplication.\n", - "\n", - "**integer:**\n", - "A type that represents numbers with no fractional or decimal part.\n", - "\n", - "**floating-point:**\n", - "A type that represents integers and numbers with decimal parts.\n", - "\n", - "**integer division:**\n", - "An operator, `//`, that divides two numbers and rounds down to an integer.\n", - "\n", - "**expression:**\n", - "A combination of variables, values, and operators.\n", - "\n", - "**value:**\n", - "An integer, floating-point number, or string -- or one of other kinds of values we will see later.\n", - "\n", - "**function:**\n", - "A named sequence of statements that performs some useful operation.\n", - "Functions may or may not take arguments and may or may not produce a result.\n", - "\n", - "**function call:**\n", - "An expression -- or part of an expression -- that runs a function.\n", - "It consists of the function name followed by an argument list in parentheses.\n", - "\n", - "**syntax error:**\n", - "An error in a program that makes it impossible to parse -- and therefore impossible to run.\n", - "\n", - "**string:**\n", - " A type that represents sequences of characters.\n", - "\n", - "**concatenation:**\n", - "Joining two strings end-to-end.\n", - "\n", - "**type:**\n", - "A category of values.\n", - "The types we have seen so far are integers (type `int`), floating-point numbers (type ` float`), and strings (type `str`).\n", - "\n", - "**operand:**\n", - "One of the values on which an operator operates.\n", - "\n", - "**natural language:**\n", - "Any of the languages that people speak that evolved naturally.\n", - "\n", - "**formal language:**\n", - "Any of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs.\n", - "All programming languages are formal languages.\n", - "\n", - "**bug:**\n", - "An error in a program.\n", - "\n", - "**debugging:**\n", - "The process of finding and correcting errors." + "### Глоссарий\n\n** Арифметический оператор: **\nСимвол, такой как «+» и «*», обозначает арифметическую операцию, такую как сложение или умножение.\n\n**целое число**\nТип, который представляет числа без дробной или десятичной части.\n\n** плавающая точка:**\nТип, который представляет целые числа и числа с десятичными частями.\n\n**целое деление**\nОператор, '//', который делит два числа и округляет до целого числа.\n\n** Выражение: **\nКомбинация переменных, значений и операторов.\n\n**значение: **\nЦелое число, число с плавающей запятой или строка — или один из других видов значений, которые мы увидим позже.\n\n** Функция: **\nИменованная последовательность утверждений, выполняющая некоторую полезную операцию.\nФункции могут принимать или не принимать аргументы и могут или не могут давать результат.\n\n** Функциональный звонок: **\nВыражение — или часть выражения — выполняет функцию.\nОн состоит из имени функции, за которым следует список аргументов в скобках.\n\n**ошибка синтаксиса**\nОшибка в программе, которая делает невозможным анализ и, следовательно, невозможным запуск.\n\n** строка:**\nТип, который представляет последовательности символов.\n\n**соединение:**\nСоединение двух струн сквозное.\n\n** Тип: **\nКатегория ценностей.\nТипы, которые мы видели до сих пор, являются целыми числами (тип 'int'), числами с плавающей точкой (тип ' float') и строками (тип 'str').\n\n**операнд:**\nОдно из значений, на котором оперирует оператор.\n\nЕстественный язык: **\nЯзыки, на которых говорят люди, развивались естественным образом.\n\n** Официальный язык: **\nЛюбой из языков, которые люди разработали для конкретных целей, таких как представление математических идей или компьютерных программ.\nВсе языки программирования являются формальными.\n\n** Баг:**\nОшибка в программе.\n\n** отладка:**\nПроцесс поиска и исправления ошибок." ] }, { @@ -934,7 +750,7 @@ "id": "ed4ec01b", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -957,15 +773,7 @@ "id": "23adf208", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", - "\n", - "As you work through this book, there are several ways you can use a virtual assistant or chatbot to help you learn.\n", - "\n", - "* If you want to learn more about a topic in the chapter, or anything is unclear, you can ask for an explanation.\n", - "\n", - "* If you are having a hard time with any of the exercises, you can ask for help.\n", - "\n", - "In each chapter, I'll suggest exercises you can do with a virtual assistant, but I encourage you to try things on your own and see what works for you." + "#### Попросите виртуального помощника\n\nРаботая над этой книгой, вы можете использовать виртуального помощника или чат-бота, чтобы помочь вам учиться.\n\n* Если вы хотите узнать больше о теме в главе или что-то неясное, вы можете попросить объяснение.\n\n* Если вы испытываете трудности с любым из упражнений, вы можете попросить о помощи.\n\nВ каждой главе я предлагаю упражнения, которые вы можете делать с виртуальным помощником, но я призываю вас попробовать что-то самостоятельно и посмотреть, что работает для вас." ] }, { @@ -973,15 +781,7 @@ "id": "ebf1a451", "metadata": {}, "source": [ - "Here are some topics you could ask a virtual assistant about:\n", - "\n", - "* Earlier I mentioned bitwise operators but I didn't explain why the value of `7 ^ 2` is 5. Try asking \"What are the bitwise operators in Python?\" or \"What is the value of `7 XOR 2`?\"\n", - "\n", - "* I also mentioned the order of operations. For more details, ask \"What is the order of operations in Python?\"\n", - "\n", - "* The `round` function, which we used to round a floating-point number to the nearest integer, can take a second argument. Try asking \"What are the arguments of the round function?\" or \"How do I round pi off to three decimal places?\"\n", - "\n", - "* There's one more arithmetic operator I didn't mention; try asking \"What is the modulus operator in Python?\"" + "Вот некоторые темы, которые вы можете задать виртуальному помощнику:\n\n* Ранее Я упомянул о битовых операторах, но не объяснил, почему значение 7^2 равно 5. Попробуйте спросить: «Что такое битовые операторы в Python?» или «Каково значение 7 XOR 2?»\n\nЯ также упомянул порядок операций. Для более подробной информации задайте вопрос: «Каков порядок операций в Python?»\n\n* Функция «круглый», которую мы использовали для округления числа с плавающей точкой до ближайшего целого числа, может принимать второй аргумент. Попробуйте спросить: «Каковы аргументы функции раунда?» или «Как мне округлить пи до трех десятичных знаков?»\n\n* Есть еще один оператор арифметики, о котором я не упоминал; попробуйте спросить: «Что такое оператор модуля в Python?»" ] }, { @@ -989,9 +789,7 @@ "id": "9be3e1c7", "metadata": {}, "source": [ - "Most virtual assistants know about Python, so they answer questions like this pretty reliably.\n", - "But remember that these tools make mistakes.\n", - "If you get code from a chatbot, test it!" + "Большинство виртуальных помощников знают о Python, поэтому они довольно надежно отвечают на подобные вопросы.\nНо помните, что эти инструменты делают ошибки.\nЕсли вы получаете код от чат-бота, проверьте его!" ] }, { @@ -999,11 +797,7 @@ "id": "03c1ef93", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "You might wonder what `round` does if a number ends in `0.5`.\n", - "The answer is that it sometimes rounds up and sometimes rounds down.\n", - "Try these examples and see if you can figure out what rule it follows." + "###Упражнения\n\nВы можете задаться вопросом, что делает круг, если число заканчивается на 0,5.\nОтвет заключается в том, что он иногда округляется, а иногда округляется.\nПопробуйте эти примеры и посмотрите, можете ли вы понять, какое правило следует." ] }, { @@ -1027,7 +821,7 @@ "id": "dd2f890e", "metadata": {}, "source": [ - "If you are curious, ask a virtual assistant, \"If a number ends in 0.5, does Python round up or down?\"" + "Если вам интересно, спросите виртуального помощника: «Если число заканчивается на 0,5, Python округляется или опускается?»" ] }, { @@ -1035,17 +829,7 @@ "id": "2cd03bcb", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "When you learn about a new feature, you should try it out and make mistakes on purpose.\n", - "That way, you learn the error messages, and when you see them again, you will know what they mean.\n", - "It is better to make mistakes now and deliberately than later and accidentally.\n", - "\n", - "1. You can use a minus sign to make a negative number like `-2`. What happens if you put a plus sign before a number? What about `2++2`?\n", - "\n", - "2. What happens if you have two values with no operator between them, like `4 2`?\n", - "\n", - "3. If you call a function like `round(42.5)`, what happens if you leave out one or both parentheses?" + "###Упражнения\n\nКогда вы узнаете о новой функции, вы должны попробовать ее и сделать ошибки нарочно.\nТаким образом, вы узнаете сообщения об ошибках, и когда вы увидите их снова, вы узнаете, что они означают.\nЛучше совершать ошибки сейчас и сознательно, чем потом и случайно.\n\n1. Вы можете использовать знак минус, чтобы сделать отрицательное число, такое как «-2». Что произойдет, если поставить знак плюс перед номером? Что такое «2++2»?\n\n2. Что произойдет, если у вас есть два значения без оператора между ними, например «4 2»?\n\n3. Если вы называете функцию «круглым» (42.5), что произойдет, если вы оставите одну или обе скобки?" ] }, { @@ -1053,27 +837,7 @@ "id": "1fb0adfe", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "Recall that every expression has a value, every value has a type, and we can use the `type` function to find the type of any value.\n", - "\n", - "What is the type of the value of the following expressions? Make your best guess for each one, and then use `type` to find out.\n", - "\n", - "* `765`\n", - "\n", - "* `2.718`\n", - "\n", - "* `'2 pi'`\n", - "\n", - "* `abs(-7)`\n", - "\n", - "* `abs(-7.0)`\n", - "\n", - "* `abs`\n", - "\n", - "* `int`\n", - "\n", - "* `type`" + "###Упражнения\n\nПомните, что каждое выражение имеет значение, каждое значение имеет тип, и мы можем использовать функцию «тип», чтобы найти тип любого значения.\n\nКакова ценность следующих выражений? Сделайте лучшее предположение для каждого из них, а затем используйте «тип», чтобы узнать.\n\n* \"765\"\n\n* \"2.718\"\n\n* \"2 пи\" ''\n\n* \"abs(-7)\"\n\n* \"abs(-7.0)\"\n\n*абс пункт\n\n* \"инт\"\n\n* Тип пункт" ] }, { @@ -1081,22 +845,7 @@ "id": "23762eec", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "The following questions give you a chance to practice writing arithmetic expressions.\n", - "\n", - "1. How many seconds are there in 42 minutes 42 seconds?\n", - "\n", - "2. How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile.\n", - "\n", - "3. If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace in seconds per mile? \n", - " \n", - "4. What is your average pace in minutes and seconds per mile?\n", - "\n", - "5. What is your average speed in miles per hour?\n", - "\n", - "If you already know about variables, you can use them for this exercise.\n", - "If you don't, you can do the exercise without them -- and then we'll see them in the next chapter." + "###Упражнения\n\nСледующие вопросы дают вам возможность практиковать написание арифметических выражений.\n\n1. Сколько секунд в 42 минуты 42 секунды?\n\n2. Сколько миль в 10 километрах? Подсказка: в миле 1,61 километра.\n\n3. Если вы пробегаете 10-километровую гонку за 42 минуты 42 секунды, какой у вас средний темп в секундах за милю?\n\n4. Каков ваш средний темп в минутах и секундах на милю?\n\n5. Какова средняя скорость в милях в час?\n\nЕсли вы уже знаете о переменных, вы можете использовать их для этого упражнения.\nЕсли вы этого не сделаете, вы можете выполнять упражнения без них, и мы увидим их в следующей главе." ] }, { @@ -1170,13 +919,7 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", - "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", - "\n", - "Code license: [MIT License](https://mit-license.org/)\n", - "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "[Think Python: 3rd Edition] (https://allendowney.github.io/ThinkPython/index.html)\n\nАвторское право 2024 [Аллен Б. Дауни] (https://allendowney.com)\n\nКодовая лицензия: [MIT License] (https://mit-license.org/)\n\nТекстовая лицензия: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International] (https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -1202,4 +945,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From dd3ce109f88e1f9bb7ffc880ddbfe6c3bbce6924 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 12:44:20 +0300 Subject: [PATCH 03/44] Translate chap02 notebook to Russian --- blank/chap02.ipynb | 352 ++++++++++++++++++++++----------------------- 1 file changed, 172 insertions(+), 180 deletions(-) diff --git a/blank/chap02.ipynb b/blank/chap02.ipynb index 345e793..198b06b 100644 --- a/blank/chap02.ipynb +++ b/blank/chap02.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать печатные и электронные версии *Think Python 3e* от\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -41,12 +41,12 @@ "id": "d0286422", "metadata": {}, "source": [ - "# Variables and Statements\n", + "# Переменные и операторы\n", "\n", - "In the previous chapter, we used operators to write expressions that perform arithmetic computations.\n", + "В предыдущей главе мы использовали операторы для написания выражений, которые выполняют арифметические вычисления.\n", "\n", - "In this chapter, you'll learn about variables and statements, the `import` statement, and the `print` function.\n", - "And I'll introduce more of the vocabulary we use to talk about programs, including \"argument\" and \"module\".\n" + "В этой главе вы узнаете о переменных и инструкциях, инструкции `import` и функции `print`.\n", + "И я представлю больше лексики, которую мы используем для разговора о программах, включая «аргумент» и «модуль».\n" ] }, { @@ -54,10 +54,10 @@ "id": "4ac44f0c", "metadata": {}, "source": [ - "## Variables\n", + "## Переменные\n", "\n", - "A **variable** is a name that refers to a value.\n", - "To create a variable, we can write a **assignment statement** like this." + "**переменная** - это имя, которое ссылается на значение.\n", + "Чтобы создать переменную, мы можем написать ** инструкцию присваивания** вот так." ] }, { @@ -73,9 +73,9 @@ "id": "52f187f1", "metadata": {}, "source": [ - "An assignment statement has three parts: the name of the variable on the left, the equals operator, `=`, and an expression on the right.\n", - "In this example, the expression is an integer.\n", - "In the following example, the expression is a floating-point number." + "Оператор присваивания состоит из трех частей: имя переменной слева, оператор равно, `=` и выражение справа.\n", + "В этом примере выражение представляет собой целое число.\n", + "В следующем примере выражение является числом с плавающей запятой." ] }, { @@ -91,7 +91,7 @@ "id": "3e27e65c", "metadata": {}, "source": [ - "And in the following example, the expression is a string." + "И в следующем примере выражение является строкой." ] }, { @@ -107,10 +107,10 @@ "id": "cb5916ea", "metadata": {}, "source": [ - "When you run an assignment statement, there is no output.\n", - "Python creates the variable and gives it a value, but the assignment statement has no visible effect.\n", - "However, after creating a variable, you can use it as an expression.\n", - "So we can display the value of `message` like this:" + "При запуске инструкции присваивания выходные данные отсутствуют.\n", + "Python создает переменную и присваивает ей значение, но инструкция присваивания не имеет видимого эффекта.\n", + "Однако после создания переменной вы можете использовать ее в качестве выражения.\n", + "Таким образом, мы можем отобразить значение «message» следующим образом:" ] }, { @@ -126,7 +126,7 @@ "id": "e3fd81de", "metadata": {}, "source": [ - "You can also use a variable as part of an expression with arithmetic operators." + "Вы также можете использовать переменную как часть выражения с арифметическими операторами." ] }, { @@ -150,7 +150,7 @@ "id": "97396e7d", "metadata": {}, "source": [ - "And you can use a variable when you call a function." + "И вы можете использовать переменную при вызове функции." ] }, { @@ -174,10 +174,10 @@ "id": "397d9da3", "metadata": {}, "source": [ - "## State diagrams\n", + "## Диаграммы состояний\n", "\n", - "A common way to represent variables on paper is to write the name with\n", - "an arrow pointing to its value. " + "Распространенный способ представления переменных на бумаге - написать имя с\n", + "стрелка, указывающая на его значение." ] }, { @@ -223,8 +223,8 @@ "id": "6f40da93", "metadata": {}, "source": [ - "This kind of figure is called a **state diagram** because it shows what state each of the variables is in (think of it as the variable's state of mind).\n", - "We'll use state diagrams throughout the book to represent a model of how Python stores variables and their values." + "Такая фигура называется * * диаграммой состояния **, потому что она показывает, в каком состоянии находится каждая из переменных (думайте об этом как о состоянии ума переменной).\n", + "Мы будем использовать диаграммы состояний по всей книге, чтобы представить модель того, как Python хранит переменные и их значения." ] }, { @@ -232,16 +232,14 @@ "id": "ba252c85", "metadata": {}, "source": [ - "## Variable names\n", + "Имена переменных могут быть такими длинными, как вам нравится. Они могут содержать как буквы, так и цифры, но они не могут начинаться с числа.\n", + "Это законно использовать заглавные буквы, но принято использовать только строчные буквы для\n", + "имен переменных.\n", "\n", - "Variable names can be as long as you like. They can contain both letters and numbers, but they can't begin with a number. \n", - "It is legal to use uppercase letters, but it is conventional to use only lower case for\n", - "variable names.\n", + "Единственный символ пунктуации, который может появляться в имени переменной, — это символ подчеркивания `_`. Он часто используется в именах из нескольких слов, например `your_name` или `airspeed_of_unladen_swallow`.\n", "\n", - "The only punctuation that can appear in a variable name is the underscore character, `_`. It is often used in names with multiple words, such as `your_name` or `airspeed_of_unladen_swallow`.\n", - "\n", - "If you give a variable an illegal name, you get a syntax error.\n", - "The name `million!` is illegal because it contains punctuation." + "Если вы дадите переменной недопустимое имя, возникнет синтаксическая ошибка.\n", + "Имя `million!` недопустимо, потому что содержит знак препинания." ] }, { @@ -259,7 +257,7 @@ "id": "a1cefe3e", "metadata": {}, "source": [ - "`76trombones` is illegal because it starts with a number." + "«76 тромбонов» является незаконным, потому что начинается с цифры." ] }, { @@ -277,7 +275,7 @@ "id": "94aa7e60", "metadata": {}, "source": [ - "`class` is also illegal, but it might not be obvious why." + "«класс» также является незаконным, но может быть неясно, почему." ] }, { @@ -295,10 +293,10 @@ "id": "784cfb5c", "metadata": {}, "source": [ - "It turns out that `class` is a **keyword**, which is a special word used to specify the structure of a program.\n", - "Keywords can't be used as variable names.\n", + "Получается, что «класс» - это **ключевое слово**, которое является специальным словом, используемым для указания структуры программы.\n", + "Ключевые слова не могут использоваться в качестве имен переменных.\n", "\n", - "Here's a complete list of Python's keywords:" + "Вот полный список ключевых слов Python:" ] }, { @@ -332,9 +330,9 @@ "id": "6f14d301", "metadata": {}, "source": [ - "You don't have to memorize this list. In most development environments,\n", - "keywords are displayed in a different color; if you try to use one as a\n", - "variable name, you'll know." + "Вам не нужно запоминать этот список. В большинстве сред разработки\n", + "ключевые слова отображаются другим цветом; если вы попытаетесь использовать их в качестве\n", + "имя переменной, вы узнаете." ] }, { @@ -342,10 +340,10 @@ "id": "c954a3b0", "metadata": {}, "source": [ - "## The import statement\n", + "## Отчет об импорте\n", "\n", - "In order to use some Python features, you have to **import** them.\n", - "For example, the following statement imports the `math` module." + "Чтобы использовать некоторые функции Python, вы должны **импортировать** их.\n", + "Например, следующая инструкция импортирует модуль «математика»." ] }, { @@ -361,9 +359,9 @@ "id": "ea4f75ec", "metadata": {}, "source": [ - "A **module** is a collection of variables and functions.\n", - "The math module provides a variable called `pi` that contains the value of the mathematical constant denoted $\\pi$.\n", - "We can display its value like this." + "**модуль** представляет собой набор переменных и функций.\n", + "Математический модуль предоставляет переменную под названием `pi`, которая содержит значение математической константы, обозначаемой $\\pi$.\n", + "Мы можем отобразить его значение таким образом." ] }, { @@ -379,10 +377,10 @@ "id": "c96106e4", "metadata": {}, "source": [ - "To use a variable in a module, you have to use the **dot operator** (`.`) between the name of the module and the name of the variable.\n", + "Чтобы использовать переменную в модуле, необходимо использовать **точечный оператор** (`.`) между именем модуля и именем переменной.\n", "\n", - "The math module also contains functions.\n", - "For example, `sqrt` computes square roots." + "Математический модуль также содержит функции.\n", + "Например, `sqrt` вычисляет квадратные корни." ] }, { @@ -398,7 +396,7 @@ "id": "185e94a3", "metadata": {}, "source": [ - "And `pow` raises one number to the power of a second number." + "И «POW» повышает одно число до степени второго числа." ] }, { @@ -414,8 +412,8 @@ "id": "5df25a9a", "metadata": {}, "source": [ - "At this point we've seen two ways to raise a number to a power: we can use the `math.pow` function or the exponentiation operator, `**`.\n", - "Either one is fine, but the operator is used more often than the function." + "На данный момент мы видели два способа возведения числа в степень: мы можем использовать функцию `math.pow' или оператор возведения в степень `**`.\n", + "Любой из них хорош, но оператор используется чаще, чем функция." ] }, { @@ -423,13 +421,13 @@ "id": "6538f22b", "metadata": {}, "source": [ - "## Expressions and statements\n", + "## Выражения и утверждения\n", "\n", - "So far, we've seen a few kinds of expressions.\n", - "An expression can be a single value, like an integer, floating-point number, or string.\n", - "It can also be a collection of values and operators.\n", - "And it can include variable names and function calls.\n", - "Here's an expression that includes several of these elements." + "До сих пор мы видели несколько видов выражений.\n", + "Выражение может быть одним значением, например целым числом, числом с плавающей запятой или строкой.\n", + "Это также может быть коллекция значений и операторов.\n", + "И он может включать имена переменных и вызовы функций.\n", + "Вот выражение, которое включает в себя несколько из этих элементов." ] }, { @@ -445,9 +443,9 @@ "id": "000dd2ba", "metadata": {}, "source": [ - "We have also seen a few kind of statements.\n", - "A **statement** is a unit of code that has an effect, but no value.\n", - "For example, an assignment statement creates a variable and gives it a value, but the statement itself has no value." + "Мы также видели несколько видов заявлений.\n", + "**инструкция** - это единица кода, которая имеет эффект, но не имеет значения.\n", + "Например, инструкция присваивания создает переменную и присваивает ей значение, но сама инструкция не имеет значения." ] }, { @@ -463,7 +461,7 @@ "id": "cff0414b", "metadata": {}, "source": [ - "Similarly, an import statement has an effect -- it imports a module so we can use the variables and functions it contains -- but it has no visible effect." + "Аналогичным образом, инструкция импорта имеет эффект - она импортирует модуль, чтобы мы могли использовать содержащиеся в нем переменные и функции - но она не имеет видимого эффекта." ] }, { @@ -479,8 +477,8 @@ "id": "2aeb1000", "metadata": {}, "source": [ - "Computing the value of an expression is called **evaluation**.\n", - "Running a statement is called **execution**." + "Вычисление значения выражения называется * * вычислением**.\n", + "Выполнение оператора называется **execution**." ] }, { @@ -488,9 +486,9 @@ "id": "f61601e4", "metadata": {}, "source": [ - "## The print function\n", + "## Функция печати\n", "\n", - "When you evaluate an expression, the result is displayed." + "Когда вы оцениваете выражение, отображается результат." ] }, { @@ -506,7 +504,7 @@ "id": "efacf0fa", "metadata": {}, "source": [ - "But if you evaluate more than one expression, only the value of the last one is displayed." + "Но если вы вычисляете более одного выражения, отображается только значение последнего." ] }, { @@ -522,7 +520,7 @@ "id": "cf2b991d", "metadata": {}, "source": [ - "To display more than one value, you can use the `print` function." + "Чтобы отобразить более одного значения, вы можете использовать функцию «печать»." ] }, { @@ -538,7 +536,7 @@ "id": "29af1f89", "metadata": {}, "source": [ - "It also works with floating-point numbers and strings." + "Он также работает с числами и строками с плавающей запятой." ] }, { @@ -554,7 +552,7 @@ "id": "8b4d7f4a", "metadata": {}, "source": [ - "You can also use a sequence of expressions separated by commas." + "Вы также можете использовать последовательность выражений, разделенных запятыми." ] }, { @@ -570,7 +568,7 @@ "id": "af447ec4", "metadata": {}, "source": [ - "Notice that the `print` function puts a space between the values." + "Обратите внимание, что функция `print` помещает пробел между значениями." ] }, { @@ -578,12 +576,12 @@ "id": "7c73a2fa", "metadata": {}, "source": [ - "## Arguments\n", + "## Аргументы\n", "\n", - "When you call a function, the expression in parenthesis is called an **argument**.\n", - "Normally I would explain why, but in this case the technical meaning of a term has almost nothing to do with the common meaning of the word, so I won't even try.\n", + "При вызове функции выражение в скобках называется * * аргументом**.\n", + "Обычно я объясняю, почему, но в этом случае техническое значение термина почти не имеет ничего общего с общим значением этого слова, поэтому я даже не буду пытаться.\n", "\n", - "Some of the functions we've seen so far take only one argument, like `int`." + "Некоторые из функций, которые мы видели до сих пор, принимают только один аргумент, например, «int»." ] }, { @@ -599,7 +597,7 @@ "id": "c4ad4f2c", "metadata": {}, "source": [ - "Some take two, like `math.pow`." + "Некоторые берут два, например «math.pow»." ] }, { @@ -615,8 +613,8 @@ "id": "17293749", "metadata": {}, "source": [ - "Some can take additional arguments that are optional. \n", - "For example, `int` can take a second argument that specifies the base of the number." + "Некоторые могут принимать дополнительные аргументы, которые являются необязательными. \n", + "Например, `int` может принимать второй аргумент, указывающий основание числа." ] }, { @@ -632,9 +630,9 @@ "id": "c95589a1", "metadata": {}, "source": [ - "The sequence of digits `101` in base 2 represents the number 5 in base 10.\n", + "Последовательность цифр «101» в основании 2 представляет собой число 5 в основании 10.\n", "\n", - "`round` also takes an optional second argument, which is the number of decimal places to round off to." + "`round` также принимает необязательный второй аргумент, который является числом знаков после запятой, до которого нужно округлить." ] }, { @@ -650,7 +648,7 @@ "id": "21e4a448", "metadata": {}, "source": [ - "Some functions can take any number of arguments, like `print`." + "Некоторые функции могут принимать любое количество аргументов, например `print`." ] }, { @@ -666,7 +664,7 @@ "id": "667cff14", "metadata": {}, "source": [ - "If you call a function and provide too many arguments, that's a `TypeError`." + "Если вы вызываете функцию и предоставляете слишком много аргументов, это `TypeError`." ] }, { @@ -684,7 +682,7 @@ "id": "5103368e", "metadata": {}, "source": [ - "If you provide too few arguments, that's also a `TypeError`." + "Если вы предоставляете слишком мало аргументов, это также `TypeError`." ] }, { @@ -702,7 +700,7 @@ "id": "5333c416", "metadata": {}, "source": [ - "And if you provide an argument with a type the function can't handle, that's a `TypeError`, too." + "И если вы предоставляете аргумент с типом, который функция не может обработать, это тоже `TypeError`." ] }, { @@ -720,7 +718,7 @@ "id": "548828af", "metadata": {}, "source": [ - "This kind of checking can be annoying when you are getting started, but it helps you detect and correct errors." + "Такая проверка может раздражать, когда вы начинаете, но она помогает обнаруживать и исправлять ошибки." ] }, { @@ -728,13 +726,13 @@ "id": "be2b6a9b", "metadata": {}, "source": [ - "## Comments\n", + "## Комментарии\n", "\n", - "As programs get bigger and more complicated, they get more difficult to read.\n", - "Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing and why.\n", + "По мере того, как программы становятся больше и сложнее, их становится труднее читать.\n", + "Формальные языки плотные, и часто бывает трудно взглянуть на кусок кода и понять, что он делает и почему.\n", "\n", - "For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. \n", - "These notes are called **comments**, and they start with the `#` symbol." + "По этой причине рекомендуется добавлять заметки к своим программам, чтобы объяснить на естественном языке, что делает программа. \n", + "Эти заметки называются * * комментариями * * и начинаются с символа #." ] }, { @@ -750,8 +748,8 @@ "id": "519c83a9", "metadata": {}, "source": [ - "In this case, the comment appears on a line by itself. You can also put\n", - "comments at the end of a line:" + "В этом случае комментарий появляется на строке сам по себе. Вы также можете поставить\n", + "комментарии в конце строки:" ] }, { @@ -767,13 +765,13 @@ "id": "87c8d10c", "metadata": {}, "source": [ - "Everything from the `#` to the end of the line is ignored---it has no\n", - "effect on the execution of the program.\n", + "Все, от «#» до конца строки, игнорируется --- у него нет\n", + "влияние на выполнение программы.\n", "\n", - "Comments are most useful when they document non-obvious features of the code.\n", - "It is reasonable to assume that the reader can figure out *what* the code does; it is more useful to explain *why*.\n", + "Комментарии наиболее полезны, когда они документируют неочевидные особенности кода.\n", + "Разумно предположить, что читатель может понять *что* делает код; полезнее объяснить *почему*.\n", "\n", - "This comment is redundant with the code and useless:" + "Этот комментарий лишний с кодом и бесполезный:" ] }, { @@ -789,7 +787,7 @@ "id": "eb83b14a", "metadata": {}, "source": [ - "This comment contains useful information that is not in the code:" + "Этот комментарий содержит полезную информацию, которой нет в коде:" ] }, { @@ -805,8 +803,8 @@ "id": "6cd60d4f", "metadata": {}, "source": [ - "Good variable names can reduce the need for comments, but long names can\n", - "make complex expressions hard to read, so there is a tradeoff." + "Хорошие имена переменных могут уменьшить потребность в комментариях, но длинные имена могут\n", + "сделать сложные выражения трудными для чтения, поэтому есть компромисс." ] }, { @@ -814,16 +812,15 @@ "id": "7d61e416", "metadata": {}, "source": [ - "## Debugging\n", + "## Отладка\n", "\n", - "Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors.\n", - "It is useful to distinguish between them in order to track them down more quickly.\n", + "В программе могут возникать три вида ошибок: синтаксические ошибки, ошибки времени выполнения и семантические ошибки. Полезно различать их, чтобы быстрее находить.\n", "\n", - "* **Syntax error**: \"Syntax\" refers to the structure of a program and the rules about that structure. If there is a syntax error anywhere in your program, Python does not run the program. It displays an error message immediately.\n", + "* **Синтаксическая ошибка**: \"Синтаксис\" относится к структуре программы и правилам этой структуры. Если где-то в программе есть синтаксическая ошибка, Python не запускает программу и сразу выводит сообщение об ошибке.\n", "\n", - "* **Runtime error**: If there are no syntax errors in your program, it can start running. But if something goes wrong, Python displays an error message and stops. This type of error is called a runtime error. It is also called an **exception** because it indicates that something exceptional has happened.\n", + "* **Ошибка времени выполнения**: если синтаксических ошибок нет, программа может начать выполняться. Но если что-то идёт не так, Python выводит сообщение об ошибке и останавливается. Такая ошибка называется ошибкой времени выполнения, или **исключением**, потому что она означает возникновение исключительной ситуации.\n", "\n", - "* **Semantic error**: The third type of error is \"semantic\", which means related to meaning. If there is a semantic error in your program, it runs without generating error messages, but it does not do what you intended. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing." + "* **Семантическая ошибка**: третий тип ошибок связан со смыслом. Если в программе есть семантическая ошибка, она выполняется без сообщений об ошибке, но делает не то, что вы ожидали. Выявить такие ошибки сложно, потому что приходится анализировать результаты работы программы и пытаться понять, что она делает." ] }, { @@ -831,7 +828,7 @@ "id": "6cd52721", "metadata": {}, "source": [ - "As we've seen, an illegal variable name is a syntax error." + "Как мы видели, недопустимое имя переменной является синтаксической ошибкой." ] }, { @@ -849,7 +846,7 @@ "id": "b8971d33", "metadata": {}, "source": [ - "If you use an operator with a type it doesn't support, that's a runtime error. " + "Если вы используете оператор с типом, который он не поддерживает, это ошибка времени выполнения." ] }, { @@ -867,8 +864,8 @@ "id": "e51fa6e2", "metadata": {}, "source": [ - "Finally, here's an example of a semantic error.\n", - "Suppose we want to compute the average of `1` and `3`, but we forget about the order of operations and write this:" + "Наконец, вот пример семантической ошибки.\n", + "Предположим, мы хотим вычислить среднее значение `1` и `3`, но забываем о порядке операций и пишем так:" ] }, { @@ -884,9 +881,9 @@ "id": "0828afc0", "metadata": {}, "source": [ - "When this expression is evaluated, it does not produce an error message, so there is no syntax error or runtime error.\n", - "But the result is not the average of `1` and `3`, so the program is not correct.\n", - "This is a semantic error because the program runs but it doesn't do what's intended." + "Когда это выражение вычисляется, оно не выдает сообщение об ошибке, поэтому нет синтаксической ошибки или ошибки во время выполнения.\n", + "Но результат не является средним из «1» и «3», поэтому программа неверна.\n", + "Это семантическая ошибка, потому что программа работает, но не делает то, что задумано." ] }, { @@ -894,52 +891,52 @@ "id": "07396f3d", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**variable:**\n", - "A name that refers to a value.\n", + "**переменная:**\n", + "Имя, которое ссылается на значение.\n", "\n", - "**assignment statement:**\n", - "A statement that assigns a value to a variable.\n", + "**оператор присваивания:**\n", + "Инструкция, которая присваивает значение переменной.\n", "\n", - "**state diagram:**\n", - "A graphical representation of a set of variables and the values they refer to.\n", + "**диаграмма состояния:**\n", + "Графическое представление набора переменных и связанных с ними значений.\n", "\n", - "**keyword:**\n", - "A special word used to specify the structure of a program.\n", + "**ключевое слово:**\n", + "Специальное слово, используемое для задания структуры программы.\n", "\n", - "**import statement:**\n", - "A statement that reads a module file so we can use the variables and functions it contains.\n", + "**инструкция import:**\n", + "Инструкция, которая читает файл модуля, чтобы мы могли использовать содержащиеся в нём переменные и функции.\n", "\n", - "**module:**\n", - "A file that contains Python code, including function definitions and sometimes other statements.\n", + "**модуль:**\n", + "Файл, который содержит код на Python, включая определения функций и иногда другие инструкции.\n", "\n", - "**dot operator:**\n", - "The operator, `.`, used to access a function in another module by specifying the module name followed by a dot and the function name.\n", + "**оператор точки:**\n", + "Оператор `.` , используемый для доступа к функции в другом модуле путём указания имени модуля, за которым следует точка и имя функции.\n", "\n", - "**evaluate:**\n", - "Perform the operations in an expression in order to compute a value.\n", + "**вычислить:**\n", + "Выполнить операции в выражении, чтобы получить значение.\n", "\n", - "**statement:**\n", - "One or more lines of code that represent a command or action.\n", + "**инструкция:**\n", + "Одна или несколько строк кода, представляющие команду или действие.\n", "\n", - "**execute:**\n", - "Run a statement and do what it says.\n", + "**выполнить:**\n", + "Запустить инструкцию и сделать то, что она предписывает.\n", "\n", - "**argument:**\n", - "A value provided to a function when the function is called.\n", + "**аргумент:**\n", + "Значение, передаваемое функции при её вызове.\n", "\n", - "**comment:**\n", - "Text included in a program that provides information about the program but has no effect on its execution.\n", + "**комментарий:**\n", + "Текст в программе, который предоставляет информацию, но не влияет на выполнение.\n", "\n", - "**runtime error:**\n", - "An error that causes a program to display an error message and exit.\n", + "**ошибка времени выполнения:**\n", + "Ошибка, из-за которой программа выводит сообщение об ошибке и завершается.\n", "\n", - "**exception:**\n", - "An error that is detected while the program is running.\n", + "**исключение:**\n", + "Ошибка, обнаруженная во время выполнения программы.\n", "\n", - "**semantic error:**\n", - "An error that causes a program to do the wrong thing, but not to display an error message." + "**семантическая ошибка:**\n", + "Ошибка, из-за которой программа делает не то, что нужно, но сообщение об ошибке не выводится." ] }, { @@ -947,7 +944,7 @@ "id": "70ee273d", "metadata": {}, "source": [ - "## Exercises" + "Упражнения" ] }, { @@ -970,20 +967,17 @@ "id": "7256a9b2", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "Again, I encourage you to use a virtual assistant to learn more about any of the topics in this chapter.\n", + "Снова призываю вас пользоваться виртуальным помощником, чтобы узнать больше о любой теме этой главы.\n", "\n", - "If you are curious about any of keywords I listed, you could ask \"Why is class a keyword?\" or \"Why can't variable names be keywords?\"\n", + "Если вам любопытны какие-либо из перечисленных мною ключевых слов, спросите: \"Почему `class` является ключевым словом?\" или \"Почему имена переменных не могут быть ключевыми словами?\"\n", "\n", - "You might have noticed that `int`, `float`, and `str` are not Python keywords.\n", - "They are variables that represent types, and they can be used as functions.\n", - "So it is *legal* to have a variable or function with one of those names, but it is strongly discouraged. Ask an assistant \"Why is it bad to use int, float, and str as variable names?\"\n", + "Вы могли заметить, что `int`, `float` и `str` не являются ключевыми словами Python. Это переменные, обозначающие типы, и их можно использовать как функции. Поэтому *допустимо* назвать переменную или функцию одним из этих имён, но этого настоятельно не рекомендуют. Спросите помощника: \"Почему плохо использовать int, float и str как имена переменных?\"\n", "\n", - "Also ask, \"What are the built-in functions in Python?\"\n", - "If you are curious about any of them, ask for more information.\n", + "Спросите также: \"Какие встроенные функции есть в Python?\" Если что-то заинтересует, узнайте подробности.\n", "\n", - "In this chapter we imported the `math` module and used some of the variable and functions it provides. Ask an assistant, \"What variables and functions are in the math module?\" and \"Other than math, what modules are considered core Python?\"" + "В этой главе мы импортировали модуль `math` и использовали некоторые его переменные и функции. Спросите помощника: \"Какие переменные и функции есть в модуле math?\" и \"Какие модули, кроме math, входят в стандартную библиотеку Python?\"" ] }, { @@ -991,20 +985,19 @@ "id": "f92afde0", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Repeating my advice from the previous chapter, whenever you learn a new feature, you should make errors on purpose to see what goes wrong.\n", + "Повторяя совет из предыдущей главы: каждый раз, когда осваиваете новую возможность, нарочно допускайте ошибки, чтобы увидеть, что пойдёт не так.\n", "\n", - "- We've seen that `n = 17` is legal. What about `17 = n`?\n", + "- Мы видели, что `n = 17` — допустимо. А что насчёт `17 = n`?\n", "\n", - "- How about `x = y = 1`?\n", + "- А как насчёт `x = y = 1`?\n", "\n", - "- In some languages every statement ends with a semi-colon (`;`). What\n", - " happens if you put a semi-colon at the end of a Python statement?\n", + "- В некоторых языках каждое выражение заканчивается точкой с запятой (`;`). Что будет, если поставить точку с запятой в конце инструкции Python?\n", "\n", - "- What if you put a period at the end of a statement?\n", + "- Что если поставить точку в конце инструкции?\n", "\n", - "- What happens if you spell the name of a module wrong and try to import `maath`?" + "- Что произойдёт, если ошибиться в названии модуля и попытаться импортировать `maath`?" ] }, { @@ -1012,11 +1005,11 @@ "id": "9d562609", "metadata": {}, "source": [ - "### Exercise\n", - "Practice using the Python interpreter as a calculator:\n", + "### Упражнение\n", + "Практика использования интерпретатора Python в качестве калькулятора:\n", "\n", - "**Part 1.** The volume of a sphere with radius $r$ is $\\frac{4}{3} \\pi r^3$.\n", - "What is the volume of a sphere with radius 5? Start with a variable named `radius` and then assign the result to a variable named `volume`. Display the result. Add comments to indicate that `radius` is in centimeters and `volume` in cubic centimeters." + "**Часть 1.** Объем сферы с радиусом $r $ равен $\\frac {4}{3} \\pi r^3 $.\n", + "Каков объем сферы с радиусом 5? Начните с переменной с именем «RADIUS», а затем назначьте результат переменной с именем «Volume». Отображение результата. Добавьте комментарии, чтобы указать, что «радиус» указан в сантиметрах, а «объем» - в кубических сантиметрах." ] }, { @@ -1032,12 +1025,12 @@ "id": "6449b12b", "metadata": {}, "source": [ - "**Part 2.** A rule of trigonometry says that for any value of $x$, $(\\cos x)^2 + (\\sin x)^2 = 1$. Let's see if it's true for a specific value of $x$ like 42.\n", + "**Часть 2.** Правило тригонометрии гласит, что для любого значения $x $, $(\\cos x)^2 + (\\sin x)^2 = 1 $. Давайте посмотрим, верно ли это для определенного значения $x$, например 42.\n", "\n", - "Create a variable named `x` with this value.\n", - "Then use `math.cos` and `math.sin` to compute the sine and cosine of $x$, and the sum of their squared.\n", + "Создайте переменную с именем `x` с этим значением.\n", + "Затем используйте `math.cos` и 'math.sin` для вычисления синуса и косинуса $x$ и суммы их квадрата.\n", "\n", - "The result should be close to 1. It might not be exactly 1 because floating-point arithmetic is not exact---it is only approximately correct." + "Результат должен быть близок к 1. Это может быть не совсем 1, потому что арифметика с плавающей точкой не является точной --- это только приблизительно правильно." ] }, { @@ -1053,16 +1046,15 @@ "id": "4986801f", "metadata": {}, "source": [ - "**Part 3.** In addition to `pi`, the other variable defined in the `math` module is `e`, which represents the base of the natural logarithm, written in math notation as $e$. If you are not familiar with this value, ask a virtual assistant \"What is `math.e`?\" Now let's compute $e^2$ three ways:\n", + "**Часть 3.** Помимо `pi`, другая переменная в модуле `math` — `e`, представляющая основание натурального логарифма, обозначаемое как $e$. Если вы не знаете это значение, спросите виртуального помощника: \"Что такое `math.e`?\" Теперь вычислим $e^2$ тремя способами:\n", "\n", - "* Use `math.e` and the exponentiation operator (`**`).\n", + "* Используйте `math.e` и оператор возведения в степень (`**`).\n", "\n", - "* Use `math.pow` to raise `math.e` to the power `2`.\n", + "* Используйте `math.pow`, чтобы возвести `math.e` в степень `2`.\n", "\n", - "* Use `math.exp`, which takes as an argument a value, $x$, and computes $e^x$.\n", + "* Используйте `math.exp`, который принимает значение $x$ и вычисляет $e^x$.\n", "\n", - "You might notice that the last result is slightly different from the other two.\n", - "See if you can find out which is correct." + "Вы можете заметить, что последний результат немного отличается от двух других. Попробуйте выяснить, какой из них верный." ] }, { @@ -1106,11 +1098,11 @@ "source": [ "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Авторское право 2024 [Аллен Б. Дауни](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [Лицензия MIT](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -1141,4 +1133,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 0447f429c5191bf0beb742080e0b5eac6798e374 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 12:45:10 +0300 Subject: [PATCH 04/44] Translate chapter 3 notebook to Russian --- blank/chap03.ipynb | 354 ++++++++++++++++++++++----------------------- 1 file changed, 174 insertions(+), 180 deletions(-) diff --git a/blank/chap03.ipynb b/blank/chap03.ipynb index a2b6766..252fa45 100644 --- a/blank/chap03.ipynb +++ b/blank/chap03.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать печатную и электронную версии *Think Python 3e* на\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -41,15 +41,15 @@ "id": "6bd858a8", "metadata": {}, "source": [ - "# Functions\n", + "# Функции\n", "\n", - "In the previous chapter we used several functions provided by Python, like `int` and `float`, and a few provided by the `math` module, like `sqrt` and `pow`.\n", - "In this chapter, you will learn how to create your own functions and run them.\n", - "And we'll see how one function can call another.\n", - "As examples, we'll display lyrics from Monty Python songs.\n", - "These silly examples demonstrate an important feature -- the ability to write your own functions is the foundation of programming.\n", + "В предыдущей главе мы использовали несколько функций, предоставляемых Python, например `int` и `float`, и некоторые из модуля `math`, такие как `sqrt` и `pow`.\n", + "В этой главе вы научитесь создавать свои собственные функции и запускать их.\n", + "И мы увидим, как одна функция может вызывать другую.\n", + "В качестве примеров мы выведем строки из песен Монти Пайтона.\n", + "Эти забавные примеры демонстрируют важную особенность — умение писать собственные функции является основой программирования.\n", "\n", - "This chapter also introduces a new statement, the `for` loop, which is used to repeat a computation." + "Эта глава также вводит новую инструкцию — цикл `for`, который используется для повторения вычислений." ] }, { @@ -57,9 +57,9 @@ "id": "b4ea99c5", "metadata": {}, "source": [ - "## Defining new functions\n", + "## Определение новых функций\n", "\n", - "A **function definition** specifies the name of a new function and the sequence of statements that run when the function is called. Here's an example:" + "Определение функции (**function definition**) задаёт имя новой функции и последовательность инструкций, которые выполняются при её вызове. Вот пример:" ] }, { @@ -75,17 +75,17 @@ "id": "0174fc41", "metadata": {}, "source": [ - "`def` is a keyword that indicates that this is a function definition.\n", - "The name of the function is `print_lyrics`.\n", - "Anything that's a legal variable name is also a legal function name.\n", + "`def` — это ключевое слово, которое обозначает определение функции.\n", + "Имя функции — `print_lyrics`.\n", + "Любое корректное имя переменной может быть именем функции.\n", "\n", - "The empty parentheses after the name indicate that this function doesn't take any arguments.\n", + "Пустые скобки после имени означают, что функция не принимает аргументов.\n", "\n", - "The first line of the function definition is called the **header** -- the rest is called the **body**.\n", - "The header has to end with a colon and the body has to be indented. By convention, indentation is always four spaces. \n", - "The body of this function is two print statements; in general, the body of a function can contain any number of statements of any kind.\n", + "Первая строка определения функции называется **заголовком**, остальная часть — **телом**.\n", + "Заголовок должен заканчиваться двоеточием, а тело должно быть с отступом. По соглашению отступ составляет четыре пробела. \n", + "Тело этой функции состоит из двух команд `print`; в целом в теле функции может быть сколько угодно инструкций любого вида.\n", "\n", - "Defining a function creates a **function object**, which we can display like this." + "Определение функции создаёт **функциональный объект**, который можно вывести вот так." ] }, { @@ -101,10 +101,10 @@ "id": "12bd0879", "metadata": {}, "source": [ - "The output indicates that `print_lyrics` is a function that takes no arguments.\n", - "`__main__` is the name of the module that contains `print_lyrics`.\n", + "Вывод показывает, что `print_lyrics` — функция без аргументов.\n", + "`__main__` — имя модуля, где находится `print_lyrics`.\n", "\n", - "Now that we've defined a function, we can call it the same way we call built-in functions." + "Теперь, когда функция определена, мы можем вызывать её так же, как встроенные функции." ] }, { @@ -120,7 +120,7 @@ "id": "8f0fc45d", "metadata": {}, "source": [ - "When the function runs, it executes the statements in the body, which display the first two lines of \"The Lumberjack Song\"." + "Когда функция выполняется, она исполняет инструкции в теле, которые выводят первые две строки \"The Lumberjack Song\"." ] }, { @@ -128,12 +128,12 @@ "id": "6d35193e", "metadata": {}, "source": [ - "## Parameters\n", + "## Параметры\n", "\n", - "Some of the functions we have seen require arguments; for example, when you call `abs` you pass a number as an argument.\n", - "Some functions take more than one argument; for example, `math.pow` takes two, the base and the exponent.\n", + "Некоторые из встреченных нами функций требуют аргументы; например, при вызове `abs` вы передаёте число.\n", + "Некоторые функции принимают больше одного аргумента; например, `math.pow` принимает два — основание и степень.\n", "\n", - "Here is a definition for a function that takes an argument." + "Вот определение функции, которая принимает аргумент." ] }, { @@ -149,9 +149,9 @@ "id": "1716e3dc", "metadata": {}, "source": [ - "The variable name in parentheses is a **parameter**.\n", - "When the function is called, the value of the argument is assigned to the parameter.\n", - "For example, we can call `print_twice` like this." + "Имя переменной в скобках — это **параметр**.\n", + "Когда функция вызывается, значение аргумента присваивается параметру.\n", + "Например, мы можем вызвать `print_twice` так:" ] }, { @@ -167,7 +167,7 @@ "id": "f02be6d2", "metadata": {}, "source": [ - "Running this function has the same effect as assigning the argument to the parameter and then executing the body of the function, like this." + "Выполнение этой функции имеет тот же эффект, что и присваивание аргумента параметру с последующим выполнением тела функции, вот так." ] }, { @@ -183,7 +183,7 @@ "id": "ea8b8b6e", "metadata": {}, "source": [ - "You can also use a variable as an argument." + "Можно также использовать переменную в качестве аргумента." ] }, { @@ -199,7 +199,7 @@ "id": "5c1884ad", "metadata": {}, "source": [ - "In this example, the value of `line` gets assigned to the parameter `string`." + "В этом примере значение `line` присваивается параметру `string`." ] }, { @@ -207,18 +207,18 @@ "id": "a3e5a790", "metadata": {}, "source": [ - "## Calling functions\n", + "## Вызов функций\n", "\n", - "Once you have defined a function, you can use it inside another function.\n", - "To demonstrate, we'll write functions that print the lyrics of \"The Spam Song\" ().\n", + "После того как вы определили функцию, её можно использовать внутри другой функции.\n", + "Чтобы продемонстрировать это, напишем функции, которые выводят слова \"The Spam Song\" ().\n", "\n", - "> Spam, Spam, Spam, Spam, \n", - "> Spam, Spam, Spam, Spam, \n", - "> Spam, Spam, \n", - "> (Lovely Spam, Wonderful Spam!) \n", + "> Spam, Spam, Spam, Spam,\n", + "> Spam, Spam, Spam, Spam,\n", + "> Spam, Spam,\n", + "> (Lovely Spam, Wonderful Spam!)\n", "> Spam, Spam,\n", "\n", - "We'll start with the following function, which takes two parameters.\n" + "Начнём со следующей функции, которая принимает два параметра.\n" ] }, { @@ -234,7 +234,7 @@ "id": "bdd4daa4", "metadata": {}, "source": [ - "We can use this function to print the first line of the song, like this." + "Мы можем использовать эту функцию, чтобы напечатать первую строку песни, вот так." ] }, { @@ -250,7 +250,7 @@ "id": "c6f81e09", "metadata": {}, "source": [ - "To display the first two lines, we can define a new function that uses `repeat`." + "Чтобы вывести первые две строки, мы можем определить новую функцию, которая использует `repeat`." ] }, { @@ -266,7 +266,7 @@ "id": "8058ffe4", "metadata": {}, "source": [ - "And then call it like this." + "А затем вызвать её вот так." ] }, { @@ -282,7 +282,7 @@ "id": "07ca432a", "metadata": {}, "source": [ - "To display the last three lines, we can define another function, which also uses `repeat`." + "Чтобы вывести последние три строки, можно определить ещё одну функцию, также использующую `repeat`." ] }, { @@ -306,7 +306,7 @@ "id": "d6456a19", "metadata": {}, "source": [ - "Finally, we can bring it all together with one function that prints the whole verse." + "Наконец, можно объединить всё в одной функции, которая печатает весь куплет." ] }, { @@ -330,10 +330,10 @@ "id": "d088fe68", "metadata": {}, "source": [ - "When we run `print_verse`, it calls `first_two_lines`, which calls `repeat`, which calls `print`.\n", - "That's a lot of functions.\n", + "Когда мы запускаем `print_verse`, она вызывает `first_two_lines`, которая вызывает `repeat`, а та, в свою очередь, `print`.\n", + "Многовато функций.\n", "\n", - "Of course, we could have done the same thing with fewer functions, but the point of this example is to show how functions can work together." + "Конечно, то же самое можно было сделать и меньшим числом функций, но цель примера — показать, как функции могут взаимодействовать." ] }, { @@ -341,10 +341,10 @@ "id": "c3b16e3f", "metadata": {}, "source": [ - "## Repetition\n", + "## Повторение\n", "\n", - "If we want to display more than one verse, we can use a `for` statement.\n", - "Here's a simple example." + "Если мы хотим вывести больше одного куплета, можно использовать оператор `for`.\n", + "Вот простой пример." ] }, { @@ -360,20 +360,20 @@ "id": "bf320549", "metadata": {}, "source": [ - "The first line is a header that ends with a colon.\n", - "The second line is the body, which has to be indented.\n", + "Первая строка — заголовок, который заканчивается двоеточием.\n", + "Вторая строка — тело, которое должно иметь отступ.\n", "\n", - "The header starts with the keyword `for`, a new variable named `i`, and another keyword, `in`. \n", - "It uses the `range` function to create a sequence of two values, which are `0` and `1`.\n", - "In Python, when we start counting, we usually start from `0`.\n", + "Заголовок начинается с ключевого слова `for`, новой переменной `i` и ещё одного ключевого слова `in`. \n", + "Он использует функцию `range`, чтобы создать последовательность из двух значений: `0` и `1`.\n", + "В Python обычно начинают счёт с `0`.\n", "\n", - "When the `for` statement runs, it assigns the first value from `range` to `i` and then runs the `print` function in the body, which displays `0`.\n", + "Когда выполняется оператор `for`, он присваивает переменной `i` первое значение из `range`, а затем выполняет `print` в теле, выводя `0`.\n", "\n", - "When it gets to the end of the body, it loops back around to the header, which is why this statement is called a **loop**.\n", - "The second time through the loop, it assigns the next value from `range` to `i`, and displays it.\n", - "Then, because that's the last value from `range`, the loop ends.\n", + "Дойдя до конца тела, выполнение возвращается к заголовку, поэтому эта конструкция называется **циклом**.\n", + "Во второй проход цикла в `i` помещается следующее значение из `range`, которое выводится.\n", + "Затем, поскольку это последнее значение из `range`, цикл завершается.\n", "\n", - "Here's how we can use a `for` loop to print two verses of the song." + "Вот как можно с помощью цикла `for` напечатать два куплета песни." ] }, { @@ -389,8 +389,8 @@ "id": "88a46733", "metadata": {}, "source": [ - "You can put a `for` loop inside a function.\n", - "For example, `print_n_verses` takes a parameter named `n`, which has to be an integer, and displays the given number of verses. " + "Внутри функции можно поместить цикл `for`.\n", + "Например, `print_n_verses` принимает параметр `n`, который должен быть целым числом, и выводит указанное количество куплетов. " ] }, { @@ -406,7 +406,7 @@ "id": "ad8060fe", "metadata": {}, "source": [ - "In this example, we don't use `i` in the body of the loop, but there has to be a variable name in the header anyway." + "В этом примере переменная `i` в теле цикла не используется, но имя переменной в заголовке всё равно должно быть." ] }, { @@ -414,11 +414,11 @@ "id": "b320ec90", "metadata": {}, "source": [ - "## Variables and parameters are local\n", + "## Переменные и параметры являются локальными\n", "\n", - "When you create a variable inside a function, it is **local**, which\n", - "means that it only exists inside the function.\n", - "For example, the following function takes two arguments, concatenates them, and prints the result twice." + "Когда вы создаёте переменную внутри функции, она **локальная**,\n", + "то есть она существует только внутри функции.\n", + "Например, следующая функция принимает два аргумента, объединяет их и печатает результат дважды." ] }, { @@ -434,7 +434,7 @@ "id": "3a35a6d0", "metadata": {}, "source": [ - "Here's an example that uses it:" + "Вот пример его использования:" ] }, { @@ -450,8 +450,8 @@ "id": "4ab4e008", "metadata": {}, "source": [ - "When `cat_twice` runs, it creates a local variable named `cat`, which is destroyed when the function ends.\n", - "If we try to display it, we get a `NameError`:" + "Когда выполняется `cat_twice`, создаётся локальная переменная `cat`, которая уничтожается после завершения функции.\n", + "Если попытаться вывести её, получится `NameError`:" ] }, { @@ -469,10 +469,10 @@ "id": "3ae36c29", "metadata": {}, "source": [ - "Outside of the function, `cat` is not defined. \n", + "Вне функции `cat` не определена.\n", "\n", - "Parameters are also local.\n", - "For example, outside `cat_twice`, there is no such thing as `part1` or `part2`." + "Параметры тоже локальны.\n", + "Например, вне `cat_twice` не существует `part1` или `part2`." ] }, { @@ -480,15 +480,15 @@ "id": "eabac8a6", "metadata": {}, "source": [ - "## Stack diagrams\n", + "## Диаграммы стека\n", "\n", - "To keep track of which variables can be used where, it is sometimes useful to draw a **stack diagram**. \n", - "Like state diagrams, stack diagrams show the value of each variable, but they also show the function each variable belongs to.\n", + "Чтобы отслеживать, какие переменные где доступны, иногда полезно рисовать **диаграмму стека**. \n", + "Как и диаграммы состояний, диаграммы стека показывают значения каждой переменной, а также функцию, к которой она относится.\n", "\n", - "Each function is represented by a **frame**.\n", - "A frame is a box with the name of a function on the outside and the parameters and local variables of the function on the inside.\n", + "Каждая функция представлена **кадром**.\n", + "Кадр — это прямоугольник с именем функции снаружи и параметрами и локальными переменными внутри.\n", "\n", - "Here's the stack diagram for the previous example." + "Вот диаграмма стека для предыдущего примера." ] }, { @@ -543,12 +543,12 @@ "id": "854fee12", "metadata": {}, "source": [ - "The frames are arranged in a stack that indicates which function called\n", - "which, and so on. Reading from the bottom, `print` was called by `print_twice`, which was called by `cat_twice`, which was called by `__main__` -- which is a special name for the topmost frame.\n", - "When you create a variable outside of any function, it belongs to `__main__`.\n", + "Кадры расположены в стеке, показывая, какая функция вызвала\n", + "какую, и так далее. Снизу вверх: `print` вызвана `print_twice`, её вызвала `cat_twice`, а её — `__main__`, что является особым именем верхнего кадра.\n", + "Когда вы создаёте переменную вне какой-либо функции, она принадлежит `__main__`.\n", "\n", - "In the frame for `print`, the question mark indicates that we don't know the name of the parameter.\n", - "If you are curious, ask a virtual assistant, \"What are the parameters of the Python print function?\"" + "В кадре для `print` знак вопроса означает, что мы не знаем имя параметра.\n", + "Если вам интересно, спросите виртуального помощника: «Каковы параметры функции `print` в Python?»" ] }, { @@ -556,10 +556,10 @@ "id": "5690cfc0", "metadata": {}, "source": [ - "## Tracebacks\n", + "## Обратные трассировки\n", "\n", - "When a runtime error occurs in a function, Python displays the name of the function that was running, the name of the function that called it, and so on, up the stack.\n", - "To see an example, I'll define a version of `print_twice` that contains an error -- it tries to print `cat`, which is a local variable in another function." + "Когда во время выполнения в функции возникает ошибка, Python показывает имя выполнявшейся функции, имя вызвавшей её функции и так далее вверх по стеку.\n", + "Чтобы увидеть пример, я определю версию `print_twice`, содержащую ошибку — она пытается вывести `cat`, которая является локальной переменной в другой функции." ] }, { @@ -575,7 +575,7 @@ "id": "d7c0713b", "metadata": {}, "source": [ - "Now here's what happens when we run `cat_twice`." + "А вот что происходит, когда мы запускаем `cat_twice`." ] }, { @@ -608,11 +608,11 @@ "id": "2f4defcf", "metadata": {}, "source": [ - "The error message includes a **traceback**, which shows the function that was running when the error occurred, the function that called it, and so on.\n", - "In this example, it shows that `cat_twice` called `print_twice`, and the error occurred in a `print_twice`.\n", + "Сообщение об ошибке содержит **обратную трассировку**, в которой показана функция, во время работы которой произошла ошибка, функция, вызвавшая её, и так далее.\n", + "В этом примере видно, что `cat_twice` вызвала `print_twice`, и ошибка произошла в `print_twice`.\n", "\n", - "The order of the functions in the traceback is the same as the order of the frames in the stack diagram.\n", - "The function that was running is at the bottom." + "Порядок функций в трассировке соответствует порядку кадров на диаграмме стека.\n", + "Функция, выполнявшаяся в момент ошибки, находится внизу." ] }, { @@ -620,23 +620,18 @@ "id": "374b4696", "metadata": {}, "source": [ - "## Why functions?\n", + "## Зачем нужны функции?\n", "\n", - "It may not be clear yet why it is worth the trouble to divide a program into\n", - "functions.\n", - "There are several reasons:\n", + "Пока может быть непонятно, зачем делить программу на функции.\n", + "Есть несколько причин:\n", "\n", - "- Creating a new function gives you an opportunity to name a group of\n", - " statements, which makes your program easier to read and debug.\n", + "- Создавая новую функцию, вы можете дать название группе инструкций, что делает программу понятнее и упрощает отладку.\n", "\n", - "- Functions can make a program smaller by eliminating repetitive code.\n", - " Later, if you make a change, you only have to make it in one place.\n", + "- Функции позволяют уменьшить программу, убрав повторяющийся код. Внесённые изменения нужно делать только в одном месте.\n", "\n", - "- Dividing a long program into functions allows you to debug the parts\n", - " one at a time and then assemble them into a working whole.\n", + "- Разбивая большую программу на функции, можно отлаживать части по отдельности, а затем собрать их в работающую систему.\n", "\n", - "- Well-designed functions are often useful for many programs. Once you\n", - " write and debug one, you can reuse it." + "- Хорошо спроектированные функции часто пригодятся в других программах. Написав и отладив их однажды, можно использовать снова." ] }, { @@ -644,25 +639,24 @@ "id": "c6dd486e", "metadata": {}, "source": [ - "## Debugging\n", + "## Отладка\n", "\n", - "Debugging can be frustrating, but it is also challenging, interesting, and sometimes even fun.\n", - "And it is one of the most important skills you can learn.\n", + "Отладка может быть раздражающей, но в то же время она сложна, интересна и порой даже увлекательна.\n", + "И это один из важнейших навыков, которым стоит овладеть.\n", "\n", - "In some ways debugging is like detective work.\n", - "You are given clues and you have to infer the events that led to the\n", - "results you see.\n", + "В некотором смысле отладка похожа на детективное расследование.\n", + "У вас есть улики, и вам нужно восстановить события, которые привели к наблюдаемому результату.\n", "\n", - "Debugging is also like experimental science.\n", - "Once you have an idea about what is going wrong, you modify your program and try again.\n", - "If your hypothesis was correct, you can predict the result of the modification, and you take a step closer to a working program.\n", - "If your hypothesis was wrong, you have to come up with a new one.\n", + "Отладка также похожа на экспериментальную науку.\n", + "Получив предположение о причине сбоя, вы изменяете программу и пробуете снова.\n", + "Если гипотеза верна, вы можете предсказать результат изменения и приблизиться к рабочей программе.\n", + "Если же гипотеза ошибочна, придётся придумать новую.\n", "\n", - "For some people, programming and debugging are the same thing; that is, programming is the process of gradually debugging a program until it does what you want.\n", - "The idea is that you should start with a working program and make small modifications, debugging them as you go.\n", + "Для некоторых людей программирование и отладка — это одно и то же: программирование — это процесс постепенной отладки программы, пока она не станет делать то, что нужно.\n", + "Идея в том, чтобы начинать с работающей программы и вносить небольшие изменения, отлаживая их по мере продвижения.\n", "\n", - "If you find yourself spending a lot of time debugging, that is often a sign that you are writing too much code before you start tests.\n", - "If you take smaller steps, you might find that you can move faster." + "Если вы тратите много времени на отладку, это часто означает, что вы пишете слишком много кода до начала тестирования.\n", + "Делая более короткие шаги, можно обнаружить, что работа идёт быстрее." ] }, { @@ -670,39 +664,39 @@ "id": "d4e95e63", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**function definition:**\n", - "A statement that creates a function.\n", + "**определение функции:**\n", + "Инструкция, создающая функцию.\n", "\n", - "**header:**\n", - " The first line of a function definition.\n", + "**заголовок:**\n", + " Первая строка определения функции.\n", "\n", - "**body:**\n", - " The sequence of statements inside a function definition.\n", + "**тело:**\n", + " Набор инструкций внутри определения функции.\n", "\n", - "**function object:**\n", - "A value created by a function definition.\n", - "The name of the function is a variable that refers to a function object.\n", + "**объект функции:**\n", + "Значение, создаваемое определением функции.\n", + "Имя функции — это переменная, которая ссылается на объект функции.\n", "\n", - "**parameter:**\n", - " A name used inside a function to refer to the value passed as an argument.\n", + "**параметр:**\n", + " Имя, используемое внутри функции для обращения к переданному аргументу.\n", "\n", - "**loop:**\n", - " A statement that runs one or more statements, often repeatedly.\n", + "**цикл:**\n", + " Инструкция, которая выполняет одну или несколько инструкций, часто повторяя их.\n", "\n", - "**local variable:**\n", - "A variable defined inside a function, and which can only be accessed inside the function.\n", + "**локальная переменная:**\n", + "Переменная, объявленная внутри функции и доступная только в этой функции.\n", "\n", - "**stack diagram:**\n", - "A graphical representation of a stack of functions, their variables, and the values they refer to.\n", + "**диаграмма стека:**\n", + "Графическое представление стека функций, их переменных и значений, на которые они ссылаются.\n", "\n", - "**frame:**\n", - " A box in a stack diagram that represents a function call.\n", - " It contains the local variables and parameters of the function.\n", + "**кадр:**\n", + " Прямоугольник на диаграмме стека, представляющий вызов функции.\n", + " Он содержит локальные переменные и параметры функции.\n", "\n", - "**traceback:**\n", - " A list of the functions that are executing, printed when an exception occurs." + "**обратная трассировка:**\n", + " Список выполнявшихся функций, выводимый при возникновении исключения." ] }, { @@ -710,7 +704,7 @@ "id": "eca485f2", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -733,31 +727,31 @@ "id": "82951027", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "The statements in a function or a `for` loop are indented by four spaces, by convention.\n", - "But not everyone agrees with that convention.\n", - "If you are curious about the history of this great debate, ask a virtual assistant to \"tell me about spaces and tabs in Python\".\n", + "Инструкции в функции или цикле `for` обычно имеют отступ в четыре пробела.\n", + "Но не все согласны с таким правилом.\n", + "Если вам интересна история этого великого спора, спросите виртуального помощника: «расскажи про пробелы и табы в Python».\n", "\n", - "Virtual assistant are pretty good at writing small functions.\n", + "Виртуальные помощники неплохо справляются с написанием небольших функций.\n", "\n", - "1. Ask your favorite VA to \"Write a function called repeat that takes a string and an integer and prints the string the given number of times.\" \n", + "1. Попросите своего любимого помощника: «Напиши функцию `repeat`, которая принимает строку и целое число и печатает строку указанное число раз».\n", "\n", - "2. If the result uses a `for` loop, you could ask, \"Can you do it without a for loop?\"\n", + "2. Если в результате используется цикл `for`, спросите: «А можно без цикла for?»\n", "\n", - "3. Pick any other function in this chapter and ask a VA to write it. The challenge is to describe the function precisely enough to get what you want. Use the vocabulary you have learned so far in this book.\n", + "3. Выберите любую другую функцию из этой главы и попросите помощника написать её. Важно описать функцию достаточно точно, используя терминологию, которую вы уже узнали.\n", "\n", - "Virtual assistants are also pretty good at debugging functions.\n", + "Виртуальные помощники также неплохо отлаживают функции.\n", "\n", - "1. Ask a VA what's wrong with this version of `print_twice`.\n", + "1. Спросите у помощника, что не так с этой версией `print_twice`.\n", "\n", " ```\n", " def print_twice(string):\n", " print(cat)\n", " print(cat)\n", " ```\n", - " \n", - "And if you get stuck on any of the exercises below, consider asking a VA for help." + "\n", + "Если вы застрянете на каком-либо из упражнений ниже, попросите помощника о помощи." ] }, { @@ -765,9 +759,9 @@ "id": "b7157b09", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function named `print_right` that takes a string named `text` as a parameter and prints the string with enough leading spaces that the last letter of the string is in the 40th column of the display." + "Напишите функцию `print_right`, которая принимает строку `text` и выводит её с таким количеством пробелов в начале, чтобы последняя буква оказалась в 40-й колонке." ] }, { @@ -783,9 +777,9 @@ "id": "428fbee5", "metadata": {}, "source": [ - "Hint: Use the `len` function, the string concatenation operator (`+`) and the string repetition operator (`*`).\n", + "Подсказка: используйте функцию `len`, оператор конкатенации строк (`+`) и оператор повторения строк (`*`).\n", "\n", - "Here's an example that shows how it should work." + "Вот пример того, как это должно работать." ] }, { @@ -807,9 +801,9 @@ "id": "b47467fa", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `triangle` that takes a string and an integer and draws a pyramid with the given height, made up using copies of the string. Here's an example of a pyramid with `5` levels, using the string `'L'`." + "Напишите функцию `triangle`, которая принимает строку и целое число и рисует пирамиду заданной высоты из повторений этой строки. Вот пример пирамиды из `5` уровней со строкой `'L'`." ] }, { @@ -838,9 +832,9 @@ "id": "4a28f635", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `rectangle` that takes a string and two integers and draws a rectangle with the given width and height, made up using copies of the string. Here's an example of a rectangle with width `5` and height `4`, made up of the string `'H'`." + "Напишите функцию `rectangle`, которая принимает строку и два целых числа и выводит прямоугольник заданной ширины и высоты из копий этой строки. Ниже приведён пример прямоугольника шириной `5` и высотой `4` из строки `'H'`." ] }, { @@ -869,20 +863,20 @@ "id": "44a5de6f", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "The song \"99 Bottles of Beer\" starts with this verse:\n", + "Песня «99 бутылок пива» начинается с такого куплета:\n", "\n", - "> 99 bottles of beer on the wall \n", - "> 99 bottles of beer \n", - "> Take one down, pass it around \n", - "> 98 bottles of beer on the wall \n", + "> 99 bottles of beer on the wall\n", + "> 99 bottles of beer\n", + "> Take one down, pass it around\n", + "> 98 bottles of beer on the wall\n", "\n", - "Then the second verse is the same, except that it starts with 98 bottles and ends with 97. The song continues -- for a very long time -- until there are 0 bottles of beer.\n", + "Затем второй куплет такой же, только начинается с 98 бутылок и заканчивается 97. Песня продолжается очень долго, пока не останется 0 бутылок.\n", "\n", - "Write a function called `bottle_verse` that takes a number as a parameter and displays the verse that starts with the given number of bottles.\n", + "Напишите функцию `bottle_verse`, которая принимает число и выводит куплет, начинающийся с указанного количества бутылок.\n", "\n", - "Hint: Consider starting with a function that can print the first, second, or last line of the verse, and then use it to write `bottle_verse`." + "Подсказка: начните с функции, которая умеет печатать первую, вторую или последнюю строку куплета, и используйте её, чтобы написать `bottle_verse`." ] }, { @@ -908,7 +902,7 @@ "tags": [] }, "source": [ - "Use this function call to display the first verse." + "Используйте этот вызов функции, чтобы вывести первый куплет." ] }, { @@ -930,8 +924,8 @@ "tags": [] }, "source": [ - "If you want to print the whole song, you can use this `for` loop, which counts down from `99` to `1`.\n", - "You don't have to completely understand this example---we'll learn more about `for` loops and the `range` function later." + "Если хотите напечатать всю песню, используйте этот цикл `for`, который считает от `99` до `1`.\n", + "Пока не обязательно полностью понимать этот пример — позже мы подробнее рассмотрим циклы `for` и функцию `range`." ] }, { @@ -963,13 +957,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3-е издание](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -995,4 +989,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 1e8ddf0fa7587cf427d6bf50a1cc89aa94183892 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 12:45:52 +0300 Subject: [PATCH 05/44] Translate remaining heading --- blank/chap04.ipynb | 356 ++++++++++++++++++++++----------------------- 1 file changed, 178 insertions(+), 178 deletions(-) diff --git a/blank/chap04.ipynb b/blank/chap04.ipynb index 23e5490..b6d5d4b 100644 --- a/blank/chap04.ipynb +++ b/blank/chap04.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -35,10 +35,10 @@ "id": "fbb4d5a2", "metadata": {}, "source": [ - "# Functions and Interfaces\n", + "# Функции и интерфейсы\n", "\n", - "This chapter introduces a module called `jupyturtle`, which allows you to create simple drawings by giving instructions to an imaginary turtle.\n", - "We will use this module to write functions that draw squares, polygons, and circles -- and to demonstrate **interface design**, which is a way of designing functions that work together." + "В этой главе представлен модуль под названием `jupyturtle`, который позволяет создавать простые чертежи, давая инструкции воображаемой черепахе.\n", + "Мы будем использовать этот модуль для написания функций, которые рисуют квадраты, полигоны и круги - и для демонстрации ** дизайна интерфейса **, который является способом разработки функций, которые работают вместе." ] }, { @@ -48,9 +48,9 @@ "tags": [] }, "source": [ - "## The jupyturtle module\n", + "## Модуль JupyTurtle\n", "\n", - "To use the `jupyturtle` module, we can import it like this." + "Чтобы использовать модуль `jupyturtle`, мы можем импортировать его так." ] }, { @@ -66,7 +66,7 @@ "id": "8c801121", "metadata": {}, "source": [ - "Now we can use the functions defined in the module, like `make_turtle` and `forward`." + "Теперь мы можем использовать функции, определенные в модуле, такие как `make_turtle` и `forward`." ] }, { @@ -82,14 +82,14 @@ "id": "77a61cbb", "metadata": {}, "source": [ - "`make_turtle` creates a **canvas**, which is a space on the screen where we can draw, and a turtle, which is represented by a circular shell and a triangular head.\n", - "The circle shows the location of the turtle and the triangle indicates the direction it is facing.\n", + "`make_turtle` создает ** холст **, который представляет собой пространство на экране, где мы можем нарисовать, и черепаха, которая представлена круговой оболочкой и треугольной головкой.\n", + "Круг показывает местоположение черепахи, а треугольник указывает направление, в котором он находится.\n", "\n", - "`forward` moves the turtle a given distance in the direction it's facing, drawing a line segment along the way.\n", - "The distance is in arbitrary units -- the actual size depends on your computer's screen.\n", + "`forward` перемещает черепаху на данном расстоянии в направлении, которую она обращается, протягивая линейный сегмент по пути.\n", + "Расстояние находится в произвольных единицах - фактический размер зависит от экрана вашего компьютера.\n", "\n", - "We will use functions defined in the `jupyturtle` module many times, so it would be nice if we did not have to write the name of the module every time.\n", - "That's possible if we import the module like this." + "Мы будем использовать функции, определенные в модуле `jupyturtle` много раз, поэтому было бы неплохо, если бы нам не пришлось писать имя модуля каждый раз.\n", + "Это возможно, если мы импортируем модуль, как этот." ] }, { @@ -105,7 +105,7 @@ "id": "c1322d31", "metadata": {}, "source": [ - "This version of the import statement imports `make_turtle` and `forward` from the `jupyturtle` module so we can call them like this." + "Эта версия оператора импорта импортирует `make_turtle` и `forward` из модуля `jupyturtle`, поэтому мы можем назвать их такими." ] }, { @@ -121,8 +121,8 @@ "id": "bd319754", "metadata": {}, "source": [ - "`jupyturtle` provides two other functions we'll use, called `left` and `right`.\n", - "We'll import them like this." + "`jupyturtle` предоставляет две другие функции, которые мы используем, называемые `left` и `right`.\n", + "Мы импортируем их так." ] }, { @@ -138,8 +138,8 @@ "id": "0da2a311", "metadata": {}, "source": [ - "`left` causes the turtle to turn left. It takes one argument, which is the angle of the turn in degrees.\n", - "For example, we can make a 90 degree left turn like this." + "`left` заставляет черепаху повернуть налево.Требуется один аргумент, который является углом поворота в градусах.\n", + "Например, мы можем сделать 90 -градусный левый поворот, как это." ] }, { @@ -155,8 +155,8 @@ "id": "cea2940f", "metadata": {}, "source": [ - "This program moves the turtle east and then north, leaving two line segments behind.\n", - "Before you go on, see if you can modify the previous program to make a square." + "Эта программа перемещает черепаху на восток, а затем на север, оставляя два сегмента линии позади.\n", + "Прежде чем продолжить, посмотрите, сможете ли вы изменить предыдущую программу, чтобы создать квадрат." ] }, { @@ -164,9 +164,9 @@ "id": "e20ea96c", "metadata": {}, "source": [ - "## Making a square\n", + "## Сделать квадрат\n", "\n", - "Here's one way to make a square." + "Вот один из способов сделать квадрат." ] }, { @@ -182,7 +182,7 @@ "id": "a7500957", "metadata": {}, "source": [ - "Because this program repeats the same pair of lines four times, we can do the same thing more concisely with a `for` loop." + "Поскольку эта программа повторяет одну и ту же пару линий четыре раза, мы можем сделать то же самое более кратко с петлей `for`." ] }, { @@ -200,9 +200,9 @@ "tags": [] }, "source": [ - "## Encapsulation and generalization\n", + "## инкапсуляция и обобщение\n", "\n", - "Let's take the square-drawing code from the previous section and put it in a function called `square`." + "Давайте возьмем код квадратного рисунка из предыдущего раздела и поместим его в функцию, называемую `square`." ] }, { @@ -218,7 +218,7 @@ "id": "0789b5d9", "metadata": {}, "source": [ - "Now we can call the function like this." + "Теперь мы можем назвать функцию такой." ] }, { @@ -234,11 +234,11 @@ "id": "da905fc6", "metadata": {}, "source": [ - "Wrapping a piece of code up in a function is called **encapsulation**.\n", - "One of the benefits of encapsulation is that it attaches a name to the code, which serves as a kind of documentation. Another advantage is that if you re-use the code, it is more concise to call a function twice than to copy and paste the body!\n", + "Обертывание куска кода в функцию называется ** инкапсуляцией **.\n", + "Одним из преимуществ инкапсуляции является то, что он придает имя к коду, которое служит своего рода документацией.Другое преимущество заключается в том, что если вы повторно используете код, более кратко вызывать функцию дважды, чем копировать и вставить тело!\n", "\n", - "In the current version, the size of the square is always `50`.\n", - "If we want to draw squares with different sizes, we can take the length of the sides as a parameter. " + "В текущей версии размер квадрата всегда `50`.\n", + "Если мы хотим нарисовать квадраты с разными размерами, мы можем взять длину бок в качестве параметра." ] }, { @@ -254,7 +254,7 @@ "id": "397fda4b", "metadata": {}, "source": [ - "Now we can draw squares with different sizes." + "Теперь мы можем нарисовать квадраты с разными размерами." ] }, { @@ -270,10 +270,10 @@ "id": "5a46bf64", "metadata": {}, "source": [ - "Adding a parameter to a function is called **generalization** because it makes the function more general: with the previous version, the square is always the same size; with this version it can be any size.\n", + "Добавление параметра в функцию называется ** обобщение **, потому что он делает функцию более общей: с предыдущей версией квадрат всегда одинаковый размер;С этой версией это может быть любой размер.\n", "\n", - "If we add another parameter, we can make it even more general.\n", - "The following function draws regular polygons with a given number of sides." + "Если мы добавим другой параметр, мы можем сделать его еще более общим.\n", + "Следующая функция привлекает обычные многоугольники с заданным количеством сторон." ] }, { @@ -289,9 +289,9 @@ "id": "286d3c77", "metadata": {}, "source": [ - "In a regular polygon with `n` sides, the angle between adjacent sides is `360 / n` degrees. \n", + "В обычном многоугольнике с сторонами `n` угол между соседними сторонами составляет `360 / n` градусов.\n", "\n", - "The following example draws a `7`-sided polygon with side length `30`." + "Следующий пример рисует полигон с `7` с боковой длиной `30`." ] }, { @@ -307,8 +307,8 @@ "id": "dc0226db", "metadata": {}, "source": [ - "When a function has more than a few numeric arguments, it is easy to forget what they are, or what order they should be in. \n", - "It can be a good idea to include the names of the parameters in the argument list." + "Когда функция имеет более чем несколько цифровых аргументов, легко забыть, каким они есть или в каком порядке они должны быть.\n", + "Это может быть хорошей идеей включить имена параметров в список аргументов." ] }, { @@ -326,10 +326,10 @@ "id": "6aa28eba", "metadata": {}, "source": [ - "These are sometimes called \"named arguments\" because they include the parameter names.\n", - "But in Python they are more often called **keyword arguments** (not to be confused with Python keywords like `for` and `def`).\n", + "Они иногда называют «названными аргументами», потому что они включают имена параметров.\n", + "Но в Python их чаще называют ** аргументы ключевого слова ** (не путать с ключевыми словами Python, такими как `for` и `def`).\n", "\n", - "This use of the assignment operator, `=`, is a reminder about how arguments and parameters work -- when you call a function, the arguments are assigned to the parameters." + "Это использование оператора назначения `=` является напоминанием о том, как работают аргументы и параметры - когда вы вызываете функцию, аргументы присваиваются параметрам." ] }, { @@ -337,11 +337,11 @@ "id": "b10184b4", "metadata": {}, "source": [ - "## Approximating a circle\n", + "## аппроксимирование круга\n", "\n", - "Now suppose we want to draw a circle.\n", - "We can do that, approximately, by drawing a polygon with a large number of sides, so each side is small enough that it's hard to see.\n", - "Here is a function that uses `polygon` to draw a `30`-sided polygon that approximates a circle." + "Теперь предположим, что мы хотим нарисовать круг.\n", + "Примерно мы можем сделать это, нарисовав многоугольник с большим количеством сторон, поэтому каждая сторона достаточно мала, что ее трудно увидеть.\n", + "Вот функция, которая использует `polygon` для нарисования полигона, связанного с `30`, который приближается к кругу." ] }, { @@ -357,13 +357,13 @@ "id": "39023314", "metadata": {}, "source": [ - "`circle` takes the radius of the the circle as a parameter.\n", - "It computes `circumference`, which is the circumference of a circle with the given radius.\n", - "`n` is the number of sides, so `circumference / n` is the length of each side.\n", + "`circle` принимает радиус круга в качестве параметра.\n", + "Он вычисляет `circumference`, который является окружностью круга с данным радиусом.\n", + "`n` - это количество сторон, поэтому `circumference / n` - длина каждой стороны.\n", "\n", - "This function might take a long time to run.\n", - "We can speed it up by calling `make_turtle` with a keyword argument called `delay` that sets the time, in seconds, the turtle waits after each step.\n", - "The default value is `0.2` seconds -- if we set it to `0.02` it runs about 10 times faster." + "Эта функция может занять много времени, чтобы запустить.\n", + "Мы можем ускорить его, позвонив `make_turtle` с помощью аргумента ключевого слова, называемого `delay`, который устанавливает время, в считанные секунды, черепаха ждет после каждого шага.\n", + "Значение по умолчанию составляет `0.2` секунд - если мы установим его на `0.02`, оно работает примерно в 10 раз быстрее." ] }, { @@ -379,11 +379,11 @@ "id": "701f9cf8", "metadata": {}, "source": [ - "A limitation of this solution is that `n` is a constant, which means\n", - "that for very big circles, the sides are too long, and for small\n", - "circles, we waste time drawing very short sides.\n", - "One option is to generalize the function by taking `n` as a parameter.\n", - "But let's keep it simple for now." + "Ограничением этого решения является то, что `n` является постоянным, что означает\n", + "Это для очень больших кругов, стороны слишком длинные, и для маленьких\n", + "Круги, мы тратим время на то, чтобы рисовать очень короткие стороны.\n", + "Одним из вариантов является обобщение функции, взяв `n` в качестве параметра.\n", + "Но давайте пока будем простыми." ] }, { @@ -391,15 +391,15 @@ "id": "c48f262c", "metadata": {}, "source": [ - "## Refactoring\n", + "## Рефакторинг\n", "\n", - "Now let's write a more general version of `circle`, called `arc`, that takes a second parameter, `angle`, and draws an arc of a circle that spans the given angle.\n", - "For example, if `angle` is `360` degrees, it draws a complete circle. If `angle` is `180` degrees, it draws a half circle.\n", + "Теперь давайте напишем более общую версию `circle`, называемой `arc`, которая занимает второй параметр `angle`, и рисует дугу круга, который охватывает заданный угол.\n", + "Например, если `angle` составляет `360` градусов, он привлекает полный круг.Если `angle` составляет `180` градусов, он привлекает половину круга.\n", "\n", - "To write `circle`, we were able to reuse `polygon`, because a many-sided polygon is a good approximation of a circle.\n", - "But we can't use `polygon` to write `arc`.\n", + "Чтобы написать `circle`, мы смогли повторно использовать `polygon`, потому что многоугольный многоугольник-это хорошее приближение круга.\n", + "Но мы не можем использовать `polygon`, чтобы написать `arc`0.\n", "\n", - "Instead, we'll create the more general version of `polygon`, called `polyline`." + "Вместо этого мы создадим более общую версию `arc`1, называемой `arc`2." ] }, { @@ -415,9 +415,9 @@ "id": "c2b2503e", "metadata": {}, "source": [ - "`polyline` takes as parameters the number of line segments to draw, `n`, the length of the segments, `length`, and the angle between them, `angle`.\n", + "`polyline` принимает в качестве параметров количество линейных сегментов для рисования, `n`, длины сегментов, `length` и угла между ними, `angle`.\n", "\n", - "Now we can rewrite `polygon` to use `polyline`." + "Теперь мы можем переписать `polygon`, чтобы использовать `polyline`." ] }, { @@ -433,7 +433,7 @@ "id": "2714a59e", "metadata": {}, "source": [ - "And we can use `polyline` to write `arc`." + "И мы можем использовать `polyline` для написания `arc`." ] }, { @@ -449,9 +449,9 @@ "id": "3c18773c", "metadata": {}, "source": [ - "`arc` is similar to `circle`, except that it computes `arc_length`, which is a fraction of the circumference of a circle.\n", + "`arc` похож на `circle`, за исключением того, что он вычисляет `arc_length`, который является частью окружности круга.\n", "\n", - "Finally, we can rewrite `circle` to use `arc`." + "Наконец, мы можем переписать `circle`, чтобы использовать `arc`." ] }, { @@ -467,8 +467,8 @@ "id": "313a357c", "metadata": {}, "source": [ - "To check that these functions work as expected, we'll use them to draw something like a snail.\n", - "With `delay=0`, the turtle runs as fast as possible." + "Чтобы проверить, что эти функции работают так, как ожидалось, мы будем использовать их, чтобы нарисовать что -то вроде улитки.\n", + "С `delay=0` черепаха работает как можно быстрее." ] }, { @@ -484,12 +484,12 @@ "id": "a34da3d8", "metadata": {}, "source": [ - "In this example, we started with working code and reorganized it with different functions.\n", - "Changes like this, which improve the code without changing its behavior, are called **refactoring**.\n", + "В этом примере мы начали с рабочего кода и реорганизовали его с различными функциями.\n", + "Подобные изменения, которые улучшают код без изменения его поведения, называются ** Рефакторинг **.\n", "\n", - "If we had planned ahead, we might have written `polyline` first and avoided refactoring, but often you don't know enough at the beginning of a project to design all the functions.\n", - "Once you start coding, you understand the problem better.\n", - "Sometimes refactoring is a sign that you have learned something." + "Если бы мы запланировали заранее, мы могли бы сначала написать `polyline` и избежать рефакторинга, но часто вы недостаточно знаете в начале проекта для разработки всех функций.\n", + "Как только вы начнете кодировать, вы лучше понимаете проблему.\n", + "Иногда рефакторинг - это признак того, что вы что -то узнали." ] }, { @@ -497,10 +497,10 @@ "id": "d18c9d16", "metadata": {}, "source": [ - "## Stack diagram\n", + "## диаграмма стека\n", "\n", - "When we call `circle`, it calls `arc`, which calls `polyline`.\n", - "We can use a stack diagram to show this sequence of function calls and the parameters for each one." + "Когда мы называем `circle`, он вызывает `arc`, который вызывает `polyline`.\n", + "Мы можем использовать диаграмму стека, чтобы показать эту последовательность вызовов функций и параметры для каждого из них." ] }, { @@ -528,8 +528,8 @@ "id": "3160bba1", "metadata": {}, "source": [ - "Notice that the value of `angle` in `polyline` is different from the value of `angle` in `arc`.\n", - "Parameters are local, which means you can use the same parameter name in different functions; it's a different variable in each function, and it can refer to a different value. " + "Обратите внимание, что значение `angle` в `polyline` отличается от значения `angle` в `arc`.\n", + "Параметры локальные, что означает, что вы можете использовать одно и то же имя параметра в разных функциях;Это другая переменная в каждой функции, и она может относиться к другому значению." ] }, { @@ -537,27 +537,27 @@ "id": "c23552d3", "metadata": {}, "source": [ - "## A development plan\n", + "## план разработки\n", "\n", - "A **development plan** is a process for writing programs.\n", - "The process we used in this chapter is \"encapsulation and generalization\".\n", - "The steps of this process are:\n", + "** План развития ** - это процесс для написания программ.\n", + "Процесс, который мы использовали в этой главе, - это «инкапсуляция и обобщение».\n", + "Шаги этого процесса:\n", "\n", - "1. Start by writing a small program with no function definitions.\n", + "1. Начните с написания небольшой программы без определений функций.\n", "\n", - "2. Once you get the program working, identify a coherent piece of it,\n", - " encapsulate the piece in a function and give it a name.\n", + "2. Как только вы заработаете программу, определите ее последовательный элемент,\n", + "Инкапсулируйте часть в функцию и дайте ему имя.\n", "\n", - "3. Generalize the function by adding appropriate parameters.\n", + "3. Обобщение функции, добавив соответствующие параметры.\n", "\n", - "4. Repeat Steps 1 to 3 until you have a set of working functions.\n", + "4. Повторите шаги с 1 по 3, пока у вас не будет набора рабочих функций.\n", "\n", - "5. Look for opportunities to improve the program by refactoring. For\n", - " example, if you have similar code in several places, consider\n", - " factoring it into an appropriately general function.\n", + "5. Ищите возможности для улучшения программы путем рефакторинга.Для\n", + "Пример, если у вас есть похожий код в нескольких местах, рассмотрите\n", + "учитывать это в соответствующую общую функцию.\n", "\n", - "This process has some drawbacks -- we will see alternatives later -- but it can be useful if you don't know ahead of time how to divide the program into functions.\n", - "This approach lets you design as you go along." + "Этот процесс имеет некоторые недостатки - мы увидим альтернативы позже - но это может быть полезно, если вы не знаете заранее, как разделить программу на функции.\n", + "Такой подход позволяет вам дизайн по мере продвижения." ] }, { @@ -565,13 +565,13 @@ "id": "a3b6b83d", "metadata": {}, "source": [ - "The design of a function has two parts:\n", + "Дизайн функции имеет две части:\n", "\n", - "* The **interface** is how the function is used, including its name, the parameters it takes and what the function is supposed to do.\n", + "*** Интерфейс ** - это то, как используется функция, включая ее имя, параметры, которые он принимает и что должна выполнять функция.\n", "\n", - "* The **implementation** is how the function does what it's supposed to do.\n", + "*** Реализация ** - это то, как функция делает то, что она должна делать.\n", "\n", - "For example, here's the first version of `circle` we wrote, which uses `polygon`." + "Например, вот первая версия `circle`, которую мы написали, которая использует `polygon`." ] }, { @@ -587,7 +587,7 @@ "id": "5d3d2e79", "metadata": {}, "source": [ - "And here's the refactored version that uses `arc`." + "А вот рефакторированная версия, которая использует `arc`." ] }, { @@ -603,7 +603,7 @@ "id": "b726f72c", "metadata": {}, "source": [ - "These two functions have the same interface -- they take the same parameters and do the same thing -- but they have different implementations." + "Эти две функции имеют одинаковый интерфейс - они принимают одинаковые параметры и делают одно и то же, но у них разные реализации." ] }, { @@ -613,10 +613,10 @@ "tags": [] }, "source": [ - "## Docstrings\n", + "## Докстроки\n", "\n", - "A **docstring** is a string at the beginning of a function that explains the interface (\"doc\" is short for \"documentation\").\n", - "Here is an example:" + "** Docstring ** - это строка в начале функции, которая объясняет интерфейс («DOC» является коротким для «документации»).\n", + "Вот пример:" ] }, { @@ -632,18 +632,18 @@ "id": "55b60cbc", "metadata": {}, "source": [ - "By convention, docstrings are triple-quoted strings, also known as **multiline strings** because the triple quotes allow the string to span more than one line.\n", + "По соглашению, Docstrings представляют собой строки с тройным цитированием, также известные как ** многослойные строки **, потому что тройные кавычки позволяют строке охватывать более одной строки.\n", "\n", - "A docstring should:\n", + "Докстронг должен:\n", "\n", - "* Explain concisely what the function does, without getting into the details of how it works,\n", + "* Объясните кратко, что делает функция, не вдаваясь в подробности того, как она работает,\n", "\n", - "* Explain what effect each parameter has on the behavior of the function, and\n", + "* Объясните, какой эффект каждый параметр оказывает на поведение функции, и\n", "\n", - "* Indicate what type each parameter should be, if it is not obvious.\n", + "* Укажите, какой тип должен быть каждый параметр, если он не очевиден.\n", "\n", - "Writing this kind of documentation is an important part of interface design.\n", - "A well-designed interface should be simple to explain; if you have a hard time explaining one of your functions, maybe the interface could be improved." + "Написание такого рода документации является важной частью дизайна интерфейса.\n", + "Хорошо разработанный интерфейс должен быть прост в объяснении;Если вам трудно объяснить одну из ваших функций, возможно, интерфейс может быть улучшен." ] }, { @@ -651,20 +651,20 @@ "id": "f1115940", "metadata": {}, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "An interface is like a contract between a function and a caller. The\n", - "caller agrees to provide certain arguments and the function agrees to\n", - "do certain work.\n", + "Интерфейс похож на контракт между функцией и вызывающим абонент.А\n", + "Абонент соглашается предоставить определенные аргументы, и функция соглашается\n", + "Делайте определенную работу.\n", "\n", - "For example, `polyline` requires three arguments: `n` has to be an integer; `length` should be a positive number; and `angle` has to be a number, which is understood to be in degrees.\n", + "Например, `polyline` требует трех аргументов: `n` должен быть целым числом;`length` должен быть положительным числом;и `angle` должен быть числом, которое, как понимается, находится в градусах.\n", "\n", - "These requirements are called **preconditions** because they are supposed to be true before the function starts executing. Conversely, conditions at the end of the function are **postconditions**.\n", - "Postconditions include the intended effect of the function (like drawing line segments) and any side effects (like moving the turtle or making other changes).\n", + "Эти требования называются ** предварительные условия **, потому что они должны быть истинными, прежде чем функция начнет выполнять.И наоборот, условия в конце функции - это ** Посткондиционирование **.\n", + "Пост -кондиционирование включают предполагаемый эффект функции (например, сегменты линий рисования) и любые побочные эффекты (например, перемещение черепахи или внесение других изменений).\n", "\n", - "Preconditions are the responsibility of the caller. If the caller violates a precondition and the function doesn't work correctly, the bug is in the caller, not the function.\n", + "Предварительные условия являются обязанностью звонящего.Если вызывающий абонент нарушает предпосылку, а функция не работает правильно, ошибка находится в вызывающем абоненте, а не на функции.\n", "\n", - "If the preconditions are satisfied and the postconditions are not, the bug is in the function. If your pre- and postconditions are clear, they can help with debugging." + "Если предварительные условия выполняются, а пост -кондиционирования нет, ошибка в функции.Если ваши до- и почтовые ведения ясны, они могут помочь с отладкой." ] }, { @@ -672,40 +672,40 @@ "id": "a4d33a70", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**interface design:**\n", - "A process for designing the interface of a function, which includes the parameters it should take.\n", + "** Дизайн интерфейса: **\n", + "Процесс разработки интерфейса функции, который включает в себя параметры, которые он должен взять.\n", "\n", - "**canvas:**\n", - "A window used to display graphical elements including lines, circles, rectangles, and other shapes.\n", + "**холст:**\n", + "Окно, используемое для отображения графических элементов, включая линии, круги, прямоугольники и другие формы.\n", "\n", - "**encapsulation:**\n", - " The process of transforming a sequence of statements into a function definition.\n", + "** инкапсуляция: **\n", + "Процесс преобразования последовательности операторов в определение функции.\n", "\n", - "**generalization:**\n", - " The process of replacing something unnecessarily specific (like a number) with something appropriately general (like a variable or parameter).\n", + "**обобщение:**\n", + "Процесс замены чего -то излишне конкретного (например, число) на что -то соответствующим образом общее (например, переменная или параметр).\n", "\n", - "**keyword argument:**\n", - "An argument that includes the name of the parameter.\n", + "** Аргумент ключевого слова: **\n", + "Аргумент, который включает имя параметра.\n", "\n", - "**refactoring:**\n", - " The process of modifying a working program to improve function interfaces and other qualities of the code.\n", + "** Рефакторинг: **\n", + "Процесс изменения рабочей программы для улучшения функциональных интерфейсов и других качеств кода.\n", "\n", - "**development plan:**\n", - "A process for writing programs.\n", + "** План развития: **\n", + "Процесс написания программ.\n", "\n", - "**docstring:**\n", - " A string that appears at the top of a function definition to document the function's interface.\n", + "** Докстронг: **\n", + "Строка, которая появляется в верхней части определения функции, для документирования интерфейса функции.\n", "\n", - "**multiline string:**\n", - "A string enclosed in triple quotes that can span more than one line of a program.\n", + "** Многослойная строка: **\n", + "Строка, заключенная в тройные кавычки, которая может охватывать более одной строки программы.\n", "\n", - "**precondition:**\n", - " A requirement that should be satisfied by the caller before a function starts.\n", + "** Предварительное условие: **\n", + "Требование, которое должно быть удовлетворено вызывающим абонент до начала функции.\n", "\n", - "**postcondition:**\n", - " A requirement that should be satisfied by the function before it ends." + "** Посткондиционирование: **\n", + "Требование, которое должно быть удовлетворено функцией, прежде чем она закончится." ] }, { @@ -713,7 +713,7 @@ "id": "0bfe2e19", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -731,13 +731,13 @@ "id": "50ed5c38", "metadata": {}, "source": [ - "For the exercises below, there are a few more turtle functions you might want to use.\n", + "Для приведенных ниже упражнений есть еще несколько функций черепах, которые вы, возможно, захотите использовать.\n", "\n", - "* `penup` lifts the turtle's imaginary pen so it doesn't leave a trail when it moves.\n", + "* `penup` поднимает воображаемую ручку черепахи, чтобы она не оставляла след, когда он движется.\n", "\n", - "* `pendown` puts the pen back down.\n", + "* `pendown` кладет ручку обратно.\n", "\n", - "The following function uses `penup` and `pendown` to move the turtle without leaving a trail." + "Следующая функция использует `penup` и `pendown` для перемещения черепахи, не выходя из следа." ] }, { @@ -753,10 +753,10 @@ "id": "c78c1e17", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `rectangle` that draws a rectangle with given side lengths.\n", - "For example, here's a rectangle that's `80` units wide and `40` units tall." + "Напишите функцию, называемую `rectangle`, которая рисует прямоугольник с данной боковой длиной.\n", + "Например, вот прямоугольник, который имеет ширину `80` и высокие единицы `40`." ] }, { @@ -774,7 +774,7 @@ "tags": [] }, "source": [ - "You can use the following code to test your function." + "Вы можете использовать следующий код для проверки вашей функции." ] }, { @@ -792,9 +792,9 @@ "id": "8b8faaf6", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `rhombus` that draws a rhombus with a given side length and a given interior angle. For example, here's a rhombus with side length `50` and an interior angle of `60` degrees." + "Напишите функцию, называемую `rhombus`, которая рисует ромб с данной длиной боковой стороны и заданным внутренним углом.Например, вот ромб с боковой длиной `50` и внутренним углом градусов `60`." ] }, { @@ -812,7 +812,7 @@ "tags": [] }, "source": [ - "You can use the following code to test your function." + "Вы можете использовать следующий код для проверки вашей функции." ] }, { @@ -830,9 +830,9 @@ "id": "a9175a90", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Now write a more general function called `parallelogram` that draws a quadrilateral with parallel sides. Then rewrite `rectangle` and `rhombus` to use `parallelogram`." + "Теперь напишите более общую функцию, называемую `parallelogram`, которая привлекает четырехугольник с параллельными сторонами.Затем переписывайте `rectangle` и `rhombus`, чтобы использовать `parallelogram`." ] }, { @@ -866,7 +866,7 @@ "tags": [] }, "source": [ - "You can use the following code to test your functions." + "Вы можете использовать следующий код для проверки ваших функций." ] }, { @@ -884,13 +884,13 @@ "id": "991ab59d", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write an appropriately general set of functions that can draw shapes like this.\n", + "Напишите соответствующим образом общий набор функций, которые могут рисовать такие формы.\n", "\n", "![](https://github.com/AllenDowney/ThinkPython/raw/v3/jupyturtle_pie.png)\n", "\n", - "Hint: Write a function called `triangle` that draws one triangular segment, and then a function called `draw_pie` that uses `triangle`." + "Подсказка: напишите функцию, называемую `triangle`, которая рисует один треугольный сегмент, а затем функцию, называемую `draw_pie`, которая использует `triangle`." ] }, { @@ -916,7 +916,7 @@ "tags": [] }, "source": [ - "You can use the following code to test your functions." + "Вы можете использовать следующий код для проверки ваших функций." ] }, { @@ -944,13 +944,13 @@ "id": "9c78b76f", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write an appropriately general set of functions that can draw flowers like this.\n", + "Напишите соответствующим образом общий набор функций, которые могут рисовать такие цветы.\n", "\n", "![](https://github.com/AllenDowney/ThinkPython/raw/v3/jupyturtle_flower.png)\n", "\n", - "Hint: Use `arc` to write a function called `petal` that draws one flower petal." + "Подсказка: используйте `arc`, чтобы написать функцию, называемую `petal`, которая рисует один лепесток цветов." ] }, { @@ -976,12 +976,12 @@ "tags": [] }, "source": [ - "You can use the following code to test your functions.\n", + "Вы можете использовать следующий код для проверки ваших функций.\n", "\n", - "Because the solution draws a lot of small line segments, it tends to slow down as it runs.\n", - "To avoid that, you can add the keyword argument `auto_render=False` to avoid drawing after every step, and then call the `render` function at the end to show the result.\n", + "Поскольку решение привлекает много небольших линейных сегментов, оно имеет тенденцию замедляться при запуске.\n", + "Чтобы избежать этого, вы можете добавить аргумент ключевого слова `auto_render=False`, чтобы избежать рисования после каждого шага, а затем вызвать функцию `render` в конце, чтобы показать результат.\n", "\n", - "While you are debugging, you might want to remove `auto_render=False`." + "Пока вы отладки, вы можете удалить `auto_render=False`." ] }, { @@ -1009,12 +1009,12 @@ "id": "9d9f35d1", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "There are several modules like `jupyturtle` in Python, and the one we used in this chapter has been customized for this book.\n", - "So if you ask a virtual assistant for help, it won't know which module to use.\n", - "But if you give it a few examples to work with, it can probably figure it out.\n", - "For example, try this prompt and see if it can write a function that draws a spiral:\n", + "В Python есть несколько модулей, таких как `jupyturtle`, и те, которые мы использовали в этой главе, были настроены для этой книги.\n", + "Поэтому, если вы попросите виртуального помощника за помощью, он не узнает, какой модуль использовать.\n", + "Но если вы привнесете несколько примеров для работы, это, вероятно, может понять это.\n", + "Например, попробуйте эту подсказку и посмотрите, может ли она написать функцию, которая рисует спираль:\n", "\n", "```\n", "The following program uses a turtle graphics module to draw a circle:\n", @@ -1046,9 +1046,9 @@ "id": "7beb2afe", "metadata": {}, "source": [ - "Keep in mind that the result might use features we have not seen yet, and it might have errors.\n", - "Copy the code from the VA and see if you can get it working.\n", - "If you didn't get what you wanted, try modifying the prompt.\n" + "Имейте в виду, что результат может использовать функции, которые мы еще не видели, и у него могут быть ошибки.\n", + "Скопируйте код из VA и посмотрите, сможете ли вы заставить его работать.\n", + "Если вы не получили то, что хотели, попробуйте изменить подсказку." ] }, { @@ -1078,9 +1078,9 @@ "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], From 2f4d13158957f2dca984ec5a076271c8ff6ef500 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 12:46:28 +0300 Subject: [PATCH 06/44] Translate chapter 5 notebook to Russian --- blank/chap05.ipynb | 534 ++++++++++++++++++++++----------------------- 1 file changed, 262 insertions(+), 272 deletions(-) diff --git a/blank/chap05.ipynb b/blank/chap05.ipynb index 9f9ad19..b2e1aa0 100644 --- a/blank/chap05.ipynb +++ b/blank/chap05.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432? ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325).\n" ] }, { @@ -25,12 +25,12 @@ "id": "75b60d6c", "metadata": {}, "source": [ - "# Conditionals and Recursion\n", + "# Условные и рекурсию\n", "\n", - "The main topic of this chapter is the `if` statement, which executes different code depending on the state of the program.\n", - "And with the `if` statement we'll be able to explore one of the most powerful ideas in computing, **recursion**.\n", + "Основной темой этой главы является оператор «если», который выполняет различный код в зависимости от состояния программы.\n", + "И с помощью утверждения, если мы сможем изучить одну из самых мощных идей в вычислительных вычислениях, ** рекурсия **.\n", "\n", - "But we'll start with three new features: the modulus operator, boolean expressions, and logical operators." + "Но мы начнем с трех новых функций: оператор модуля, логические выражения и логические операторы.\n" ] }, { @@ -38,13 +38,13 @@ "id": "4ab7caf4", "metadata": {}, "source": [ - "## Integer division and modulus\n", + "## Integer Division и Modulus\n", "\n", - "Recall that the integer division operator, `//`, divides two numbers and rounds\n", - "down to an integer.\n", - "For example, suppose the run time of a movie is 105 minutes. \n", - "You might want to know how long that is in hours.\n", - "Conventional division returns a floating-point number:" + "Напомним, что оператор целочисленного дивизиона, `//`, делит два числа и раунды\n", + "вплоть до целого числа.\n", + "Например, предположим, что время выполнения фильма составляет 105 минут.\n", + "Возможно, вы захотите знать, как долго это в часы.\n", + "Обычное подразделение возвращает номер с плавающей запятой:\n" ] }, { @@ -60,8 +60,8 @@ "id": "3f224403", "metadata": {}, "source": [ - "But we don't normally write hours with decimal points.\n", - "Integer division returns the integer number of hours, rounding down:" + "Но мы обычно не пишем часы с десятичными очками.\n", + "Целочисленное подразделение возвращает целое число часов, округление:\n" ] }, { @@ -77,7 +77,7 @@ "id": "bfa9b0cf", "metadata": {}, "source": [ - "To get the remainder, you could subtract off one hour in minutes:" + "Чтобы получить остаток, вы можете вычесть один час за считанные минуты:\n" ] }, { @@ -93,7 +93,7 @@ "id": "05caf27f", "metadata": {}, "source": [ - "Or you could use the **modulus operator**, `%`, which divides two numbers and returns the remainder." + "Или вы можете использовать оператор модуля ** **, `%`, который делит два числа и возвращает остаток.\n" ] }, { @@ -109,12 +109,12 @@ "id": "18c1e0d0", "metadata": {}, "source": [ - "The modulus operator is more useful than it might seem.\n", - "For example, it can check whether one number is divisible by another -- if `x % y` is zero, then `x` is divisible by `y`.\n", + "Оператор модуля более полезен, чем может показаться.\n", + "Например, он может проверить, делится ли одно число на другое - если `x % y` равен нулю, то` x` делится на `y`.\n", "\n", - "Also, it can extract the right-most digit or digits from a number.\n", - "For example, `x % 10` yields the right-most digit of `x` (in base 10).\n", - "Similarly, `x % 100` yields the last two digits." + "Кроме того, он может извлечь правую цифру или цифры из числа.\n", + "Например, «x % 10» дает самую правую цифру `x` (в основании 10).\n", + "Точно так же «X % 100» дает две последние цифры.\n" ] }, { @@ -138,8 +138,8 @@ "id": "f2344fc0", "metadata": {}, "source": [ - "Finally, the modulus operator can do \"clock arithmetic\".\n", - "For example, if an event starts at 11 AM and lasts three hours, we can use the modulus operator to figure out what time it ends." + "Наконец, оператор модуля может делать «часовую арифметику».\n", + "Например, если событие начинается в 11 часов утра и длится три часа, мы можем использовать оператор модуля, чтобы выяснить, сколько времени оно заканчивается.\n" ] }, { @@ -155,7 +155,7 @@ "id": "351c30df", "metadata": {}, "source": [ - "The event would end at 2 PM." + "Мероприятие закончится в 14:00.\n" ] }, { @@ -163,10 +163,10 @@ "id": "5ed1b58b", "metadata": {}, "source": [ - "## Boolean Expressions\n", + "## Логические выражения\n", "\n", - "A **boolean expression** is an expression that is either true or false.\n", - "For example, the following expressions use the equals operator, `==`, which compares two values and produces `True` if they are equal and `False` otherwise:" + "** логическое выражение ** - это выражение, которое является либо истинным, либо ложным.\n", + "Например, в следующих выражениях используется оператор Equals, `==`, который сравнивает два значения и создает `true`, если они равны и` false 'в противном случае:\n" ] }, { @@ -190,8 +190,8 @@ "id": "41fbc642", "metadata": {}, "source": [ - "A common error is to use a single equal sign (`=`) instead of a double equal sign (`==`).\n", - "Remember that `=` assigns a value to a variable and `==` compares two values. " + "Распространенной ошибкой является использование единого равного знака (`=`) вместо двойного равного знака (`==`).\n", + "Помните, что `=` присваивает значение переменной и `==` сравнивает два значения.\n" ] }, { @@ -215,8 +215,8 @@ "id": "d3ec6b48", "metadata": {}, "source": [ - "`True` and `False` are special values that belong to the type `bool`;\n", - "they are not strings:" + "`True` и` false ' - это специальные значения, которые принадлежат типу `bool`;\n", + "Они не струны:\n" ] }, { @@ -240,7 +240,7 @@ "id": "451b2e8d", "metadata": {}, "source": [ - "The `==` operator is one of the **relational operators**; the others are:" + "Оператор `==` является одним из ** реляционных операторов **; остальные:\n" ] }, { @@ -288,12 +288,12 @@ "id": "db5a9477", "metadata": {}, "source": [ - "## Logical operators\n", + "## Логические операторы\n", "\n", - "To combine boolean values into expressions, we can use **logical operators**.\n", - "The most common are `and`, ` or`, and `not`.\n", - "The meaning of these operators is similar to their meaning in English.\n", - "For example, the value of the following expression is `True` only if `x` is greater than `0` *and* less than `10`." + "Чтобы объединить логические значения в выражения, мы можем использовать ** логические операторы **.\n", + "Наиболее распространенными являются `и`, `или` и `not '.\n", + "Значение этих операторов похоже на их значение на английском языке.\n", + "Например, значение следующего выражения составляет `true` только в том случае, если` x` больше, чем `0` * и * меньше, чем` 10`.\n" ] }, { @@ -309,7 +309,7 @@ "id": "e8c14026", "metadata": {}, "source": [ - "The following expression is `True` if *either or both* of the conditions is true, that is, if the number is divisible by 2 *or* 3:" + "Следующее выражение является `true`, если * либо, или оба * условия верно, то есть, если число делится на 2 * или * 3:\n" ] }, { @@ -325,7 +325,7 @@ "id": "3bd0ef52", "metadata": {}, "source": [ - "Finally, the `not` operator negates a boolean expression, so the following expression is `True` if `x > y` is `False`." + "Наконец, оператор «Не» отрицает логическое выражение, поэтому следующее выражение является `true`, если` x> y` равно `false`.\n" ] }, { @@ -341,8 +341,8 @@ "id": "fc6098c2", "metadata": {}, "source": [ - "Strictly speaking, the operands of a logical operator should be boolean expressions, but Python is not very strict.\n", - "Any nonzero number is interpreted as `True`:" + "Строго говоря, операнды логического оператора должны быть логическими выражениями, но Python не очень строг.\n", + "Любое ненулевое число интерпретируется как «true»:\n" ] }, { @@ -358,8 +358,8 @@ "id": "102ceab9", "metadata": {}, "source": [ - "This flexibility can be useful, but there are some subtleties to it that can be confusing.\n", - "You might want to avoid it." + "Эта гибкость может быть полезной, но есть некоторые тонкости, которые могут запутаться.\n", + "Вы можете избежать этого.\n" ] }, { @@ -367,12 +367,12 @@ "id": "6b0f2dc1", "metadata": {}, "source": [ - "## if statements\n", + "## if Заявления\n", "\n", - "In order to write useful programs, we almost always need the ability to\n", - "check conditions and change the behavior of the program accordingly.\n", - "**Conditional statements** give us this ability. The simplest form is\n", - "the `if` statement:" + "Чтобы написать полезные программы, нам почти всегда нужна возможность\n", + "Проверьте условия и измените поведение программы соответственно.\n", + "** Условные утверждения ** Дайте нам эту способность. Самая простая форма - это\n", + "оператор `if`:\n" ] }, { @@ -388,16 +388,16 @@ "id": "973f705e", "metadata": {}, "source": [ - "`if` is a Python keyword.\n", - "`if` statements have the same structure as function definitions: a\n", - "header followed by an indented statement or sequence of statements called a **block**.\n", + "`Если ключевое слово Python.\n", + "`За операторы имеют ту же структуру, что и определения функций:\n", + "Заголовок, за которым следует отступе или последовательность утверждений, называемых ** блоком **.\n", "\n", - "The boolean expression after `if` is called the **condition**.\n", - "If it is true, the statements in the indented block run. If not, they don't.\n", + "Логическое выражение после `if` называется ** условием **.\n", + "Если это правда, операторы в блоке с отступом. Если нет, они этого не делают.\n", "\n", - "There is no limit to the number of statements that can appear in the block, but there has to be at least one.\n", - "Occasionally, it is useful to have a block that does nothing -- usually as a place keeper for code you haven't written yet.\n", - "In that case, you can use the `pass` statement, which does nothing." + "Нет ограничений на количество заявлений, которые могут появиться в блоке, но должен быть как минимум один.\n", + "Иногда полезно иметь блок, который ничего не делает - обычно как хранитель места для кода, который вы еще не написали.\n", + "В этом случае вы можете использовать оператор «Pass», который ничего не делает.\n" ] }, { @@ -413,7 +413,7 @@ "id": "adf3f6c5", "metadata": {}, "source": [ - "The word `TODO` in a comment is a conventional reminder that there's something you need to do later." + "Слово «Тодо» в комментарии является обычным напоминанием о том, что есть что -то, что вам нужно сделать позже.\n" ] }, { @@ -421,10 +421,10 @@ "id": "eb39bcd9", "metadata": {}, "source": [ - "## The `else` clause\n", + "## пункт `else`\n", "\n", - "An `if` statement can have a second part, called an `else` clause.\n", - "The syntax looks like this:" + "Оператор «if» может иметь вторую часть, называемую пунктом `else`.\n", + "Синтаксис выглядит так:\n" ] }, { @@ -440,14 +440,12 @@ "id": "e7dc8943", "metadata": {}, "source": [ - "If the condition is true, the first indented statement runs; otherwise, the second indented statement runs.\n", + "В этом примере, если `x` ровно, оставшаяся часть, когда` x` делится на `2`, является` 0`, так что условие верно, а программа отображает `x evely`.\n", + "Если `x` нечетный, оставшаяся часть` 1`, так что условие\n", + "ложь, а программа отображает `x add.\n", "\n", - "In this example, if `x` is even, the remainder when `x` is divided by `2` is `0`, so the condition is true and the program displays `x is even`.\n", - "If `x` is odd, the remainder is `1`, so the condition\n", - "is false, and the program displays `x is odd`.\n", - "\n", - "Since the condition must be true or false, exactly one of the alternatives will run. \n", - "The alternatives are called **branches**." + "Поскольку условие должно быть истинным или ложным, именно одна из альтернатив будет работать.\n", + "Альтернативы называются ** филиалами **.\n" ] }, { @@ -455,10 +453,10 @@ "id": "20c8adb6", "metadata": {}, "source": [ - "## Chained conditionals\n", + "## прикованные условия\n", "\n", - "Sometimes there are more than two possibilities and we need more than two branches.\n", - "One way to express a computation like that is a **chained conditional**, which includes an `elif` clause." + "Иногда существует более двух возможностей, и нам нужно более двух ветвей.\n", + "Одним из способов выразить подобное вычисление является ** при цепочке условной **, который включает в себя пункт «elif».\n" ] }, { @@ -474,15 +472,15 @@ "id": "46916379", "metadata": {}, "source": [ - "`elif` is an abbreviation of \"else if\".\n", - "There is no limit on the number of `elif` clauses.\n", - "If there is an `else` clause, it has to be at the end, but there doesn't have to be\n", - "one.\n", + "«Элиф» - это аббревиатура «else, если».\n", + "Нет ограничений на количество положений `elif.\n", + "Если есть пункт «еще», это должно быть в конце, но не должно быть\n", + "один.\n", + "\n", + "Каждое условие проверяется по порядку.\n", "\n", - "Each condition is checked in order.\n", - "If the first is false, the next is checked, and so on.\n", - "If one of them is true, the corresponding branch runs and the `if` statement ends.\n", - "Even if more than one condition is true, only the first true branch runs." + "Если один из них правда, соответствующая ветвь работает, а оператор «if» заканчивается.\n", + "Даже если более одного условия верно, только первая настоящая ветвь работает.\n" ] }, { @@ -490,10 +488,10 @@ "id": "e0c0b9dd", "metadata": {}, "source": [ - "## Nested Conditionals\n", + "## вложенные условия\n", "\n", - "One conditional can also be nested within another.\n", - "We could have written the example in the previous section like this:" + "Один кондиционер также может быть вложенным в другой.\n", + "Мы могли бы написать пример в предыдущем разделе, как это:\n" ] }, { @@ -509,15 +507,15 @@ "id": "29f67a0a", "metadata": {}, "source": [ - "The outer `if` statement contains two branches. \n", - "The first branch contains a simple statement. The second branch contains another `if` statement, which has two branches of its own.\n", - "Those two branches are both simple statements, although they could have been conditional statements as well.\n", + "Внешний оператор `if` содержит две ветви.\n", + "Первая ветка содержит простое утверждение. Вторая ветвь содержит еще одно утверждение «если», в котором есть два собственных ветви.\n", + "Эти две ветви являются простыми утверждениями, хотя они могли быть условными утверждениями.\n", "\n", - "Although the indentation of the statements makes the structure apparent, **nested conditionals** can be difficult to read.\n", - "I suggest you avoid them when you can.\n", + "Хотя отступ в утверждениях делает структуру очевидной, ** вложенные условия ** могут быть трудно читать.\n", + "Я предлагаю вам избежать их, когда сможете.\n", "\n", - "Logical operators often provide a way to simplify nested conditional statements.\n", - "Here's an example with a nested conditional." + "Логические операторы часто предоставляют способ упростить вложенные условные утверждения.\n", + "Вот пример с вложенным условным.\n" ] }, { @@ -533,7 +531,7 @@ "id": "5292eb11", "metadata": {}, "source": [ - "The `print` statement runs only if we make it past both conditionals, so we get the same effect with the `and` operator." + "Оператор «print» работает только в том случае, если мы переживаем оба условия, поэтому мы получаем одинаковый эффект с оператором `и`.\n" ] }, { @@ -549,7 +547,7 @@ "id": "dd8e808a", "metadata": {}, "source": [ - "For this kind of condition, Python provides a more concise option:" + "Для такого рода условия Python предоставляет более краткий вариант:\n" ] }, { @@ -567,9 +565,9 @@ "source": [ "## Recursion\n", "\n", - "It is legal for a function to call itself.\n", - "It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do.\n", - "Here's an example." + "Это законно, чтобы функция вызвала себя.\n", + "Может быть не очевидно, почему это хорошо, но это оказывается одной из самых волшебных вещей, которые может сделать программа.\n", + "Вот пример.\n" ] }, { @@ -585,10 +583,7 @@ "id": "c88e0dc7", "metadata": {}, "source": [ - "If `n` is 0 or negative, `countdown` outputs the word, \"Blastoff!\" Otherwise, it\n", - "outputs `n` and then calls itself, passing `n-1` as an argument.\n", - "\n", - "Here's what happens when we call this function with the argument `3`." + "Если `n` равно 0 или негативно,« обратный отсчет »выводит слово« Blastoff! » В противном случае это\n" ] }, { @@ -604,23 +599,23 @@ "id": "3f3c87ec", "metadata": {}, "source": [ - "The execution of `countdown` begins with `n=3`, and since `n` is greater\n", - "than `0`, it displays `3`, and then calls itself\\...\n", + "Выполнение «обратного отсчета» начинается с `n = 3`, и, поскольку` n` больше\n", + "чем `0`, он отображает` 3`, а затем вызывает себя \\ ...\n", "\n", - "> The execution of `countdown` begins with `n=2`, and since `n` is\n", - "> greater than `0`, it displays `2`, and then calls itself\\...\n", + "> Выполнение `обратное отсчетное значение начинается с` n = 2`, и, поскольку `n`\n", + "> больше, чем `0`, он отображает` 2`, а затем вызывает себя \\ ...\n", ">\n", - "> > The execution of `countdown` begins with `n=1`, and since `n` is\n", - "> > greater than `0`, it displays `1`, and then calls itself\\...\n", - "> >\n", - "> > > The execution of `countdown` begins with `n=0`, and since `n` is\n", - "> > > not greater than `0`, it displays \"Blastoff!\" and returns.\n", - "> >\n", - "> > The `countdown` that got `n=1` returns.\n", + ">> Выполнение `обратное отсчетное снижение` начинается с `n = 1`, и, поскольку` n`\n", + ">> больше, чем `0`, он отображает` 1`, а затем вызывает себя \\ ...\n", + ">>\n", + ">>> выполнение `countdown` начинается с` n = 0` ', и, поскольку `n`\n", + ">>> Не больше, чем `0`, он отображает\" Blastoff! \" и возвращается.\n", + ">>\n", + ">> `Обратный отсчет\n", ">\n", - "> The `countdown` that got `n=2` returns.\n", + "> «Обратный отсчет», который получил `n = 2` Возврат.\n", "\n", - "The `countdown` that got `n=3` returns." + "`Обратный отсчет ', который получил` n = 3` возвращает.\n" ] }, { @@ -628,8 +623,8 @@ "id": "782e95bb", "metadata": {}, "source": [ - "A function that calls itself is **recursive**.\n", - "As another example, we can write a function that prints a string `n` times." + "Функция, которая вызывает себя, является ** рекурсивной **.\n", + "В качестве другого примера мы можем написать функцию, которая печатает строку `n` Times.\n" ] }, { @@ -645,11 +640,11 @@ "id": "73d07c17", "metadata": {}, "source": [ - "If `n` is positive, `print_n_times` displays the value of `string` and then calls itself, passing along `string` and `n-1` as arguments.\n", + "Если `n` положительный,` print_n_times` отображает значение `string ', а затем вызывает себя, передавая` string` и `n-1` в качестве аргументов.\n", "\n", - "If `n` is `0` or negative, the condition is false and `print_n_times` does nothing.\n", + "Если `n`` 0` или отрицательный, условие является ложным, а `print_n_times` ничего не делает.\n", "\n", - "Here's how it works." + "Вот как это работает.\n" ] }, { @@ -665,9 +660,9 @@ "id": "1fb55a78", "metadata": {}, "source": [ - "For simple examples like this, it is probably easier to use a `for`\n", - "loop. But we will see examples later that are hard to write with a `for`\n", - "loop and easy to write with recursion, so it is good to start early." + "Для таких простых примеров, вероятно, легче использовать `for\n", + "петля. Но позже мы увидим примеры, которые трудно написать с `for\n", + "петля и легко писать с рекурсией, так что хорошо начать рано.\n" ] }, { @@ -675,9 +670,9 @@ "id": "c652c739", "metadata": {}, "source": [ - "## Stack diagrams for recursive functions\n", + "## Схема стека для рекурсивных функций\n", "\n", - "Here's a stack diagram that shows the frames created when we called `countdown` with `n = 3`." + "Вот схема стека, которая показывает кадры, созданные, когда мы называем «обратный отсчет» с `n = 3`.\n" ] }, { @@ -705,9 +700,9 @@ "id": "9282331b", "metadata": {}, "source": [ - "The four `countdown` frames have different values for the parameter `n`.\n", - "The bottom of the stack, where `n=0`, is called the **base case**.\n", - "It does not make a recursive call, so there are no more frames." + "Четыре кадра «обратный отсчет» имеют разные значения для параметра `n`.\n", + "Нижняя часть стека, где `n = 0`, называется ** базовый корпус **.\n", + "Это не делает рекурсивный вызов, поэтому больше нет кадров.\n" ] }, { @@ -725,12 +720,12 @@ "id": "37bbc2b8", "metadata": {}, "source": [ - "## Infinite recursion\n", + "## бесконечная рекурсия\n", "\n", - "If a recursion never reaches a base case, it goes on making recursive\n", - "calls forever, and the program never terminates. This is known as\n", - "**infinite recursion**, and it is generally not a good idea.\n", - "Here's a minimal function with an infinite recursion." + "Если рекурсия никогда не достигает базового корпуса, она продолжает рекурсивно\n", + "Звонки навсегда, и программа никогда не завершается. Это известно как\n", + "** Бесконечная рекурсия **, и это, как правило, не очень хорошая идея.\n", + "Вот минимальная функция с бесконечной рекурсией.\n" ] }, { @@ -746,9 +741,9 @@ "id": "450a20ac", "metadata": {}, "source": [ - "Every time `recurse` is called, it calls itself, which creates another frame.\n", - "In Python, there is a limit to the number of frames that can be on the stack at the same time.\n", - "If a program exceeds the limit, it causes a runtime error." + "Каждый раз, когда называется «Recurse», он называет себя, что создает другой кадр.\n", + "В Python существует ограничение на количество кадров, которые могут быть на стеке одновременно.\n", + "Если программа превышает предел, она вызывает ошибку времени выполнения.\n" ] }, { @@ -776,9 +771,9 @@ "id": "39fc5c31", "metadata": {}, "source": [ - "The traceback indicates that there were almost 3000 frames on the stack when the error occurred.\n", + "Traceback указывает, что в стеке было почти 3000 кадров, когда произошла ошибка.\n", "\n", - "If you encounter an infinite recursion by accident, review your function to confirm that there is a base case that does not make a recursive call. And if there is a base case, check whether you are guaranteed to reach it." + "Если вы столкнетесь с бесконечной рекурсией в случае случайности, просмотрите свою функцию, чтобы подтвердить, что существует базовый случай, который не делает рекурсивный вызов. И если есть базовый случай, проверьте, достигнете ли вы его добраться.\n" ] }, { @@ -786,15 +781,15 @@ "id": "45299414", "metadata": {}, "source": [ - "## Keyboard input\n", + "## Ввод клавиатуры\n", "\n", - "The programs we have written so far accept no input from the user. They\n", - "just do the same thing every time.\n", + "Программы, которые мы написали до сих пор, не принимают вклад от пользователя. Они\n", + "Просто делай то же самое каждый раз.\n", "\n", - "Python provides a built-in function called `input` that stops the\n", - "program and waits for the user to type something. When the user presses\n", - "*Return* or *Enter*, the program resumes and `input` returns what the user\n", - "typed as a string." + "Python предоставляет встроенную функцию, называемую `input`, которая останавливает\n", + "Программа и ожидает, пока пользователь что -то напечатает. Когда пользователь нажимает\n", + "*Return*или*enter*, программа возобновляется, и `input` возвращает, что пользователь\n", + "напечатано как строка.\n" ] }, { @@ -820,8 +815,8 @@ "id": "acf9ec53", "metadata": {}, "source": [ - "Before getting input from the user, you might want to display a prompt\n", - "telling the user what to type. `input` can take a prompt as an argument:" + "Прежде чем получить ввод от пользователя, вы можете отобразить подсказку\n", + "сообщать пользователю, что печатать. `input` может взять на себя приглашение в качестве аргумента:\n" ] }, { @@ -847,9 +842,10 @@ "id": "1b754b39", "metadata": {}, "source": [ - "The sequence `\\n` at the end of the prompt represents a **newline**, which is a special character that causes a line break -- that way the user's input appears below the prompt.\n", + "Последовательность `\n", + "`В конце подсказки представляет ** Newline **, который является специальным символом, который вызывает разрыв строки - таким образом, ввод пользователя появляется ниже подсказки.\n", "\n", - "If you expect the user to type an integer, you can use the `int` function to convert the return value to `int`." + "Если вы ожидаете, что пользователь вводит целое число, вы можете использовать функцию `int`, чтобы преобразовать возвращаемое значение в` int`.\n" ] }, { @@ -875,7 +871,7 @@ "id": "0a65f2af", "metadata": {}, "source": [ - "But if they type something that's not an integer, you'll get a runtime error." + "Но если они вводят что -то, что не является целым числом, вы получите ошибку времени выполнения.\n" ] }, { @@ -903,7 +899,7 @@ "id": "a4ce3ed5", "metadata": {}, "source": [ - "We will see how to handle this kind of error later." + "Посмотрим, как обработать эту ошибку позже.\n" ] }, { @@ -911,19 +907,19 @@ "id": "14c1d3dc", "metadata": {}, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "When a syntax or runtime error occurs, the error message contains a lot\n", - "of information, but it can be overwhelming. The most useful parts are\n", - "usually:\n", + "Когда происходит синтаксис или ошибка во время выполнения, сообщение об ошибке содержит много\n", + "информации, но это может быть ошеломляющим. Наиболее полезные детали - это\n", + "обычно:\n", "\n", - "- What kind of error it was, and\n", + "- Какая это была ошибка, и\n", "\n", - "- Where it occurred.\n", + "- Где это произошло.\n", "\n", - "Syntax errors are usually easy to find, but there are a few gotchas.\n", - "Errors related to spaces and tabs can be tricky because they are invisible\n", - "and we are used to ignoring them." + "Синтаксические ошибки обычно легко найти, но есть несколько GotChas.\n", + "Ошибки, связанные с пробелами и вкладками, могут быть сложными, потому что они невидимы\n", + "И мы привыкли игнорировать их.\n" ] }, { @@ -941,12 +937,12 @@ "id": "d1d06263", "metadata": {}, "source": [ - "In this example, the problem is that the second line is indented by one space.\n", - "But the error message points to `y`, which is misleading.\n", - "Error messages indicate where the problem was discovered, but the actual error might be earlier in the code.\n", + "В этом примере проблема заключается в том, что вторая строка содержит одно пространство.\n", + "Но сообщение об ошибке указывает на `y`, что вводит в заблуждение.\n", + "Сообщения об ошибках указывают, где была обнаружена проблема, но фактическая ошибка может быть ранее в коде.\n", "\n", - "The same is true of runtime errors. \n", - "For example, suppose you are trying to convert a ratio to decibels, like this:" + "То же самое относится и к ошибкам времени выполнения.\n", + "Например, предположим, что вы пытаетесь преобразовать соотношение в децибел, например:\n" ] }, { @@ -974,11 +970,11 @@ "id": "55914374", "metadata": {}, "source": [ - "The error message indicates line 5, but there is nothing wrong with that line.\n", - "The problem is in line 4, which uses integer division instead of floating-point division -- as a result, the value of `ratio` is `0`.\n", - "When we call `math.log10`, we get a `ValueError` with the message `math domain error`, because `0` is not in the \"domain\" of valid arguments for `math.log10`, because the logarithm of `0` is undefined.\n", + "Сообщение об ошибке указывает строку 5, но в этой строке нет ничего плохого.\n", + "Проблема в строке 4, которая использует целочисленное деление вместо деления с плавающей запятой-в результате значение «соотношение» равно `0`.\n", + "Когда мы называем `math.log10`, мы получаем` valueError` с сообщением `math Domain Error ', потому что« 0` не находится в «домене» действительных аргументов для `math.log10`, потому что логарифм` 0` не определен.\n", "\n", - "In general, you should take the time to read error messages carefully, but don't assume that everything they say is correct." + "В общем, вы должны потратить время на то, чтобы тщательно прочитать сообщения об ошибках, но не думайте, что все, что они говорят, правильно.\n" ] }, { @@ -986,62 +982,60 @@ "id": "8ffe690e", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**recursion:**\n", - "The process of calling the function that is currently executing.\n", + "** Рекурсия: **\n", + "Процесс вызова функции, которая в настоящее время выполняет.\n", "\n", - "**modulus operator:**\n", - "An operator, `%`, that works on integers and returns the remainder when one number is divided by another.\n", + "** Оператор модуля: **\n", + "Оператор, «%», который работает на целых числах и возвращает остаток, когда одно число разделено на другое.\n", "\n", - "**boolean expression:**\n", - "An expression whose value is either `True` or `False`.\n", + "** Логическое выражение: **\n", + "Выражение, значение которого либо `true`, либо` false '.\n", "\n", - "**relational operator:**\n", - "One of the operators that compares its operands: `==`, `!=`, `>`, `<`, `>=`, and `<=`.\n", + "** Реляционный оператор: **\n", + "Один из операторов, который сравнивает его операнды: `==`, `! =`, `>`, `<`, `> =` И `<=`.\n", "\n", - "**logical operator:**\n", - "One of the operators that combines boolean expressions, including `and`, `or`, and `not`.\n", + "** Логический оператор: **\n", + "Один из операторов, который сочетает в себе логические выражения, в том числе «и», «или» и «Не».\n", "\n", - "**conditional statement:**\n", - "A statement that controls the flow of execution depending on some condition.\n", + "** условное утверждение: **\n", + "Оператор, который контролирует поток выполнения в зависимости от какого -либо условия.\n", "\n", - "**condition:**\n", - "The boolean expression in a conditional statement that determines which branch runs.\n", + "**состояние:**\n", + "Логическое выражение в условном утверждении, которое определяет, какая ветвь работает.\n", "\n", - "**block:**\n", - "One or more statements indented to indicate they are part of another statement.\n", + "**блокировать:**\n", + "Одно или несколько утверждений отступают, чтобы указать, что они являются частью другого утверждения.\n", "\n", - "**branch:**\n", - "One of the alternative sequences of statements in a conditional statement.\n", + "**ветвь:**\n", + "Одна из альтернативных последовательностей утверждений в условном утверждении.\n", "\n", - "**chained conditional:**\n", - "A conditional statement with a series of alternative branches.\n", + "** Прикованные в цепных условиях: **\n", + "Условное утверждение с серией альтернативных ветвей.\n", "\n", - "**nested conditional:**\n", - "A conditional statement that appears in one of the branches of another conditional statement.\n", + "** Вложенное условное: **\n", + "Условное утверждение, которое появляется в одной из ветвей другого условного утверждения.\n", "\n", - "**recursive:**\n", - "A function that calls itself is recursive.\n", + "** рекурсивный: **\n", + "Функция, которая вызывает себя, является рекурсивной.\n", "\n", - "**base case:**\n", - "A conditional branch in a recursive function that does not make a recursive call.\n", + "** Базовый случай: **\n", + "Условная ветвь в рекурсивной функции, которая не делает рекурсивный вызов.\n", "\n", - "**infinite recursion:**\n", - "A recursion that doesn't have a base case, or never reaches it.\n", - "Eventually, an infinite recursion causes a runtime error.\n", + "** Бесконечная рекурсия: **\n", + "Рекурсия, у которой нет базового случая или никогда не достигает его.\n", + "В конце концов, бесконечная рекурсия вызывает ошибку времени выполнения.\n", "\n", - "**newline:**\n", - "A character that creates a line break between two parts of a string." + "** Newline: **\n", + "Персонаж, который создает разрыв линии между двумя частями струны.\n" ] }, { "cell_type": "markdown", "id": "8d783953", "metadata": {}, - "source": [ - "## Exercises" - ] + "source": [] }, { "cell_type": "code", @@ -1058,15 +1052,13 @@ "id": "02f9f1d7", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", - "\n", - "* Ask a virtual assistant, \"What are some uses of the modulus operator?\"\n", + "* Спросите виртуального помощника: «Каковы некоторые применения оператора модуля?»\n", "\n", - "* Python provides operators to compute the logical operations `and`, `or`, and `not`, but it doesn't have an operator that computes the exclusive `or` operation, usually written `xor`. Ask an assistant \"What is the logical xor operation and how do I compute it in Python?\"\n", + "* Python предоставляет операторам вычислять логические операции `и ',` или' и `not ', но у него нет оператора, который вычисляет эксклюзивную операцию` or', обычно написанную `xor '. Спросите помощника: «Какова логическая операция XOR и как я могу вычислить ее в Python?»\n", "\n", - "In this chapter, we saw two ways to write an `if` statement with three branches, using a chained conditional or a nested conditional.\n", - "You can use a virtual assistant to convert from one to the other.\n", - "For example, ask a VA, \"Convert this statement to a chained conditional.\"" + "В этой главе мы увидели два способа написать утверждение «если» с тремя ветвями, используя прикованные условные или вложенные условные.\n", + "Вы можете использовать виртуального помощника для преобразования из одного в другой.\n", + "Например, спросите VA: «Преобразовать это утверждение в прикованную условную».\n" ] }, { @@ -1092,7 +1084,7 @@ "id": "9c2a8466", "metadata": {}, "source": [ - "Ask a VA, \"Rewrite this statement with a single conditional.\"" + "Спросите VA: «Перепишите это утверждение с одним условным».\n" ] }, { @@ -1108,7 +1100,7 @@ "id": "e0fbed08", "metadata": {}, "source": [ - "See if a VA can simplify this unnecessary complexity." + "Посмотрите, может ли VA упростить эту ненужную сложность.\n" ] }, { @@ -1124,7 +1116,7 @@ "id": "74ef776d", "metadata": {}, "source": [ - "Here's an attempt at a recursive function that counts down by two." + "Вот попытка рекурсивной функции, которая считается двумя.\n" ] }, { @@ -1140,7 +1132,7 @@ "id": "77178e79", "metadata": {}, "source": [ - "It seems to work." + "Кажется, работает.\n" ] }, { @@ -1156,8 +1148,8 @@ "id": "c9d3a8dc", "metadata": {}, "source": [ - "But it has an error. Ask a virtual assistant what's wrong and how to fix it.\n", - "Paste the solution it provides back here and test it." + "Но у этого есть ошибка. Спросите виртуального помощника, что случилось и как это исправить.\n", + "Вставьте решение, которое он обеспечивает здесь и проверьте его.\n" ] }, { @@ -1165,10 +1157,10 @@ "id": "240a3888", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "The `time` module provides a function, also called `time`, that returns\n", - "returns the number of seconds since the \"Unix epoch\", which is January 1, 1970, 00:00:00 UTC (Coordinated Universal Time)." + "Модуль «Time» предоставляет функцию, также называемую «Time», которая возвращает\n", + "Возвращает количество секунд с момента «эпохи UNIX», которая составляет 1 января 1970 г., 00:00:00 UTC (скоординированное универсальное время).\n" ] }, { @@ -1184,7 +1176,7 @@ "id": "054c3197", "metadata": {}, "source": [ - "Use integer division and the modulus operator to compute the number of days since January 1, 1970 and the current time of day in hours, minutes, and seconds." + "Используйте целочисленное подразделение и оператор модуля для вычисления количества дней с 1 января 1970 года и текущего времени суток в часах, минутах и секундах.\n" ] }, { @@ -1194,7 +1186,7 @@ "tags": [] }, "source": [ - "You can read more about the `time` module at ." + "Вы можете прочитать больше о модуле `time` по адресу .\n" ] }, { @@ -1234,24 +1226,23 @@ "id": "6b1fd514", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "If you are given three sticks, you may or may not be able to arrange\n", - "them in a triangle. For example, if one of the sticks is 12 inches long\n", - "and the other two are one inch long, you will not be able to get the\n", - "short sticks to meet in the middle. For any three lengths, there is a\n", - "test to see if it is possible to form a triangle:\n", + "Если вам дают три палки, вы можете или не можете договориться\n", + "их в треугольнике. Например, если одна из палочек длиной 12 дюймов\n", + "а два других имеют длину один дюйм, вы не сможете получить\n", + "Короткие палки, чтобы встретиться в середине. Для любых трех длин есть\n", + "Проверьте, чтобы увидеть, возможно ли сформировать треугольник:\n", "\n", - "> If any of the three lengths is greater than the sum of the other two,\n", - "> then you cannot form a triangle. Otherwise, you can. (If the sum of\n", - "> two lengths equals the third, they form what is called a \"degenerate\"\n", - "> triangle.)\n", + "> Если какая -либо из трех длин больше, чем сумма двух других,\n", + "> Тогда вы не можете сформировать треугольник. В противном случае вы можете. (Если сумма\n", + "> Две длины равны третьей, они образуют так называемое «вырожденное»\n", + "> Треугольник.)\n", "\n", - "Write a function named `is_triangle` that takes three integers as\n", - "arguments, and that prints either \"Yes\" or \"No\", depending on\n", - "whether you can or cannot form a triangle from sticks with the given\n", - "lengths. Hint: Use a chained conditional.\n", - "\n" + "Напишите функцию с именем `is_triangle`, которая принимает три целых числа как\n", + "аргументы, и это печатает либо «да», либо «нет», в зависимости от\n", + "Можете ли вы или не можете сформировать треугольник из палочек с данным\n", + "длина Подсказка: используйте прикованные условные.\n" ] }, { @@ -1271,7 +1262,7 @@ "tags": [] }, "source": [ - "Test your function with the following cases." + "Проверьте свою функцию со следующими случаями.\n" ] }, { @@ -1319,10 +1310,10 @@ "id": "2ba42106", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "What is the output of the following program? Draw a stack diagram that\n", - "shows the state of the program when it prints the result." + "Каковы результаты следующей программы? Нарисуйте диаграмму стека, которая\n", + "показывает состояние программы, когда она печатает результат.\n" ] }, { @@ -1356,14 +1347,13 @@ "id": "bca9517d", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "The following exercises use the `jupyturtle` module, described in Chapter 4.\n", + "В следующих упражнениях используются модуль `jupyturtle`, описанный в главе 4.\n", "\n", - "Read the following function and see if you can figure out what it does.\n", - "Then run it and see if you got it right.\n", - "Adjust the values of `length`, `angle` and `factor` and see what effect they have on the result.\n", - "If you are not sure you understand how it works, try asking a virtual assistant." + "Прочитайте следующую функцию и посмотрите, сможете ли вы выяснить, что она делает.\n", + "Затем запустите его и посмотрите, правильно ли вы это поняли.\n", + "Отрегулируйте значения `length`,` angle 'и `фактор' и посмотрите, какой эффект они оказывают на результат.\n" ] }, { @@ -1387,30 +1377,30 @@ "id": "e525ba59", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Ask a virtual assistant \"What is the Koch curve?\"\n", + "Спросите виртуального помощника \"Что такое кривая Кох?\"\n", "\n", - "To draw a Koch curve with length `x`, all you\n", - "have to do is\n", + "Чтобы нарисовать кривую Кох с длиной `x`, все вы\n", + "должен сделать\n", "\n", - "1. Draw a Koch curve with length `x/3`.\n", + "1. Нарисуйте кривую кох с длиной `x/3`.\n", "\n", - "2. Turn left 60 degrees.\n", + "2. Поверните налево 60 градусов.\n", "\n", - "3. Draw a Koch curve with length `x/3`.\n", + "3. Нарисуйте кривую Кох с длиной `x/3`.\n", "\n", - "4. Turn right 120 degrees.\n", + "4. Поверните направо 120 градусов.\n", "\n", - "5. Draw a Koch curve with length `x/3`.\n", + "5. Нарисуйте кривую Кох с длиной `x/3`.\n", "\n", - "6. Turn left 60 degrees.\n", + "6. Поверните налево 60 градусов.\n", "\n", - "7. Draw a Koch curve with length `x/3`.\n", + "7. Нарисуйте кривую Кох с длиной `x/3`.\n", "\n", - "The exception is if `x` is less than `5` -- in that case, you can just draw a straight line with length `x`.\n", + "Исключение заключается в том, что `x` меньше, чем` 5` - в этом случае вы можете просто нарисовать прямую линию с длиной `x`.\n", "\n", - "Write a function called `koch` that takes `x` as an argument and draws a Koch curve with the given length.\n" + "Напишите функцию, называемую `koch`, которая принимает` x` как аргумент и рисует кривую Кох с заданной длиной.\n" ] }, { @@ -1426,7 +1416,7 @@ "id": "2991143a", "metadata": {}, "source": [ - "The result should look like this:" + "Результат должен выглядеть так:\n" ] }, { @@ -1444,7 +1434,7 @@ "tags": [] }, "source": [ - "Once you have koch working, you can use this loop to draw three Koch curves in the shape of a snowflake." + "После того, как у вас есть Koch, вы можете использовать эту петлю, чтобы нарисовать три кривые Koch в форме снежинки.\n" ] }, { @@ -1462,17 +1452,17 @@ "id": "4c964239", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Virtual assistants know about the functions in the `jupyturtle` module, but there are many versions of these functions, with different names, so a VA might not know which one you are talking about.\n", + "Виртуальные помощники знают о функциях в модуле `jupyturtle ', но есть много версий этих функций, с разными именами, поэтому VA может не знать, о каком вы говорите.\n", "\n", - "To solve this problem, you can provide additional information before you ask a question.\n", - "For example, you could start a prompt with \"Here's a program that uses the `jupyturtle` module,\" and then paste in one of the examples from this chapter.\n", - "After that, the VA should be able to generate code that uses this module.\n", + "Чтобы решить эту проблему, вы можете предоставить дополнительную информацию, прежде чем задать вопрос.\n", + "Например, вы можете начать подсказку с «Вот программа, которая использует модуль` jupyturtle », а затем вставить в один из примеров из этой главы.\n", + "После этого VA должен иметь возможность генерировать код, который использует этот модуль.\n", "\n", - "As an example, ask a VA for a program that draws a Sierpiński triangle.\n", - "The code you get should be a good starting place, but you might have to do some debugging.\n", - "If the first attempt doesn't work, you can tell the VA what happened and ask for help -- or you can debug it yourself." + "Например, спросите VA для программы, которая привлекает треугольник Sierpiński.\n", + "Код, который вы получаете, должен быть хорошей отправной точкой, но вам, возможно, придется провести некоторую отладку.\n", + "Если первая попытка не работает, вы можете рассказать VA, что случилось, и попросить о помощи - или вы можете отладить ее самостоятельно.\n" ] }, { @@ -1488,7 +1478,7 @@ "id": "6a95097a", "metadata": {}, "source": [ - "Here's what the result might look like, although the version you get might be different." + "Вот как может выглядеть результат, хотя версия, которую вы получаете, может быть другой.\n" ] }, { @@ -1514,13 +1504,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT] (https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik\n" ] } ], @@ -1546,4 +1536,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From e5f05dab03e0d04cdecb8fde9022889254cc7bac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:00:30 +0300 Subject: [PATCH 07/44] Translate chapter 7 notebook to Russian --- blank/chap07.ipynb | 369 ++++++++++++++++++++++----------------------- 1 file changed, 182 insertions(+), 187 deletions(-) diff --git a/blank/chap07.ipynb b/blank/chap07.ipynb index 22ea459..bb60fbb 100644 --- a/blank/chap07.ipynb +++ b/blank/chap07.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать печатную и электронную версии *Think Python 3e* на\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и на\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -27,15 +27,15 @@ "tags": [] }, "source": [ - "# Iteration and Search\n", + "# Итерации и поиск\n", "\n", - "In 1939 Ernest Vincent Wright published a 50,000 word novel called *Gadsby* that does not contain the letter \"e\". Since \"e\" is the most common letter in English, writing even a few words without using it is difficult.\n", - "To get a sense of how difficult, in this chapter we'll compute the fraction of English words have at least one \"e\".\n", + "В 1939 году Эрнест Винсент Райт опубликовал роман из 50 000 слов под названием *Gadsby*, в котором нет буквы \"e\". Поскольку \"e\" — самая распространённая буква в английском языке, написать даже несколько слов, не используя её, сложно.\n", + "Чтобы понять, насколько это сложно, в этой главе мы вычислим долю английских слов, в которых есть хотя бы одна \"e\".\n", "\n", - "For that, we'll use `for` statements to loop through the letters in a string and the words in a file, and we'll update variables in a loop to count the number of words that contain an \"e\".\n", - "We'll use the `in` operator to check whether a letter appears in a word, and you'll learn a programming pattern called a \"linear search\".\n", + "Для этого мы будем использовать инструкции `for`, чтобы перебирать буквы в строке и слова в файле, а также будем обновлять переменные в цикле, считая количество слов, содержащих \"e\".\n", + "Мы воспользуемся оператором `in`, чтобы проверить, встречается ли буква в слове, а также познакомимся с программным шаблоном под названием \"линейный поиск\".\n", "\n", - "As an exercise, you'll use these tools to solve a word puzzle called \"Spelling Bee\"." + "В качестве упражнения вы примените эти инструменты для решения головоломки \"Spelling Bee\"." ] }, { @@ -43,9 +43,9 @@ "id": "389f5162-0a8c-4cc7-99f1-a261e0b39006", "metadata": {}, "source": [ - "## Loops and strings\n", + "## Циклы и строки\n", "\n", - "In Chapter 3 we saw a `for` loop that uses the `range` function to display a sequence of numbers." + "В главе 3 мы видели цикл `for`, использующий функцию `range` для вывода последовательности чисел." ] }, { @@ -61,9 +61,9 @@ "id": "937a0af9-5486-4195-8e59-6f819db1cf3f", "metadata": {}, "source": [ - "This version uses the keyword argument `end` so the `print` function puts a space after each number rather than a newline.\n", + "В этой версии используется именованный аргумент `end`, поэтому функция `print` ставит пробел после каждого числа вместо новой строки.\n", "\n", - "We can also use a `for` loop to display the letters in a string." + "Мы также можем использовать цикл `for`, чтобы вывести буквы в строке." ] }, { @@ -79,10 +79,10 @@ "id": "72044436-ed85-407b-8821-9696648ec29c", "metadata": {}, "source": [ - "Notice that I changed the name of the variable from `i` to `letter`, which provides more information about the value it refers to.\n", - "The variable defined in a `for` loop is called the **loop variable**.\n", + "Обратите внимание, что я изменил имя переменной с `i` на `letter`, что даёт больше информации о значении, на которое она ссылается.\n", + "Переменная, определённая в заголовке цикла `for`, называется **переменной цикла**.\n", "\n", - "Now that we can loop through the letters in a word, we can check whether it contains the letter \"e\"." + "Теперь, когда мы можем перебирать буквы в слове, мы можем проверить, содержит ли оно букву \"e\"." ] }, { @@ -98,7 +98,7 @@ "id": "644b7df2-4528-48d9-a003-2d21fbefbaab", "metadata": {}, "source": [ - "Before we go on, let's encapsulate that loop in a function." + "Прежде чем продолжить, давайте заключим этот цикл в функцию." ] }, { @@ -114,7 +114,7 @@ "id": "31cfacd9-5721-457a-be40-80cf002723b2", "metadata": {}, "source": [ - "And let's make it a pure function that return `True` if the word contains an \"e\" and `False` otherwise." + "И сделаем её чистой функцией, которая возвращает `True`, если слово содержит \"e\", и `False` в противном случае." ] }, { @@ -130,7 +130,7 @@ "id": "8f45502e-6db3-4fcc-802c-c97398787dbd", "metadata": {}, "source": [ - "We can generalize it to take the word as a parameter." + "Мы можем обобщить её, передавая слово в качестве параметра." ] }, { @@ -146,7 +146,7 @@ "id": "590f4399-16d3-4f1c-93bc-b1fe7ce46633", "metadata": {}, "source": [ - "Now we can test it like this:" + "Теперь мы можем проверить её так:" ] }, { @@ -170,10 +170,10 @@ "id": "8adf1e92-435e-4b54-837a-bad603ebcafd", "metadata": {}, "source": [ - "## Reading the word list\n", + "## Чтение списка слов\n", "\n", - "To see how many words contain an \"e\", we'll need a word list.\n", - "The one we'll use is a list of about 114,000 official crosswords; that is, words that are considered valid in crossword puzzles and other word games. " + "Чтобы узнать, сколько слов содержит \"e\", нам понадобится список слов.\n", + "Мы будем использовать список примерно из 114 000 слов, официально допущенных в кроссворды и другие словесные игры." ] }, { @@ -183,7 +183,7 @@ "tags": [] }, "source": [ - "The following cell downloads the word list, which is a modified version of a list collected and contributed to the public domain by Grady Ward as part of the Moby lexicon project (see )." + "Следующая ячейка загружает список слов, который представляет собой модифицированную версию списка, собранного Грэйди Уордом и переданного в общественное достояние в рамках проекта Moby lexicon (см. )." ] }, { @@ -201,8 +201,8 @@ "id": "5b383a3c-d173-4a66-bf86-23b329032004", "metadata": {}, "source": [ - "The word list is in a file called `words.txt`, which is downloaded in the notebook for this chapter.\n", - "To read it, we'll use the built-in function `open`, which takes the name of the file as a parameter and returns a **file object** we can use to read the file." + "Список слов находится в файле `words.txt`, который загружается вместе с ноутбуком этой главы.\n", + "Чтобы его прочитать, мы воспользуемся встроенной функцией `open`, которая принимает имя файла и возвращает **файловый объект**, с помощью которого можно считывать файл." ] }, { @@ -218,7 +218,7 @@ "id": "4414d9b1-cb8e-472e-818c-0555e29b1ad5", "metadata": {}, "source": [ - "The file object provides a function called `readline`, which reads characters from the file until it gets to a newline and returns the result as a string:" + "Файловый объект предоставляет функцию `readline`, которая читает символы из файла до символа новой строки и возвращает результат в виде строки:" ] }, { @@ -234,14 +234,13 @@ "id": "d74e9fe9-117e-436a-ade3-3d08dfda2a00", "metadata": {}, "source": [ - "Notice that the syntax for calling `readline` is different from functions we've seen so far. That's because it is a **method**, which is a function associated with an object.\n", - "In this case `readline` is associated with the file object, so we call it using the name of the object, the dot operator, and the name of the method.\n", + "Обратите внимание, что синтаксис вызова `readline` отличается от тех функций, которые мы видели ранее. Дело в том, что это **метод**, то есть функция, связанная с объектом.\n", + "В данном случае `readline` связан с файловым объектом, поэтому мы вызываем его, используя имя объекта, оператор точки и имя метода.\n", "\n", - "The first word in the list is \"aa\", which is a kind of lava.\n", - "The sequence `\\n` represents the newline character that separates this word from the next.\n", + "Первое слово в списке — \"aa\", разновидность лавы.\n", + "Последовательность `\\n` обозначает символ новой строки, который отделяет это слово от следующего.\n", "\n", - "The file object keeps track of where it is in the file, so if you call\n", - "`readline` again, you get the next word:" + "Файловый объект отслеживает своё положение в файле, поэтому если вызвать `readline` снова, вы получите следующее слово:" ] }, { @@ -257,7 +256,7 @@ "id": "cd466fdb-38ce-4e5b-92c7-05dc23922005", "metadata": {}, "source": [ - "To remove the newline from the end of the word, we can use `strip`, which is a method associated with strings, so we can call it like this." + "Чтобы убрать перевод строки в конце слова, можно использовать `strip` — метод строк, который вызывается так." ] }, { @@ -273,10 +272,10 @@ "id": "6dda6bac-e02e-47ee-9bab-70cef8c27d7a", "metadata": {}, "source": [ - "`strip` removes whitespace characters -- including spaces, tabs, and newlines -- from the beginning and end of the string.\n", + "`strip` удаляет пробельные символы — включая пробелы, табуляции и переводы строк — в начале и в конце строки.\n", "\n", - "You can also use a file object as part of a `for` loop. \n", - "This program reads `words.txt` and prints each word, one per line:" + "Файловый объект можно также использовать в цикле `for`.\n", + "Эта программа читает `words.txt` и выводит каждое слово на отдельной строке:" ] }, { @@ -294,8 +293,8 @@ "id": "93e320a5-4827-487e-a8ce-216392f398a8", "metadata": {}, "source": [ - "Now that we can read the word list, the next step is to count them.\n", - "For that, we will need the ability to update variables." + "Теперь, когда мы умеем читать список слов, следующий шаг — их подсчитать.\n", + "Для этого нам понадобится возможность изменять значения переменных." ] }, { @@ -303,13 +302,12 @@ "id": "b63a6877", "metadata": {}, "source": [ - "## Updating variables\n", + "## Обновление переменных\n", "\n", - "As you may have discovered, it is legal to make more than one assignment\n", - "to the same variable.\n", - "A new assignment makes an existing variable refer to a new value (and stop referring to the old value).\n", + "Как вы, возможно, уже выяснили, допустимо присваивать значение одной и той же переменной несколько раз.\n", + "Новое присваивание заставляет существующую переменную ссылаться на новое значение (и перестать ссылаться на старое).\n", "\n", - "For example, here is an initial assignment that creates a variable." + "Например, вот первоначальное присваивание, которое создаёт переменную." ] }, { @@ -325,7 +323,7 @@ "id": "c9735982", "metadata": {}, "source": [ - "And here is an assignment that changes the value of a variable." + "А вот присваивание, которое изменяет значение переменной." ] }, { @@ -341,7 +339,7 @@ "id": "fbcd1092-ce06-47fc-9204-fce1c9a100a5", "metadata": {}, "source": [ - "The following figure shows what these assignments looks like in a state diagram." + "Следующий рисунок показывает, как эти присваивания выглядят на диаграмме состояний." ] }, { @@ -369,11 +367,10 @@ "id": "42b7b044-f83b-4483-9a24-64980c688c94", "metadata": {}, "source": [ - "The dotted arrow indicates that `x` no longer refers to `5`.\n", - "The solid arrow indicates that it now refers to `7`.\n", + "Пунктирная стрелка показывает, что `x` больше не ссылается на `5`.\n", + "Сплошная стрелка показывает, что теперь она ссылается на `7`.\n", "\n", - "A common kind of assignment is an **update**, where the new value of\n", - "the variable depends on the old." + "Распространённый вид присваивания — **обновление**, когда новое значение переменной зависит от старого." ] }, { @@ -399,9 +396,9 @@ "id": "d3025706", "metadata": {}, "source": [ - "This statement means \"get the current value of `x`, add one, and assign the result back to `x`.\"\n", + "Эта инструкция означает: «возьми текущее значение `x`, прибавь единицу и запиши результат обратно в `x`».\n", "\n", - "If you try to update a variable that doesn't exist, you get an error, because Python evaluates the expression on the right before it assigns a value to the variable on the left." + "Если попытаться обновить переменную, которой не существует, возникнет ошибка, потому что Python вычисляет выражение справа прежде, чем присвоить значение переменной слева." ] }, { @@ -419,8 +416,7 @@ "id": "03d3959f", "metadata": {}, "source": [ - "Before you can update a variable, you have to **initialize** it, usually\n", - "with a simple assignment:" + "Прежде чем обновлять переменную, её необходимо **инициализировать**, обычно простым присваиванием:" ] }, { @@ -436,9 +432,9 @@ "id": "374fb3d5", "metadata": {}, "source": [ - "Increasing the value of a variable is called an **increment**; decreasing the value is called a **decrement**.\n", - "Because these operations are so common, Python provides **augmented assignment operators** that update a variable more concisely.\n", - "For example, the `+=` operator increments a variable by the given amount." + "Увеличение значения переменной называется **инкрементом**, уменьшение — **декрементом**.\n", + "Поскольку эти операции очень распространены, Python предоставляет **операторы составного присваивания**, позволяющие обновлять переменную короче.\n", + "Например, оператор `+=` увеличивает переменную на указанную величину." ] }, { @@ -454,7 +450,7 @@ "id": "3f4eedf1", "metadata": {}, "source": [ - "There are augmented assignment operators for the other arithmetic operators, including `-=` and `*=`." + "Для других арифметических операторов тоже есть составные операторы присваивания, включая `-=` и `*=`." ] }, { @@ -462,9 +458,9 @@ "id": "70eeef60-6a34-403a-96bb-aa5c4574a5fe", "metadata": {}, "source": [ - "## Looping and counting\n", + "## Цикл и подсчёт\n", "\n", - "The following program counts the number of words in the word list." + "Следующая программа подсчитывает количество слов в списке." ] }, { @@ -480,9 +476,9 @@ "id": "9bd83ddd", "metadata": {}, "source": [ - "It starts by initializing `total` to `0`.\n", - "Each time through the loop, it increments `total` by `1`.\n", - "So when the loop exits, `total` refers to the total number of words." + "Она начинается с инициализации переменной `total` значением `0`.\n", + "Каждый проход цикла увеличивает `total` на `1`.\n", + "Когда цикл заканчивается, `total` содержит общее число слов." ] }, { @@ -498,9 +494,9 @@ "id": "54904394", "metadata": {}, "source": [ - "A variable like this, used to count the number of times something happens, is called a **counter**.\n", + "Такая переменная, используемая для подсчёта количества происшествий, называется **счётчиком**.\n", "\n", - "We can add a second counter to the program to keep track of the number of words that contain an \"e\"." + "Мы можем добавить второй счётчик, чтобы отслеживать количество слов, содержащих букву «e»." ] }, { @@ -516,7 +512,7 @@ "id": "ab73c1e3", "metadata": {}, "source": [ - "Let's see how many words contain an \"e\"." + "Посмотрим, сколько слов содержит «e»." ] }, { @@ -532,7 +528,7 @@ "id": "d2262e64", "metadata": {}, "source": [ - "As a percentage of `total`, about two-thirds of the words use the letter \"e\"." + "В процентах от `total` примерно две трети слов используют букву «e»." ] }, { @@ -548,7 +544,7 @@ "id": "fe002dde", "metadata": {}, "source": [ - "So you can understand why it's difficult to craft a book without using any such words." + "Теперь вы понимаете, почему сложно написать книгу, не используя такие слова." ] }, { @@ -556,10 +552,10 @@ "id": "632a992f", "metadata": {}, "source": [ - "## The in operator\n", + "## Оператор in\n", "\n", - "The version of `has_e` we wrote in this chapter is more complicated than it needs to be.\n", - "Python provides an operator, `in`, that checks whether a character appears in a string." + "Версия `has_e`, которую мы написали в этой главе, сложнее, чем нужно.\n", + "Python предоставляет оператор `in`, который проверяет, встречается ли символ в строке." ] }, { @@ -575,7 +571,7 @@ "id": "ede36fe9", "metadata": {}, "source": [ - "So we can rewrite `has_e` like this." + "Поэтому мы можем переписать `has_e` так." ] }, { @@ -591,7 +587,7 @@ "id": "f86f6fc7", "metadata": {}, "source": [ - "And because the conditional of the `if` statement has a boolean value, we can eliminate the `if` statement and return the boolean directly." + "И поскольку условие оператора `if` уже имеет булево значение, можно убрать `if` и возвращать булево значение напрямую." ] }, { @@ -607,8 +603,8 @@ "id": "f2a05319", "metadata": {}, "source": [ - "We can simplify this function even more using the method `lower`, which converts the letters in a string to lowercase.\n", - "Here's an example." + "Эту функцию можно ещё упростить, использовав метод `lower`, который переводит буквы строки в нижний регистр.\n", + "Вот пример." ] }, { @@ -624,7 +620,7 @@ "id": "57aa625a", "metadata": {}, "source": [ - "`lower` makes a new string -- it does not modify the existing string -- so the value of `word` is unchanged. " + "`lower` создаёт новую строку — он не изменяет существующую, — поэтому значение `word` остаётся прежним." ] }, { @@ -640,7 +636,7 @@ "id": "9f0bd075", "metadata": {}, "source": [ - "Here's how we can use `lower` in `has_e`." + "Вот как можно использовать `lower` в `has_e`." ] }, { @@ -672,10 +668,10 @@ "id": "1c39cb6b", "metadata": {}, "source": [ - "## Search\n", + "## Поиск\n", "\n", - "Based on this simpler version of `has_e`, let's write a more general function called `uses_any` that takes a second parameter that is a string of letters.\n", - "If returns `True` if the word uses any of the letters and `False` otherwise." + "На основе упрощённой версии `has_e` напишем более общую функцию `uses_any`, принимающую вторым параметром строку букв.\n", + "Она возвращает `True`, если слово использует любую из этих букв, и `False` в противном случае." ] }, { @@ -691,7 +687,7 @@ "id": "dc2d6290", "metadata": {}, "source": [ - "Here's an example where the result is `True`." + "Вот пример, в котором результат `True`." ] }, { @@ -707,7 +703,7 @@ "id": "2c3c1553", "metadata": {}, "source": [ - "And another where it is `False`." + "А вот пример, где результат `False`." ] }, { @@ -723,7 +719,7 @@ "id": "b2acc611", "metadata": {}, "source": [ - "`uses_any` converts `word` and `letters` to lowercase, so it works with any combination of cases. " + "`uses_any` переводит `word` и `letters` в нижний регистр, поэтому работает при любом сочетании заглавных и строчных букв." ] }, { @@ -739,13 +735,13 @@ "id": "673786a5", "metadata": {}, "source": [ - "The structure of `uses_any` is similar to `has_e`.\n", - "It loops through the letters in `word` and checks them one at a time.\n", - "If it finds one that appears in `letters`, it returns `True` immediately.\n", - "If it gets all the way through the loop without finding any, it returns `False`.\n", + "Структура `uses_any` похожа на `has_e`.\n", + "Она перебирает буквы слова и проверяет их по одной.\n", + "Если встречается буква из `letters`, функция немедленно возвращает `True`.\n", + "Если цикл завершается, не найдя ни одной, возвращается `False`.\n", "\n", - "This pattern is called a **linear search**.\n", - "In the exercises at the end of this chapter, you'll write more functions that use this pattern." + "Такой шаблон называется **линейным поиском**.\n", + "В упражнениях в конце главы вы напишете ещё функции с использованием этого шаблона." ] }, { @@ -755,9 +751,9 @@ "source": [ "## Doctest\n", "\n", - "In [Chapter 4](section_docstring) we used a docstring to document a function -- that is, to explain what it does.\n", - "It is also possible to use a docstring to *test* a function.\n", - "Here's a version of `uses_any` with a docstring that includes tests." + "В [главе 4](section_docstring) мы использовали docstring для документирования функции — то есть чтобы объяснить, что она делает.\n", + "Docstring можно также использовать для *тестирования* функции.\n", + "Вот версия `uses_any` с docstring, который содержит тесты." ] }, { @@ -773,15 +769,15 @@ "id": "2871d018", "metadata": {}, "source": [ - "Each test begins with `>>>`, which is used as a prompt in some Python environments to indicate where the user can type code.\n", - "In a doctest, the prompt is followed by an expression, usually a function call.\n", - "The following line indicates the value the expression should have if the function works correctly.\n", + "Каждый тест начинается с `>>>`, что используется в некоторых средах Python как приглашение, куда пользователь может вводить код.\n", + "В doctest за приглашением следует выражение, обычно вызов функции.\n", + "Следующая строка указывает значение, которое должно получиться, если функция работает правильно.\n", "\n", - "In the first example, `'banana'` uses `'a'`, so the result should be `True`.\n", - "In the second example, `'apple'` does not use any of `'xyz'`, so the result should be `False`.\n", + "В первом примере `'banana'` содержит букву `'a'`, поэтому результат должен быть `True`.\n", + "Во втором примере `'apple'` не содержит ни одной из букв `'xyz'`, поэтому результат должен быть `False`.\n", "\n", - "To run these tests, we have to import the `doctest` module and run a function called `run_docstring_examples`.\n", - "To make this function easier to use, I wrote the following function, which takes a function object as an argument." + "Чтобы запустить эти тесты, нужно импортировать модуль `doctest` и вызвать функцию `run_docstring_examples`.\n", + "Чтобы было удобнее, я написал следующую функцию, принимающую объект функции в качестве аргумента." ] }, { @@ -797,8 +793,7 @@ "id": "79e3de21", "metadata": {}, "source": [ - "We haven't learned about `globals` and `__name__` yet -- you can ignore them.\n", - "Now we can test `uses_any` like this." + "Мы ещё не изучали `globals` и `__name__` — можете их игнорировать. Теперь мы можем протестировать `uses_any` вот так." ] }, { @@ -814,12 +809,12 @@ "id": "432d8c31", "metadata": {}, "source": [ - "`run_doctests` finds the expressions in the docstring and evaluates them.\n", - "If the result is the expected value, the test **passes**.\n", - "Otherwise it **fails**.\n", + "`run_doctests` находит выражения в docstring и вычисляет их.\n", + "Если результат соответствует ожидаемому значению, тест **проходит**.\n", + "Иначе он **проваливается**.\n", "\n", - "If all tests pass, `run_doctests` displays no output -- in that case, no news is good news.\n", - "To see what happens when a test fails, here's an incorrect version of `uses_any`." + "Если все тесты прошли, `run_doctests` ничего не выводит — отсутствие сообщений означает, что всё хорошо.\n", + "Чтобы увидеть, что происходит при неудачном тесте, вот некорректная версия `uses_any`." ] }, { @@ -835,7 +830,7 @@ "id": "34b78be4", "metadata": {}, "source": [ - "And here's what happens when we test it." + "И вот что происходит, когда мы её тестируем." ] }, { @@ -851,9 +846,9 @@ "id": "473aa6ec", "metadata": {}, "source": [ - "The output includes the example that failed, the value the function was expected to produce, and the value the function actually produced.\n", + "В вывод включается пример, который не прошёл, ожидаемое значение и фактический результат работы функции.\n", "\n", - "If you are not sure why this test failed, you'll have a chance to debug it as an exercise." + "Если вы не понимаете, почему тест не прошёл, у вас будет возможность разобраться с этим в упражнении." ] }, { @@ -861,40 +856,40 @@ "id": "382c134e", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**loop variable:**\n", - "A variable defined in the header of a `for` loop.\n", + "**переменная цикла:**\n", + "Переменная, определённая в заголовке цикла `for`.\n", "\n", - "**file object:**\n", - "An object that represents an open file and keeps track of which parts of the file have been read or written.\n", + "**файловый объект:**\n", + "Объект, представляющий открытый файл и отслеживающий, какие части файла уже прочитаны или записаны.\n", "\n", - "**method:**\n", - " A function that is associated with an object and called using the dot operator.\n", + "**метод:**\n", + " Функция, связанная с объектом и вызываемая через точку.\n", "\n", - "**update:**\n", - "An assignment statement that give a new value to a variable that already exists, rather than creating a new variables.\n", + "**обновление:**\n", + "Оператор присваивания, который задаёт новое значение существующей переменной, а не создаёт новую.\n", "\n", - "**initialize:**\n", - "Create a new variable and give it a value.\n", + "**инициализация:**\n", + "Создание новой переменной и присвоение ей значения.\n", "\n", - "**increment:**\n", - "Increase the value of a variable.\n", + "**инкремент:**\n", + "Увеличение значения переменной.\n", "\n", - "**decrement:**\n", - "Decrease the value of a variable.\n", + "**декремент:**\n", + "Уменьшение значения переменной.\n", "\n", - "**counter:**\n", - " A variable used to count something, usually initialized to zero and then incremented.\n", + "**счётчик:**\n", + " Переменная, используемая для подсчёта чего-либо, обычно инициализируется нулём и затем увеличивается.\n", "\n", - "**linear search:**\n", - "A computational pattern that searches through a sequence of elements and stops what it finds what it is looking for.\n", + "**линейный поиск:**\n", + "Вычислительный шаблон, который проходит по последовательности элементов и останавливается, когда находит искомое.\n", "\n", - "**pass:**\n", - "If a test runs and the result is as expected, the test passes.\n", + "**успех (pass):**\n", + "Тест проходит, если результат соответствует ожидаемому.\n", "\n", - "**fail:**\n", - "If a test runs and the result is not as expected, the test fails." + "**неудача (fail):**\n", + "Тест не проходит, если результат отличается от ожидаемого." ] }, { @@ -902,7 +897,7 @@ "id": "0a2b3510-e8d3-439b-a771-a4a58db6ac59", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -920,9 +915,9 @@ "id": "8e8606b8-9a48-4cbd-a0b0-ea848666c77d", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "In `uses_any`, you might have noticed that the first `return` statement is inside the loop and the second is outside." + "В `uses_any` вы могли заметить, что первый оператор `return` находится внутри цикла, а второй — снаружи." ] }, { @@ -938,7 +933,7 @@ "id": "e1920737-b485-4823-ac20-c1e35aa93e7f", "metadata": {}, "source": [ - "When people first write functions like this, it is a common error to put both `return` statements inside the loop, like this." + "Когда люди впервые пишут такие функции, они часто ошибочно помещают оба оператора `return` внутрь цикла, вот так." ] }, { @@ -954,7 +949,7 @@ "id": "d9b46591-6c80-4ff8-9378-e9318ce5e429", "metadata": {}, "source": [ - "Ask a virtual assistant what's wrong with this version." + "Спросите виртуального помощника, что не так с этой версией." ] }, { @@ -962,12 +957,12 @@ "id": "99eff99e", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function named `uses_none` that takes a word and a string of forbidden letters, and returns `True` if the word does not use any of the forbidden letters.\n", + "Напишите функцию `uses_none`, которая принимает слово и строку запрещённых букв и возвращает `True`, если слово не использует ни одной из этих букв.\n", "\n", - "Here's an outline of the function that includes two doctests.\n", - "Fill in the function so it passes these tests, and add at least one more doctest." + "Ниже приведён шаблон функции с двумя doctest.\n", + "Заполните функцию так, чтобы она проходила эти тесты, и добавьте как минимум ещё один." ] }, { @@ -1001,12 +996,12 @@ "id": "9465b09f-0c62-49f6-bbe2-365ecf1717ef", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `uses_only` that takes a word and a string of letters, and that returns `True` if the word contains only letters in the string.\n", + "Напишите функцию `uses_only`, которая принимает слово и строку букв и возвращает `True`, если слово состоит только из букв из этой строки.\n", "\n", - "Here's an outline of the function that includes two doctests.\n", - "Fill in the function so it passes these tests, and add at least one more doctest." + "Ниже приведён шаблон функции с двумя doctest.\n", + "Заполните функцию так, чтобы она проходила эти тесты, и добавьте как минимум ещё один." ] }, { @@ -1040,12 +1035,12 @@ "id": "74259f36", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `uses_all` that takes a word and a string of letters, and that returns `True` if the word contains all of the letters in the string at least once.\n", + "Напишите функцию `uses_all`, которая принимает слово и строку букв и возвращает `True`, если слово содержит все буквы из строки хотя бы по одному разу.\n", "\n", - "Here's an outline of the function that includes two doctests.\n", - "Fill in the function so it passes these tests, and add at least one more doctest." + "Ниже приведён шаблон функции с двумя doctest.\n", + "Заполните функцию так, чтобы она проходила эти тесты, и добавьте как минимум ещё один." ] }, { @@ -1079,21 +1074,21 @@ "id": "7210adfa", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "*The New York Times* publishes a daily puzzle called \"Spelling Bee\" that challenges readers to spell as many words as possible using only seven letters, where one of the letters is required.\n", - "The words must have at least four letters.\n", + "*The New York Times* публикует ежедневную головоломку «Spelling Bee», в которой читателям предлагается составлять как можно больше слов, используя только семь букв, причём одна из них обязательна.\n", + "Слова должны состоять как минимум из четырёх букв.\n", "\n", - "For example, on the day I wrote this, the letters were `ACDLORT`, with `R` as the required letter.\n", - "So \"color\" is an acceptable word, but \"told\" is not, because it does not use `R`, and \"rat\" is not because it has only three letters.\n", - "Letters can be repeated, so \"ratatat\" is acceptable.\n", + "Например, в день, когда я писал это, буквы были `ACDLORT`, а обязательной — `R`.\n", + "Так что «color» — подходящее слово, а «told» нет, потому что в нём нет `R`, и «rat» тоже нет, так как оно состоит всего из трёх букв.\n", + "Буквы могут повторяться, поэтому «ratatat» допустимо.\n", "\n", - "Write a function called `check_word` that checks whether a given word is acceptable.\n", - "It should take as parameters the word to check, a string of seven available letters, and a string containing the single required letter.\n", - "You can use the functions you wrote in previous exercises.\n", + "Напишите функцию `check_word`, которая проверяет, удовлетворяет ли заданное слово условиям.\n", + "Она должна принимать само слово, строку из семи доступных букв и строку с обязательной буквой.\n", + "Вы можете использовать функции из предыдущих упражнений.\n", "\n", - "Here's an outline of the function that includes doctests.\n", - "Fill in the function and then check that all tests pass." + "Ниже приведён шаблон функции с doctest.\n", + "Заполните функцию и проверьте, что все тесты проходят." ] }, { @@ -1127,18 +1122,18 @@ "id": "0b9589fc", "metadata": {}, "source": [ - "According to the \"Spelling Bee\" rules,\n", + "Согласно правилам «Spelling Bee»,\n", "\n", - "* Four-letter words are worth 1 point each.\n", + "* Слова из четырёх букв стоят по 1 очку каждое.\n", "\n", - "* Longer words earn 1 point per letter.\n", + "* Более длинные слова приносят по 1 очку за каждую букву.\n", "\n", - "* Each puzzle includes at least one \"pangram\" which uses every letter. These are worth 7 extra points!\n", + "* В каждой головоломке есть хотя бы один «панграм», который использует все буквы. За такие слова дают дополнительно 7 очков!\n", "\n", - "Write a function called `score_word` that takes a word and a string of available letters and returns its score.\n", - "You can assume that the word is acceptable.\n", + "Напишите функцию `score_word`, которая принимает слово и строку доступных букв и возвращает его счёт.\n", + "Можно считать, что слово допустимо.\n", "\n", - "Again, here's an outline of the function with doctests." + "Ниже снова приведён шаблон функции с doctest." ] }, { @@ -1174,7 +1169,7 @@ "tags": [] }, "source": [ - "When all of your functions pass their tests, use the following loop to search the word list for acceptable words and add up their scores." + "Когда все ваши функции проходят тесты, используйте следующий цикл, чтобы просмотреть список слов и сложить очки за подходящие слова." ] }, { @@ -1194,9 +1189,9 @@ "tags": [] }, "source": [ - "Visit the \"Spelling Bee\" page at and type in the available letters for the day. The letter in the middle is required.\n", + "Зайдите на страницу «Spelling Bee» по адресу и введите доступные на сегодня буквы. Буква в центре обязательна.\n", "\n", - "I found a set of letters that spells words with a total score of 5820. Can you beat that? Finding the best set of letters might be too hard -- you have to be a realist." + "Мне удалось подобрать набор букв, которые дают суммарный счёт 5820. Сможете ли вы превзойти этот результат? Найти лучший набор может оказаться слишком сложно — будьте реалистами." ] }, { @@ -1204,12 +1199,12 @@ "id": "9ae466ed", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "You might have noticed that the functions you wrote in the previous exercises had a lot in common.\n", - "In fact, they are so similar you can often use one function to write another.\n", + "Вы могли заметить, что функции из предыдущих упражнений во многом похожи.\n", + "На самом деле они настолько схожи, что часто одну функцию можно написать с помощью другой.\n", "\n", - "For example, if a word uses none of a set forbidden letters, that means it doesn't use any. So we can write a version of `uses_none` like this." + "Например, если слово не использует ни одной из запрещённых букв, значит, оно не использует их вообще. Поэтому можно написать `uses_none` так." ] }, { @@ -1235,8 +1230,8 @@ "id": "32aa2c09", "metadata": {}, "source": [ - "There is also a similarity between `uses_only` and `uses_all` that you can take advantage of.\n", - "If you have a working version of `uses_only`, see if you can write a version of `uses_all` that calls `uses_only`." + "Сходство есть и между `uses_only` и `uses_all`, чем можно воспользоваться.\n", + "Если у вас есть рабочая версия `uses_only`, попробуйте написать вариант `uses_all`, который вызывает `uses_only`." ] }, { @@ -1244,11 +1239,11 @@ "id": "fa758462", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "If you got stuck on the previous question, try asking a virtual assistant, \"Given a function, `uses_only`, which takes two strings and checks that the first uses only the letters in the second, use it to write `uses_all`, which takes two strings and checks whether the first uses all the letters in the second, allowing repeats.\"\n", + "Если вы застряли на предыдущем задании, спросите виртуального помощника: «Имея функцию `uses_only`, которая принимает две строки и проверяет, что первая использует только буквы из второй, как написать `uses_all`, которая принимает две строки и проверяет, использует ли первая все буквы из второй, допуская повторы?»\n", "\n", - "Use `run_doctests` to check the answer." + "Используйте `run_doctests`, чтобы проверить ответ." ] }, { @@ -1274,13 +1269,13 @@ "id": "18f407b3", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Now let's see if we can write `uses_all` based on `uses_any`.\n", + "Теперь давайте посмотрим, получится ли написать `uses_all` на основе `uses_any`.\n", "\n", - "Ask a virtual assistant, \"Given a function, `uses_any`, which takes two strings and checks whether the first uses any of the letters in the second, can you use it to write `uses_all`, which takes two strings and checks whether the first uses all the letters in the second, allowing repeats.\"\n", + "Спросите виртуального помощника: «Имея функцию `uses_any`, которая принимает две строки и проверяет, использует ли первая любую из букв второй, можно ли с её помощью написать `uses_all`, которая проверяет, использует ли первая все буквы второй, допускаются ли повторы?»\n", "\n", - "If it says it can, be sure to test the result!" + "Если помощник даст ответ, обязательно проверьте его!" ] }, { @@ -1314,13 +1309,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3-е издание](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -1346,4 +1341,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 011cccad7fd28ccc923ac4715f25ee2928478216 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:01:29 +0300 Subject: [PATCH 08/44] Translate text cells in chap08 to Russian --- blank/chap08.ipynb | 456 ++++++++++++++++++++++----------------------- 1 file changed, 228 insertions(+), 228 deletions(-) diff --git a/blank/chap08.ipynb b/blank/chap08.ipynb index 00a2a91..b391447 100644 --- a/blank/chap08.ipynb +++ b/blank/chap08.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -25,14 +25,14 @@ "id": "9d97603b", "metadata": {}, "source": [ - "# Strings and Regular Expressions\n", + "# Струны и регулярные выражения\n", "\n", - "Strings are not like integers, floats, and booleans. A string is a **sequence**, which means it contains multiple values in a particular order.\n", - "In this chapter we'll see how to access the values that make up a string, and we'll use functions that process strings.\n", + "Строки не похожи на целые числа, поплавки и логические.Строка - это ** последовательность **, что означает, что она содержит несколько значений в определенном порядке.\n", + "В этой главе мы увидим, как получить доступ к значениям, которые составляют строку, и мы будем использовать функции, которые обрабатывают строки.\n", "\n", - "We'll also use regular expressions, which are a powerful tool for finding patterns in a string and performing operations like search and replace.\n", + "Мы также будем использовать регулярные выражения, которые являются мощным инструментом для поиска шаблонов в строке и выполнения операций, таких как поиск и замена.\n", "\n", - "As an exercise, you'll have a chance to apply these tools to a word game called Wordle." + "В качестве упражнения у вас будет возможность применить эти инструменты к игре Word под названием Wordle." ] }, { @@ -40,13 +40,13 @@ "id": "1280dd83", "metadata": {}, "source": [ - "## A string is a sequence\n", + "## строка - это последовательность\n", "\n", - "A string is a sequence of characters. A **character** can be a letter (in almost any alphabet), a digit, a punctuation mark, or white space.\n", + "Строка - это последовательность символов.** символ ** может быть буквой (практически в любом алфавите), цифра, отметка пунктуации или белое пространство.\n", "\n", - "You can select a character from a string with the bracket operator.\n", - "This example statement selects character number 1 from `fruit` and\n", - "assigns it to `letter`:" + "Вы можете выбрать символ из строки с оператором кронштейна.\n", + "Этот пример оператора выбирает символ номера 1 из `fruit` и\n", + "назначает это `letter`:" ] }, { @@ -62,8 +62,8 @@ "id": "a307e429", "metadata": {}, "source": [ - "The expression in brackets is an **index**, so called because it *indicates* which character in the sequence to select.\n", - "But the result might not be what you expect." + "Выражение в скобках - это ** индекс **, так называемый, потому что оно*указывает*какой символ в последовательности выбрать.\n", + "Но результат может быть не то, что вы ожидаете." ] }, { @@ -79,8 +79,8 @@ "id": "57c13319", "metadata": {}, "source": [ - "The letter with index `1` is actually the second letter of the string.\n", - "An index is an offset from the beginning of the string, so the offset of the first letter is `0`." + "Письмо с индексом `1` на самом деле является второй буквой строки.\n", + "Индекс - это смещение с начала строки, поэтому смещение первой буквы - `0`." ] }, { @@ -96,9 +96,9 @@ "id": "57d8e54c", "metadata": {}, "source": [ - "You can think of `'b'` as the 0th letter of `'banana'` -- pronounced \"zero-eth\".\n", + "Вы можете думать о `'b'` как о 0-й букве `'banana'`-произносится «Zero-eth».\n", "\n", - "The index in brackets can be a variable." + "Индекс в скобках может быть переменной." ] }, { @@ -114,7 +114,7 @@ "id": "9630e2e7", "metadata": {}, "source": [ - "Or an expression that contains variables and operators." + "Или выражение, которое содержит переменные и операторы." ] }, { @@ -130,7 +130,7 @@ "id": "939b602d", "metadata": {}, "source": [ - "But the value of the index has to be an integer -- otherwise you get a `TypeError`." + "Но значение индекса должно быть целым числом - в противном случае вы получаете `TypeError`." ] }, { @@ -148,7 +148,7 @@ "id": "3f0f7e3a", "metadata": {}, "source": [ - "As we saw in Chapter 1, we can use the built-in function `len` to get the length of a string." + "Как мы видели в главе 1, мы можем использовать встроенную функцию `len`, чтобы получить длину строки." ] }, { @@ -164,7 +164,7 @@ "id": "29013c47", "metadata": {}, "source": [ - "To get the last letter of a string, you might be tempted to write this:" + "Чтобы получить последнюю букву строки, у вас может возникнуть соблазн написать это:" ] }, { @@ -182,7 +182,7 @@ "id": "b87e09bd", "metadata": {}, "source": [ - "But that causes an `IndexError` because there is no letter in `'banana'` with the index 6. Because we started counting at `0`, the six letters are numbered `0` to `5`. To get the last character, you have to subtract `1` from `n`:" + "Но это вызывает `IndexError`, поскольку в `'banana'` с индексом 600000 не будет буквы. Поскольку мы начали подсчитать на `0`, шесть букв пронумерованы `0` до `5`. Чтобы получить последний персонаж, вы должны вычесть `1` из `n`:" ] }, { @@ -198,8 +198,8 @@ "id": "3c79dcec", "metadata": {}, "source": [ - "But there's an easier way.\n", - "To get the last letter in a string, you can use a negative index, which counts backward from the end. " + "Но есть более простой способ.\n", + "Чтобы получить последнюю букву в строке, вы можете использовать отрицательный индекс, который считается отсталым от конца." ] }, { @@ -215,7 +215,7 @@ "id": "5677b727", "metadata": {}, "source": [ - "The index `-1` selects the last letter, `-2` selects the second to last, and so on." + "Индекс `-1` выбирает последнюю букву, `-2` выбирает второе -последнее и так далее." ] }, { @@ -223,10 +223,10 @@ "id": "8392a12a", "metadata": {}, "source": [ - "## String slices\n", + "## Строки\n", "\n", - "A segment of a string is called a **slice**.\n", - "Selecting a slice is similar to selecting a character." + "Сегмент строки называется ** среза **.\n", + "Выбор среза аналогичен выбору персонажа." ] }, { @@ -242,9 +242,9 @@ "id": "5cc12531", "metadata": {}, "source": [ - "The operator `[n:m]` returns the part of the string from the `n`th\n", - "character to the `m`th character, including the first but excluding the second.\n", - "This behavior is counterintuitive, but it might help to imagine the indices pointing *between* the characters, as in this figure:" + "Оператор `[n:m]` возвращает часть строки из `n` -й\n", + "Персонаж для `m` -го персонажа, в том числе первый, но исключая второе.\n", + "Такое поведение нелогично, но оно может помочь представить показатели, указывающие * между * символами, как на этом рисунке:" ] }, { @@ -272,10 +272,10 @@ "id": "c391abbf", "metadata": {}, "source": [ - "For example, the slice `[3:6]` selects the letters `ana`, which means that `6` is legal as part of a slice, but not legal as an index.\n", + "Например, Slice `[3:6]` выбирает буквы `ana`, что означает, что `6` является законным как часть среза, но не легальный в качестве индекса.\n", "\n", "\n", - "If you omit the first index, the slice starts at the beginning of the string." + "Если вы опустите первый индекс, ломтик начинается в начале строки." ] }, { @@ -291,7 +291,7 @@ "id": "1bd7dcb1", "metadata": {}, "source": [ - "If you omit the second index, the slice goes to the end of the string:" + "Если вы опустите второй индекс, ломтик переходит к концу строки:" ] }, { @@ -307,7 +307,7 @@ "id": "4701123b", "metadata": {}, "source": [ - "If the first index is greater than or equal to the second, the result is an **empty string**, represented by two quotation marks:" + "Если первый индекс больше или равен второму, результатом является ** пустая строка **, представленная двумя кавычками:" ] }, { @@ -323,10 +323,10 @@ "id": "d12735ab", "metadata": {}, "source": [ - "An empty string contains no characters and has length 0.\n", + "Пустая строка не содержит символов и имеет длину 0.\n", "\n", - "Continuing this example, what do you think `fruit[:]` means? Try it and\n", - "see." + "Продолжая этот пример, что, по вашему мнению, означает `fruit[:]`?Попробуйте и\n", + "видеть." ] }, { @@ -344,10 +344,10 @@ "id": "918d3dd0", "metadata": {}, "source": [ - "## Strings are immutable\n", + "## струны неизменны\n", "\n", - "It is tempting to use the `[]` operator on the left side of an\n", - "assignment, with the intention of changing a character in a string, like this:" + "Заманчиво использовать оператора `[]` на левой стороне\n", + "назначение, с намерением изменить символ в строке, например:" ] }, { @@ -365,13 +365,13 @@ "id": "df3dd7d1", "metadata": {}, "source": [ - "The result is a `TypeError`.\n", - "In the error message, the \"object\" is the string and the \"item\" is the character\n", - "we tried to assign.\n", - "For now, an **object** is the same thing as a value, but we will refine that definition later.\n", + "Результатом является `TypeError`.\n", + "В сообщении об ошибке «объект» - это строка, а «элемент» - это символ\n", + "Мы пытались назначить.\n", + "На данный момент ** объект ** - это то же самое, что и значение, но мы усовершенствоваем это определение позже.\n", "\n", - "The reason for this error is that strings are **immutable**, which means you can't change an existing string.\n", - "The best you can do is create a new string that is a variation of the original." + "Причина этой ошибки заключается в том, что строки ** неизменны **, что означает, что вы не можете изменить существующую строку.\n", + "Лучшее, что вы можете сделать, это создать новую строку, которая является вариацией оригинала." ] }, { @@ -387,8 +387,8 @@ "id": "2848546f", "metadata": {}, "source": [ - "This example concatenates a new first letter onto a slice of `greeting`.\n", - "It has no effect on the original string." + "Этот пример объединяет новую первую букву на кусок `greeting`.\n", + "Это не влияет на исходную строку." ] }, { @@ -404,10 +404,10 @@ "id": "49e4da57", "metadata": {}, "source": [ - "## String comparison\n", + "## Сравнение строк\n", "\n", - "The relational operators work on strings. To see if two strings are\n", - "equal, we can use the `==` operator." + "Реляционные операторы работают над строками.Чтобы увидеть, являются ли две строки\n", + "Равное, мы можем использовать оператор `==`." ] }, { @@ -423,8 +423,8 @@ "id": "e9be6097", "metadata": {}, "source": [ - "Other relational operations are useful for putting words in alphabetical\n", - "order:" + "Другие реляционные операции полезны для постановки слов в алфавиту\n", + "заказ:" ] }, { @@ -448,9 +448,9 @@ "id": "b66f449a", "metadata": {}, "source": [ - "Python does not handle uppercase and lowercase letters the same way\n", - "people do. All the uppercase letters come before all the lowercase\n", - "letters, so:" + "Python не обрабатывает прописные и строчные буквы одинаково\n", + "люди делают.Все заглавные буквы представлены до всех строк\n", + "буквы, так:" ] }, { @@ -466,8 +466,8 @@ "id": "f9b916c9", "metadata": {}, "source": [ - "To solve this problem, we can convert strings to a standard format, such as all lowercase, before performing the comparison.\n", - "Keep that in mind if you have to defend yourself against a man armed with a Pineapple." + "Чтобы решить эту проблему, мы можем преобразовать строки в стандартный формат, например, все строчные, прежде чем выполнять сравнение.\n", + "Имейте это в виду, если вам нужно защитить себя от человека, вооруженного ананасом." ] }, { @@ -475,13 +475,13 @@ "id": "531069f1", "metadata": {}, "source": [ - "## String methods\n", + "## Строковые методы\n", "\n", - "Strings provide methods that perform a variety of useful operations. \n", - "A method is similar to a function -- it takes arguments and returns a value -- but the syntax is different.\n", - "For example, the method `upper` takes a string and returns a new string with all uppercase letters.\n", + "Строки предоставляют методы, которые выполняют различные полезные операции.\n", + "Метод похож на функцию - он принимает аргументы и возвращает значение - но синтаксис отличается.\n", + "Например, метод `upper` принимает строку и возвращает новую строку со всеми заглавными буквами.\n", "\n", - "Instead of the function syntax `upper(word)`, it uses the method syntax `word.upper()`." + "Вместо синтаксиса функции `upper(word)` он использует синтаксис метода `word.upper()`." ] }, { @@ -497,10 +497,10 @@ "id": "1ac41744", "metadata": {}, "source": [ - "This use of the dot operator specifies the name of the method, `upper`, and the name of the string to apply the method to, `word`.\n", - "The empty parentheses indicate that this method takes no arguments.\n", + "Это использование оператора DOT указывает имя метода `upper`, и имя строки для применения метода к `word`.\n", + "Пустые скобки указывают, что этот метод не принимает аргументов.\n", "\n", - "A method call is called an **invocation**; in this case, we would say that we are invoking `upper` on `word`." + "Вызов метода называется ** вызов **;В этом случае мы бы сказали, что мы вызываем `upper` на `word`." ] }, { @@ -510,10 +510,10 @@ "tags": [] }, "source": [ - "## Writing files\n", + "## Написание файлов\n", "\n", - "String operators and methods are useful for reading and writing text files.\n", - "As an example, we'll work with the text of *Dracula*, a novel by Bram Stoker that is available from Project Gutenberg ()." + "Строковые операторы и методы полезны для чтения и написания текстовых файлов.\n", + "Например, мы будем работать с текстом *Dracula *, романа Bram Stoker, который доступен от Project Gutenberg ()." ] }, { @@ -531,7 +531,7 @@ "id": "963dda79", "metadata": {}, "source": [ - "I've downloaded the book in a plain text file called `pg345.txt`, which we can open for reading like this:" + "Я загрузил книгу в простом текстовом файле под названием `pg345.txt`, который мы можем открыть для чтения, так:" ] }, { @@ -547,11 +547,11 @@ "id": "b5d99e8c", "metadata": {}, "source": [ - "In addition to the text of the book, this file contains a section at the beginning with information about the book and a section at the end with information about the license.\n", - "Before we process the text, we can remove this extra material by finding the special lines at the beginning and end that begin with `'***'`.\n", + "В дополнение к тексту книги, этот файл содержит раздел в начале с информацией о книге и разделом в конце с информацией о лицензии.\n", + "Прежде чем обрабатывать текст, мы сможем удалить этот дополнительный материал, найдя специальные линии в начале и конце, которые начинаются с `'***'`.\n", "\n", - "The following function takes a line and checks whether it is one of the special lines.\n", - "It uses the `startswith` method, which checks whether a string starts with a given sequence of characters." + "Следующая функция принимает линию и проверяет, является ли это одной из специальных линий.\n", + "Он использует метод `startswith`, который проверяет, начинается ли строка с заданной последовательности символов." ] }, { @@ -567,7 +567,7 @@ "id": "2efdfe35", "metadata": {}, "source": [ - "We can use this function to loop through the lines in the file and print only the special lines." + "Мы можем использовать эту функцию, чтобы пройти через строки в файле и распечатать только специальные строки." ] }, { @@ -583,9 +583,9 @@ "id": "07fb5992", "metadata": {}, "source": [ - "Now let's create a new file, called `pg345_cleaned.txt`, that contains only the text of the book.\n", - "In order to loop through the book again, we have to open it again for reading.\n", - "And, to write a new file, we can open it for writing." + "Теперь давайте создадим новый файл, называемый `pg345_cleaned.txt`, который содержит только текст книги.\n", + "Чтобы снова пройти через книгу, мы должны снова открыть ее для чтения.\n", + "И, чтобы написать новый файл, мы можем открыть его для написания." ] }, { @@ -601,10 +601,10 @@ "id": "96d881aa", "metadata": {}, "source": [ - "`open` takes an optional parameters that specifies the \"mode\" -- in this example, `'w'` indicates that we're opening the file for writing.\n", - "If the file doesn't exist, it will be created; if it already exists, the contents will be replaced.\n", + "`open` принимает дополнительные параметры, которые указывают «режим» - в этом примере `'w'` указывает, что мы открываем файл для написания.\n", + "Если файл не существует, он будет создан;Если он уже существует, содержимое будет заменено.\n", "\n", - "As a first step, we'll loop through the file until we find the first special line." + "В качестве первого шага мы проберим файл, пока не найдем первую специальную строку." ] }, { @@ -620,9 +620,9 @@ "id": "1989d5a1", "metadata": {}, "source": [ - "The `break` statement \"breaks\" out of the loop -- that is, it causes the loop to end immediately, before we get to the end of the file.\n", + "Заявление `break` «вырывается» из петли, то есть он приводит к немедленному контуру, прежде чем мы доберемся до конца файла.\n", "\n", - "When the loop exits, `line` contains the special line that made the conditional true." + "Когда петля выходит, `line` содержит специальную линию, которая сделала условную истину." ] }, { @@ -638,11 +638,11 @@ "id": "9f28c3b4", "metadata": {}, "source": [ - "Because `reader` keeps track of where it is in the file, we can use a second loop to pick up where we left off.\n", + "Поскольку `reader` отслеживает, где он находится в файле, мы можем использовать второй цикл, чтобы забрать, где мы остановились.\n", "\n", - "The following loop reads the rest of the file, one line at a time.\n", - "When it finds the special line that indicates the end of the text, it breaks out of the loop.\n", - "Otherwise, it writes the line to the output file." + "Следующий цикл считывает остальную часть файла, по одной строке за раз.\n", + "Когда он находит специальную строку, которая указывает на конец текста, она выходит из петли.\n", + "В противном случае он записывает строку в выходной файл." ] }, { @@ -658,7 +658,7 @@ "id": "c07032a4", "metadata": {}, "source": [ - "When this loop exits, `line` contains the second special line." + "Когда этот цикл выходит, `line` содержит вторую специальную линию." ] }, { @@ -674,8 +674,8 @@ "id": "0c30b41c", "metadata": {}, "source": [ - "At this point `reader` and `writer` are still open, which means we could keep reading lines from `reader` or writing lines to `writer`.\n", - "To indicate that we're done, we can close both files by invoking the `close` method." + "На этом этапе `reader` и `writer` все еще открыты, что означает, что мы можем продолжать чтение линий от `reader` или записи линий до `writer`.\n", + "Чтобы указать, что мы закончили, мы можем закрыть оба файла, вызывая метод `close`." ] }, { @@ -691,7 +691,7 @@ "id": "d5084cdc", "metadata": {}, "source": [ - "To check whether this process was successful, we can read the first few lines from the new file we just created." + "Чтобы проверить, был ли этот процесс успешным, мы можем прочитать первые несколько строк из нового файла, который мы только что создали." ] }, { @@ -707,7 +707,7 @@ "id": "34c93df3", "metadata": {}, "source": [ - "The `endswidth` method checks whether a string ends with a given sequence of characters." + "Метод `endswidth` проверяет, заканчивается ли строка данной последовательности символов." ] }, { @@ -715,12 +715,12 @@ "id": "fcdb4bbf", "metadata": {}, "source": [ - "## Find and replace\n", + "## Найти и заменить\n", "\n", - "In the Icelandic translation of *Dracula* from 1901, the name of one of the characters was changed from \"Jonathan\" to \"Thomas\".\n", - "To make this change in the English version, we can loop through the book, use the `replace` method to replace one name with another, and write the result to a new file.\n", + "В исландском переводе * Дракула * с 1901 года имя одного из персонажей было изменено с «Джонатана» на «Томас».\n", + "Чтобы внести это изменение в английскую версию, мы можем пройти через книгу, использовать метод `replace`, чтобы заменить одно имя другим, и написать результат в новый файл.\n", "\n", - "We'll start by counting the lines in the cleaned version of the file." + "Мы начнем с подсчета строк в очищенной версии файла." ] }, { @@ -736,7 +736,7 @@ "id": "8ba9b9ca", "metadata": {}, "source": [ - "To see whether a line contains \"Jonathan\", we can use the `in` operator, which checks whether this sequence of characters appears anywhere in the line." + "Чтобы увидеть, содержит ли строка «Джонатан», мы можем использовать оператор `in`, который проверяет, появляется ли эта последовательность символов в любом месте в линии." ] }, { @@ -752,8 +752,8 @@ "id": "27805245", "metadata": {}, "source": [ - "There are 199 lines that contain the name, but that's not quite the total number of times it appears, because it can appear more than once in a line.\n", - "To get the total, we can use the `count` method, which returns the number of times a sequence appears in a string." + "Есть 199 строк, которые содержат имя, но это не совсем то, что появляется, потому что оно может появляться более одного раза в линии.\n", + "Чтобы получить общую сумму, мы можем использовать метод `count`, который возвращает количество раз, когда последовательность появляется в строке." ] }, { @@ -769,7 +769,7 @@ "id": "68026797", "metadata": {}, "source": [ - "Now we can replace `'Jonathan'` with `'Thomas'` like this:" + "Теперь мы можем заменить `'Jonathan'` на `'Thomas'`, как это:" ] }, { @@ -785,7 +785,7 @@ "id": "57ba56f3", "metadata": {}, "source": [ - "The result is a new file called `pg345_replaced.txt` that contains a version of *Dracula* where Jonathan Harker is called Thomas." + "Результатом является новый файл под названием `pg345_replaced.txt`, который содержит версию * Dracula *, где Джонатан Харкер называется Thomas." ] }, { @@ -803,15 +803,15 @@ "id": "cc9af187", "metadata": {}, "source": [ - "## Regular expressions\n", + "## Регулярные выражения\n", "\n", - "If we know exactly what sequence of characters we're looking for, we can use the `in` operator to find it and the `replace` method to replace it.\n", - "But there is another tool, called a **regular expression** that can also perform these operations -- and a lot more.\n", + "Если мы точно знаем, какую последовательность символов мы ищем, мы можем использовать оператора `in`, чтобы найти его и метод `replace` для его замены.\n", + "Но есть еще один инструмент, называемый ** регулярным выражением **, которое также может выполнять эти операции - и многое другое.\n", "\n", - "To demonstrate, I'll start with a simple example and we'll work our way up.\n", - "Suppose, again, that we want to find all lines that contain a particular word.\n", - "For a change, let's look for references to the titular character of the book, Count Dracula.\n", - "Here's a line that mentions him." + "Чтобы продемонстрировать, я начну с простого примера, и мы будем подняться.\n", + "Предположим, опять же, мы хотим найти все строки, которые содержат определенное слово.\n", + "Для разнообразия давайте рассмотрим ссылки на титульный характер книги, граф Дракула.\n", + "Вот линия, в которой упоминается его." ] }, { @@ -827,7 +827,7 @@ "id": "d4fd6d11", "metadata": {}, "source": [ - "And here's the **pattern** we'll use to search." + "А вот схема ** **, мы будем использовать для поиска." ] }, { @@ -843,8 +843,8 @@ "id": "268f647c", "metadata": {}, "source": [ - "A module called `re` provides functions related to regular expressions.\n", - "We can import it like this and use the `search` function to check whether the pattern appears in the text." + "Модуль под названием `re` предоставляет функции, связанные с регулярными выражениями.\n", + "Мы можем импортировать его так и использовать функцию `search`, чтобы проверить, появляется ли шаблон в тексте." ] }, { @@ -860,8 +860,8 @@ "id": "e17f6731", "metadata": {}, "source": [ - "If the pattern appears in the text, `search` returns a `Match` object that contains the results of the search.\n", - "Among other information, it has a variable named `string` that contains the text that was searched." + "Если в тексте появляется шаблон, `search` возвращает объект `Match`, который содержит результаты поиска.\n", + "Среди другой информации он имеет переменную с именем `string`, которая содержит искательный текст." ] }, { @@ -877,7 +877,7 @@ "id": "a8eab0f6", "metadata": {}, "source": [ - "It also provides a method called `group` that returns the part of the text that matched the pattern." + "Он также предоставляет метод под названием `group`, который возвращает часть текста, который соответствует шаблону." ] }, { @@ -893,7 +893,7 @@ "id": "b6962a7d", "metadata": {}, "source": [ - "And it provides a method called `span` that returns the index in the text where the pattern starts and ends." + "И он предоставляет метод под названием `span`, который возвращает индекс в тексте, где запускается и заканчивается шаблон." ] }, { @@ -909,7 +909,7 @@ "id": "8f1e5261", "metadata": {}, "source": [ - "If the pattern doesn't appear in the text, the return value from `search` is `None`." + "Если шаблон не отображается в тексте, возвращаемое значение от `search` составляет `None`." ] }, { @@ -925,7 +925,7 @@ "id": "d5ed33ff", "metadata": {}, "source": [ - "So we can check whether the search was successful by checking whether the result is `None`." + "Таким образом, мы можем проверить, был ли поиск успешным, проверив, является ли результат `None`." ] }, { @@ -941,7 +941,7 @@ "id": "a08e38f6", "metadata": {}, "source": [ - "Putting all that together, here's a function that loops through the lines in the book until it finds one that matches the given pattern, and returns the `Match` object." + "Собрав все это вместе, вот функция, которая проходит через строки в книге, пока она не найдет ту, которая соответствует данной шаблоне, и возвращает объект `Match`." ] }, { @@ -957,7 +957,7 @@ "id": "96570515", "metadata": {}, "source": [ - "We can use it to find the first mention of a character." + "Мы можем использовать его, чтобы найти первое упоминание о персонаже." ] }, { @@ -973,12 +973,12 @@ "id": "3f687fdc", "metadata": {}, "source": [ - "For this example, we didn't have to use regular expressions -- we could have done the same thing more easily with the `in` operator.\n", - "But regular expressions can do things the `in` operator cannot.\n", + "Для этого примера нам не нужно было использовать регулярные выражения - мы могли бы сделать то же самое легче с оператором `in`.\n", + "Но регулярные выражения могут делать то, что не может оператор `in`.\n", "\n", - "For example, if the pattern includes the vertical bar character, `'|'`, it can match either the sequence on the left or the sequence on the right.\n", - "Suppose we want to find the first mention of Mina Murray in the book, but we are not sure whether she is referred to by first name or last.\n", - "We can use the following pattern, which matches either name." + "Например, если шаблон включает в себя вертикальный символ стержня, `'|'`, он может соответствовать либо последовательности слева, либо последовательности справа.\n", + "Предположим, мы хотим найти первое упоминание о Мине Мюррей в книге, но мы не уверены, упоминается ли ее по имени или последнему.\n", + "Мы можем использовать следующий шаблон, который соответствует любому имени." ] }, { @@ -994,8 +994,8 @@ "id": "8bea66a6", "metadata": {}, "source": [ - "We can use a pattern like this to see how many times a character is mentioned by either name.\n", - "Here's a function that loops through the book and counts the number of lines that match the given pattern." + "Мы можем использовать такой шаблон, чтобы увидеть, сколько раз персонаж упоминается любого имени.\n", + "Вот функция, которая проходит через книгу и считает количество строк, которые соответствуют данному шаблону." ] }, { @@ -1011,7 +1011,7 @@ "id": "0e753a5b", "metadata": {}, "source": [ - "Now let's see how many times Mina is mentioned." + "Теперь посмотрим, сколько раз упоминается Мина." ] }, { @@ -1027,7 +1027,7 @@ "id": "780c9fab", "metadata": {}, "source": [ - "The special character `'^'` matches the beginning of a string, so we can find a line that starts with a given pattern." + "Специальный символ `'^'` соответствует началу строки, поэтому мы можем найти линию, которая начинается с данного шаблона." ] }, { @@ -1043,7 +1043,7 @@ "id": "332bad2e", "metadata": {}, "source": [ - "And the special character `'$'` matches the end of a string, so we can find a line that ends with a given pattern (ignoring the newline at the end)." + "А специальный символ `'$'` соответствует конец строки, поэтому мы можем найти линию, которая заканчивается данным шаблоном (игнорируя новую линию в конце)." ] }, { @@ -1059,11 +1059,11 @@ "id": "d4b22b6e", "metadata": {}, "source": [ - "## String substitution\n", + "## Строковая замена\n", "\n", - "Bram Stoker was born in Ireland, and when *Dracula* was published in 1897, he was living in England.\n", - "So we would expect him to use the British spelling of words like \"centre\" and \"colour\".\n", - "To check, we can use the following pattern, which matches either \"centre\" or the American spelling \"center\"." + "Брэм Стокер родился в Ирландии, и когда * Дракула * был опубликован в 1897 году, он жил в Англии.\n", + "Таким образом, мы ожидаем, что он будет использовать британское написание слов, таких как «Центр» и «Цвет».\n", + "Чтобы проверить, мы можем использовать следующий шаблон, который соответствует либо «центру», либо американскому правописанию «центр»." ] }, { @@ -1079,8 +1079,8 @@ "id": "35abfd7d", "metadata": {}, "source": [ - "In this pattern, the parentheses enclose the part of the pattern the vertical bar applies to.\n", - "So this pattern matches a sequence that starts with `'cent'` and ends with either `'er'` or `'re'`." + "В этой схеме скобки охватывают часть шаблона, к которой применяется вертикальная полоса.\n", + "Таким образом, этот шаблон соответствует последовательности, которая начинается с `'cent'` и заканчивается ни `'er'`, так и `'re'`." ] }, { @@ -1096,10 +1096,10 @@ "id": "e5703c18", "metadata": {}, "source": [ - "As expected, he used the British spelling.\n", + "Как и ожидалось, он использовал британское правописание.\n", "\n", - "We can also check whether he used the British spelling of \"colour\".\n", - "The following pattern uses the special character `'?'`, which means that the previous character is optional." + "Мы также можем проверить, использовал ли он британское написание «цвета».\n", + "Следующий шаблон использует специальный символ `'?'`, что означает, что предыдущий символ является необязательным." ] }, { @@ -1115,7 +1115,7 @@ "id": "beed9a7b", "metadata": {}, "source": [ - "This pattern matches either \"colour\" with the `'u'` or \"color\" without it." + "Этот рисунок соответствует либо «цвету» с `'u'` или «цветом» без него." ] }, { @@ -1131,10 +1131,10 @@ "id": "1a31f179", "metadata": {}, "source": [ - "Again, as expected, he used the British spelling.\n", + "Опять же, как и ожидалось, он использовал британское правописание.\n", "\n", - "Now suppose we want to produce an edition of the book with American spellings.\n", - "We can use the `sub` function in the `re` module, which does **string substitution**." + "Теперь предположим, что мы хотим создать издание книги с американскими написаниями.\n", + "Мы можем использовать функцию `sub` в модуле `re`, который выполняет ** строковую замену **." ] }, { @@ -1150,8 +1150,8 @@ "id": "04a80fc6", "metadata": {}, "source": [ - "The first argument is the pattern we want to find and replace, the second is what we want to replace it with, and the third is the string we want to search.\n", - "In the result, you can see that \"colour\" has been replaced with \"color\"." + "Первый аргумент - это шаблон, который мы хотим найти и заменить, второе - это то, что мы хотим заменить его, а третий - это строка, которую мы хотим найти.\n", + "В результате вы можете видеть, что «цвет» был заменен на «цвет»." ] }, { @@ -1179,11 +1179,11 @@ "id": "0318507d", "metadata": {}, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "When you are reading and writing files, debugging can be tricky.\n", - "If you are working in a Jupyter notebook, you can use **shell commands** to help.\n", - "For example, to display the first few lines of a file, you can use the command `!head`, like this:" + "Когда вы читаете и пишете файлы, отладка может быть сложной.\n", + "Если вы работаете в ноутбуке Jupyter, вы можете использовать ** команды оболочки **, чтобы помочь.\n", + "Например, чтобы отобразить первые несколько строк файла, вы можете использовать команду `!head`, например:" ] }, { @@ -1201,8 +1201,8 @@ "id": "1d480c02", "metadata": {}, "source": [ - "The initial exclamation point, `!`, indicates that this is a shell command, which is not part of Python.\n", - "To display the last few lines, you can use `!tail`." + "Начальная восклицательная точка, `!`, указывает на то, что это команда оболочки, которая не является частью Python.\n", + "Чтобы отобразить последние несколько строк, вы можете использовать `!tail`." ] }, { @@ -1220,10 +1220,10 @@ "id": "6874023a", "metadata": {}, "source": [ - "When you are working with large files, debugging can be difficult because there might be too much output to check by hand.\n", - "A good debugging strategy is to start with just part of the file, get the program working, and then run it with the whole file.\n", + "Когда вы работаете с большими файлами, отладка может быть трудной, потому что может быть слишком много выводов, чтобы проверить вручную.\n", + "Хорошая стратегия отладки состоит в том, чтобы начать только с части файла, заработать программу, а затем запустить ее со всем файлом.\n", "\n", - "To make a small file that contains part of a larger file, we can use `!head` again with the redirect operator, `>`, which indicates that the results should be written to a file rather than displayed." + "Чтобы сделать небольшой файл, который содержит часть более крупного файла, мы можем снова использовать `!head` с оператором перенаправления, `>`, что указывает на то, что результаты должны быть записаны в файл, а не отображаются." ] }, { @@ -1239,7 +1239,7 @@ "id": "3fc851f8", "metadata": {}, "source": [ - "By default, `!head` reads the first 10 lines, but it takes an optional argument that indicates the number of lines to read." + "По умолчанию `!head` считывает первые 10 строк, но ему требуется дополнительный аргумент, который указывает количество строк для чтения." ] }, { @@ -1255,11 +1255,11 @@ "id": "24871c78", "metadata": {}, "source": [ - "This shell command reads the first 100 lines from `pg345_cleaned.txt` and writes them to a file called `pg345_cleaned_100_lines.txt`.\n", + "Эта команда оболочки считывает первые 100 строк из `pg345_cleaned.txt` и записывает их в файл под названием `pg345_cleaned_100_lines.txt`.\n", "\n", - "Note: The shell commands `!head` and `!tail` are not available on all operating systems.\n", - "If they don't work for you, we can write similar functions in Python.\n", - "See the first exercise at the end of this chapter for suggestions." + "Примечание. Команды Shell `!head` и `!tail` не доступны во всех операционных системах.\n", + "Если они не работают на вас, мы можем написать похожие функции в Python.\n", + "Смотрите первое упражнение в конце этой главы для предложений." ] }, { @@ -1267,43 +1267,43 @@ "id": "c842524d", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**sequence:**\n", - " An ordered collection of values where each value is identified by an integer index.\n", + "**последовательность:**\n", + "Упорядоченный сбор значений, где каждое значение определяется целочисленным индексом.\n", "\n", - "**character:**\n", - "An element of a string, including letters, numbers, and symbols.\n", + "**характер:**\n", + "Элемент строки, включая буквы, числа и символы.\n", "\n", - "**index:**\n", - " An integer value used to select an item in a sequence, such as a character in a string. In Python indices start from `0`.\n", + "** Индекс: **\n", + "Целое значение, используемое для выбора элемента в последовательности, такой как символ в строке.В индексах Python начинаются с `0`.\n", "\n", - "**slice:**\n", - " A part of a string specified by a range of indices.\n", + "** Slice: **\n", + "Часть строки, указанная в диапазоне индексов.\n", "\n", - "**empty string:**\n", - "A string that contains no characters and has length `0`.\n", + "** пустая строка: **\n", + "Строка, которая не содержит символов и имеет длину `0`.\n", "\n", - "**object:**\n", - " Something a variable can refer to. An object has a type and a value.\n", + "**объект:**\n", + "То, на что может ссылаться переменная.Объект имеет тип и значение.\n", "\n", - "**immutable:**\n", - "If the elements of an object cannot be changed, the object is immutable.\n", + "** Неизвываемо: **\n", + "Если элементы объекта не могут быть изменены, объект неизменен.\n", "\n", - "**invocation:**\n", - " An expression -- or part of an expression -- that calls a method.\n", + "** Призыв: **\n", + "Выражение - или часть выражения - которое вызывает метод.\n", "\n", - "**regular expression:**\n", - "A sequence of characters that defines a search pattern.\n", + "** Регулярное выражение: **\n", + "Последовательность символов, которые определяют шаблон поиска.\n", "\n", - "**pattern:**\n", - "A rule that specifies the requirements a string has to meet to constitute a match.\n", + "**шаблон:**\n", + "Правило, которое указывает требования, которые должна соответствовать строке, чтобы составить матч.\n", "\n", - "**string substitution:**\n", - "Replacement of a string, or part of a string, with another string.\n", + "** Строка заменить: **\n", + "Замена строки или часть строки, с другой строкой.\n", "\n", - "**shell command:**\n", - "A statement in a shell language, which is a language used to interact with an operating system." + "** Команда оболочки: **\n", + "Заявление на языке оболочки, которое является языком, используемым для взаимодействия с операционной системой." ] }, { @@ -1311,7 +1311,7 @@ "id": "4306e765", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -1339,24 +1339,24 @@ "id": "5be97ddc", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "In this chapter, we only scratched the surface of what regular expressions can do.\n", - "To get an idea of what's possible, ask a virtual assistant, \"What are the most common special characters used in Python regular expressions?\"\n", + "В этой главе мы только поцарапали поверхность того, что могут сделать регулярные выражения.\n", + "Чтобы получить представление о том, что возможно, спросите виртуального помощника: «Какие наиболее распространенные специальные персонажи используются в регулярных выражениях Python?»\n", "\n", - "You can also ask for a pattern that matches particular kinds of strings.\n", - "For example, try asking:\n", + "Вы также можете попросить образец, который соответствует определенным видам строк.\n", + "Например, попробуйте спросить:\n", "\n", - "* Write a Python regular expression that matches a 10-digit phone number with hyphens.\n", + "* Напишите регулярное выражение Python, которое соответствует 10-значным номеру телефона с дефисами.\n", "\n", - "* Write a Python regular expression that matches a street address with a number and a street name, followed by `ST` or `AVE`.\n", + "* Напишите регулярное выражение Python, которое соответствует адресу улицы с номером и названием улицы, за которым следует `ST` или `AVE`.\n", "\n", - "* Write a Python regular expression that matches a full name with any common title like `Mr` or `Mrs` followed by any number of names beginning with capital letters, possibly with hyphens between some names.\n", + "* Напишите регулярное выражение Python, которое соответствует полному имени с любым общим названием, таким как `Mr` или `Mrs`, за которым следует любое количество имен, начинающихся с заглавных букв, возможно, с дефисами между некоторыми именами.\n", "\n", - "And if you want to see something more complicated, try asking for a regular expression that matches any legal URL.\n", + "И если вы хотите увидеть что -то более сложное, попробуйте попросить регулярное выражение, которое соответствует любому законному URL.\n", "\n", - "A regular expression often has the letter `r` before the quotation mark, which indicates that it is a \"raw string\".\n", - "For more information, ask a virtual assistant, \"What is a raw string in Python?\"" + "Регулярное выражение часто имеет букву `r` до кавычки, что указывает на то, что это «необработанная строка».\n", + "Для получения дополнительной информации спросите виртуального помощника: «Что такое необработанная строка в Python?»" ] }, { @@ -1374,13 +1374,13 @@ "id": "20dcbbb3", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "See if you can write a function that does the same thing as the shell command `!head`.\n", - "It should take as arguments the name of a file to read, the number of lines to read, and the name of the file to write the lines into.\n", - "If the third parameter is `None`, it should display the lines rather than write them to a file.\n", + "Посмотрите, сможете ли вы написать функцию, которая выполняет то же самое, что и команда Shell `!head`.\n", + "В качестве аргументов следует принимать имя файла для чтения, количество строк для чтения, и имя файла, чтобы записать строки.\n", + "Если третий параметр составляет `None`, он должен отображать строки, а не записывать их в файл.\n", "\n", - "Consider asking a virtual assistant for help, but if you do, tell it not to use a `with` statement or a `try` statement." + "Подумайте о том, чтобы попросить виртуального помощника за помощью, но если вы это сделаете, скажите ему не использовать оператор `with` или оператор `try`." ] }, { @@ -1398,7 +1398,7 @@ "tags": [] }, "source": [ - "You can use the following examples to test your function." + "Вы можете использовать следующие примеры для проверки вашей функции." ] }, { @@ -1436,18 +1436,18 @@ "id": "adb78357", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "\"Wordle\" is an online word game where the objective is to guess a five-letter word in six or fewer attempts.\n", - "Each attempt has to be recognized as a word, not including proper nouns.\n", - "After each attempt, you get information about which of the letters you guessed appear in the target word, and which ones are in the correct position.\n", + "«Wordle»-это онлайн-игра слов, в которой цель-угадать пять буквенно слова в шести или менее попытках.\n", + "Каждая попытка должна быть признана как слово, не включая правильные существительные.\n", + "После каждой попытки вы получаете информацию о том, какие из букв, которые вы догадались, появляются в целевом словом, а какие находятся в правильном положении.\n", "\n", - "For example, suppose the target word is `MOWER` and you guess `TRIED`.\n", - "You would learn that `E` is in the word and in the correct position, `R` is in the word but not in the correct position, and `T`, `I`, and `D` are not in the word.\n", + "Например, предположим, что целевое слово - `MOWER`, и вы предполагаете, что `TRIED`.\n", + "Вы узнаете, что `E` находится в словом и в правильном положении, `R` находится в слове, но не в правильном положении, а `T`, `I` и `D` не в слове.\n", "\n", - "As a different example, suppose you have guessed the words `SPADE` and `CLERK`, and you've learned that `E` is in the word, but not in either of those positions, and none of the other letters appear in the word.\n", - "Of the words in the word list, how many could be the target word?\n", - "Write a function called `check_word` that takes a five-letter word and checks whether it could be the target word, given these guesses." + "В качестве другого примера, предположим, что вы догадались о словах `SPADE` и `CLERK`, и вы узнали, что `E` находится в слове, но ни в одной из этих позиций, и ни одна из других букв не появляется в слове.\n", + "Из слов в списке, сколько может быть целевое слово?\n", + "Напишите функцию, называемую `TRIED`0, которая принимает слово пять букв и проверяет, может ли оно быть целевым словом, учитывая эти предположения." ] }, { @@ -1463,7 +1463,7 @@ "id": "87fdf676", "metadata": {}, "source": [ - "You can use any of the functions from the previous chapter, like `uses_any`." + "Вы можете использовать любую из функций из предыдущей главы, например `uses_any`." ] }, { @@ -1483,7 +1483,7 @@ "tags": [] }, "source": [ - "You can use the following loop to test your function." + "Вы можете использовать следующий цикл для проверки вашей функции." ] }, { @@ -1501,9 +1501,9 @@ "id": "d009cb52", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Continuing the previous exercise, suppose you guess the work `TOTEM` and learn that the `E` is *still* not in the right place, but the `M` is. How many words are left?" + "Продолжая предыдущее упражнение, предположим, что вы угадаете работу `TOTEM` и узнаете, что `E` все еще * не в нужном месте, но `M`.Сколько слов осталось?" ] }, { @@ -1527,16 +1527,16 @@ "id": "c1d0f892", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "*The Count of Monte Cristo* is a novel by Alexandre Dumas that is considered a classic.\n", - "Nevertheless, in the introduction of an English translation of the book, the writer Umberto Eco confesses that he found the book to be \"one of the most badly written novels of all time\".\n", + "* Count of Monte Cristo* - роман Александра Дюма, который считается классикой.\n", + "Тем не менее, во введении английского перевода книги, писатель Умберто Эко признается, что он нашел книгу «одним из самых плохо написанных романов всех времен».\n", "\n", - "In particular, he says it is \"shameless in its repetition of the same adjective,\" and mentions in particular the number of times \"its characters either shudder or turn pale.\"\n", + "В частности, он говорит, что он «бесстыдный в своем повторении одного и того же прилагательного», и в частности, упоминает о количестве «его персонажи либо вздрогнули, либо становятся бледными».\n", "\n", - "To see whether his objection is valid, let's count the number number of lines that contain the word `pale` in any form, including `pale`, `pales`, `paled`, and `paleness`, as well as the related word `pallor`. \n", - "Use a single regular expression that matches any of these words.\n", - "As an additional challenge, make sure that it doesn't match any other words, like `impale` -- you might want to ask a virtual assistant for help." + "Чтобы увидеть, является ли его возражение действительным, давайте подсчитаем количество номера строк, которые содержат слово `pale` в любой форме, включая `pale`, `pales`, `paled` и `paleness`, а также соответствующее слово `pallor`.\n", + "Используйте одно регулярное выражение, которое соответствует любому из этих слов.\n", + "В качестве дополнительной задачи, убедитесь, что он не соответствует другим словам, например, `impale` - вы можете попросить виртуального помощника за помощью." ] }, { @@ -1546,7 +1546,7 @@ "tags": [] }, "source": [ - "The following cell downloads the book from Project Gutenberg ." + "Следующая ячейка загружает книгу из Project Gutenberg ." ] }, { @@ -1566,7 +1566,7 @@ "tags": [] }, "source": [ - "The following cell runs a function that reads the file from Project Gutenberg and writes a file that contains only the text of the book, not the added information about the book." + "Следующая ячейка запускает функцию, которая считывает файл из Project Gutenberg и записывает файл, который содержит только текст книги, а не добавленную информацию о книге." ] }, { @@ -1610,7 +1610,7 @@ "tags": [] }, "source": [ - "By this count, these words appear on `223` lines of the book, so Mr. Eco might have a point." + "По этому количеству эти слова появляются в `223` строк книги, поэтому мистер Эко может иметь смысл." ] }, { @@ -1624,9 +1624,9 @@ "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], From d3f1cd441df6269e40ec337cd689d70842547fa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:02:03 +0300 Subject: [PATCH 09/44] Translate chapter 9 notebook to Russian --- blank/chap09.ipynb | 423 ++++++++++++++++++++++----------------------- 1 file changed, 211 insertions(+), 212 deletions(-) diff --git a/blank/chap09.ipynb b/blank/chap09.ipynb index c4cae84..9ff4ef7 100644 --- a/blank/chap09.ipynb +++ b/blank/chap09.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать печатные и электронные версии *Think Python 3e* от\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -25,12 +25,12 @@ "id": "3c25ca7e", "metadata": {}, "source": [ - "# Lists\n", + "# Списки\n", "\n", - "This chapter presents one of Python's most useful built-in types, lists.\n", - "You will also learn more about objects and what can happen when multiple variables refer to the same object.\n", + "В этой главе представлен один из самых полезных встроенных типов Python - списки.\n", + "Вы также узнаете больше об объектах и о том, что может произойти, когда несколько переменных ссылаются на один и тот же объект.\n", "\n", - "In the exercises at the end of the chapter, we'll make a word list and use it to search for special words like palindromes and anagrams." + "В упражнениях в конце главы мы составим список слов и будем использовать его для поиска специальных слов, таких как палиндромы и анаграммы." ] }, { @@ -38,14 +38,14 @@ "id": "4d32b3e2", "metadata": {}, "source": [ - "## A list is a sequence\n", + "## Список - это последовательность\n", "\n", - "Like a string, a **list** is a sequence of values. In a string, the\n", - "values are characters; in a list, they can be any type.\n", - "The values in a list are called **elements**.\n", + "Как и строка, **list** - это последовательность значений. В строке\n", + "значения - это символы; в списке они могут быть любого типа.\n", + "Значения в списке называются **элементами**.\n", "\n", - "There are several ways to create a new list; the simplest is to enclose the elements in square brackets (`[` and `]`).\n", - "For example, here is a list of two integers. " + "Существует несколько способов создания нового списка; самый простой - заключить элементы в квадратные скобки (`[` и `]`).\n", + "Например, вот список из двух целых чисел." ] }, { @@ -61,7 +61,7 @@ "id": "b5d6112c", "metadata": {}, "source": [ - "And here's a list of three strings." + "А вот список из трех струн." ] }, { @@ -77,8 +77,8 @@ "id": "dda58c67", "metadata": {}, "source": [ - "The elements of a list don't have to be the same type.\n", - "The following list contains a string, a float, an integer, and even another list." + "Элементы списка не обязательно должны быть одного типа.\n", + "Следующий список содержит строку, поплавок, целое число и даже другой список." ] }, { @@ -94,10 +94,10 @@ "id": "147fa217", "metadata": {}, "source": [ - "A list within another list is **nested**.\n", + "Список в другом списке **вложен**.\n", "\n", - "A list that contains no elements is called an empty list; you can create\n", - "one with empty brackets, `[]`." + "Список, не содержащий элементов, называется пустым списком; вы можете создать\n", + "с пустыми скобками, `[]`." ] }, { @@ -113,7 +113,7 @@ "id": "f95381bc", "metadata": {}, "source": [ - "The `len` function returns the length of a list." + "Функция `len` возвращает длину списка." ] }, { @@ -129,7 +129,7 @@ "id": "371403a3", "metadata": {}, "source": [ - "The length of an empty list is `0`." + "Длина пустого списка - `0`." ] }, { @@ -147,7 +147,7 @@ "id": "d3589a5d", "metadata": {}, "source": [ - "The following figure shows the state diagram for `cheeses`, `numbers` and `empty`." + "На следующем рисунке показана диаграмма состояний для `cheeses`, `numbers` и `empty`." ] }, { @@ -175,7 +175,7 @@ "id": "503f25d8", "metadata": {}, "source": [ - "Lists are represented by boxes with the word \"list\" outside and the numbered elements of the list inside." + "Списки представлены ячейками со словом «список» снаружи и пронумерованными элементами списка внутри." ] }, { @@ -183,10 +183,10 @@ "id": "e0b8ff01", "metadata": {}, "source": [ - "## Lists are mutable\n", + "## Списки могут быть изменены\n", "\n", - "To read an element of a list, we can use the bracket operator.\n", - "The index of the first element is `0`." + "Чтобы прочитать элемент списка, мы можем использовать оператор скобки.\n", + "Индекс первого элемента - `0`." ] }, { @@ -202,9 +202,9 @@ "id": "9747e951", "metadata": {}, "source": [ - "Unlike strings, lists are mutable. When the bracket operator appears on\n", - "the left side of an assignment, it identifies the element of the list\n", - "that will be assigned." + "В отличие от строк, списки изменчивы. Когда оператор скобки появляется на\n", + "левая часть задания, она идентифицирует элемент списка\n", + "которые будут назначены." ] }, { @@ -220,19 +220,19 @@ "id": "5097a517", "metadata": {}, "source": [ - "The second element of `numbers`, which used to be `123`, is now `17`.\n", + "Второй элемент `numbers`, который раньше был `123`, теперь `17`.\n", "\n", - "List indices work the same way as string indices:\n", + "Индексы списка работают так же, как и строковые индексы:\n", "\n", - "- Any integer expression can be used as an index.\n", + "- В качестве индекса можно использовать любое целочисленное выражение.\n", "\n", - "- If you try to read or write an element that does not exist, you get\n", - " an `IndexError`.\n", + "- Если вы попытаетесь прочитать или написать несуществующий элемент, вы получите\n", + " xYZ3ZYX.\n", "\n", - "- If an index has a negative value, it counts backward from the end of\n", - " the list.\n", + "- Если индекс имеет отрицательное значение, он считается в обратном направлении с конца\n", + " списка.\n", "\n", - "The `in` operator works on lists -- it checks whether a given element appears anywhere in the list." + "Оператор `in` работает со списками - он проверяет, отображается ли данный элемент в любом месте списка." ] }, { @@ -256,7 +256,7 @@ "id": "89d01ebf", "metadata": {}, "source": [ - "Although a list can contain another list, the nested list still counts as a single element -- so in the following list, there are only four elements." + "Хотя список может содержать другой список, вложенный список по-прежнему считается одним элементом - поэтому в следующем списке есть только четыре элемента." ] }, { @@ -272,7 +272,7 @@ "id": "4e0ea41d", "metadata": {}, "source": [ - "And `10` is not considered to be an element of `t` because it is an element of a nested list, not `t`." + "И `10` не считается элементом `t`, потому что он является элементом вложенного списка, а не `t`." ] }, { @@ -288,10 +288,10 @@ "id": "1ee7a4d9", "metadata": {}, "source": [ - "## List slices\n", + "## Список срезов\n", "\n", - "The slice operator works on lists the same way it works on strings.\n", - "The following example selects the second and third elements from a list of four letters." + "Оператор среза работает со списками так же, как он работает со строками.\n", + "В следующем примере выбираются второй и третий элементы из списка из четырех букв." ] }, { @@ -307,7 +307,7 @@ "id": "bc59d952", "metadata": {}, "source": [ - "If you omit the first index, the slice starts at the beginning. " + "Если вы опустите первый индекс, срез начнется с начала." ] }, { @@ -323,7 +323,7 @@ "id": "1aaaae86", "metadata": {}, "source": [ - "If you omit the second, the slice goes to the end. " + "Если опустить вторую, срез идет до конца." ] }, { @@ -339,7 +339,7 @@ "id": "67ad02e8", "metadata": {}, "source": [ - "So if you omit both, the slice is a copy of the whole list." + "Поэтому, если вы опустите оба, срез будет копией всего списка." ] }, { @@ -355,7 +355,7 @@ "id": "9232c1ef", "metadata": {}, "source": [ - "Another way to copy a list is to use the `list` function." + "Другой способ скопировать список - использовать функцию `list`." ] }, { @@ -371,7 +371,7 @@ "id": "50e4b182", "metadata": {}, "source": [ - "Because `list` is the name of a built-in function, you should avoid using it as a variable name.\n" + "Поскольку `list` - это имя встроенной функции, вам не следует использовать его в качестве имени переменной." ] }, { @@ -379,9 +379,9 @@ "id": "1b057c0c", "metadata": {}, "source": [ - "## List operations\n", + "## Список операций\n", "\n", - "The `+` operator concatenates lists." + "Оператор `+` объединяет списки." ] }, { @@ -397,7 +397,7 @@ "id": "474a5c40", "metadata": {}, "source": [ - "The `*` operator repeats a list a given number of times." + "Оператор `*` повторяет список заданное количество раз." ] }, { @@ -413,7 +413,7 @@ "id": "5b33bc51", "metadata": {}, "source": [ - "No other mathematical operators work with lists, but the built-in function `sum` adds up the elements." + "Никакие другие математические операторы не работают со списками, но встроенная функция `sum` складывает элементы." ] }, { @@ -429,7 +429,7 @@ "id": "f216a14d", "metadata": {}, "source": [ - "And `min` and `max` find the smallest and largest elements." + "А `min` и `max` находят самые маленькие и самые большие элементы." ] }, { @@ -453,10 +453,10 @@ "id": "533a2009", "metadata": {}, "source": [ - "## List methods\n", + "## Методы списка\n", "\n", - "Python provides methods that operate on lists. For example, `append`\n", - "adds a new element to the end of a list:" + "Python предоставляет методы, которые работают со списками. Например, `append`\n", + "добавляет новый элемент в конец списка:" ] }, { @@ -472,7 +472,7 @@ "id": "ccc57f77", "metadata": {}, "source": [ - "`extend` takes a list as an argument and appends all of the elements:" + "`extend` принимает список в качестве аргумента и добавляет все элементы:" ] }, { @@ -488,8 +488,8 @@ "id": "0f39d9f6", "metadata": {}, "source": [ - "There are two methods that remove elements from a list.\n", - "If you know the index of the element you want, you can use `pop`." + "Существует два метода удаления элементов из списка.\n", + "Если вы знаете индекс нужного элемента, вы можете использовать `pop`." ] }, { @@ -505,8 +505,8 @@ "id": "6729415a", "metadata": {}, "source": [ - "The return value is the element that was removed.\n", - "And we can confirm that the list has been modified." + "Возвращаемое значение - это элемент, который был удален.\n", + "И мы можем подтвердить, что список был изменен." ] }, { @@ -522,7 +522,7 @@ "id": "1e97ee7d", "metadata": {}, "source": [ - "If you know the element you want to remove (but not the index), you can use `remove`:" + "Если вы знаете элемент, который хотите удалить (но не индекс), вы можете использовать `remove`:" ] }, { @@ -538,8 +538,8 @@ "id": "60e710fe", "metadata": {}, "source": [ - "The return value from `remove` is `None`.\n", - "But we can confirm that the list has been modified." + "Возвращаемое значение из `remove` равно `None`.\n", + "Но мы можем подтвердить, что список был изменен." ] }, { @@ -555,7 +555,7 @@ "id": "2a9448a8", "metadata": {}, "source": [ - "If the element you ask for is not in the list, that's a ValueError." + "Если запрашиваемого элемента нет в списке, это ошибка ValueError." ] }, { @@ -573,11 +573,11 @@ "id": "18305f96", "metadata": {}, "source": [ - "## Lists and strings\n", + "## Списки и строки\n", "\n", - "A string is a sequence of characters and a list is a sequence of values,\n", - "but a list of characters is not the same as a string. \n", - "To convert from a string to a list of characters, you can use the `list` function." + "Строка - это последовательность символов, а список - последовательность значений,\n", + "но список символов - это не то же самое, что строка. \n", + "Для преобразования строки в список символов можно использовать функцию `list`." ] }, { @@ -593,8 +593,8 @@ "id": "0291ef69", "metadata": {}, "source": [ - "The `list` function breaks a string into individual letters.\n", - "If you want to break a string into words, you can use the `split` method:" + "Функция `list` разбивает строку на отдельные буквы.\n", + "Если вы хотите разбить строку на слова, вы можете использовать метод `split`:" ] }, { @@ -610,7 +610,7 @@ "id": "0e16909d", "metadata": {}, "source": [ - "An optional argument called a **delimiter** specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter." + "Необязательный аргумент, называемый * * разделителем * *, указывает, какие символы использовать в качестве границ слов. В следующем примере в качестве разделителя используется дефис." ] }, { @@ -626,8 +626,8 @@ "id": "7c61f916", "metadata": {}, "source": [ - "If you have a list of strings, you can concatenate them into a single string using `join`.\n", - "`join` is a string method, so you have to invoke it on the delimiter and pass the list as an argument." + "Если у вас есть список строк, вы можете объединить их в одну строку с помощью `join`.\n", + "`join` - это строковый метод, поэтому вы должны вызвать его на разделителе и передать список в качестве аргумента." ] }, { @@ -643,9 +643,9 @@ "id": "bedd842b", "metadata": {}, "source": [ - "In this case the delimiter is a space character, so `join` puts a space\n", - "between words.\n", - "To join strings without spaces, you can use the empty string, `''`, as a delimiter." + "В этом случае разделитель является символом пробела, поэтому `join` помещает пробел\n", + "между словами.\n", + "Чтобы соединить строки без пробелов, вы можете использовать пустую строку `''` в качестве разделителя." ] }, { @@ -653,9 +653,9 @@ "id": "181215ce", "metadata": {}, "source": [ - "## Looping through a list\n", + "## Циклический просмотр списка\n", "\n", - "You can use a `for` statement to loop through the elements of a list." + "Инструкцию `for` можно использовать для циклического просмотра элементов списка." ] }, { @@ -671,7 +671,7 @@ "id": "c0e53a09", "metadata": {}, "source": [ - "For example, after using `split` to make a list of words, we can use `for` to loop through them." + "Например, после использования `split` для составления списка слов мы можем использовать `for` для их повторения." ] }, { @@ -687,7 +687,7 @@ "id": "0857b55b", "metadata": {}, "source": [ - "A `for` loop over an empty list never runs the indented statements." + "Цикл `for` над пустым списком никогда не запускает операторы с отступами." ] }, { @@ -703,9 +703,9 @@ "id": "6e5f55c9", "metadata": {}, "source": [ - "## Sorting lists\n", + "## Сортировка списков\n", "\n", - "Python provides a built-in function called `sorted` that sorts the elements of a list." + "Python предоставляет встроенную функцию `sorted`, которая сортирует элементы списка." ] }, { @@ -721,7 +721,7 @@ "id": "44e028cf", "metadata": {}, "source": [ - "The original list is unchanged." + "Исходный список без изменений." ] }, { @@ -737,7 +737,7 @@ "id": "530146af", "metadata": {}, "source": [ - "`sorted` works with any kind of sequence, not just lists. So we can sort the letters in a string like this." + "`sorted` работает с любой последовательностью, а не только со списками. Таким образом, мы можем отсортировать буквы в такой строке." ] }, { @@ -753,8 +753,8 @@ "id": "f90bd9ea", "metadata": {}, "source": [ - "The result it a list.\n", - "To convert the list to a string, we can use `join`." + "Результат - список.\n", + "Чтобы преобразовать список в строку, мы можем использовать `join`." ] }, { @@ -770,7 +770,7 @@ "id": "a57084e2", "metadata": {}, "source": [ - "With an empty string as the delimiter, the elements of the list are joined with nothing between them." + "С пустой строкой в качестве разделителя элементы списка соединяются ни с чем между ними." ] }, { @@ -778,9 +778,9 @@ "id": "ce98b3d5", "metadata": {}, "source": [ - "## Objects and values\n", + "## Объекты и значения\n", "\n", - "If we run these assignment statements:" + "Если мы запустим эти инструкции присваивания:" ] }, { @@ -796,8 +796,8 @@ "id": "33d020aa", "metadata": {}, "source": [ - "We know that `a` and `b` both refer to a string, but we don't know whether they refer to the *same* string. \n", - "There are two possible states, shown in the following figure." + "Мы знаем, что `a` и `b` относятся к строке, но мы не знаем, относятся ли они к одной и той же строке. \n", + "Существует два возможных состояния, показанных на следующем рисунке." ] }, { @@ -825,9 +825,9 @@ "id": "2f0b0431", "metadata": {}, "source": [ - "In the diagram on the left, `a` and `b` refer to two different objects that have the\n", - "same value. In the diagram on the right, they refer to the same object.\n", - "To check whether two variables refer to the same object, you can use the `is` operator." + "На диаграмме слева `a` и `b` относятся к двум различным объектам, которые имеют\n", + "одинаковое значение. На диаграмме справа они относятся к одному и тому же объекту.\n", + "Чтобы проверить, относятся ли две переменные к одному и тому же объекту, вы можете использовать оператор `is`." ] }, { @@ -843,9 +843,9 @@ "id": "d1eb0e36", "metadata": {}, "source": [ - "In this example, Python only created one string object, and both `a`\n", - "and `b` refer to it.\n", - "But when you create two lists, you get two objects." + "В этом примере Python создал только один строковый объект, и оба `a`\n", + "и `b` ссылаются на него.\n", + "Но когда вы создаете два списка, вы получаете два объекта." ] }, { @@ -861,7 +861,7 @@ "id": "a8d4c3d4", "metadata": {}, "source": [ - "So the state diagram looks like this." + "Диаграмма состояний выглядит так." ] }, { @@ -889,8 +889,8 @@ "id": "cc115a9f", "metadata": {}, "source": [ - "In this case we would say that the two lists are **equivalent**, because they have the same elements, but not **identical**, because they are not the same object. \n", - "If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical." + "В этом случае мы бы сказали, что эти два списка * * эквивалентны * *, потому что они имеют одни и те же элементы, но не * * идентичны * *, потому что они не являются одним и тем же объектом. \n", + "Если два объекта идентичны, они также эквивалентны, но если они эквивалентны, они не обязательно идентичны." ] }, { @@ -898,9 +898,9 @@ "id": "a58db021", "metadata": {}, "source": [ - "## Aliasing\n", + "## Алиасинг\n", "\n", - "If `a` refers to an object and you assign `b = a`, then both variables refer to the same object." + "Если `a` ссылается на объект, и вы назначаете `b = a`, то обе переменные ссылаются на один и тот же объект." ] }, { @@ -916,7 +916,7 @@ "id": "f6ab3262", "metadata": {}, "source": [ - "So the state diagram looks like this." + "Диаграмма состояний выглядит так." ] }, { @@ -944,12 +944,12 @@ "id": "c676fde9", "metadata": {}, "source": [ - "The association of a variable with an object is called a **reference**.\n", - "In this example, there are two references to the same object.\n", + "Связь переменной с объектом называется * * ссылкой * *.\n", + "В этом примере есть две ссылки на один и тот же объект.\n", "\n", - "An object with more than one reference has more than one name, so we say the object is **aliased**.\n", - "If the aliased object is mutable, changes made with one name affect the other.\n", - "In this example, if we change the object `b` refers to, we are also changing the object `a` refers to." + "Объект с более чем одной ссылкой имеет более одного имени, поэтому мы говорим, что объект имеет **псевдоним**.\n", + "Если псевдоним изменен, изменения, внесенные с одним именем, влияют на другое.\n", + "В этом примере, если мы изменим объект, на который ссылается `b`, мы также изменим объект, на который ссылается `a`." ] }, { @@ -965,12 +965,12 @@ "id": "e3ef0537", "metadata": {}, "source": [ - "So we would say that `a` \"sees\" this change.\n", - "Although this behavior can be useful, it is error-prone.\n", - "In general, it is safer to avoid aliasing when you are working with mutable objects.\n", + "Таким образом, мы бы сказали, что `a` «видит» это изменение.\n", + "Хотя такое поведение может быть полезным, оно подвержено ошибкам.\n", + "В целом, безопаснее избегать псевдонимов при работе с изменяемыми объектами.\n", "\n", - "For immutable objects like strings, aliasing is not as much of a problem.\n", - "In this example:" + "Для неизменных объектов, таких как строки, псевдоним не так уж и проблема.\n", + "В этом примере:" ] }, { @@ -986,8 +986,8 @@ "id": "952bbf60", "metadata": {}, "source": [ - "It almost never makes a difference whether `a` and `b` refer to the same\n", - "string or not." + "Почти никогда не имеет значения, относятся ли `a` и `b` к одному и тому же\n", + "строку или нет." ] }, { @@ -995,11 +995,11 @@ "id": "35045bef", "metadata": {}, "source": [ - "## List arguments\n", + "## Список аргументов\n", "\n", - "When you pass a list to a function, the function gets a reference to the\n", - "list. If the function modifies the list, the caller sees the change. For\n", - "example, `pop_first` uses the list method `pop` to remove the first element from a list." + "Когда вы передаете список функции, функция получает ссылку на\n", + "список. Если функция изменяет список, вызывающий видит изменение. Для\n", + "например, `pop_first` использует метод списка `pop` для удаления первого элемента из списка." ] }, { @@ -1015,7 +1015,7 @@ "id": "4953b0f9", "metadata": {}, "source": [ - "We can use it like this." + "Мы можем использовать его вот так." ] }, { @@ -1031,7 +1031,7 @@ "id": "ef5d3c1e", "metadata": {}, "source": [ - "The return value is the first element, which has been removed from the list -- as we can see by displaying the modified list." + "Возвращаемое значение - это первый элемент, который был удален из списка - как мы видим, отобразив измененный список." ] }, { @@ -1047,7 +1047,7 @@ "id": "e5288e08", "metadata": {}, "source": [ - "In this example, the parameter `lst` and the variable `letters` are aliases for the same object, so the state diagram looks like this:" + "В этом примере параметр `lst` и переменная `letters` являются псевдонимами для одного и того же объекта, поэтому диаграмма состояний выглядит следующим образом:" ] }, { @@ -1075,8 +1075,8 @@ "id": "c1a093d2", "metadata": {}, "source": [ - "Passing a reference to an object as an argument to a function creates a form of aliasing.\n", - "If the function modifies the object, those changes persist after the function is done." + "Передача ссылки на объект в качестве аргумента к функции создает форму псевдонима.\n", + "Если функция изменяет объект, эти изменения сохраняются после выполнения функции." ] }, { @@ -1086,12 +1086,12 @@ "tags": [] }, "source": [ - "## Making a word list\n", + "## Составление списка слов\n", "\n", - "In the previous chapter, we read the file `words.txt` and searched for words with certain properties, like using the letter `e`.\n", - "But we read the entire file many times, which is not efficient.\n", - "It is better to read the file once and put the words in a list.\n", - "The following loop shows how." + "В предыдущей главе мы читали файл `words.txt` и искали слова с определенными свойствами, например, используя букву `e`.\n", + "Но мы много раз читаем весь файл, что неэффективно.\n", + "Файл лучше прочитать один раз и сложить слова в список.\n", + "Следующий цикл показывает, как." ] }, { @@ -1117,11 +1117,11 @@ "id": "44450ffa", "metadata": {}, "source": [ - "Before the loop, `word_list` is initialized with an empty list.\n", - "Each time through the loop, the `append` method adds a word to the end.\n", - "When the loop is done, there are more than 113,000 words in the list.\n", + "Перед циклом `word_list` инициализируется пустым списком.\n", + "Каждый раз в цикле метод `append` добавляет слово в конец.\n", + "Когда цикл завершен, в списке более 113 000 слов.\n", "\n", - "Another way to do the same thing is to use `read` to read the entire file into a string." + "Другой способ сделать то же самое - использовать `read` для чтения всего файла в строку." ] }, { @@ -1137,8 +1137,8 @@ "id": "65718c7f", "metadata": {}, "source": [ - "The result is a single string with more than a million characters.\n", - "We can use the `split` method to split it into a list of words." + "В результате получается одна строка с более чем миллионом символов.\n", + "Мы можем использовать метод `split`, чтобы разбить его на список слов." ] }, { @@ -1154,8 +1154,8 @@ "id": "1b5b25a3", "metadata": {}, "source": [ - "Now, to check whether a string appears in the list, we can use the `in` operator.\n", - "For example, `'demotic'` is in the list." + "Теперь, чтобы проверить, появляется ли строка в списке, можно использовать оператор `in`.\n", + "Например, `'demotic'` находится в списке." ] }, { @@ -1171,7 +1171,7 @@ "id": "9df6674d", "metadata": {}, "source": [ - "But `'contrafibularities'` is not." + "Но `'contrafibularities'` - нет." ] }, { @@ -1187,7 +1187,7 @@ "id": "243c25b6", "metadata": {}, "source": [ - "And I have to say, I'm anaspeptic about it." + "И я должен сказать, что я анаспептик по этому поводу." ] }, { @@ -1195,12 +1195,12 @@ "id": "ce9ffd79", "metadata": {}, "source": [ - "## Debugging\n", + "## Отладка\n", "\n", - "Note that most list methods modify the argument and return `None`.\n", - "This is the opposite of the string methods, which return a new string and leave the original alone.\n", + "Обратите внимание, что большинство методов списка изменяют аргумент и возвращают `None`.\n", + "Это противоположность строковым методам, которые возвращают новую строку и оставляют оригинал в покое.\n", "\n", - "If you are used to writing string code like this:" + "Если вы привыкли писать строковый код так:" ] }, { @@ -1216,7 +1216,7 @@ "id": "d2117582", "metadata": {}, "source": [ - "It is tempting to write list code like this:" + "Заманчиво написать код списка следующим образом:" ] }, { @@ -1232,7 +1232,7 @@ "id": "991c439d", "metadata": {}, "source": [ - "`remove` modifies the list and returns `None`, so next operation you perform with `t` is likely to fail." + "`remove` изменяет список и возвращает `None`, поэтому следующая операция, которую вы выполняете с `t`, вероятно, завершится неудачей." ] }, { @@ -1250,11 +1250,11 @@ "id": "c500e2d8", "metadata": {}, "source": [ - "This error message takes some explaining.\n", - "An **attribute** of an object is a variable or method associated with it.\n", - "In this case, the value of `t` is `None`, which is a `NoneType` object, which does not have a attribute named `remove`, so the result is an `AttributeError`.\n", + "Это сообщение об ошибке требует некоторого объяснения.\n", + "**атрибут** объекта - это переменная или метод, связанный с ним.\n", + "В этом случае значение `t` равно `None`, что является объектом `NoneType`, который не имеет атрибута с именем `remove`, поэтому результатом является `AttributeError`.\n", "\n", - "If you see an error message like this, you should look backward through the program and see if you might have called a list method incorrectly." + "Если вы видите подобное сообщение об ошибке, вам следует оглянуться назад и посмотреть, не вызвали ли вы метод списка неправильно." ] }, { @@ -1262,34 +1262,34 @@ "id": "f90db780", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**list:**\n", - " An object that contains a sequence of values.\n", + "**список:**\n", + " Объект, содержащий последовательность значений.\n", "\n", - "**element:**\n", - " One of the values in a list or other sequence.\n", + "**Element:**\n", + " Одно из значений в списке или другой последовательности.\n", "\n", - "**nested list:**\n", - "A list that is an element of another list.\n", + "**вложенный список:**\n", + "Список, который является элементом другого списка.\n", "\n", - "**delimiter:**\n", - " A character or string used to indicate where a string should be split.\n", + "**разделитель:**\n", + " Символ или строка, используемая для указания, где строка должна быть разделена.\n", "\n", - "**equivalent:**\n", - " Having the same value.\n", + "**эквивалент:**\n", + " Имеет одинаковое значение.\n", "\n", - "**identical:**\n", - " Being the same object (which implies equivalence).\n", + "**идентично:**\n", + " Быть одним и тем же объектом (что подразумевает эквивалентность).\n", "\n", - "**reference:**\n", - " The association between a variable and its value.\n", + "**ссылка:**\n", + " Связь между переменной и ее значением.\n", "\n", - "**aliased:**\n", - "If there is more than one variable that refers to an object, the object is aliased.\n", + "**псевдоним:**\n", + "Если есть более одногокоторая относится к объекту, объект имеет псевдоним.\n", "\n", "**attribute:**\n", - " One of the named values associated with an object." + " Одно из именованных значений, связанных с объектом." ] }, { @@ -1297,8 +1297,7 @@ "id": "e67864e5", "metadata": {}, "source": [ - "## Exercises\n", - "\n" + "Упражнения" ] }, { @@ -1316,24 +1315,24 @@ "id": "ae9c42da", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Задать вопрос виртуальному помощнику\n", "\n", - "In this chapter, I used the words \"contrafibularities\" and \"anaspeptic\", but they are not actually English words.\n", - "They were used in the British television show *Black Adder*, Season 3, Episode 2, \"Ink and Incapability\".\n", + "В этой главе я использовал слова «contrafibularities» и «anaspeptic», но на самом деле это не английские слова.\n", + "Их использовали в британском телешоу *Black Adder*, сезон 3, эпизод 2, «Чернила и недееспособность».\n", "\n", - "However, when I asked ChatGPT 3.5 (August 3, 2023 version) where those words came from, it initially claimed they are from Monty Python, and later claimed they are from the Tom Stoppard play *Rosencrantz and Guildenstern Are Dead*.\n", + "Однако, когда я спросил ChatGPT 3.5 (версия от 3 августа 2023 года), откуда взялись эти слова, он изначально утверждал, что они из Monty Python, а позже утверждал, что они из пьесы Тома Стоппарда *Rosencrantz and Guildenstern Are Dead*.\n", "\n", - "If you ask now, you might get different results.\n", - "But this example is a reminder that virtual assistants are not always accurate, so you should check whether the results are correct.\n", - "As you gain experience, you will get a sense of which questions virtual assistants can answer reliably.\n", - "In this example, a conventional web search can identify the source of these words quickly.\n", + "Если вы спросите сейчас,вы можете получить разные результаты.\n", + "Но этот пример - напоминание о том, что виртуальные помощники не всегда точны, поэтому стоит проверить, корректны ли результаты.\n", + "По мере накопления опыта вы поймете, на какие вопросы могут надежно ответить виртуальные помощники.\n", + "В этом примере обычный веб-поиск может быстро определить источник этих слов.\n", "\n", - "If you get stuck on any of the exercises in this chapter, consider asking a virtual assistant for help.\n", - "If you get a result that uses features we haven't learned yet, you can assign the VA a \"role\".\n", + "Если вы застряли на каком-либо из упражнений в этой главе, обратитесь за помощью к виртуальному помощнику.\n", + "Если вы получите результат, который используетфункции, которые мы еще не изучили, вы можете назначить ВА «роль».\n", "\n", - "For example, before you ask a question try typing \"Role: Basic Python Programming Instructor\".\n", - "After that, the responses you get should use only basic features.\n", - "If you still see features we you haven't learned, you can follow up with \"Can you write that using only basic Python features?\"" + "Например, перед тем, как задать вопрос, попробуйте набрать «Role: Basic Python Programming Instructor».\n", + "После этого ответы, которые вы получите, должны использовать только базовые функции.\n", + "Если вы все еще видите функции, которые вы еще не изучили, вы можете задать вопрос «Можете ли вы написать это, используя только базовые функции Python?»" ] }, { @@ -1341,15 +1340,15 @@ "id": "31d5b304", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Two words are anagrams if you can rearrange the letters from one to spell the other.\n", - "For example, `tops` is an anagram of `stop`.\n", + "Два слова являются анаграммами, если вы можете переупорядочить буквы с одного на другое.\n", + "Например, `tops` является анаграммой `stop`.\n", "\n", - "One way to check whether two words are anagrams is to sort the letters in both words.\n", - "If the lists of sorted letters are the same, the words are anagrams.\n", + "Один из способов проверить, являются ли два слова анаграммами, - это отсортировать буквы в обоих словах.\n", + "Если списки отсортированных букв совпадают, слова являются анаграммами.\n", "\n", - "Write a function called `is_anagram` that takes two strings and returns `True` if they are anagrams." + "Напишите функцию `is_anagram`, которая принимает две строки и возвращает `True`, если они являются анаграммами." ] }, { @@ -1359,7 +1358,7 @@ "tags": [] }, "source": [ - "To get you started, here's an outline of the function with doctests." + "Для начала, вот краткое описание функции с доктринами." ] }, { @@ -1387,7 +1386,7 @@ "tags": [] }, "source": [ - "You can use `doctest` to test your function." + "Вы можете использовать `doctest` для проверки своей функции." ] }, { @@ -1405,7 +1404,7 @@ "id": "8501f3ba", "metadata": {}, "source": [ - "Using your function and the word list, find all the anagrams of `takes`." + "Используя свою функцию и список слов, найдите все анаграммы `takes`." ] }, { @@ -1421,9 +1420,9 @@ "id": "7f279f2f", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Python provides a built-in function called `reversed` that takes as an argument a sequence of elements -- like a list or string -- and returns a `reversed` object that contains the elements in reverse order." + "Python предоставляет встроенную функцию `reversed`, которая принимает в качестве аргумента последовательность элементов - например, список или строку - и возвращает объект `reversed`, содержащий элементы в обратном порядке." ] }, { @@ -1439,7 +1438,7 @@ "id": "0f95c76f", "metadata": {}, "source": [ - "If you want the reversed elements in a list, you can use the `list` function." + "Если вы хотите, чтобы обратные элементы были в списке, вы можете использовать функцию `list`." ] }, { @@ -1455,7 +1454,7 @@ "id": "8fc79a2f", "metadata": {}, "source": [ - "Of if you want them in a string, you can use the `join` method." + "Если вы хотите, чтобы они были в строке, вы можете использовать метод `join`." ] }, { @@ -1471,7 +1470,7 @@ "id": "ec4ce196", "metadata": {}, "source": [ - "So we can write a function that reverses a word like this." + "Таким образом, мы можем написать функцию, которая меняет слово на противоположное." ] }, { @@ -1487,8 +1486,8 @@ "id": "21550b5f", "metadata": {}, "source": [ - "A palindrome is a word that is spelled the same backward and forward, like \"noon\" and \"rotator\".\n", - "Write a function called `is_palindrome` that takes a string argument and returns `True` if it is a palindrome and `False` otherwise." + "Палиндром - это слово, которое пишется одинаково назад и вперед, как «полдень» и «ротатор».\n", + "Напишите функцию с именем `is_palindrome`, которая принимает строковый аргумент и возвращает `True`, если это палиндром, и `False` в противном случае." ] }, { @@ -1498,7 +1497,7 @@ "tags": [] }, "source": [ - "Here's an outline of the function with doctests you can use to check your function." + "Вот краткое описание функции с доктринами, которые вы можете использовать для проверки своей функции." ] }, { @@ -1534,7 +1533,7 @@ "id": "ad857abf", "metadata": {}, "source": [ - "You can use the following loop to find all of the palindromes in the word list with at least 7 letters." + "Вы можете использовать следующий цикл, чтобы найти все палиндромы в списке слов, содержащем не менее 7 букв." ] }, { @@ -1552,13 +1551,13 @@ "id": "11386f70", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `reverse_sentence` that takes as an argument a string that contains any number of words separated by spaces.\n", - "It should return a new string that contains the same words in reverse order.\n", - "For example, if the argument is \"Reverse this sentence\", the result should be \"Sentence this reverse\".\n", + "Напишите функцию `reverse_sentence`, которая принимает в качестве аргумента строку, содержащую любое количество слов, разделенных пробелами.\n", + "Он должен возвращать новую строку, содержащую те же слова в обратном порядке.\n", + "Например, если аргумент «Обратить это предложение», результатом должно быть «Предложение это обратное».\n", "\n", - "Hint: You can use the `capitalize` methods to capitalize the first word and convert the other words to lowercase. " + "Подсказка: Вы можете использовать методы `capitalize` для написания первого слова с заглавной буквы и преобразования других слов в нижний регистр." ] }, { @@ -1568,7 +1567,7 @@ "tags": [] }, "source": [ - "To get you started, here's an outline of the function with doctests." + "Для начала, вот краткое описание функции с доктринами." ] }, { @@ -1604,10 +1603,10 @@ "id": "fb5f24b1", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `total_length` that takes a list of strings and returns the total length of the strings.\n", - "The total length of the words in `word_list` should be $902{,}728$." + "Напишите функцию `total_length`, которая берет список строк и возвращает общую длину строк.\n", + "Общая длина слов в `word_list` должна составлять $ 902{,}728 $." ] }, { @@ -1643,11 +1642,11 @@ "source": [ "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Авторское право 2024 [Allen B. Дауни](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [Лицензия MIT](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -1673,4 +1672,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From f5ac9f2cfd68c4b3a4b998097b90b991b50fd19f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:02:55 +0300 Subject: [PATCH 10/44] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=D0=B0=20=D0=B2=20=D0=B3?= =?UTF-8?q?=D0=BB=D0=B0=D0=B2=D0=B5=2010?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blank/chap10.ipynb | 480 +++++++++++++++++++++++---------------------- 1 file changed, 241 insertions(+), 239 deletions(-) diff --git a/blank/chap10.ipynb b/blank/chap10.ipynb index 56d77c9..270837c 100644 --- a/blank/chap10.ipynb +++ b/blank/chap10.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432? ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325).\n" ] }, { @@ -25,13 +25,13 @@ "id": "737e79eb", "metadata": {}, "source": [ - "# Dictionaries\n", + "# Словарь\n", "\n", - "This chapter presents a built-in type called a dictionary.\n", - "It is one of Python's best features -- and the building block of many efficient and elegant algorithms.\n", + "В этой главе представлен встроенный тип, называемый словарем.\n", + "Это одна из лучших функций Python - и строительный блок многих эффективных и элегантных алгоритмов.\n", "\n", - "We'll use dictionaries to compute the number of unique words in a book and the number of times each one appears.\n", - "And in the exercises, we'll use dictionaries to solve word puzzles." + "Мы будем использовать словаря для вычисления количества уникальных слов в книге, и количество раз появляется каждый раз.\n", + "И в упражнениях мы будем использовать словари для решения головоломок.\n" ] }, { @@ -39,11 +39,11 @@ "id": "be7467bb", "metadata": {}, "source": [ - "## A dictionary is a mapping\n", + "## Словарь - это картирование\n", "\n", - "A **dictionary** is like a list, but more general.\n", - "In a list, the indices have to be integers; in a dictionary they can be (almost) any type.\n", - "For example, suppose we make a list of number words, like this." + "** Словарь ** похож на список, но более общий.\n", + "В списке индексы должны быть целыми числами; В словаре они могут быть (почти) любого типа.\n", + "Например, предположим, что мы составляем список чисел слов, как это.\n" ] }, { @@ -59,7 +59,7 @@ "id": "aa626f88", "metadata": {}, "source": [ - "We can use an integer as an index to get the corresponding word." + "Мы можем использовать целое число в качестве индекса для получения соответствующего слова.\n" ] }, { @@ -75,9 +75,9 @@ "id": "c38e143b", "metadata": {}, "source": [ - "But suppose we want to go in the other direction, and look up a word to get the corresponding integer.\n", - "We can't do that with a list, but we can with a dictionary.\n", - "We'll start by creating an empty dictionary and assigning it to `numbers`." + "Но предположим, что мы хотим пойти в другом направлении и посмотреть слово, чтобы получить соответствующее целое число.\n", + "Мы не можем сделать это со списком, но мы можем с словарем.\n", + "Мы начнем с создания пустого словаря и назначим его «номерам».\n" ] }, { @@ -93,8 +93,8 @@ "id": "3acce992", "metadata": {}, "source": [ - "The curly braces, `{}`, represent an empty dictionary.\n", - "To add items to the dictionary, we'll use square brackets." + "Кудрявые скобки, `{}`, представляют пустой словарь.\n", + "Чтобы добавить предметы в словарь, мы будем использовать квадратные кронштейны.\n" ] }, { @@ -110,9 +110,9 @@ "id": "1dbe12c3", "metadata": {}, "source": [ - "This assignment adds to the dictionary an **item**, which represents the association of a **key** and a **value**.\n", - "In this example, the key is the string `'zero'` and the value is the integer `0`.\n", - "If we display the dictionary, we see that it contains one item, which contains a key and a value separated by a colon, `:`." + "Это задание добавляет в словарь ** пункт **, который представляет ассоциацию ** ключа ** и ** значение **.\n", + "В этом примере ключ - это строка «Zero», а значение - целое число `0`.\n", + "Если мы отобразим словарь, мы видим, что он содержит один элемент, который содержит ключ и значение, разделенное толстой кишкой, `:`.\n" ] }, { @@ -128,7 +128,7 @@ "id": "ad32c23d", "metadata": {}, "source": [ - "We can add more items like this." + "Мы можем добавить больше таких предметов.\n" ] }, { @@ -144,9 +144,9 @@ "id": "278901e5", "metadata": {}, "source": [ - "Now the dictionary contains three items.\n", + "Теперь словарь содержит три пункта.\n", "\n", - "To look up a key and get the corresponding value, we use the bracket operator." + "Чтобы найти ключ и получить соответствующее значение, мы используем оператор кронштейна.\n" ] }, { @@ -162,7 +162,7 @@ "id": "df5724e6", "metadata": {}, "source": [ - "If the key isn't in the dictionary, we get a `KeyError`." + "Если ключ не в словаре, мы получаем `keeError '.\n" ] }, { @@ -180,7 +180,7 @@ "id": "2a027a6b", "metadata": {}, "source": [ - "The `len` function works on dictionaries; it returns the number of items." + "Функция `Len` работает на словари; Возвращает количество предметов.\n" ] }, { @@ -196,10 +196,10 @@ "id": "58221e96", "metadata": {}, "source": [ - "In mathematical language, a dictionary represents a **mapping** from keys to values, so you can also say that each key \"maps to\" a value.\n", - "In this example, each number word maps to the corresponding integer.\n", + "На математическом языке словарь представляет ** отображение ** от ключей к значениям, поэтому вы также можете сказать, что каждый ключ «карты к» значению.\n", + "В этом примере каждое число слов отображается на соответствующее целое число.\n", "\n", - "The following figure shows the state diagram for `numbers`." + "На следующем рисунке показана диаграмма состояния для «чисел».\n" ] }, { @@ -227,9 +227,9 @@ "id": "b092aa61", "metadata": {}, "source": [ - "A dictionary is represented by a box with the word \"dict\" outside and the items inside.\n", - "Each item is represented by a key and an arrow pointing to a value.\n", - "The quotation marks indicate that the keys here are strings, not variable names." + "Словарь представлен коробкой со словом «дикта» снаружи и элементами внутри.\n", + "Каждый элемент представлен ключом и стрелкой, указывающей на значение.\n", + "Цитаты указывают на то, что ключи здесь - это строки, а не имена переменных.\n" ] }, { @@ -237,10 +237,10 @@ "id": "2a0a128a", "metadata": {}, "source": [ - "## Creating dictionaries\n", + "## Создание словари\n", "\n", - "In the previous section we created an empty dictionary and added items one at a time using the bracket operator.\n", - "Instead, we could have created the dictionary all at once like this." + "В предыдущем разделе мы создали пустой словарь и добавляли элементы по одному, используя оператор кронштейна.\n", + "Вместо этого мы могли бы создать словарь одновременно, как это.\n" ] }, { @@ -256,11 +256,11 @@ "id": "31ded5b2", "metadata": {}, "source": [ - "Each item consists of a key and a value separated by a colon.\n", - "The items are separated by commas and enclosed in curly braces.\n", + "Каждый элемент состоит из ключа и значения, разделенного толстой кишкой.\n", + "Предметы разделены запятыми и закрываются в кудрявые скобки.\n", "\n", - "Another way to create a dictionary is to use the `dict` function.\n", - "We can make an empty dictionary like this." + "Другим способом создания словаря является использование функции «дикта».\n", + "Мы можем сделать такой пустой словарь таким.\n" ] }, { @@ -276,7 +276,7 @@ "id": "bfb215c9", "metadata": {}, "source": [ - "And we can make a copy of a dictionary like this." + "И мы можем сделать копию такого словаря.\n" ] }, { @@ -292,7 +292,7 @@ "id": "966c5539", "metadata": {}, "source": [ - "It is often useful to make a copy before performing operations that modify dictionaries." + "Часто полезно сделать копию перед выполнением операций, которые изменяют словаря.\n" ] }, { @@ -302,9 +302,9 @@ "tags": [] }, "source": [ - "## The in operator\n", + "## оператор\n", "\n", - "The `in` operator works on dictionaries, too; it tells you whether something appears as a *key* in the dictionary." + "Оператор `in 'также работает над словари; Он говорит вам, появляется ли что -то как * ключ * в словаре.\n" ] }, { @@ -320,7 +320,7 @@ "id": "80f6b264", "metadata": {}, "source": [ - "The `in` operator does *not* check whether something appears as a value." + "Оператор `in` * НЕ * проверяет, появляется ли что -то как значение.\n" ] }, { @@ -336,7 +336,7 @@ "id": "84856c8b", "metadata": {}, "source": [ - "To see whether something appears as a value in a dictionary, you can use the method `values`, which returns a sequence of values, and then use the `in` operator." + "Чтобы увидеть, появляется ли что -то как значение в словаре, вы можете использовать метод «значения», который возвращает последовательность значений, а затем использовать оператор `in`.\n" ] }, { @@ -352,8 +352,8 @@ "id": "45dc3d16", "metadata": {}, "source": [ - "The items in a Python dictionary are stored in a **hash table**, which is a way of organizing data that has a remarkable property: the `in` operator takes about the same amount of time no matter how many items are in the dictionary.\n", - "That makes it possible to write some remarkably efficient algorithms." + "Предметы в словаре Python хранятся в ** хэш -таблице **, которая является способом организации данных, которые имеют замечательное свойство: оператор в `in` занимает около того же количества времени, независимо от того, сколько элементов находится в словаре.\n", + "Это позволяет написать несколько удивительно эффективных алгоритмов.\n" ] }, { @@ -371,8 +371,8 @@ "id": "bba0522c", "metadata": {}, "source": [ - "To demonstrate, we'll compare two algorithms for finding pairs of words where one is the reverse of another -- like `stressed` and `desserts`.\n", - "We'll start by reading the word list." + "Чтобы продемонстрировать, мы сравним два алгоритма для поиска пар слов, где одно наоборот другое - например, «стресс» и «десерты».\n", + "Мы начнем с прочтения слова.\n" ] }, { @@ -388,7 +388,7 @@ "id": "ab29fb8a", "metadata": {}, "source": [ - "And here's `reverse_word` from the previous chapter." + "А вот `reverse_word` из предыдущей главы.\n" ] }, { @@ -404,8 +404,8 @@ "id": "93f7ac1b", "metadata": {}, "source": [ - "The following function loops through the words in the list.\n", - "For each one, it reverses the letters and then checks whether the reversed word in the word list." + "Следующая функция проходит через слова в списке.\n", + "Для каждого из них он меняет буквы, а затем проверяет, является ли обратное слово в списке слов.\n" ] }, { @@ -421,9 +421,9 @@ "id": "d4ebb84d", "metadata": {}, "source": [ - "This function takes more than a minute to run.\n", - "The problem is that the `in` operator checks the words in the list one at a time, starting at the beginning.\n", - "If it doesn't find what it's looking for -- which happens most of the time -- it has to search all the way to the end." + "Эта функция занимает более минуты.\n", + "Проблема в том, что оператор «в` »проверяет слова в списке по одному, начиная с начала.\n", + "Если он не найдет то, что он ищет - что происходит большую часть времени - он должен искать до конца.\n" ] }, { @@ -441,8 +441,8 @@ "id": "2acb6c50", "metadata": {}, "source": [ - "And the `in` operator is inside the loop, so it runs once for each word.\n", - "Since there are more than 100,000 words in the list, and for each one we check more than 100,000 words, the total number of comparisons is the number of words squared -- roughly -- which is almost 13 billion. " + "И оператор `in` находится внутри петли, поэтому он работает один раз для каждого слова.\n", + "Поскольку в списке насчитывается более 100 000 слов, и для каждого из них мы проверяем более 100 000 слов, общее количество сравнений - это количество квадратных слов - примерно - почти 13 миллиардов.\n" ] }, { @@ -458,8 +458,8 @@ "id": "5dbf01b7", "metadata": {}, "source": [ - "We can make this function much faster with a dictionary.\n", - "The following loop creates a dictionary that contains the words as keys." + "Мы можем сделать эту функцию намного быстрее с словарем.\n", + "Следующий цикл создает словарь, который содержит слова как ключи.\n" ] }, { @@ -475,9 +475,9 @@ "id": "b7f6a1b7", "metadata": {}, "source": [ - "The values in `word_dict` are all `1`, but they could be anything, because we won't ever look them up -- we will only use this dictionary to check whether a key exists.\n", + "Значения в `word_dict` - все« 1` », но они могут быть чем угодно, потому что мы никогда не будем их смотреть - мы будем использовать только этот словарь, чтобы проверить, существует ли ключ.\n", "\n", - "Now here's a version of the previous function that replaces `word_list` with `word_dict`." + "Теперь вот версия предыдущей функции, которая заменяет `word_list` на` word_dict`.\n" ] }, { @@ -493,7 +493,7 @@ "id": "5f41e54c", "metadata": {}, "source": [ - "This function takes less than one hundredth of a second, so it's about 10,000 times faster than the previous version." + "Эта функция занимает меньше, чем на сотни секунды, поэтому она примерно в 10 000 раз быстрее, чем в предыдущей версии.\n" ] }, { @@ -511,8 +511,8 @@ "id": "4cd91c99", "metadata": {}, "source": [ - "In general, the time it takes to find an element in a list is proportional to the length of the list.\n", - "The time it takes to find a key in a dictionary is almost constant -- regardless of the number of items." + "В целом, время, необходимое для поиска элемента в списке, пропорционально длине списка.\n", + "Время, необходимое для поиска ключа в словаре, почти постоянно - независимо от количества элементов.\n" ] }, { @@ -528,11 +528,11 @@ "id": "b3bfa8a5", "metadata": {}, "source": [ - "## A collection of counters\n", + "## Коллекция счетчиков\n", "\n", - "Suppose you are given a string and you want to count how many times each letter appears.\n", - "A dictionary is a good tool for this job.\n", - "We'll start with an empty dictionary." + "Предположим, вам дают строку, и вы хотите подсчитать, сколько раз появляется каждая буква.\n", + "Словарь - хороший инструмент для этой работы.\n", + "Мы начнем с пустого словаря.\n" ] }, { @@ -548,8 +548,8 @@ "id": "34a9498a", "metadata": {}, "source": [ - "As we loop through the letters in the string, suppose we see the letter `'a'` for the first time.\n", - "We can add it to the dictionary like this." + "Когда мы пробегаем буквы в строке, предположим, что мы видим букву «A» впервые.\n", + "Мы можем добавить его в словарь, как это.\n" ] }, { @@ -565,8 +565,8 @@ "id": "bca9fa11", "metadata": {}, "source": [ - "The value `1` indicates that we have seen the letter once.\n", - "Later, if we see the same letter again, we can increment the counter like this." + "Значение `1` указывает на то, что мы видели букву один раз.\n", + "Позже, если мы снова увидим ту же букву, мы сможем увеличить счетчик.\n" ] }, { @@ -582,7 +582,7 @@ "id": "274ea014", "metadata": {}, "source": [ - "Now the value associated with `'a'` is `2`, because we've seen the letter twice." + "Теперь значение, связанное с «a», - это `2`, потому что мы видели букву дважды.\n" ] }, { @@ -598,7 +598,7 @@ "id": "2ca8f99d", "metadata": {}, "source": [ - "The following function uses these features to count the number of times each letter appears in a string." + "Следующая функция использует эти функции, чтобы подсчитать количество раз, когда каждая буква появляется в строке.\n" ] }, { @@ -614,10 +614,10 @@ "id": "735c758b", "metadata": {}, "source": [ - "Each time through the loop, if `letter` is not in the dictionary, we create a new item with key `letter` and value `1`.\n", - "If `letter` is already in the dictionary we increment the value associated with `letter`.\n", + "Каждый раз через цикл, если «буква» нет в словаре, мы создаем новый элемент с ключом `witter` и значением` 1`.\n", + "Если «буква» уже находится в словаре, мы увеличиваем значение, связанное с «буквой».\n", "\n", - "Here's an example." + "Вот пример.\n" ] }, { @@ -633,7 +633,7 @@ "id": "8ac1fea4", "metadata": {}, "source": [ - "The items in `counter` show that the letter `'b'` appears once, `'r'` appears twice, and so on." + "Элементы в «счетчике» показывают, что буква «b» появляется один раз, «r'» появляется дважды, и так далее.\n" ] }, { @@ -641,10 +641,10 @@ "id": "912bdf5d", "metadata": {}, "source": [ - "## Looping and dictionaries\n", + "## Цикл и словари\n", "\n", - "If you use a dictionary in a `for` statement, it traverses the keys of the dictionary.\n", - "To demonstrate, let's make a dictionary that counts the letters in `'banana'`." + "Если вы используете словарь в утверждении «for», он пересекает ключи словаря.\n", + "Чтобы продемонстрировать, давайте сделаем словарь, который считает буквы в «банане».\n" ] }, { @@ -660,7 +660,7 @@ "id": "fe263f3d", "metadata": {}, "source": [ - "The following loop prints the keys, which are the letters." + "Следующая петля печатает ключи, которые являются буквами.\n" ] }, { @@ -676,7 +676,7 @@ "id": "bf1b7824", "metadata": {}, "source": [ - "To print the values, we can use the `values` method." + "Чтобы распечатать значения, мы можем использовать метод «значений».\n" ] }, { @@ -692,7 +692,7 @@ "id": "721135be", "metadata": {}, "source": [ - "To print the keys and values, we can loop through the keys and look up the corresponding values." + "Чтобы распечатать клавиши и значения, мы можем пройти через клавиши и искать соответствующие значения.\n" ] }, { @@ -708,7 +708,7 @@ "id": "efa1bce5", "metadata": {}, "source": [ - "In the next chapter, we'll see a more concise way to do the same thing." + "В следующей главе мы увидим более краткий способ сделать то же самое.\n" ] }, { @@ -716,10 +716,10 @@ "id": "a160c0ef", "metadata": {}, "source": [ - "## Lists and dictionaries\n", + "## списки и словари\n", "\n", - "You can put a list in a dictionary as a value.\n", - "For example, here's a dictionary that maps from the number `4` to a list of four letters." + "Вы можете поместить список в словаре в качестве значения.\n", + "Например, вот словарь, который отображает от номера «4» в список из четырех букв.\n" ] }, { @@ -735,8 +735,8 @@ "id": "815a829f", "metadata": {}, "source": [ - "But you can't put a list in a dictionary as a key.\n", - "Here's what happens if we try." + "Но вы не можете поместить список в словаре в качестве ключа.\n", + "Вот что произойдет, если мы попробуем.\n" ] }, { @@ -754,17 +754,17 @@ "id": "2469b08a", "metadata": {}, "source": [ - "I mentioned earlier that dictionaries use hash tables, and that means that the keys have to be **hashable**.\n", + "Ранее я упоминал, что словаря используют хэш -таблицы, а это означает, что ключи должны быть ** хэшабл **.\n", "\n", - "A **hash** is a function that takes a value (of any kind) and returns an integer.\n", - "Dictionaries use these integers, called hash values, to store and look up keys.\n", + "** Хэш ** - это функция, которая принимает значение (любого рода) и возвращает целое число.\n", + "Словари используют эти целые числа, называемые хэш -значениями, для хранения и поиска ключей.\n", "\n", - "This system only works if a key is immutable, so its hash value is always the same.\n", - "But if a key is mutable, its hash value could change, and the dictionary would not work.\n", - "That's why keys have to be hashable, and why mutable types like lists aren't.\n", + "Эта система работает только в том случае, если ключ неизменен, поэтому ее хэш -значение всегда одинаковое.\n", + "Но если ключ измененен, его хэш -ценность может измениться, и словарь не сработает.\n", + "Вот почему клавиши должны быть хранением, и почему изменяемые типы, такие как списки, не являются.\n", "\n", - "Since dictionaries are mutable, they can't be used as keys, either.\n", - "But they *can* be used as values." + "Поскольку словарры изменяются, их также нельзя использовать в качестве ключей.\n", + "Но они * могут * использоваться в качестве значений.\n" ] }, { @@ -774,13 +774,13 @@ "tags": [] }, "source": [ - "## Accumulating a list\n", + "## накапливание списка\n", "\n", - "For many programming tasks, it is useful to loop through one list or dictionary while building another.\n", - "As an example, we'll loop through the words in `word_dict` and make a list of palindromes -- that is, words that are spelled the same backward and forward, like \"noon\" and \"rotator\".\n", + "Для многих задач по программированию полезно пройти через один список или словарь при создании другого.\n", + "В качестве примера мы рассмотрим слова в `word_dict` и составим список палиндромов, то есть слова, которые пишутся одинаково назад и вперед, как« полдень »и« ротатор ».\n", "\n", - "In the previous chapter, one of the exercises asked you to write a function that checks whether a word is a palindrome.\n", - "Here's a solution that uses `reverse_word`." + "В предыдущей главе одно из упражнений попросило вас написать функцию, которая проверяет, является ли слово палиндромом.\n", + "Вот решение, которое использует `reverse_word`.\n" ] }, { @@ -796,7 +796,7 @@ "id": "af545fcd", "metadata": {}, "source": [ - "If we loop through the words in `word_dict`, we can count the number of palindromes like this." + "Если мы пробегаем слова в `word_dict`, мы можем подсчитать количество таких палиндромов.\n" ] }, { @@ -812,15 +812,15 @@ "id": "73c1ce1e", "metadata": {}, "source": [ - "By now, this pattern is familiar.\n", + "К настоящему времени этот шаблон знаком.\n", "\n", - "* Before the loop, `count` is initialized to `0`.\n", + "* Перед циклом `count` инициализируется до` 0`.\n", "\n", - "* Inside the loop, if `word` is a palindrome, we increment `count`.\n", + "* Внутри цикла, если `word` - палиндром, мы увеличиваем` count '.\n", "\n", - "* When the loop ends, `count` contains the total number of palindromes.\n", + "* Когда заканчивается цикл, «count» содержит общее количество палиндромов.\n", "\n", - "We can use a similar pattern to make a list of palindromes." + "Мы можем использовать аналогичный шаблон, чтобы составить список палиндромов.\n" ] }, { @@ -836,18 +836,18 @@ "id": "be909f3b", "metadata": {}, "source": [ - "Here's how it works:\n", + "Вот как это работает:\n", "\n", - "* Before the loop, `palindromes` is initialized with an empty list.\n", + "* Перед петлей `palindromes 'инициализируется с пустым списком.\n", "\n", - "* Inside the loop, if `word` is a palindrome, we append it to the end of `palindromes`.\n", + "* Внутри петли, если `word` - палиндром, мы добавляем его в конце« palindromes ».\n", "\n", - "* When the loop ends, `palindromes` is a list of palindromes.\n", + "* Когда заканчивается петля, `palindromes 'является списком палиндромов.\n", "\n", - "In this loop, `palindromes` is used as an **accumulator**, which is a variable that collects or accumulates data during a computation.\n", + "В этом цикле «Palindromes» используется в качестве ** аккумулятора **, которая является переменной, которая собирает или накапливает данные во время вычисления.\n", "\n", - "Now suppose we want to select only palindromes with seven or more letters.\n", - "We can loop through `palindromes` and make a new list that contains only long palindromes." + "Теперь предположим, что мы хотим выбрать только палиндромы с семь или более буквами.\n", + "Мы можем пройти через «palindromes» и составить новый список, который содержит только длинные палиндромы.\n" ] }, { @@ -863,7 +863,7 @@ "id": "fa8ed275", "metadata": {}, "source": [ - "Looping through a list like this, selecting some elements and omitting others, is called **filtering**." + "Проверка в таком списке, выбор некоторых элементов и пропущенные другие, называется ** Фильтрация **.\n" ] }, { @@ -873,9 +873,9 @@ "tags": [] }, "source": [ - "## Memos\n", + "## memos\n", "\n", - "If you ran the `fibonacci` function from [Chapter 6](section_fibonacci), maybe you noticed that the bigger the argument you provide, the longer the function takes to run." + "Если вы запустили функцию `fibonacci` из [Глава 6] (section_fibonacci), может быть, вы заметили, что чем больше аргумент, который вы предоставляете, тем дольше требуется функция.\n" ] }, { @@ -891,9 +891,9 @@ "id": "1b5203c2", "metadata": {}, "source": [ - "Furthermore, the run time increases quickly.\n", - "To understand why, consider the following figure, which shows the **call graph** for\n", - "`fibonacci` with `n=4`:" + "Кроме того, время выполнения быстро увеличивается.\n", + "Чтобы понять почему, рассмотрим следующую рисунок, который показывает график ** вызовов ** для\n", + "`fibonacci` с` n = 4`:\n" ] }, { @@ -931,16 +931,16 @@ "id": "4ee2a87c", "metadata": {}, "source": [ - "A call graph shows a set of function frames, with lines connecting each frame to the frames of the functions it calls.\n", - "At the top of the graph, `fibonacci` with `n=4` calls `fibonacci` with ` n=3` and `n=2`.\n", - "In turn, `fibonacci` with `n=3` calls `fibonacci` with `n=2` and `n=1`. And so on.\n", + "График вызовов показывает набор функциональных рам, с линиями, соединяющими каждый кадр к кадрам функций, которые он вызывает.\n", + "В верхней части графика, `fibonacci` с` n = 4` вызывает `fibonacci` с` n = 3` и `n = 2`.\n", + "В свою очередь, `fibonacci` с` n = 3` вызывает `fibonacci с` n = 2` и `n = 1`. И так далее.\n", "\n", - "Count how many times `fibonacci(0)` and `fibonacci(1)` are called. \n", - "This is an inefficient solution to the problem, and it gets worse as the argument gets bigger.\n", + "Подсчитайте, сколько раз называются фибоначчи (0) `и` fibonacci (1) `. \n", + "Это неэффективное решение проблемы, и это становится хуже, поскольку аргумент становится больше.\n", "\n", - "One solution is to keep track of values that have already been computed by storing them in a dictionary.\n", - "A previously computed value that is stored for later use is called a **memo**.\n", - "Here is a \"memoized\" version of `fibonacci`:" + "Одним из решений является отслеживание значений, которые уже были рассчитаны путем их хранения в словаре.\n", + "Ранее вычисленное значение, которое хранится для последующего использования, называется ** меморандум **.\n", + "Вот «запоминающая» версия «Фибоначчи»:\n" ] }, { @@ -956,16 +956,16 @@ "id": "d2ac4dd7", "metadata": {}, "source": [ - "`known` is a dictionary that keeps track of the Fibonacci numbers we already know\n", - "It starts with two items: `0` maps to `0` and `1` maps to `1`.\n", + "`Известный ' - это словарь, который отслеживает номера Фибоначчи, которые мы уже знаем\n", + "Это начинается с двух элементов: `0` Карты на` 0` и `1` карты до` 1`.\n", "\n", - "Whenever `fibonacci_memo` is called, it checks `known`.\n", - "If the result is already there, it can return immediately.\n", - "Otherwise it has to compute the new value, add it to the dictionary, and return it.\n", + "Всякий раз, когда называется `fibonacci_memo`, он проверяет« известный ».\n", + "Если результат уже есть, он может немедленно вернуться.\n", + "В противном случае он должен вычислить новое значение, добавить его в словарь и вернуть его.\n", "\n", - "Comparing the two functions, `fibonacci(40)` takes about 30 seconds to run.\n", - "`fibonacci_memo(40)` takes about 30 microseconds, so it's a million times faster.\n", - "In the notebook for this chapter, you'll see where these measurements come from." + "Сравнивая две функции, `fibonacci (40)` занимает около 30 секунд.\n", + "`fibonacci_memo (40)` занимает около 30 микросекунд, так что это в миллион раз быстрее.\n", + "В записной книжке для этой главы вы увидите, откуда поступают эти измерения.\n" ] }, { @@ -975,8 +975,8 @@ "tags": [] }, "source": [ - "To measure how long a function takes, we can use `%time` which is one of Jupyter's \"built-in magic commands\".\n", - "These commands are not part of the Python language, so they might not work in other development environments." + "Чтобы измерить, сколько времени занимает функция, мы можем использовать «%времени», которое является одним из «встроенных магических команд» Юпитера.\n", + "Эти команды не являются частью языка питона, поэтому они могут не работать в других условиях разработки.\n" ] }, { @@ -1004,18 +1004,18 @@ "id": "ec969e51", "metadata": {}, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "As you work with bigger datasets it can become unwieldy to debug by printing and checking the output by hand. Here are some suggestions for debugging large datasets:\n", + "Работая с более крупными наборами данных, он может стать громоздким, чтобы отлаживать путем печати и проверки вывода вручную. Вот несколько предложений по отладке больших наборов данных:\n", "\n", - "1. Scale down the input: If possible, reduce the size of the dataset. For example if the\n", - " program reads a text file, start with just the first 10 lines, or\n", - " with the smallest example you can find. You can either edit the\n", - " files themselves, or (better) modify the program so it reads only\n", - " the first `n` lines.\n", + "1. Увеличьте вход: если возможно, уменьшите размер набора данных. Например, если\n", + " Программа считывает текстовый файл, начните с первых 10 строк, или\n", + " С наименьшим примером вы можете найти. Вы можете либо отредактировать\n", + " сами файлы или (лучше) изменить программу, чтобы она только читала\n", + " Первые линии `n`.\n", "\n", - " If there is an error, you can reduce `n` to the smallest value where the error occurs.\n", - " As you find and correct errors, you can increase `n` gradually." + " Если есть ошибка, вы можете уменьшить `n` до наименьшего значения, где происходит ошибка.\n", + " Поскольку вы найдете и исправляете ошибки, вы можете постепенно увеличить `n`.\n" ] }, { @@ -1023,11 +1023,11 @@ "id": "1a62288b", "metadata": {}, "source": [ - "2. Check summaries and types: Instead of printing and checking the entire dataset, consider\n", - " printing summaries of the data -- for example, the number of items in\n", - " a dictionary or the total of a list of numbers.\n", + "2. Проверьте резюме и типы: вместо печати и проверки всего набора данных, рассмотрите\n", + " Печать резюме данных - например, количество элементов в\n", + " Словарь или общая сумма списка чисел.\n", "\n", - " A common cause of runtime errors is a value that is not the right type. For debugging this kind of error, it is often enough to print the type of a value." + " Общей причиной ошибок во время выполнения является значение, которое не является правильным типом. Для отладки такого рода ошибки часто бывает достаточно, чтобы распечатать тип значения.\n" ] }, { @@ -1035,13 +1035,15 @@ "id": "c749ea3c", "metadata": {}, "source": [ - "3. Write self-checks: Sometimes you can write code to check for errors automatically. For\n", - " example, if you are computing the average of a list of numbers, you\n", - " could check that the result is not greater than the largest element\n", - " in the list or less than the smallest. This is called a \"sanity\n", - " check\" because it detects results that are \"insane\".\n", + "3. Напишите самопроверка: иногда вы можете записать код, чтобы автоматически проверять ошибки. Для\n", + " Пример, если вы вычисляете среднее значение списка чисел, вы\n", + " мог бы проверить, что результат не больше, чем самый большой элемент\n", + " в списке или меньше, чем самый маленький. Это назыв\n", + "1659\n", + "ается «здравомыслием\n", + " Проверьте «потому что это обнаруживает результаты, которые« безумны ».\n", "\n", - " Another kind of check compares the results of two different computations to see if they are consistent. This is called a \"consistency check\"." + " Другой вид проверки сравнивает результаты двух разных вычислений, чтобы увидеть, являются ли они последовательными. Это называется «проверка согласованности».\n" ] }, { @@ -1049,9 +1051,9 @@ "id": "749b91e9", "metadata": {}, "source": [ - "4. Format the output: Formatting debugging output can make it easier to spot an error. We saw an example in [Chapter 6](section_debugging_factorial). Another tool you might find useful is the `pprint` module, which provides a `pprint` function that displays built-in types in a more human-readable format (`pprint` stands for \"pretty print\").\n", + "4. Форматирование вывода: форматирование отладки вывода может облегчить обнаружение ошибки. Мы увидели пример в [Глава 6] (section_debugging_factorial). Другим инструментом, который вы можете найти полезным, является модуль `pprint`, который обеспечивает функцию« pprint`, которая отображает встроенные типы в более читаемом человеке формате (`pprint` обозначает\" симпатичный печатный \").\n", "\n", - " Again, time you spend building scaffolding can reduce the time you spend debugging." + " Опять же, время, когда вы тратите строительные леса, может сократить время, которое вы проводите отладки.\n" ] }, { @@ -1059,44 +1061,44 @@ "id": "9820175f", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**dictionary:**\n", - " An object that contains key-value pairs, also called items.\n", + "**словарь:**\n", + " Объект, который содержит пары клавиш, также называемые элементами.\n", "\n", - "**item:**\n", - " In a dictionary, another name for a key-value pair.\n", + "**элемент:**\n", + " В словаре другое имя для пары ключей.\n", "\n", - "**key:**\n", - " An object that appears in a dictionary as the first part of a key-value pair.\n", + "**ключ:**\n", + " Объект, который появляется в словаре как первая часть пары ключей.\n", "\n", - "**value:**\n", - " An object that appears in a dictionary as the second part of a key-value pair. This is more specific than our previous use of the word \"value\".\n", + "**ценить:**\n", + " Объект, который появляется в словаре как вторая часть пары ключевых значений. Это более конкретно, чем наше предыдущее использование слова «значение».\n", "\n", - "**mapping:**\n", - " A relationship in which each element of one set corresponds to an element of another set.\n", + "** Картирование: **\n", + " Отношения, в которых каждый элемент из одного набора соответствует элементу другого набора.\n", "\n", - "**hash table:**\n", - "A collection of key-value pairs organized so that we can look up a key and find its value efficiently.\n", + "** Хэш -таблица: **\n", + "Коллекция парных пар, организованных таким образом, чтобы мы могли найти ключ и эффективно найти его значение.\n", "\n", - "**hashable:**\n", - " Immutable types like integers, floats and strings are hashable.\n", - " Mutable types like lists and dictionaries are not.\n", + "** Hashable: **\n", + " Необываемые типы, такие как целые числа, поплавки и струны, являются хэшабельными.\n", + " Между ними, такими как списки и словари, нет.\n", "\n", - "**hash function:**\n", - "A function that takes an object and computes an integer that is used to locate a key in a hash table.\n", + "** Хэш -функция: **\n", + "Функция, которая принимает объект и вычисляет целое число, которое используется для поиска ключа в хэш -таблице.\n", "\n", - "**accumulator:**\n", - " A variable used in a loop to add up or accumulate a result.\n", + "** Аккумулятор: **\n", + " Переменная, используемая в цикле, чтобы снять или накапливать результат.\n", "\n", - "**filtering:**\n", - "Looping through a sequence and selecting or omitting elements.\n", + "** Фильтрация: **\n", + "Зацикливание через последовательность и выбор или пропущение элементов.\n", "\n", - "**call graph:**\n", - "A diagram that shows every frame created during the execution of a program, with an arrow from each caller to each callee.\n", + "** Звоните в график: **\n", + "Диаграмма, которая показывает каждый кадр, созданный во время выполнения программы, со стрелкой от каждого вызывающего абонента до каждого Callee.\n", "\n", - "**memo:**\n", - " A computed value stored to avoid unnecessary future computation." + "** Памятка: **\n", + " Вычисленное значение, сохраненное, чтобы избежать ненужных будущих вычислений.\n" ] }, { @@ -1104,7 +1106,7 @@ "id": "906c1236", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения\n" ] }, { @@ -1122,13 +1124,13 @@ "id": "170f1deb", "metadata": {}, "source": [ - "### Ask an assistant\n", + "### Спросите помощника\n", "\n", - "In this chapter, I said the keys in a dictionary have to be hashable and I gave a short explanation. If you would like more details, ask a virtual assistant, \"Why do keys in Python dictionaries have to be hashable?\"\n", + "В этой главе я сказал, что ключи в словаре должны быть хранением, и я дал краткое объяснение. Если вам нужна более подробная информация, спросите виртуального помощника: «Почему ключи в словарях Python должны быть хранением?»\n", "\n", - "In [a previous section](section_dictionary_in_operator), we stored a list of words as keys in a dictionary so that we could use an efficient version of the `in` operator.\n", - "We could have done the same thing using a `set`, which is another built-in data type.\n", - "Ask a virtual assistant, \"How do I make a Python set from a list of strings and check whether a string is an element of the set?\"" + "В [предыдущий раздел] (section_dictionary_in_operator) мы сохранили список слов в качестве ключей в словаре, чтобы мы могли использовать эффективную версию оператора `in.\n", + "Мы могли бы сделать то же самое, используя «SET», который является еще одним встроенным типом данных.\n", + "Спросите виртуального помощника: «Как сделать набор Python из списка строк и проверить, является ли строка элементом набора?»\n" ] }, { @@ -1136,11 +1138,11 @@ "id": "badf7d65", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Dictionaries have a method called `get` that takes a key and a default value. \n", - "If the key appears in the dictionary, `get` returns the corresponding value; otherwise it returns the default value.\n", - "For example, here's a dictionary that maps from the letters in a string to the number of times they appear." + "В словари есть метод под названием «get», который занимает ключ и значение по умолчанию. \n", + "Если ключ появляется в словаре, `get 'возвращает соответствующее значение; В противном случае он возвращает значение по умолчанию.\n", + "Например, вот словарь, который отображает от букв в строке до количества раз, когда они появляются.\n" ] }, { @@ -1156,7 +1158,7 @@ "id": "c3f6458d", "metadata": {}, "source": [ - "If we look up a letter that appears in the word, `get` returns the number of times it appears." + "Если мы посмотрим на букву, которая появляется в слове, «get» возвращает количество раз, когда она появляется.\n" ] }, { @@ -1172,7 +1174,7 @@ "id": "49bbff3e", "metadata": {}, "source": [ - "If we look up a letter that doesn't appear, we get the default value, `0`." + "Если мы посмотрим букву, которая не появляется, мы получим значение по умолчанию, `0`.\n" ] }, { @@ -1188,8 +1190,8 @@ "id": "4ac3210f", "metadata": {}, "source": [ - "Use `get` to write a more concise version of `value_counts`.\n", - "You should be able to eliminate the `if` statement." + "Используйте `get`, чтобы написать более краткую версию` value_counts`.\n", + "Вы должны быть в состоянии устранить оператор «если».\n" ] }, { @@ -1197,12 +1199,12 @@ "id": "5413af6e", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "What is the longest word you can think of where each letter appears only once?\n", - "Let's see if we can find one longer than `unpredictably`.\n", + "Какое самое длинное слово вы можете подумать о том, где каждая буква появляется только один раз?\n", + "Давайте посмотрим, сможем ли мы найти один дольше, чем «непредсказуемо».\n", "\n", - "Write a function named `has_duplicates` that takes a sequence -- like a list or string -- as a parameter and returns `True` if there is any element that appears in the sequence more than once." + "Напишите функцию с именем `has_duplicates`, которая принимает последовательность - как список или строку - в качестве параметра и возвращает` true`, если есть какой -либо элемент, который появляется в последовательности более одного раза.\n" ] }, { @@ -1212,7 +1214,7 @@ "tags": [] }, "source": [ - "To get you started, here's an outline of the function with doctests." + "Чтобы начать, вот схема функции с Doctests.\n" ] }, { @@ -1240,7 +1242,7 @@ "tags": [] }, "source": [ - "You can use `doctest` to test your function." + "Вы можете использовать `doctest`, чтобы проверить вашу функцию.\n" ] }, { @@ -1260,7 +1262,7 @@ "tags": [] }, "source": [ - "You can use this loop to find the longest words with no repeated letters." + "Вы можете использовать этот цикл, чтобы найти самые длинные слова без повторяющихся букв.\n" ] }, { @@ -1278,11 +1280,11 @@ "id": "afd5f3b6", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write function called `find_repeats` that takes a dictionary that maps from each key to a counter, like the result from `value_counts`.\n", - "It should loop through the dictionary and return a list of keys that have counts greater than `1`.\n", - "You can use the following outline to get started." + "Функция записи называется `find_repeats`, которая принимает словарь, который отображает из каждого ключа на счетчик, например, результат` value_counts`.\n", + "Он должен пройти через словарь и вернуть список клавиш, которые имеют значение больше, чем «1».\n", + "Вы можете использовать следующий план, чтобы начать.\n" ] }, { @@ -1308,8 +1310,8 @@ "tags": [] }, "source": [ - "You can use the following examples to test your code.\n", - "First, we'll make a dictionary that maps from letters to counts." + "Вы можете использовать следующие примеры для проверки вашего кода.\n", + "Во -первых, мы сделаем словарь, который отображает от букв к счетам.\n" ] }, { @@ -1329,7 +1331,7 @@ "tags": [] }, "source": [ - "The result from `find_repeats` should be `['a', 'n']`." + "Результатом «find_repeats» должен быть «['a', 'n']`.\n" ] }, { @@ -1349,8 +1351,8 @@ "tags": [] }, "source": [ - "Here's another example that starts with a list of numbers.\n", - "The result should be `[1, 2]`." + "Вот еще один пример, который начинается со списка чисел.\n", + "Результат должен быть `[1, 2]`.\n" ] }, { @@ -1368,9 +1370,9 @@ "id": "1c700d84", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Suppose you run `value_counts` with two different words and save the results in two dictionaries." + "Предположим, вы запускаете `value_counts` с двумя разными словами и сохраните результаты в двух словарных.\n" ] }, { @@ -1386,11 +1388,11 @@ "id": "deb14c7a", "metadata": {}, "source": [ - "Each dictionary maps from a set of letters to the number of times they appear.\n", - "Write a function called `add_counters` that takes two dictionaries like this and returns a new dictionary that contains all of the letters and the total number of times they appear in either word.\n", + "Каждый словарь карты из набора букв к количеству раз, когда они появляются.\n", + "Напишите функцию, называемую «add_counters», которая принимает два словарных слоя, подобных этому, и возвращает новый словарь, который содержит все буквы, и общее количество раз они появляются в любом словом.\n", "\n", - "There are many ways to solve this problem.\n", - "Once you have a working solution, consider asking a virtual assistant for different solutions." + "Есть много способов решить эту проблему.\n", + "После того, как у вас есть рабочее решение, подумайте о том, чтобы попросить виртуального помощника для различных решений.\n" ] }, { @@ -1414,16 +1416,16 @@ "id": "f88110a9", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "A word is \"interlocking\" if we can split it into two words by taking alternating letters.\n", - "For example, \"schooled\" is an interlocking word because it can be split into \"shoe\" and \"cold\".\n", + "Слово «взаимодействует», если мы можем разделить его на два слова, принимая чередующиеся буквы.\n", + "Например, «обучение» - это взаимосвязанное слово, потому что его можно разделить на «обувь» и «холод».\n", "\n", - "To select alternating letters from a string, you can use a slice operator with three components that indicate where to start, where to stop, and the \"step size\" between the letters.\n", + "Чтобы выбрать чередующиеся буквы из строки, вы можете использовать оператор среза с тремя компонентами, которые указывают, с чего начать, где остановиться, и «размер шага» между буквами.\n", "\n", - "In the following slice, the first component is `0`, so we start with the first letter.\n", - "The second component is `None`, which means we should go all the way to the end of the string.\n", - "And the third component is `2`, so there are two steps between the letters we select." + "В следующем срезе первый компонент составляет `0`, поэтому мы начинаем с первой буквы.\n", + "Второй компонент - «нет», что означает, что мы должны пройти весь путь до конца строки.\n", + "И третий компонент - 2 ', поэтому между выбранными нами буквами есть два шага.\n" ] }, { @@ -1439,8 +1441,8 @@ "id": "d432332d", "metadata": {}, "source": [ - "Instead of providing `None` as the second component, we can get the same effect by leaving it out altogether.\n", - "For example, the following slice selects alternating letters, starting with the second letter." + "Вместо того, чтобы предоставлять «нет» в качестве второго компонента, мы можем получить тот же эффект, оставив его вообще.\n", + "Например, следующий срез выбирает чередующиеся буквы, начиная со второй буквы.\n" ] }, { @@ -1456,7 +1458,7 @@ "id": "c8c4e3ba", "metadata": {}, "source": [ - "Write a function called `is_interlocking` that takes a word as an argument and returns `True` if it can be split into two interlocking words." + "Напишите функцию, называемую `is_interlocking`, которая принимает слово в качестве аргумента и возвращает` true`, если ее можно разделить на два взаимосвязанных слова.\n" ] }, { @@ -1474,7 +1476,7 @@ "tags": [] }, "source": [ - "You can use the following loop to find the interlocking words in the word list." + "Вы можете использовать следующий цикл, чтобы найти взаимосвязанные слова в списке слов.\n" ] }, { @@ -1500,13 +1502,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT] (https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik\n" ] } ], @@ -1532,4 +1534,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 4a0b2a5fbd7635cbc2b888b68ba2bebe8af07a34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:03:23 +0300 Subject: [PATCH 11/44] Translate chapter 11 notebook to Russian --- blank/chap11.ipynb | 548 ++++++++++++++++++++++----------------------- 1 file changed, 274 insertions(+), 274 deletions(-) diff --git a/blank/chap11.ipynb b/blank/chap11.ipynb index d80bc23..c5cd971 100644 --- a/blank/chap11.ipynb +++ b/blank/chap11.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432?ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325).\n" ] }, { @@ -27,16 +27,16 @@ "tags": [] }, "source": [ - "# Tuples\n", + "# КУТУ\n", "\n", - "This chapter introduces one more built-in type, the tuple, and then shows how lists, dictionaries, and tuples work together.\n", - "It also presents tuple assignment and a useful feature for functions with variable-length argument lists: the packing and unpacking operators.\n", + "В этой главе представлены еще один встроенный тип, кортеж, а затем показывает, как списки, словари и кортежи работают вместе.\n", + "Он также представляет назначение кортежей и полезную функцию для функций с списками аргументов переменной длины: операторов упаковки и распаковки.\n", "\n", - "In the exercises, we'll use tuples, along with lists and dictionaries, to solve more word puzzles and implement efficient algorithms.\n", + "В упражнениях мы будем использовать кортежи, наряду с списками и словарями, чтобы решить больше головоломок и реализации эффективных алгоритмов.\n", "\n", - "One note: There are two ways to pronounce \"tuple\".\n", - "Some people say \"tuh-ple\", which rhymes with \"supple\".\n", - "But in the context of programming, most people say \"too-ple\", which rhymes with \"quadruple\"." + "Одно примечание: есть два способа произнесения «корзина».\n", + "Некоторые люди говорят «Tuh-Ple», который рифмуется с «пушкой».\n", + "Но в контексте программирования большинство людей говорят «Too-Ple», который рифмуется с «четырехкратным».\n" ] }, { @@ -44,12 +44,12 @@ "id": "19474596", "metadata": {}, "source": [ - "## Tuples are like lists\n", + "## КУТУ - это как списки\n", "\n", - "A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so tuples are a lot like lists.\n", - "The important difference is that tuples are immutable.\n", + "Крупель - это последовательность значений.Значения могут быть любым типом, и они индексируются целыми числами, поэтому кортежи очень похожи на списки.\n", + "Важным отличием является то, что кортежи неизменны.\n", "\n", - "To create a tuple, you can write a comma-separated list of values." + "Чтобы создать кортеж, вы можете написать список значений, разделяемый запятыми.\n" ] }, { @@ -65,7 +65,7 @@ "id": "a2ec15d8", "metadata": {}, "source": [ - "Although it is not necessary, it is common to enclose tuples in parentheses." + "Хотя в этом нет необходимости, это обычно прикладывает в скобки в скобках.\n" ] }, { @@ -81,7 +81,7 @@ "id": "9194a159", "metadata": {}, "source": [ - "To create a tuple with a single element, you have to include a final comma." + "Чтобы создать кортеж с одним элементом, вы должны включить окончательную запятую.\n" ] }, { @@ -97,7 +97,7 @@ "id": "e39b95a5", "metadata": {}, "source": [ - "A single value in parentheses is not a tuple." + "Единственное значение в скобках - это не кортеж.\n" ] }, { @@ -113,8 +113,8 @@ "id": "a64bfb64", "metadata": {}, "source": [ - "Another way to create a tuple is the built-in function `tuple`. With no\n", - "argument, it creates an empty tuple." + "Другим способом создания кортежа является встроенная функция `tuple '.Без\n", + "Аргумент, это создает пустой кортеж.\n" ] }, { @@ -130,8 +130,8 @@ "id": "f3447831", "metadata": {}, "source": [ - "If the argument is a sequence (string, list or tuple), the result is a\n", - "tuple with the elements of the sequence." + "Если аргумент представляет собой последовательность (строка, список или кортеж), результатом является\n", + "Круп с элементами последовательности.\n" ] }, { @@ -147,10 +147,10 @@ "id": "2e48b980", "metadata": {}, "source": [ - "Because `tuple` is the name of a built-in function, you should avoid using it as a variable name.\n", + "Поскольку `tuple`-это имя встроенной функции, вы должны избегать использования ее в качестве имени переменной.\n", "\n", - "Most list operators also work with tuples.\n", - "For example, the bracket operator indexes an element." + "Большинство операторов списка также работают с кортежами.\n", + "Например, оператор кронштейна индексирует элемент.\n" ] }, { @@ -166,7 +166,7 @@ "id": "2f702785", "metadata": {}, "source": [ - "And the slice operator selects a range of elements." + "И оператор среза выбирает ряд элементов.\n" ] }, { @@ -182,7 +182,7 @@ "id": "c9ed9af2", "metadata": {}, "source": [ - "The `+` operator concatenates tuples." + "Оператор `+` объединяет платы.\n" ] }, { @@ -198,7 +198,7 @@ "id": "1d7dcd6d", "metadata": {}, "source": [ - "And the `*` operator duplicates a tuple a given number of times." + "И оператор `*` дублирует кортеж на определенное количество раз.\n" ] }, { @@ -214,7 +214,7 @@ "id": "a53ce8bd", "metadata": {}, "source": [ - "The `sorted` function works with tuples -- but the result is a list, not a tuple." + "Функция «отсортированная» работает с кортежами, но результатом является список, а не кортеж.\n" ] }, { @@ -230,7 +230,7 @@ "id": "50e5cadc", "metadata": {}, "source": [ - "The `reversed` function also works with tuples." + "Функция `reversed` также работает с кортежами.\n" ] }, { @@ -246,7 +246,7 @@ "id": "f6d973c5", "metadata": {}, "source": [ - "The result is a `reversed` object, which we can convert to a list or tuple." + "Результатом является объект «обратный», который мы можем преобразовать в список или кортеж.\n" ] }, { @@ -262,7 +262,7 @@ "id": "a7cb9ee6", "metadata": {}, "source": [ - "Based on the examples so far, it might seem like tuples are the same as lists." + "Основываясь на примерах до сих пор, может показаться, что кортежи такие же, как и списки.\n" ] }, { @@ -270,9 +270,9 @@ "id": "8c3f381e", "metadata": {}, "source": [ - "## But tuples are immutable\n", + "## но кортежи неизменны\n", "\n", - "If you try to modify a tuple with the bracket operator, you get a `TypeError`." + "Если вы попытаетесь изменить кортеж с оператором кронштейна, вы получите `typeerror.\n" ] }, { @@ -290,7 +290,7 @@ "id": "592ce99c", "metadata": {}, "source": [ - "And tuples don't have any of the methods that modify lists, like `append` and `remove`." + "И у кортежей нет ни одного из методов, которые изменяют списки, такие как `adpend` и` remove '.\n" ] }, { @@ -308,10 +308,10 @@ "id": "70772ba2", "metadata": {}, "source": [ - "Recall that an \"attribute\" is a variable or method associated with an object -- this error message means that tuples don't have a method named `remove`.\n", + "Напомним, что «атрибут» - это переменная или метод, связанный с объектом - это сообщение об ошибке означает, что у кортежей нет метода с именем `remove '.\n", "\n", - "Because tuples are immutable, they are hashable, which means they can be used as keys in a dictionary.\n", - "For example, the following dictionary contains two tuples as keys that map to integers." + "Поскольку кортежи неизменны, они являются хэшабельными, что означает, что их можно использовать в качестве ключей в словаре.\n", + "Например, следующий словарь содержит две кортежи в качестве ключей, которые отображают целые числа.\n" ] }, { @@ -327,7 +327,7 @@ "id": "47ba17ab", "metadata": {}, "source": [ - "We can look up a tuple in a dictionary like this:" + "Мы можем посмотреть кортеж в таком словаре, как это:\n" ] }, { @@ -343,7 +343,7 @@ "id": "f2c0a354", "metadata": {}, "source": [ - "Or if we have a variable that refers to a tuple, we can use it as a key." + "Или, если у нас есть переменная, которая относится к кортежу, мы можем использовать ее в качестве ключа.\n" ] }, { @@ -359,7 +359,7 @@ "id": "2ea8fc3c", "metadata": {}, "source": [ - "Tuples can also appear as values in a dictionary." + "ПУЛЯ также могут появляться в виде значений в словаре.\n" ] }, { @@ -375,9 +375,9 @@ "id": "25655ab3", "metadata": {}, "source": [ - "## Tuple assignment\n", + "## назначение кортежей\n", "\n", - "You can put a tuple of variables on the left side of an assignment, and a tuple of values on the right." + "Вы можете поставить кортеж с переменными на левую сторону назначения и кортеж значений справа.\n" ] }, { @@ -393,8 +393,8 @@ "id": "92c00ceb", "metadata": {}, "source": [ - "The values are assigned to the variables from left to right -- in this example, `a` gets the value `1` and `b` gets the value `2`.\n", - "We can display the results like this:" + "Значения присваиваются переменным слева направо - в этом примере `a` получает значение` 1`, а `B` получает значение` 2`.\n", + "Мы можем отобразить результаты подобными:\n" ] }, { @@ -410,8 +410,8 @@ "id": "6362b36e", "metadata": {}, "source": [ - "More generally, if the left side of an assignment is a tuple, the right side can be any kind of sequence -- string, list or tuple. \n", - "For example, to split an email address into a user name and a domain, you could write:" + "В более общем плане, если левая сторона назначения является кортежом, правая сторона может быть какой -либо последовательности - строка, список или кортеж.\n", + "Например, чтобы разделить адрес электронной почты на имя пользователя и домен, вы можете написать:\n" ] }, { @@ -427,7 +427,7 @@ "id": "d134a94c", "metadata": {}, "source": [ - "The return value from `split` is a list with two elements -- the first element is assigned to `username`, the second to `domain`." + "Возвращаемое значение из `split` - это список с двумя элементами - первый элемент назначается« имя пользователя », второе - домен '.\n" ] }, { @@ -443,8 +443,8 @@ "id": "5a7e3c62", "metadata": {}, "source": [ - "The number of variables on the left and the number of values on the\n", - "right have to be the same -- otherwise you get a `ValueError`." + "Количество переменных слева и количество значений на\n", + "Правильно должно быть одинаковым - иначе вы получаете `valueError '.\n" ] }, { @@ -462,8 +462,8 @@ "id": "808c2928", "metadata": {}, "source": [ - "Tuple assignment is useful if you want to swap the values of two variables.\n", - "With conventional assignments, you have to use a temporary variable, like this:" + "Назначение кортежей полезно, если вы хотите поменять значения двух переменных.\n", + "С обычными заданиями вы должны использовать временную переменную, например:\n" ] }, { @@ -479,7 +479,7 @@ "id": "98496d02", "metadata": {}, "source": [ - "That works, but with tuple assignment we can do the same thing without a temporary variable." + "Это работает, но с назначением кортежей мы можем сделать то же самое без временной переменной.\n" ] }, { @@ -495,10 +495,10 @@ "id": "a66a87bc", "metadata": {}, "source": [ - "This works because all of the expressions on the right side are evaluated before any of the assignments.\n", + "Это работает, потому что все выражения на правой стороне оцениваются перед какими -либо заданиями.\n", "\n", - "We can also use tuple assignment in a `for` statement.\n", - "For example, to loop through the items in a dictionary, we can use the `items` method." + "Мы также можем использовать назначение кортежа в операторе `for`.\n", + "Например, чтобы пройти через элементы в словаре, мы можем использовать метод «элементов».\n" ] }, { @@ -514,9 +514,9 @@ "id": "dd0d4feb", "metadata": {}, "source": [ - "Each time through the loop, `item` is assigned a tuple that contains a key and the corresponding value.\n", + "Каждый раз через цикл «Item» назначается кортеж, который содержит ключ и соответствующее значение.\n", "\n", - "We can write this loop more concisely, like this:" + "Мы можем написать эту петлю более кратко, как это:\n" ] }, { @@ -532,7 +532,7 @@ "id": "f0513578", "metadata": {}, "source": [ - "Each time through the loop, a key and the corresponding value are assigned directly to `key` and `value`." + "Каждый раз через цикл, ключ и соответствующее значение назначаются непосредственно на `key` и` value`.\n" ] }, { @@ -540,16 +540,16 @@ "id": "efedeb37", "metadata": {}, "source": [ - "## Tuples as return values\n", + "## КУТУ В качестве возвращаемых значений\n", "\n", - "Strictly speaking, a function can only return one value, but if the\n", - "value is a tuple, the effect is the same as returning multiple values.\n", - "For example, if you want to divide two integers and compute the quotient\n", - "and remainder, it is inefficient to compute `x//y` and then `x%y`. It is\n", - "better to compute them both at the same time.\n", + "Строго говоря, функция может вернуть только одно значение, но если\n", + "Значение - это кортеж, эффект такой же, как и возврат нескольких значений.\n", + "Например, если вы хотите разделить два целых числа и вычислить коэффициент\n", + "а остаток неэффективен вычислять `x // y`, а затем` x%y`.Это\n", + "Лучше вычислить их обоих одновременно.\n", "\n", - "The built-in function `divmod` takes two arguments and returns a tuple\n", - "of two values, the quotient and remainder." + "Встроенная функция `divmod` принимает два аргумента и возвращает кортеж\n", + "двух значений, коэффициента и остатка.\n" ] }, { @@ -565,7 +565,7 @@ "id": "33f3c57d", "metadata": {}, "source": [ - "We can use tuple assignment to store the elements of the tuple in two variables. " + "Мы можем использовать назначение кортежа для хранения элементов кортежа в двух переменных.\n" ] }, { @@ -589,7 +589,7 @@ "id": "15079805", "metadata": {}, "source": [ - "Here is an example of a function that returns a tuple." + "Вот пример функции, которая возвращает кортеж.\n" ] }, { @@ -605,8 +605,8 @@ "id": "43c4e1e0", "metadata": {}, "source": [ - "`max` and `min` are built-in functions that find the largest and smallest elements of a sequence. \n", - "`min_max` computes both and returns a tuple of two values." + "`max` и` min '-это встроенные функции, которые находят самые большие и наименьшие элементы последовательности.\n", + "`min_max` вычисляет оба и возвращает кортеж из двух значений.\n" ] }, { @@ -622,7 +622,7 @@ "id": "86b60e71", "metadata": {}, "source": [ - "We can assign the results to variables like this:" + "Мы можем назначить результаты с такими переменными:\n" ] }, { @@ -640,11 +640,11 @@ "tags": [] }, "source": [ - "## Argument packing\n", + "## Аргумент упаковка\n", "\n", - "Functions can take a variable number of arguments. \n", - "A parameter name that begins with the `*` operator **packs** arguments into a tuple.\n", - "For example, the following function takes any number of arguments and computes their arithmetic mean -- that is, their sum divided by the number of arguments. " + "Функции могут принимать переменное количество аргументов.\n", + "Имя параметра, которое начинается с оператора `*` упаковывает ** аргументы в кортеж.\n", + "Например, следующая функция принимает любое количество аргументов и вычисляет их среднее арифметику, то есть их сумму, разделенную на количество аргументов.\n" ] }, { @@ -660,8 +660,8 @@ "id": "6044fc1b", "metadata": {}, "source": [ - "The parameter can have any name you like, but `args` is conventional.\n", - "We can call the function like this:" + "Параметр может иметь любое имя, которое вам нравится, но `args 'является обычным.\n", + "Мы можем назвать функцию так:\n" ] }, { @@ -677,8 +677,8 @@ "id": "a5e8b158", "metadata": {}, "source": [ - "If you have a sequence of values and you want to pass them to a function as multiple arguments, you can use the `*` operator to **unpack** the tuple.\n", - "For example, `divmod` takes exactly two arguments -- if you pass a tuple as a parameter, you get an error." + "Если у вас есть последовательность значений, и вы хотите передать их в функцию в качестве нескольких аргументов, вы можете использовать оператор `*` для ** распаковывать ** кортеж.\n", + "Например, «Divmod» принимает ровно два аргумента - если вы передаете кортеж в качестве параметра, вы получаете ошибку.\n" ] }, { @@ -696,8 +696,8 @@ "id": "5a9110db", "metadata": {}, "source": [ - "Even though the tuple contains two elements, it counts as a single argument.\n", - "But if you unpack the tuple, it is treated as two arguments." + "Несмотря на то, что кортеж содержит два элемента, он считается единственным аргументом.\n", + "Но если вы распаковываете кортеж, его рассматривают как два аргумента.\n" ] }, { @@ -713,8 +713,8 @@ "id": "da554863", "metadata": {}, "source": [ - "Packing and unpacking can be useful if you want to adapt the behavior of an existing function.\n", - "For example, this function takes any number of arguments, removes the lowest and highest, and computes the mean of the rest." + "Упаковка и распаковка могут быть полезны, если вы хотите адаптировать поведение существующей функции.\n", + "Например, эта функция принимает любое количество аргументов, удаляет самое низкое и самое высокое и вычисляет среднее значение для остальных.\n" ] }, { @@ -730,11 +730,11 @@ "id": "d1e05e49", "metadata": {}, "source": [ - "First it uses `min_max` to find the lowest and highest elements.\n", - "Then it converts `args` to a list so it can use the `remove` method.\n", - "Finally it unpacks the list so the elements are passed to `mean` as separate arguments, rather than as a single list.\n", + "Сначала он использует `min_max`, чтобы найти самые низкие и самые высокие элементы.\n", + "Затем он преобразует «args» в список, чтобы использовать метод `remove`.\n", + "Наконец, он распаковывает список, поэтому элементы передаются в «среднее» в виде отдельных аргументов, а не как один список.\n", "\n", - "Here's an example that shows the effect." + "Вот пример, который показывает эффект.\n" ] }, { @@ -758,7 +758,7 @@ "id": "35e04996", "metadata": {}, "source": [ - "This kind of \"trimmed\" mean is used in some sports with subjective judging -- like diving and gymnastics -- to reduce the effect of a judge whose score deviates from the others. " + "Этот вид «подстриженного» среднего значения используется в некоторых видах спорта с субъективным судейством - например, дайвинг и гимнастика - чтобы уменьшить эффект судьи, чей счет отклоняется от других.\n" ] }, { @@ -768,8 +768,8 @@ "source": [ "## Zip\n", "\n", - "Tuples are useful for looping through the elements of two sequences and performing operations on corresponding elements.\n", - "For example, suppose two teams play a series of seven games, and we record their scores in two lists, one for each team." + "Клетки полезны для зацикливания через элементы двух последовательностей и выполнения операций на соответствующих элементах.\n", + "Например, предположим, что две команды играют в серию из семи игр, и мы записываем их результаты в двух списках, по одной для каждой команды.\n" ] }, { @@ -785,8 +785,8 @@ "id": "b44f228b", "metadata": {}, "source": [ - "Let's see how many games each team won.\n", - "We'll use `zip`, which is a built-in function that takes two or more sequences and returns a **zip object**, so-called because it pairs up the elements of the sequences like the teeth of a zipper." + "Давайте посмотрим, сколько игр выиграла каждая команда.\n", + "Мы используем `Zip`, который представляет собой встроенную функцию, которая принимает две или более последовательности и возвращает ** Zip-объект **, так называемый, потому что он соединяет элементы последовательностей, таких как зубы молнии.\n" ] }, { @@ -802,7 +802,7 @@ "id": "9adcf8f9", "metadata": {}, "source": [ - "We can use the zip object to loop through the values in the sequences pairwise." + "Мы можем использовать объект ZIP, чтобы пройти через значения в последовательностях пары.\n" ] }, { @@ -818,8 +818,8 @@ "id": "51d1dabb", "metadata": {}, "source": [ - "Each time through the loop, `pair` gets assigned a tuple of scores.\n", - "So we can assign the scores to variables, and count the victories for the first team, like this:" + "Каждый раз через петлю, «Пару» назначают кортеж с результатами.\n", + "Таким образом, мы можем назначить оценки переменным и подсчитать победы для первой команды, например, это:\n" ] }, { @@ -835,9 +835,9 @@ "id": "ad740fcd", "metadata": {}, "source": [ - "Sadly, the first team won only three games and lost the series.\n", + "К сожалению, первая команда выиграла только три игры и проиграла сериал.\n", "\n", - "If you have two lists and you want a list of pairs, you can use `zip` and `list`." + "Если у вас есть два списка и вам нужен список пар, вы можете использовать `Zip` и` list`.\n" ] }, { @@ -853,7 +853,7 @@ "id": "ec4249fa", "metadata": {}, "source": [ - "The result is a list of tuples, so we can get the result of the last game like this:" + "Результатом является список кортежей, поэтому мы можем получить результат последней игры, как это:\n" ] }, { @@ -869,8 +869,8 @@ "id": "436486b9", "metadata": {}, "source": [ - "If you have a list of keys and a list of values, you can use `zip` and `dict` to make a dictionary.\n", - "For example, here's how we can make a dictionary that maps from each letter to its position in the alphabet." + "Если у вас есть список ключей и список значений, вы можете использовать `Zip` и` dict ', чтобы сделать словарь.\n", + "Например, вот как мы можем сделать словарь, который отображает из каждой буквы в ее положение в алфавите.\n" ] }, { @@ -886,7 +886,7 @@ "id": "b4de6974", "metadata": {}, "source": [ - "Now we can look up a letter and get its index in the alphabet." + "Теперь мы можем посмотреть букву и получить его индекс в алфавите.\n" ] }, { @@ -902,9 +902,9 @@ "id": "cc632542", "metadata": {}, "source": [ - "In this mapping, the index of `'a'` is `0` and the index of `'z'` is `25`.\n", + "В этом отображении индекс «a» - «0`», а индекс «Z'» - `25`.\n", "\n", - "If you need to loop through the elements of a sequence and their indices, you can use the built-in function `enumerate`." + "Если вам нужно пройти через элементы последовательности и их индексов, вы можете использовать встроенную функцию `перечислить '.\n" ] }, { @@ -920,7 +920,7 @@ "id": "92ad45bb", "metadata": {}, "source": [ - "The result is an **enumerate object** that loops through a sequence of pairs, where each pair contains an index (starting from 0) and an element from the given sequence." + "Результатом является ** перечисливший объект **, который проходит через последовательность пар, где каждая пара содержит индекс (начиная с 0) и элемент из данной последовательности.\n" ] }, { @@ -936,11 +936,11 @@ "id": "cf0b55d7", "metadata": {}, "source": [ - "## Comparing and Sorting\n", + "## Сравнение и сортировка\n", "\n", - "The relational operators work with tuples and other sequences.\n", - "For example, if you use the `<` operator with tuples, it starts by comparing the first element from each sequence.\n", - "If they are equal, it goes on to the next pair of elements, and so on, until it finds a pair that differ. " + "Реляционные операторы работают с кортежами и другими последовательностями.\n", + "Например, если вы используете оператор «<` `с кортежами, он начинается с сравнения первого элемента из каждой последовательности».\n", + "Если они равны, это переходит к следующей паре элементов, и так далее, пока не найдет пару, которая отличается.\n" ] }, { @@ -956,7 +956,7 @@ "id": "65ceea86", "metadata": {}, "source": [ - "Subsequent elements are not considered -- even if they are really big." + "Последующие элементы не рассматриваются - даже если они действительно большие.\n" ] }, { @@ -972,9 +972,9 @@ "id": "55e4a35e", "metadata": {}, "source": [ - "This way of comparing tuples is useful for sorting a list of tuples, or finding the minimum or maximum.\n", - "As an example, let's find the most common letter in a word.\n", - "In the previous chapter, we wrote `value_counts`, which takes a string and returns a dictionary that maps from each letter to the number of times it appears." + "Этот способ сравнения кортежей полезен для сортировки списка кортежей или поиска минимального или максимума.\n", + "В качестве примера, давайте найдем наиболее распространенное письмо одним словом.\n", + "В предыдущей главе мы написали `value_counts`, который берет строку и возвращает словарь, который отображает из каждой буквы в количество раз.\n" ] }, { @@ -990,7 +990,7 @@ "id": "a80012c1", "metadata": {}, "source": [ - "Here is the result for the string `'banana'`." + "Вот результат для строки `'banana''.\n" ] }, { @@ -1006,10 +1006,10 @@ "id": "cc1ea4a7", "metadata": {}, "source": [ - "With only three items, we can easily see that the most frequent letter is `'a'`, which appears three times.\n", - "But if there were more items, it would be useful to sort them automatically.\n", + "Только с тремя элементами мы можем легко увидеть, что самая частая буква - «A», которая появляется три раза.\n", + "Но если бы было больше предметов, было бы полезно разортировать их автоматически.\n", "\n", - "We can get the items from `counter` like this." + "Мы можем получить элементы от «стойки», как это.\n" ] }, { @@ -1025,7 +1025,7 @@ "id": "ac8dea7a", "metadata": {}, "source": [ - "The result is a `dict_items` object that behaves like a list of tuples, so we can sort it like this." + "Результатом является объект `dict_items`, который ведет себя как список кортежей, поэтому мы можем сортировать его так.\n" ] }, { @@ -1041,10 +1041,10 @@ "id": "b690d17a", "metadata": {}, "source": [ - "The default behavior is to use the first element from each tuple to sort the list, and use the second element to break ties.\n", + "Поведение по умолчанию состоит в том, чтобы использовать первый элемент из каждого корзина для сортировки списка и использовать второй элемент для разрыва связей.\n", "\n", - "However, to find the items with the highest counts, we want to use the second element to sort the list.\n", - "We can do that by writing a function that takes a tuple and returns the second element." + "Однако, чтобы найти элементы с наибольшим количеством количества, мы хотим использовать второй элемент для сортировки списка.\n", + "Мы можем сделать это, написав функцию, которая берет кортеж и возвращает второй элемент.\n" ] }, { @@ -1060,7 +1060,7 @@ "id": "b964aa14", "metadata": {}, "source": [ - "Then we can pass that function to `sorted` as an optional argument called `key`, which indicates that this function should be used to compute the **sort key** for each item." + "Затем мы можем передать эту функцию в «сортированное» в качестве необязательного аргумента, называемого «Key», который указывает на то, что эта функция должна использоваться для вычисления клавиши ** Sort ** для каждого элемента.\n" ] }, { @@ -1076,9 +1076,9 @@ "id": "4dc96848", "metadata": {}, "source": [ - "The sort key determines the order of the items in the list.\n", - "The letter with the lowest count appears first, and the letter with the highest count appears last.\n", - "So we can find the most common letter like this." + "Ключ сорта определяет порядок элементов в списке.\n", + "Сначала появляется письмо с самым низким подсчетом, и буква с наивысшим количеством подсчета появляется последней.\n", + "Таким образом, мы можем найти самое распространенное письмо, как это.\n" ] }, { @@ -1094,8 +1094,8 @@ "id": "d0d8b999", "metadata": {}, "source": [ - "If we only want the maximum, we don't have to sort the list.\n", - "We can use `max`, which also takes `key` as an optional argument." + "Если мы хотим только максимум, нам не нужно сортировать список.\n", + "Мы можем использовать `max`, который также принимает` key 'в качестве необязательного аргумента.\n" ] }, { @@ -1111,7 +1111,7 @@ "id": "8a8327df", "metadata": {}, "source": [ - "To find the letter with the lowest count, we could use `min` the same way." + "Чтобы найти букву с самым низким подсчетом, мы могли бы использовать «min» таким же образом.\n" ] }, { @@ -1119,15 +1119,15 @@ "id": "a62394a5", "metadata": {}, "source": [ - "## Inverting a dictionary\n", + "## инвертирование словаря\n", "\n", - "Suppose you want to invert a dictionary so you can look up a value and get the corresponding key.\n", - "For example, if you have a word counter that maps from each word to the number of times it appears, you could make a dictionary that maps from integers to the words that appear that number of times.\n", + "Предположим, вы хотите инвертировать словарь, чтобы вы могли найти значение и получить соответствующий ключ.\n", + "Например, если у вас есть счетчик слов, который отображает от каждого слова до того, как оно появляется, вы можете сделать словарь, который отображает из целых чисел в слова, которые появляются в течение этого количества раз.\n", "\n", - "But there's a problem -- the keys in a dictionary have to be unique, but the values don't. For example, in a word counter, there could be many words with the same count.\n", + "Но есть проблема - ключи в словаре должны быть уникальными, но значения нет.Например, в счетчике слова может быть много слов с тем же количеством.\n", "\n", - "So one way to invert a dictionary is to create a new dictionary where the values are lists of keys from the original.\n", - "As an example, let's count the letters in `parrot`." + "Таким образом, одним из способов инвертировать словарь является создание нового словаря, в котором значения являются списками клавиш из оригинала.\n", + "В качестве примера, давайте подсчитаем буквы в «попугаи».\n" ] }, { @@ -1143,9 +1143,9 @@ "id": "f4570eae", "metadata": {}, "source": [ - "If we invert this dictionary, the result should be `{1: ['p', 'a', 'o', 't'], 2: ['r']}`, which indicates that the letters that appear once are `'p'`, `'a'`, `'o'`, and `'t'`, and the letter than appears twice is `'r'`.\n", + "Если мы инвертируем этот словарь, результат должен быть `{1: ['p', 'a', 'o', 't'], 2: ['r']}`, что указывает на то, что буквы, которые когда -то появляются, - «p'`», `a'``,` 'O'' и `'t', и буква, чем появляется, - это два раза - это` r '.\n", "\n", - "The following function takes a dictionary and returns its inverse as a new dictionary." + "Следующая функция принимает словарь и возвращает его обратный в качестве нового словаря.\n" ] }, { @@ -1161,11 +1161,11 @@ "id": "ca5fa025", "metadata": {}, "source": [ - "The `for` statement loops through the keys and values in `d`.\n", - "If the value is not already in the new dictionary, it is added and associated with a list that contains a single element.\n", - "Otherwise it is appended to the existing list.\n", + "Оператор «для» проходит через ключи и значения в `d`.\n", + "Если значение еще не в новом словаре, оно добавлено и связано с списком, который содержит один элемент.\n", + "В противном случае он добавляется в существующий список.\n", "\n", - "We can test it like this:" + "Мы можем проверить это так:\n" ] }, { @@ -1181,10 +1181,10 @@ "id": "4cfb1693", "metadata": {}, "source": [ - "And we get the result we expected.\n", + "И мы получаем результат, который мы ожидали.\n", "\n", - "This is the first example we've seen where the values in the dictionary are lists.\n", - "We will see more!" + "Это первый пример, где мы видели, где значения в словаре являются списками.\n", + "Посмотрим больше!\n" ] }, { @@ -1194,17 +1194,17 @@ "tags": [] }, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "Lists, dictionaries and tuples are **data structures**.\n", - "In this chapter we are starting to see compound data structures, like lists of tuples, or dictionaries that contain tuples as keys and lists as values.\n", - "Compound data structures are useful, but they are prone to errors caused when a data structure has the wrong type, size, or structure.\n", - "For example, if a function expects a list of integers and you give it a plain old integer\n", - "(not in a list), it probably won't work.\n", + "Списки, словари и кортежи - это ** структуры данных **.\n", + "В этой главе мы начинаем видеть составные структуры данных, такие как списки кортежей, или словари, которые содержат кортежи в качестве ключей и списков в качестве значений.\n", + "Составные структуры данных полезны, но они подвержены ошибкам, вызванным, когда структура данных имеет неправильный тип, размер или структуру.\n", + "Например, если функция ожидает список целых чисел, и вы даете ей простое старое целое число\n", + "(Не в списке), это, вероятно, не сработает.\n", "\n", - "To help debug these kinds of errors, I wrote a module called `structshape` that provides a function, also called `structshape`, that takes any kind of data structure as an argument and returns a string that summarizes its structure.\n", - "You can download it from\n", - "." + "Чтобы помочь отладить такие ошибки, я написал модуль под названием «Structshape», который обеспечивает функцию, также называемую «Structshape», который принимает какую -либо структуру данных в качестве аргумента и возвращает строку, которая суммирует его структуру.\n", + "Вы можете скачать его с\n", + ".\n" ] }, { @@ -1222,7 +1222,7 @@ "id": "646f4d55", "metadata": {}, "source": [ - "We can import it like this." + "Мы можем импортировать его так.\n" ] }, { @@ -1238,7 +1238,7 @@ "id": "86cc6ccc", "metadata": {}, "source": [ - "Here's an example with a simple list." + "Вот пример с простым списком.\n" ] }, { @@ -1254,7 +1254,7 @@ "id": "9de4f6ec", "metadata": {}, "source": [ - "Here's a list of lists." + "Вот список списков.\n" ] }, { @@ -1270,8 +1270,8 @@ "id": "aced9984", "metadata": {}, "source": [ - "If the elements of the list are not the same type, `structshape` groups\n", - "them by type." + "Если элементы списка не являются такими же типами, `structshape\n", + "их по типу.\n" ] }, { @@ -1287,7 +1287,7 @@ "id": "f63ff690", "metadata": {}, "source": [ - "Here's a list of tuples." + "Вот список кортежей.\n" ] }, { @@ -1303,7 +1303,7 @@ "id": "c9ec67eb", "metadata": {}, "source": [ - "And here's a dictionary with three items that map integers to strings." + "А вот словарь с тремя элементами, которые отображают целые числа на струны.\n" ] }, { @@ -1319,8 +1319,8 @@ "id": "f29bb82b", "metadata": {}, "source": [ - "If you are having trouble keeping track of your data structures,\n", - "`structshape` can help." + "Если у вас проблемы с отслеживанием ваших структур данных,\n", + "`Structshape 'может помочь.\n" ] }, { @@ -1328,25 +1328,25 @@ "id": "79d93082", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**pack:**\n", - "Collect multiple arguments into a tuple.\n", + "**пакет:**\n", + "Соберите несколько аргументов в кортеж.\n", "\n", - "**unpack:**\n", - "Treat a tuple (or other sequence) as multiple arguments.\n", + "** распаковывать: **\n", + "Обратитесь в кортеж (или другую последовательность) как множественные аргументы.\n", "\n", - "**zip object:**\n", - "The result of calling the built-in function `zip`, can be used to loop through a sequence of tuples.\n", + "** Объект Zip: **\n", + "Результат вызова встроенной функции `Zip` может быть использован для перехода через последовательность кортежей.\n", "\n", - "**enumerate object:**\n", - "The result of calling the built-in function `enumerate`, can be used to loop through a sequence of tuples.\n", + "** перечислять объект: **\n", + "Результат вызова встроенной функции `enumerate` может быть использован для перехода через последовательность кортежей.\n", "\n", - "**sort key:**\n", - "A value, or function that computes a value, used to sort the elements of a collection.\n", + "** Ключ сортировки: **\n", + "Значение или функция, которая вычисляет значение, используемое для сортировки элементов коллекции.\n", "\n", - "**data structure:**\n", - "A collection of values, organized to perform certain operations efficiently." + "** Структура данных: **\n", + "Коллекция значений, организованных для эффективного выполнения определенных операций.\n" ] }, { @@ -1354,7 +1354,7 @@ "id": "1471b3c0", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения\n" ] }, { @@ -1372,17 +1372,17 @@ "id": "97a0352d", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "The exercises in this chapter might be more difficult than exercises in previous chapters, so I encourage you to get help from a virtual assistant.\n", - "When you pose more difficult questions, you might find that the answers are not correct on the first attempt, so this is a chance to practice crafting good prompts and following up with good refinements.\n", + "Упражнения в этой главе могут быть сложнее, чем упражнения в предыдущих главах, поэтому я призываю вас получить помощь от виртуального помощника.\n", + "Когда вы задаете более сложные вопросы, вы можете обнаружить, что ответы не верны с первой попытки, так что это шанс попрактиковаться в создании хороших подсказок и следовать хорошим усовершенствованиям.\n", "\n", - "One strategy you might consider is to break a big problems into pieces that can be solved with simple functions.\n", - "Ask the virtual assistant to write the functions and test them.\n", - "Then, once they are working, ask for a solution to the original problem.\n", + "Одна стратегия, которую вы можете рассмотреть, - это разбить большие проблемы на части, которые можно решить с помощью простых функций.\n", + "Попросите виртуального помощника написать функции и проверить их.\n", + "Затем, как только они работают, попросите решение исходной проблемы.\n", "\n", - "For some of the exercises below, I make suggestions about which data structures and algorithms to use.\n", - "You might find these suggestions useful when you work on the problems, but they are also good prompts to pass along to a virtual assistant." + "Для некоторых упражнений ниже я делаю предложения о том, какие структуры данных и алгоритмы использовать.\n", + "Вы можете найти эти предложения полезными, когда вы работаете над проблемами, но они также являются хорошими подсказками, чтобы передать виртуальному помощнику.\n" ] }, { @@ -1390,12 +1390,12 @@ "id": "f90e011f", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In this chapter I said that tuples can be used as keys in dictionaries because they are hashable, and they are hashable because they are immutable.\n", - "But that is not always true.\n", + "В этой главе я сказал, что кортежи могут использоваться в качестве ключей в словарях, потому что они хэшабель, и они хэшаруются, потому что они неизменны.\n", + "Но это не всегда правда.\n", "\n", - "If a tuple contains a mutable value, like a list or a dictionary, the tuple is no longer hashable because it contains elements that are not hashable. As an example, here's a tuple that contains two lists of integers." + "Если кортеж содержит изменяемое значение, например, список или словарь, кортеж больше не является хэшабельным, потому что он содержит элементы, которые не являются хэшабельными.В качестве примера, вот кортеж, который содержит два списка целых чисел.\n" ] }, { @@ -1411,7 +1411,7 @@ "id": "02799077", "metadata": {}, "source": [ - "Write a line of code that appends the value `6` to the end of the second list in `t`. If you display `t`, the result should be `([1, 2, 3], [4, 5, 6])`." + "Напишите строку кода, которая добавляет значение `6` к концу второго списка в` t`.Если вы отображаете `t`, результат должен быть` ([1, 2, 3], [4, 5, 6]) `.\n" ] }, { @@ -1429,7 +1429,7 @@ "id": "644b1dfb", "metadata": {}, "source": [ - "Try to create a dictionary that maps from `t` to a string, and confirm that you get a `TypeError`." + "Попробуйте создать словарь, который отображает от `t` на строку, и подтвердите, что вы получаете` typeerror '.\n" ] }, { @@ -1447,7 +1447,7 @@ "id": "fb77a352", "metadata": {}, "source": [ - "For more on this topic, ask a virtual assistant, \"Are Python tuples always hashable?\"" + "Для получения дополнительной информации по этой теме, спросите виртуального помощника: «Всегда ли кортежи для Python всегда хелают?»\n" ] }, { @@ -1457,9 +1457,9 @@ "tags": [] }, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In this chapter we made a dictionary that maps from each letter to its index in the alphabet." + "В этой главе мы сделали словарь, который отображает из каждой буквы в его индекс в алфавите.\n" ] }, { @@ -1475,7 +1475,7 @@ "id": "a8cd720b", "metadata": {}, "source": [ - "For example, the index of `'a'` is `0`." + "Например, индекс `'a'`` 0`.\n" ] }, { @@ -1491,8 +1491,8 @@ "id": "a04c25db", "metadata": {}, "source": [ - "To go in the other direction, we can use list indexing.\n", - "For example, the letter at index `1` is `'b'`." + "Чтобы идти в другом направлении, мы можем использовать индексацию списка.\n", + "Например, буква в индексе `1` -` 'b'.\n" ] }, { @@ -1508,18 +1508,18 @@ "id": "165ab770", "metadata": {}, "source": [ - "We can use `letter_map` and `letters` to encode and decode words using a Caesar cipher.\n", + "Мы можем использовать `lect_map` и` буквы 'для кодирования и декодирования слов с помощью шифра Цезаря.\n", "\n", - "A Caesar cipher is a weak form of encryption that involves shifting each letter\n", - "by a fixed number of places in the alphabet, wrapping around to the beginning if necessary. For example, `'a'` shifted by 2 is `'c'` and `'z'` shifted by 1 is `'a'`.\n", + "Цезарь -шифр - это слабая форма шифрования, которая включает в себя изменение каждой буквы\n", + "По фиксированному количеству мест в алфавите, при необходимости, обернувшись до начала.Например, «a», сдвинутый на 2, - это `'c'' ', а`' Z''сдвинулся на 1 IS `' a '.\n", "\n", - "Write a function called `shift_word` that takes as parameters a string and an integer, and returns a new string that contains the letters from the string shifted by the given number of places.\n", + "Напишите функцию с именем `shift_word`, которая принимает в качестве параметров строку и целое число, и возвращает новую строку, которая содержит буквы из строки, сдвинутой на заданное количество мест.\n", "\n", - "To test your function, confirm that \"cheer\" shifted by 7 is \"jolly\" and \"melon\" shifted by 16 is \"cubed\".\n", + "Чтобы проверить вашу функцию, подтвердите, что «Cheer», сдвинутое на 7, \"Jolly\" и \"melon\", сдвинутая на 16, \"кубики\".\n", "\n", - "Hints: Use the modulus operator to wrap around from `'z'` back to `'a'`. \n", - "Loop through the letters of the word, shift each one, and append the result to a list of letters.\n", - "Then use `join` to concatenate the letters into a string." + "Подсказки: используйте оператор модуля, чтобы обернуться от `Z'` 'Back to`' a '.\n", + "Проверьте буквы слова, сдвиньте каждый из них и добавьте результат в список букв.\n", + "Затем используйте `join ', чтобы объединить буквы в строку.\n" ] }, { @@ -1529,7 +1529,7 @@ "tags": [] }, "source": [ - "You can use this outline to get started." + "Вы можете использовать этот контур, чтобы начать.\n" ] }, { @@ -1577,7 +1577,7 @@ "tags": [] }, "source": [ - "You can use `doctest` to test your function." + "Вы можете использовать `doctest`, чтобы проверить вашу функцию.\n" ] }, { @@ -1595,11 +1595,11 @@ "id": "779f13af", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `most_frequent_letters` that takes a string and prints the letters in decreasing order of frequency.\n", + "Напишите функцию, называемую `most_frequent_letters`, которая принимает строку и печатает буквы в порядке уменьшения частоты.\n", "\n", - "To get the items in decreasing order, you can use `reversed` along with `sorted` or you can pass `reverse=True` as a keyword parameter to `sorted`." + "Чтобы получить элементы в порядке уменьшения, вы можете использовать `reversed` вместе с« сортированным »или вы можете передать` reverse = true` в качестве параметра ключевого слова для `sorted`.\n" ] }, { @@ -1609,7 +1609,7 @@ "tags": [] }, "source": [ - "You can use this outline of the function to get started." + "Вы можете использовать этот план функции, чтобы начать работу.\n" ] }, { @@ -1637,7 +1637,7 @@ "tags": [] }, "source": [ - "And this example to test your function." + "И этот пример для проверки вашей функции.\n" ] }, { @@ -1657,7 +1657,7 @@ "tags": [] }, "source": [ - "Once your function is working, you can use the following code to print the most common letters in *Dracula*, which we can download from Project Gutenberg." + "Как только ваша функция работает, вы можете использовать следующий код для печати наиболее распространенных букв в *Dracula *, которые мы можем загрузить из Project Gutenberg.\n" ] }, { @@ -1687,8 +1687,8 @@ "tags": [] }, "source": [ - "According to Zim's \"Codes and Secret Writing\", the sequence of letters in decreasing order of frequency in English starts with \"ETAONRISH\".\n", - "How does this sequence compare with the results from *Dracula*?" + "Согласно «кодам и секретному письму Зима», последовательность букв в уменьшении порядка частоты на английском языке начинается с «Etaonrish».\n", + "Как эта последовательность сравнивается с результатами *Dracula *?\n" ] }, { @@ -1696,20 +1696,20 @@ "id": "cbe9933e", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In a previous exercise, we tested whether two strings are anagrams by sorting the letters in both words and checking whether the sorted letters are the same.\n", - "Now let's make the problem a little more challenging.\n", + "В предыдущем упражнении мы проверили, являются ли две строки анаграммы, сортируя буквы в обоих словах и проверяя, являются ли сортированные буквы одинаковыми.\n", + "Теперь давайте сделаем проблему немного более сложной.\n", "\n", - "We'll write a program that takes a list of words and prints all the sets of words that are anagrams.\n", - "Here is an example of what the output might look like:\n", + "Мы напишем программу, которая принимает список слов и печатает все наборы слов, которые являются анаграммами.\n", + "Вот пример того, как может выглядеть выход:\n", "\n", - " ['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled']\n", - " ['retainers', 'ternaries']\n", - " ['generating', 'greatening']\n", - " ['resmelts', 'smelters', 'termless']\n", + "['deltas', 'desalt', 'Laft', «Salted», «Planted», «Staled»]\n", + "['Сборники', 'ТЕРНАРИ']\n", + "['Generation', 'Greating']\n", + "['resmelts', 'Mellters', 'termers']\n", "\n", - "Hint: For each word in the word list, sort the letters and join them back into a string. Make a dictionary that maps from this sorted string to a list of words that are anagrams of it." + "Подсказка: для каждого слова в списке слова сортируйте буквы и присоединяйтесь к ним обратно в строку.Сделайте словарь, который отображает из этой отсортированной строки в список слов, которые являются его анаграммами.\n" ] }, { @@ -1719,7 +1719,7 @@ "tags": [] }, "source": [ - "The following cells download `words.txt` and read the words into a list." + "Следующие ячейки загружают `words.txt` и читают слова в список.\n" ] }, { @@ -1749,7 +1749,7 @@ "tags": [] }, "source": [ - "Here's the `sort_word` function we've used before." + "Вот функция `sort_word`, которую мы использовали ранее.\n" ] }, { @@ -1777,8 +1777,8 @@ "tags": [] }, "source": [ - "To find the longest list of anagrams, you can use the following function, which takes a key-value pair where the key is a string and the value is a list of words.\n", - "It returns the length of the list." + "Чтобы найти самый длинный список анаграмм, вы можете использовать следующую функцию, которая принимает пару клавиш, где ключ-это строка, а значение-это список слов.\n", + "Он возвращает длину списка.\n" ] }, { @@ -1798,7 +1798,7 @@ "tags": [] }, "source": [ - "We can use this function as a sort key to find the longest lists of anagrams." + "Мы можем использовать эту функцию в качестве ключа сортировки, чтобы найти самые длинные списки анаграмм.\n" ] }, { @@ -1818,7 +1818,7 @@ "tags": [] }, "source": [ - "If you want to know the longest words that have anagrams, you can use the following loop to print some of them." + "Если вы хотите узнать самые длинные слова, которые имеют анаграммы, вы можете использовать следующий цикл, чтобы распечатать некоторые из них.\n" ] }, { @@ -1836,11 +1836,11 @@ "id": "4fbe939e", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `word_distance` that takes two words with the same length and returns the number of places where the two words differ.\n", + "Напишите функцию, называемую `word_distance`, которая занимает два слова с одинаковой длиной и возвращает количество мест, где различаются два слова.\n", "\n", - "Hint: Use `zip` to loop through the corresponding letters of the words." + "Подсказка: используйте `Zip`, чтобы пройти через соответствующие буквы слов.\n" ] }, { @@ -1850,7 +1850,7 @@ "tags": [] }, "source": [ - "Here's an outline of the function with doctests you can use to check your function." + "Вот краткий план функции с Doctests, которые вы можете использовать для проверки вашей функции.\n" ] }, { @@ -1886,15 +1886,15 @@ "id": "066eec59", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "\"Metathesis\" is the transposition of letters in a word.\n", - "Two words form a \"metathesis pair\" if you can transform one into the other by swapping two letters, like `converse` and `conserve`.\n", - "Write a program that finds all of the metathesis pairs in the word list. \n", + "«Метатезис» - это транспозиция букв в слове.\n", + "Два слова образуют «пару метатезисов», если вы можете преобразовать одно в другое, заменив две буквы, например, «Converse» и «Sonvere».\n", + "Напишите программу, которая находит все пара метатезисов в списке слов.\n", "\n", - "Hint: The words in a metathesis pair must be anagrams of each other.\n", + "Подсказка: слова в паре метатезиса должны быть анаграммами друг друга.\n", "\n", - "Credit: This exercise is inspired by an example at ." + "Кредит: Это упражнение вдохновлено примером по адресу .\n" ] }, { @@ -1912,49 +1912,49 @@ "tags": [] }, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "This is a bonus exercise that is not in the book.\n", - "It is more challenging than the other exercises in this chapter, so you might want to ask a virtual assistant for help, or come back to it after you've read a few more chapters.\n", + "Это бонусное упражнение, которого нет в книге.\n", + "Это сложнее, чем другие упражнения в этой главе, поэтому вы можете попросить виртуального помощника за помощью или вернуться к нему после того, как прочитали еще несколько глав.\n", "\n", - "Here's another Car Talk Puzzler\n", + "Вот еще одна головоломка.\n", "():\n", "\n", - "> What is the longest English word, that remains a valid English word,\n", - "> as you remove its letters one at a time?\n", + "> Какое самое длинное английское слово, которое остается действительным английским словом,\n", + "> Когда вы удаляете его буквы по одному?\n", ">\n", - "> Now, letters can be removed from either end, or the middle, but you\n", - "> can't rearrange any of the letters. Every time you drop a letter, you\n", - "> wind up with another English word. If you do that, you're eventually\n", - "> going to wind up with one letter and that too is going to be an\n", - "> English word---one that's found in the dictionary. I want to know\n", - "> what's the longest word and how many letters does it have?\n", + "> Теперь буквы могут быть удалены с конца или в середине, но вы\n", + "> Не могу изменить ни одной буквы.Каждый раз, когда вы бросаете письмо, вы\n", + "> Получить еще одно английское слово.Если вы сделаете это, вы в конце концов\n", + "> Собираюсь выйти с одной буквой, и это тоже будет\n", + "> Английское слово --- то, что найдено в словаре.Я хочу знать\n", + "> Какое самое длинное слово и сколько букв у него?\n", ">\n", - "> I'm going to give you a little modest example: Sprite. Ok? You start\n", - "> off with sprite, you take a letter off, one from the interior of the\n", - "> word, take the r away, and we're left with the word spite, then we\n", - "> take the e off the end, we're left with spit, we take the s off, we're\n", - "> left with pit, it, and I.\n", + "> Я собираюсь привести вам небольшой скромный пример: Sprite.Хорошо?Вы начинаете\n", + "> уйти с Sprite, вы снимаете письмо, один из внутренних\n", + "> Слово, заберите R, и у нас остается слово злобное, тогда мы\n", + "> Снимите E с конца, мы остаемся с Spit, мы снимаем S, мы\n", + "> остался с ямой, это и я.\n", "\n", - "Write a program to find all words that can be reduced in this way, and\n", - "then find the longest one.\n", + "Напишите программу, чтобы найти все слова, которые могут быть уменьшены таким образом, и\n", + "Затем найдите самый длинный.\n", "\n", - "This exercise is a little more challenging than most, so here are some\n", - "suggestions:\n", + "Это упражнение немного сложнее, чем большинство, так что вот некоторые\n", + "предложения:\n", "\n", - "1. You might want to write a function that takes a word and computes a\n", - " list of all the words that can be formed by removing one letter.\n", - " These are the \"children\" of the word.\n", + "1. Вы можете написать функцию, которая принимает слово и вычисляет\n", + "Список всех слов, которые могут быть сформированы путем удаления одной буквы.\n", + "Это «дети» слова.\n", "\n", - "2. Recursively, a word is reducible if any of its children are\n", - " reducible. As a base case, you can consider the empty string\n", - " reducible.\n", + "2. рекурсивно, слово уменьшается, если кто -либо из его детей\n", + "уменьшается.В качестве базового корпуса вы можете рассмотреть пустую строку\n", + "уменьшается.\n", "\n", - "3. The word list we've been using doesn't contain single letter\n", - " words. So you might have to add \"I\" and \"a\".\n", + "3. Список слов, которые мы использовали\n", + "словаТаким образом, вам, возможно, придется добавить «я» и «а».\n", "\n", - "4. To improve the performance of your program, you might want to\n", - " memoize the words that are known to be reducible." + "4. Чтобы улучшить производительность вашей программы, вы можете захотеть\n", + "Запомните слова, которые, как известно, являются уменьшенными.\n" ] }, { @@ -2004,13 +2004,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT] (https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik\n" ] } ], @@ -2036,4 +2036,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From ac1462981c58ff6c79f671c3743bf9c05d34f757 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:03:59 +0300 Subject: [PATCH 12/44] Translate chapter 12 notebook to Russian --- blank/chap12.ipynb | 546 ++++++++++++++++++++++----------------------- 1 file changed, 273 insertions(+), 273 deletions(-) diff --git a/blank/chap12.ipynb b/blank/chap12.ipynb index 220b664..f72ea46 100644 --- a/blank/chap12.ipynb +++ b/blank/chap12.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432?ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325)." ] }, { @@ -25,20 +25,20 @@ "id": "59a8621b", "metadata": {}, "source": [ - "# Text Analysis and Generation\n", + "# Анализ текста и поколение\n", "\n", - "At this point we have covered Python's core data structures -- lists, dictionaries, and tuples -- and some algorithms that use them.\n", - "In this chapter, we'll use them to explore text analysis and Markov generation:\n", + "На этом этапе мы рассмотрели основные структуры данных Python - списки, словари и кортежи - и некоторые алгоритмы, которые их используют.\n", + "В этой главе мы будем использовать их для изучения текстового анализа и генерации Маркова:\n", "\n", - "* Text analysis is a way to describe the statistical relationships between the words in a document, like the probability that one word is followed by another, and\n", + "* Анализ текста - это способ описать статистические отношения между словами в документе, например, вероятность того, что одно слово следует другому, и\n", "\n", - "* Markov generation is a way to generate new text with words and phrases similar to the original text.\n", + "* Генерация Маркова - это способ генерировать новый текст со словами и фразами, похожими на исходный текст.\n", "\n", - "These algorithms are similar to parts of a Large Language Model (LLM), which is the key component of a chatbot.\n", + "Эти алгоритмы аналогичны частям большой языковой модели (LLM), которая является ключевым компонентом чат -бота.\n", "\n", - "We'll start by counting the number of times each word appears in a book.\n", - "Then we'll look at pairs of words, and make a list of the words that can follow each word.\n", - "We'll make a simple version of a Markov generator, and as an exercise, you'll have a chance to make a more general version." + "Мы начнем с подсчета количества раз, когда каждое слово появляется в книге.\n", + "Затем мы посмотрим на пары слов и составим список слов, которые могут следовать каждому слову.\n", + "Мы сделаем простую версию генератора Маркова, и в качестве упражнения у вас будет возможность сделать более общую версию." ] }, { @@ -46,10 +46,10 @@ "id": "0e3811b8", "metadata": {}, "source": [ - "## Unique words\n", + "## уникальные слова\n", "\n", - "As a first step toward text analysis, let's read a book -- *The Strange Case Of Dr. Jekyll And Mr. Hyde* by Robert Louis Stevenson -- and count the number of unique words.\n", - "Instructions for downloading the book are in the notebook for this chapter." + "В качестве первого шага к анализу текста, давайте прочитаем книгу - * Странный случай доктора Джекилла и мистера Хайда * Роберта Луи Стивенсона - и подсчитывать количество уникальных слов.\n", + "Инструкции по загрузке книги находятся в записной книжке для этой главы." ] }, { @@ -59,7 +59,7 @@ "tags": [] }, "source": [ - "The following cell downloads the book from Project Gutenberg." + "Следующая ячейка загружает книгу из Project Gutenberg." ] }, { @@ -79,8 +79,8 @@ "tags": [] }, "source": [ - "The version available from Project Gutenberg includes information about the book at the beginning and license information at the end.\n", - "We'll use `clean_file` from Chapter 8 to remove this material and write a \"clean\" file that contains only the text of the book." + "Версия, доступная в Project Gutenberg, включает информацию о книге в начале и информацию о лицензии в конце.\n", + "Мы используем `clean_file` из главы 8, чтобы удалить этот материал и написать« чистый »файл, который содержит только текст книги." ] }, { @@ -126,8 +126,8 @@ "id": "bc66d7e2", "metadata": {}, "source": [ - "We'll use a `for` loop to read lines from the file and `split` to divide the lines into words.\n", - "Then, to keep track of unique words, we'll store each word as a key in a dictionary." + "Мы используем цикл «for» для чтения строк из файла и «разделить», чтобы разделить строки на слова.\n", + "Затем, чтобы отслеживать уникальные слова, мы сохраним каждое слово в качестве ключа в словаре." ] }, { @@ -143,11 +143,11 @@ "id": "85171a3a", "metadata": {}, "source": [ - "The length of the dictionary is the number of unique words -- about `6000` by this way of counting.\n", - "But if we inspect them, we'll see that some are not valid words.\n", + "Длина словаря - это количество уникальных слов - около `6000` по этому способу подсчета.\n", + "Но если мы осмотрим их, мы увидим, что некоторые не являются действительными словами.\n", "\n", - "For example, let's look at the longest words in `unique_words`.\n", - "We can use `sorted` to sort the words, passing the `len` function as a keyword argument so the words are sorted by length." + "Например, давайте посмотрим на самые длинные слова в `in unique_words`.\n", + "Мы можем использовать «отсортированный» для сортировки слов, передавая функцию `len` в качестве аргумента ключевого слова, чтобы слова отсортированы по длине." ] }, { @@ -163,13 +163,13 @@ "id": "795f5327", "metadata": {}, "source": [ - "The slice index, `[-5:]`, selects the last `5` elements of the sorted list, which are the longest words. \n", + "Индекс среза, `[-5:]`, выбирает последние элементы сортированного списка, которые являются самыми длинными словами.\n", "\n", - "The list includes some legitimately long words, like \"circumscription\", and some hyphenated words, like \"chocolate-coloured\".\n", - "But some of the longest \"words\" are actually two words separated by a dash.\n", - "And other words include punctuation like periods, exclamation points, and quotation marks.\n", + "Список включает в себя некоторые законно длинные слова, такие как «Ограничение», и некоторые дефис-слова, такие как «шоколадный цвет».\n", + "Но некоторые из самых длинных «слов» на самом деле являются двумя словами, разделенными чертой.\n", + "И другие слова включают пунктуацию, как периоды, восклицательные знаки и кавычки.\n", "\n", - "So, before we move on, let's deal with dashes and other punctuation." + "Итак, прежде чем мы пойдем дальше, давайте разберемся с Dashes и другими пунктуациями." ] }, { @@ -177,15 +177,15 @@ "id": "bf89fafa", "metadata": {}, "source": [ - "## Punctuation\n", + "## пунктуация\n", "\n", - "To identify the words in the text, we need to deal with two issues:\n", + "Чтобы определить слова в тексте, нам нужно решить два вопроса:\n", "\n", - "* When a dash appears in a line, we should replace it with a space -- then when we use `split`, the words will be separated.\n", + "* Когда в линии появляется черта, мы должны заменить ее пространством - затем, когда мы используем `split`, слова будут разделены.\n", "\n", - "* After splitting the words, we can use `strip` to remove punctuation.\n", + "* После разделения слов мы можем использовать `strip 'для удаления пунктуации.\n", "\n", - "To handle the first issue, we can use the following function, which takes a string, replaces dashes with spaces, splits the string, and returns the resulting list." + "Чтобы решить первую проблему, мы можем использовать следующую функцию, которая принимает строку, заменяет тире на пробелы, разбивает строку и возвращает полученный список." ] }, { @@ -201,8 +201,8 @@ "id": "d5decdec", "metadata": {}, "source": [ - "Notice that `split_line` only replaces dashes, not hyphens.\n", - "Here's an example." + "Обратите внимание, что `split_line 'только заменяет панели, а не дефисы.\n", + "Вот пример." ] }, { @@ -218,11 +218,11 @@ "id": "0d9eb318", "metadata": {}, "source": [ - "Now, to remove punctuation from the beginning and end of each word, we can use `strip`, but we need a list of characters that are considered punctuation.\n", + "Теперь, чтобы удалить пунктуацию с самого начала и конца каждого слова, мы можем использовать «полосу», но нам нужен список символов, которые считаются пунктуацией.\n", "\n", - "Characters in Python strings are in Unicode, which is an international standard used to represent letters in nearly every alphabet, numbers, symbols, punctuation marks, and more.\n", - "The `unicodedata` module provides a `category` function we can use to tell which characters are punctuation.\n", - "Given a letter, it returns a string with information about what category the letter is in." + "Персонажи в струнах Python находятся в Unicode, который является международным стандартом, используемым для представления букв почти в каждом алфавите, числах, символах, знаках пунктуации и многом другом.\n", + "Модуль `UnicodeData` обеспечивает функцию« категория », которую мы можем использовать, чтобы сказать, какие символы являются пунктуацией.\n", + "Учитывая письмо, он возвращает строку с информацией о категории, в которой находится письмо." ] }, { @@ -238,9 +238,9 @@ "id": "994835ea", "metadata": {}, "source": [ - "The category string of `'A'` is `'Lu'` -- the `'L'` means it is a letter and the `'u'` means it is uppercase.\n", + "Строка категории `'a'`` `lu'' -` 'l'`означает, что это буква, а« u »означает, что это - верх.\n", "\n", - "The category string of `'.'` is `'Po'` -- the `'P'` means it is punctuation and the `'o'` means its subcategory is \"other\"." + "Строка категории `'.'` '' Po'` - «p'» означает, что это пунктуация, а «O'» означает, что его подкатегория - «Другое»." ] }, { @@ -256,8 +256,8 @@ "id": "03773b9b", "metadata": {}, "source": [ - "We can find the punctuation marks in the book by checking for characters with categories that begin with `'P'`.\n", - "The following loop stores the unique punctuation marks in a dictionary." + "Мы можем найти знаки препинания в книге, проверив персонажей с категориями, которые начинаются с «p'».\n", + "Следующая петля хранит уникальные знаки препинания в словаре." ] }, { @@ -273,7 +273,7 @@ "id": "e6741dfa", "metadata": {}, "source": [ - "To make a list of punctuation marks, we can join the keys of the dictionary into a string." + "Чтобы составить список знаков препинания, мы можем присоединиться к ключам словаря в строку." ] }, { @@ -289,7 +289,7 @@ "id": "6af8d5a2", "metadata": {}, "source": [ - "Now that we know which characters in the book are punctuation, we can write a function that takes a word, strips punctuation from the beginning and end, and converts it to lower case." + "Теперь, когда мы знаем, какие персонажи в книге являются пунктуацией, мы можем написать функцию, которая берет слово, линит пунктуацию с самого начала и конец и преобразует ее в нижний регистр." ] }, { @@ -305,7 +305,7 @@ "id": "58a78cb1", "metadata": {}, "source": [ - "Here's an example." + "Вот пример." ] }, { @@ -321,7 +321,7 @@ "id": "314e4fbd", "metadata": {}, "source": [ - "Because `strip` removes characters from the beginning and end, it leaves hyphenated words alone." + "Поскольку `strip 'удаляет символы с самого начала и конец, он оставляет дефисацию в покое." ] }, { @@ -337,7 +337,7 @@ "id": "99050f8a", "metadata": {}, "source": [ - "Now here's a loop that uses `split_line` and `clean_word` to identify the unique words in the book." + "Теперь вот цикл, который использует `split_line` и` clean_word`, чтобы определить уникальные слова в книге." ] }, { @@ -353,8 +353,8 @@ "id": "992e5466", "metadata": {}, "source": [ - "With this stricter definition of what a word is, there are about 4000 unique words.\n", - "And we can confirm that the list of longest words has been cleaned up." + "С этим более строгим определением того, что такое слово, существует около 4000 уникальных слов.\n", + "И мы можем подтвердить, что список самых длинных слов был очищен." ] }, { @@ -370,7 +370,7 @@ "id": "8014c330", "metadata": {}, "source": [ - "Now let's see how many times each word is used." + "Теперь давайте посмотрим, сколько раз используется каждое слово." ] }, { @@ -378,9 +378,9 @@ "id": "7ef40180", "metadata": {}, "source": [ - "## Word frequencies\n", + "## частоты слов\n", "\n", - "The following loop computes the frequency of each unique word." + "Следующий цикл вычисляет частоту каждого уникального слова." ] }, { @@ -396,10 +396,10 @@ "id": "bd680b81", "metadata": {}, "source": [ - "The first time we see a word, we initialize its frequency to `1`. If we see the same word again later, we increment its frequency.\n", + "В первый раз, когда мы видим слово, мы инициализируем его частоту до `1`.Если мы снова увидим то же слово, мы увеличиваем его частоту.\n", "\n", - "To see which words appear most often, we can use `items` to get the key-value pairs from `word_counter`, and sort them by the second element of the pair, which is the frequency.\n", - "First we'll define a function that selects the second element." + "Чтобы увидеть, какие слова появляются чаще всего, мы можем использовать «элементы», чтобы получить пары клавиш значений от `word_counter` и отсортировать их по вторым элементам пары, которая является частотой.\n", + "Сначала мы определим функцию, которая выбирает второй элемент." ] }, { @@ -415,11 +415,11 @@ "id": "b15a5bd6", "metadata": {}, "source": [ - "Now we can use `sorted` with two keyword arguments:\n", + "Теперь мы можем использовать `sorted` с двумя аргументами ключевого слова:\n", "\n", - "* `key=second_element` means the items will be sorted according to the frequencies of the words.\n", + "* `key = second_element` означает, что элементы будут отсортированы в соответствии с частотами слов.\n", "\n", - "* `reverse=True` means they items will be sorted in reverse order, with the most frequent words first." + "* `reverse = true` означает, что их элементы будут отсортированы в обратном порядке, сначала с наиболее частыми словами." ] }, { @@ -435,7 +435,7 @@ "id": "db6812e2", "metadata": {}, "source": [ - "Here are the five most frequent words." + "Вот пять наиболее частых слов." ] }, { @@ -451,8 +451,8 @@ "id": "551e81bb", "metadata": {}, "source": [ - "In the next section, we'll encapsulate this loop in a function.\n", - "And we'll use it to demonstrate a new feature -- optional parameters." + "В следующем разделе мы инкапсулируем этот цикл в функцию.\n", + "И мы будем использовать его, чтобы продемонстрировать новую функцию - дополнительные параметры." ] }, { @@ -460,10 +460,10 @@ "id": "45243ccc", "metadata": {}, "source": [ - "## Optional parameters\n", + "## необязательные параметры\n", "\n", - "We've used built-in functions that take optional parameters.\n", - "For example, `round` takes an optional parameters called `ndigits` that indicates how many decimal places to keep." + "Мы использовали встроенные функции, которые принимают дополнительные параметры.\n", + "Например, «Round» принимает дополнительные параметры, называемые «ndigits», которые указывают на то, сколько десятичных мест сохранить." ] }, { @@ -479,8 +479,8 @@ "id": "6ae60945", "metadata": {}, "source": [ - "But it's not just built-in functions -- we can write functions with optional parameters, too.\n", - "For example, the following function takes two parameters, `word_counter` and `num`." + "Но это не просто встроенные функции-мы также можем написать функции с дополнительными параметрами.\n", + "Например, следующая функция принимает два параметра: `word_counter` и` num`." ] }, { @@ -496,9 +496,9 @@ "id": "78cb1531", "metadata": {}, "source": [ - "The second parameter looks like an assignment statement, but it's not -- it's an optional parameter.\n", + "Второй параметр выглядит как оператор назначения, но это не так - это необязательный параметр.\n", "\n", - "If you call this function with one argument, `num` gets the **default value**, which is `5`." + "Если вы называете эту функцию одним аргументом, `num` получает значение ** по умолчанию **, которое равно` 5`." ] }, { @@ -514,7 +514,7 @@ "id": "29753ad6", "metadata": {}, "source": [ - "If you call this function with two arguments, the second argument gets assigned to `num` instead of the default value." + "Если вы называете эту функцию с двумя аргументами, второй аргумент назначается `Numbers` вместо значения по умолчанию." ] }, { @@ -530,9 +530,9 @@ "id": "e9bf907b", "metadata": {}, "source": [ - "In that case, we would say the optional argument **overrides** the default value.\n", + "В этом случае мы бы сказали, что необязательный аргумент ** переопределяет ** значение по умолчанию.\n", "\n", - "If a function has both required and optional parameters, all of the required parameters have to come first, followed by the optional ones." + "Если функция имеет как требуемые, так и дополнительные параметры, все необходимые параметры должны быть первыми, а затем дополнительные." ] }, { @@ -552,14 +552,14 @@ "tags": [] }, "source": [ - "## Dictionary subtraction\n", + "## Словарь вычитание\n", "\n", - "Suppose we want to spell-check a book -- that is, find a list of words that might be misspelled.\n", - "One way to do that is to find words in the book that don't appear in a list of valid words.\n", - "In previous chapters, we've used a list of words that are considered valid in word games like Scrabble.\n", - "Now we'll use this list to spell-check Robert Louis Stevenson.\n", + "Предположим, мы хотим проверить книгу, то есть найти список слов, которые могут быть написаны с ошибкой.\n", + "Один из способов сделать это - найти слова в книге, которые не появляются в списке действительных слов.\n", + "В предыдущих главах мы использовали список слов, которые считаются действительными в таких словах, как Scrabble.\n", + "Теперь мы будем использовать этот список для проверки орфографии Роберта Луи Стивенсона.\n", "\n", - "We can think of this problem as set subtraction -- that is, we want to find all the words from one set (the words in the book) that are not in the other (the words in the list)." + "Мы можем думать об этой проблеме как о вычитании установки, то есть мы хотим найти все слова из одного набора (слова в книге), которые не находятся в другом (слова в списке)." ] }, { @@ -569,7 +569,7 @@ "tags": [] }, "source": [ - "The following cell downloads the word list." + "Следующая ячейка загружает список слов." ] }, { @@ -587,7 +587,7 @@ "id": "2a46556c", "metadata": {}, "source": [ - "As we've done before, we can read the contents of `words.txt` and split it into a list of strings." + "Как мы делали раньше, мы можем прочитать содержимое `words.txt` и разделить его на список строк." ] }, { @@ -603,7 +603,7 @@ "id": "22becbab", "metadata": {}, "source": [ - "The we'll store the words as keys in a dictionary so we can use the `in` operator to check quickly whether a word is valid." + "Мы храним слова как ключи в словаре, чтобы мы могли использовать оператора «в», чтобы быстро проверить, является ли слово достоверным." ] }, { @@ -619,7 +619,7 @@ "id": "94cc7c61", "metadata": {}, "source": [ - "Now, to identify words that appear in the book but not in the word list, we'll use `subtract`, which takes two dictionaries as parameters and returns a new dictionary that contains all the keys from one that are not in the other." + "Теперь, чтобы идентифицировать слова, которые появляются в книге, но не в списке слов, мы будем использовать «вычтенный», который принимает два словаря в качестве параметров и возвращает новый словарь, который содержит все ключи от одного, которых нет в другом." ] }, { @@ -635,7 +635,7 @@ "id": "e70c63b4", "metadata": {}, "source": [ - "Here's how we use it." + "Вот как мы его используем." ] }, { @@ -651,7 +651,7 @@ "id": "f8ada7bd", "metadata": {}, "source": [ - "To get a sample of words that might be misspelled, we can print the most common words in `diff`." + "Чтобы получить образец слов, которые могут быть сформулированы, мы можем распечатать наиболее распространенные слова в «diff»." ] }, { @@ -667,10 +667,10 @@ "id": "deeec418", "metadata": {}, "source": [ - "The most common \"misspelled\" words are mostly names and a few single-letter words (Mr. Utterson is Dr. Jekyll's friend and lawyer).\n", + "Наиболее распространенными словами «неправильно» являются в основном имена и несколько однобуквенных слов (мистер Уттерсон-друг и адвокат доктора Джекилла).\n", "\n", - "If we select words that only appear once, they are more likely to be actual misspellings.\n", - "We can do that by looping through the items and making a list of words with frequency `1`." + "Если мы выбираем слова, которые появляются только один раз, они с большей вероятностью будут фактическими ошибками.\n", + "Мы можем сделать это, пробежая элементы и составив список слов с частотой `1`." ] }, { @@ -686,7 +686,7 @@ "id": "98ae9281", "metadata": {}, "source": [ - "Here are the last few elements of the list." + "Вот последние несколько элементов списка." ] }, { @@ -702,8 +702,8 @@ "id": "c5040834", "metadata": {}, "source": [ - "Most of them are valid words that are not in the word list.\n", - "But `'reindue'` appears to be a misspelling of `'reinduce'`, so at least we found one legitimate error." + "Большинство из них являются действительными словами, которых нет в списке слов.\n", + "Но «охрана», по -видимому, является неправильным написанием «повторного положения», поэтому, по крайней мере, мы нашли одну законную ошибку." ] }, { @@ -711,22 +711,22 @@ "id": "afcbbe19", "metadata": {}, "source": [ - "## Random numbers\n", + "## случайные числа\n", "\n", - "As a step toward Markov text generation, next we'll choose a random sequence of words from `word_counter`.\n", - "But first let's talk about randomness.\n", + "В качестве шага к генерации текста Маркова, затем мы выберем случайную последовательность слов из `word_counter`.\n", + "Но сначала давайте поговорим о случайности.\n", "\n", - "Given the same inputs, most computer programs are **deterministic**, which means they generate the same outputs every time.\n", - "Determinism is usually a good thing, since we expect the same calculation to yield the same result.\n", - "For some applications, though, we want the computer to be unpredictable.\n", - "Games are one example, but there are more.\n", + "Учитывая те же входные данные, большинство компьютерных программ ** детерминированные **, что означает, что они генерируют одни и те же выходы каждый раз.\n", + "Обычно детерминизм - это хорошая вещь, поскольку мы ожидаем, что тот же расчет будет даст тот же результат.\n", + "Однако для некоторых приложений мы хотим, чтобы компьютер был непредсказуемым.\n", + "Игры - один из примеров, но есть еще больше.\n", "\n", - "Making a program truly nondeterministic turns out to be difficult, but there are ways to fake it.\n", - "One is to use algorithms that generate **pseudorandom** numbers.\n", - "Pseudorandom numbers are not truly random because they are generated by a deterministic computation, but just by looking at the numbers it is all but impossible to distinguish them from random.\n", + "Сделать программу по -настоящему нетерминированной оказывается трудной, но есть способы ее подделать.\n", + "Одним из них является использование алгоритмов, которые генерируют ** псевдорандома ** числа.\n", + "Числа псевдордомов не являются по -настоящему случайными, потому что они генерируются детерминированными вычислениями, но, просто глядя на числа, почти невозможно отличить их от случайных.\n", "\n", - "The `random` module provides functions that generate pseudorandom numbers -- which I will simply call \"random\" from here on.\n", - "We can import it like this." + "Модуль «случайный» предоставляет функции, которые генерируют числа псевдордомов, которые я просто назову «случайным» с этого момента.\n", + "Мы можем импортировать его так." ] }, { @@ -752,7 +752,7 @@ "id": "8cbbd7f8", "metadata": {}, "source": [ - "The `random` module provides a function called `choice` that chooses an element from a list at random, with every element having the same probability of being chosen." + "Модуль «случайный» предоставляет функцию, называемую «выбор», которая выбирает элемент из списка случайным образом, причем каждый элемент имеет одинаковую вероятность выбора." ] }, { @@ -768,7 +768,7 @@ "id": "57c15af2", "metadata": {}, "source": [ - "If you call the function again, you might get the same element again, or a different one." + "Если вы снова вызовите функцию, вы можете снова получить один и тот же элемент или другой." ] }, { @@ -784,9 +784,9 @@ "id": "6f0c2572", "metadata": {}, "source": [ - "In the long run, we expect to get every element about the same number of times.\n", + "В долгосрочной перспективе мы ожидаем получить каждый элемент примерно одинаково раз.\n", "\n", - "If you use `choice` with a dictionary, you get a `KeyError`." + "Если вы используете «выбор» с словарем, вы получите `keeError '." ] }, { @@ -804,7 +804,7 @@ "id": "592722f3", "metadata": {}, "source": [ - "To choose a random key, you have to put the keys in a list and then call `choice`." + "Чтобы выбрать случайный ключ, вы должны поместить клавиши в список, а затем позвонить «выбор»." ] }, { @@ -820,7 +820,7 @@ "id": "172d72f6", "metadata": {}, "source": [ - "If we generate a random sequence of words, it doesn't make much sense." + "Если мы генерируем случайную последовательность слов, это не имеет большого смысла." ] }, { @@ -836,10 +836,10 @@ "id": "e0e2fbc4", "metadata": {}, "source": [ - "Part of the problem is that we are not taking into account that some words are more common than others.\n", - "The results will be better if we choose words with different \"weights\", so that some are chosen more often than others.\n", + "Часть проблемы в том, что мы не учитываем, что некоторые слова чаще, чем другие.\n", + "Результаты будут лучше, если мы выберем слова с различными «весами», чтобы некоторые из них выбирались чаще, чем другие.\n", "\n", - "If we use the values from `word_counter` as weights, each word is chosen with a probability that depends on its frequency." + "Если мы используем значения из `word_counter` в качестве веса, каждое слово выбирается с вероятностью, которая зависит от его частоты." ] }, { @@ -855,7 +855,7 @@ "id": "5098bf93", "metadata": {}, "source": [ - "The `random` module provides another function called `choices` that takes weights as an optional argument." + "Модуль `случайный 'предоставляет другую функцию под названием« Выбор », которая принимает веса в качестве необязательного аргумента." ] }, { @@ -871,7 +871,7 @@ "id": "a3341e84", "metadata": {}, "source": [ - "And it takes another optional argument, `k`, that specifies the number of words to select." + "И требуется еще один необязательный аргумент, `k`, который указывает количество слов для выбора." ] }, { @@ -887,7 +887,7 @@ "id": "e57e6f3d", "metadata": {}, "source": [ - "The result is a list of strings that we can join into something that's looks more like a sentence." + "Результатом является список строк, которые мы можем присоединиться к чем -то, что больше похоже на предложение." ] }, { @@ -903,9 +903,9 @@ "id": "c7a35dff", "metadata": {}, "source": [ - "If you choose words from the book at random, you get a sense of the vocabulary, but a series of random words seldom makes sense because there is no relationship between successive words.\n", - "For example, in a real sentence you expect an article like \"the\" to be followed by an adjective or a noun, and probably not a verb or adverb.\n", - "So the next step is to look at these relationships between words." + "Если вы выбираете слова из книги случайным образом, вы понимаете словарный запас, но серия случайных слов редко имеет смысл, потому что нет никаких отношений между последовательными словами.\n", + "Например, в реальном предложении вы ожидаете, что статья, такая как «The», за которой следует прилагательное или существительное, и, вероятно, не глагол или наречие.\n", + "Таким образом, следующий шаг - взглянуть на эти отношения между словами." ] }, { @@ -915,17 +915,17 @@ "source": [ "## Bigrams\n", "\n", - "Instead of looking at one word at a time, now we'll look at sequences of two words, which are called **bigrams**.\n", - "A sequence of three words is called a **trigram**, and a sequence with some unspecified number of words is called an **n-gram**.\n", + "Вместо того, чтобы смотреть на одно слово за раз, теперь мы рассмотрим последовательности из двух слов, которые называются ** Bigrams **.\n", + "Последовательность из трех слов называется ** триграмма **, а последовательность с некоторым неустановленным количеством слов называется ** n-грамм **.\n", "\n", - "Let's write a program that finds all of the bigrams in the book and the number of times each one appears.\n", - "To store the results, we'll use a dictionary where\n", + "Давайте напишем программу, которая находит все биграмы в книге, и количество раз каждый раз.\n", + "Чтобы сохранить результаты, мы будем использовать словарь, где\n", "\n", - "* The keys are tuples of strings that represent bigrams, and \n", + "* Ключи - это корты струн, которые представляют биграмс, и\n", "\n", - "* The values are integers that represent frequencies.\n", + "* Значения - это целые числа, которые представляют частоты.\n", "\n", - "Let's call it `bigram_counter`." + "Назовем это `bigram_counter`." ] }, { @@ -941,9 +941,9 @@ "id": "33f97a2a", "metadata": {}, "source": [ - "The following function takes a list of two strings as a parameter.\n", - "First it makes a tuple of the two strings, which can be used as a key in a dictionary.\n", - "Then it adds the key to `bigram_counter`, if it doesn't exist, or increments the frequency if it does." + "Следующая функция принимает список из двух строк в качестве параметра.\n", + "Сначала он делает кортеж из двух струн, которые можно использовать в качестве ключа в словаре.\n", + "Затем он добавляет ключ к `bigram_counter`, если он не существует, или увеличивает частоту, если она это делает." ] }, { @@ -959,11 +959,11 @@ "id": "5c30f429", "metadata": {}, "source": [ - "As we go through the book, we have to keep track of each pair of consecutive words.\n", - "So if we see the sequence \"man is not truly one\", we would add the bigrams \"man is\", \"is not\", \"not truly\", and so on.\n", + "Когда мы проходим через книгу, мы должны отслеживать каждую пару последовательных слов.\n", + "Поэтому, если мы увидим последовательность «Человек не один», мы бы добавили биграмс «человек», «не», «не по -настоящему» и так далее.\n", "\n", - "To keep track of these bigrams, we'll use a list called `window`, because it is like a window that slides over the pages of the book, showing only two words at a time.\n", - "Initially, `window` is empty." + "Чтобы отслеживать эти Bigrams, мы будем использовать список под названием «Window», потому что это похоже на окно, которое скользит по страницам книги, показывая только два слова за раз.\n", + "Первоначально `window 'пусто." ] }, { @@ -979,7 +979,7 @@ "id": "9376558c", "metadata": {}, "source": [ - "We'll use the following function to process the words one at a time." + "Мы будем использовать следующую функцию для обработки слов по одному." ] }, { @@ -995,14 +995,14 @@ "id": "56895591", "metadata": {}, "source": [ - "The first time this function is called, it appends the given word to `window`.\n", - "Since there is only one word in the window, we don't have a bigram yet, so the function ends.\n", + "В первый раз, когда эта функция называется, она добавляет данное слово в `window '.\n", + "Поскольку в окне есть только одно слово, у нас еще нет биграма, поэтому функция заканчивается.\n", "\n", - "The second time it's called -- and every time thereafter -- it appends a second word to `window`.\n", - "Since there are two words in the window, it calls `count_bigram` to keep track of how many times each bigram appears.\n", - "Then it uses `pop` to remove the first word from the window.\n", + "Во второй раз это называется - и каждый раз после этого - он добавляет второе слово в «окно».\n", + "Поскольку в окне есть два слова, он называет `count_bigram`, чтобы отслеживать, сколько раз появляется каждый биграм.\n", + "Затем он использует `pop`, чтобы удалить первое слово из окна.\n", "\n", - "The following program loops through the words in the book and processes them one at a time." + "Следующая программа проходит через слова в книге и обрабатывает их по одному." ] }, { @@ -1018,8 +1018,8 @@ "id": "20c4627a", "metadata": {}, "source": [ - "The result is a dictionary that maps from each bigram to the number of times it appears.\n", - "We can use `print_most_common` to see the most common bigrams." + "Результатом является словарь, который отображает от каждого биграма до количества раз, когда он появляется.\n", + "Мы можем использовать `print_sty_common`, чтобы увидеть наиболее распространенные биграмы." ] }, { @@ -1035,8 +1035,8 @@ "id": "757bd309", "metadata": {}, "source": [ - "Looking at these results, we can get a sense of which pairs of words are most likely to appear together.\n", - "We can also use the results to generate random text, like this." + "Глядя на эти результаты, мы можем понять, какие пары слов, скорее всего, появятся вместе.\n", + "Мы также можем использовать результаты для генерации случайного текста, как это." ] }, { @@ -1062,10 +1062,10 @@ "id": "eda80407", "metadata": {}, "source": [ - "`bigrams` is a list of the bigrams that appear in the books.\n", - "`weights` is a list of their frequencies, so `random_bigrams` is a sample where the probability a bigram is selected is proportional to its frequency. \n", + "`Bigrams ' - это список биграмсов, которые появляются в книгах.\n", + "`Weews` - это список их частот, поэтому` random_bigrams` - это выборка, в которой вероятность выбора биграма пропорциональна его частоте.\n", "\n", - "Here are the results." + "Вот результаты." ] }, { @@ -1081,7 +1081,7 @@ "id": "5f24c3b6", "metadata": {}, "source": [ - "This way of generating text is better than choosing random words, but still doesn't make a lot of sense." + "Этот способ создания текста лучше, чем выбирать случайные слова, но все еще не имеет большого смысла." ] }, { @@ -1089,10 +1089,10 @@ "id": "a13d93b5", "metadata": {}, "source": [ - "## Markov analysis\n", + "## Анализ Маркова\n", "\n", - "We can do better with Markov chain text analysis, which computes, for each word in a text, the list of words that come next.\n", - "As an example, we'll analyze these lyrics from the Monty Python song *Eric, the Half a Bee*:" + "Мы можем добиться большего успеха с анализом текста цепи Маркова, который вычисляет для каждого слова в тексте, список слов, которые следуют дальше.\n", + "Например, мы проанализируем эти тексты из песни Monty Python *Eric, половина пчелы *:" ] }, { @@ -1108,7 +1108,7 @@ "id": "583ab9f0", "metadata": {}, "source": [ - "To store the results, we'll use a dictionary that maps from each word to the list of words that follow it." + "Чтобы сохранить результаты, мы будем использовать словарь, который отображает из каждого слова в список слов, которые следуют за ним." ] }, { @@ -1124,7 +1124,7 @@ "id": "d5d85b09", "metadata": {}, "source": [ - "As an example, let's start with the first two words of the song." + "В качестве примера, давайте начнем с первых двух слов песни." ] }, { @@ -1140,7 +1140,7 @@ "id": "0349fe78", "metadata": {}, "source": [ - "If the first word is not in `successor_map`, we have to add a new item that maps from the first word to a list containing the second word." + "Если первое слово не в `customor_map`, мы должны добавить новый элемент, который отображает из первого слова в список, содержащий второе слово." ] }, { @@ -1156,7 +1156,7 @@ "id": "55bb8df9", "metadata": {}, "source": [ - "If the first word is already in the dictionary, we can look it up to get the list of successors we've seen so far, and append the new one." + "Если первое слово уже в словаре, мы можем посмотреть его, чтобы получить список преемников, которых мы видели до сих пор, и добавить новый." ] }, { @@ -1172,7 +1172,7 @@ "id": "6289cc32", "metadata": {}, "source": [ - "The following function encapsulates these steps." + "Следующая функция инкапсулирует эти шаги." ] }, { @@ -1188,11 +1188,11 @@ "id": "74a51700", "metadata": {}, "source": [ - "If the same bigram appears more that once, the second word is added to the list more than once.\n", - "In this way, `successor_map` keeps track of how many times each successor appears.\n", + "Если тот же биграм появляется больше, чем один раз, второе слово добавляется в список более одного раза.\n", + "Таким образом, `custeror_map` отслеживает, сколько раз появляется каждый преемник.\n", "\n", - "As we did in the previous section, we'll use a list called `window` to store pairs of consecutive words.\n", - "And we'll use the following function to process the words one at a time." + "Как и в предыдущем разделе, мы будем использовать список под названием «Window» для хранения пар последовательных слов.\n", + "И мы будем использовать следующую функцию для обработки слов по одному." ] }, { @@ -1208,7 +1208,7 @@ "id": "861a60d9", "metadata": {}, "source": [ - "Here's how we use it to process the words in the song." + "Вот как мы используем его для обработки слов в песне." ] }, { @@ -1224,7 +1224,7 @@ "id": "bf490d67", "metadata": {}, "source": [ - "And here are the results." + "И вот результаты." ] }, { @@ -1240,11 +1240,11 @@ "id": "ff7bad74", "metadata": {}, "source": [ - "The word `'half'` can be followed by `'a'`, `'not'`, or `'the'`.\n", - "The word `'a'` can be followed by `'bee'` or `'vis'`.\n", - "Most of the other words appear only once, so they are followed by only a single word.\n", + "Слово «полу» может сопровождаться `'a' ',`' not '' или `''.\n", + "Слово «a» может сопровождаться `'bee'' 'или`' vis '.\n", + "Большинство других слов появляются только один раз, поэтому за ними следует только одно слово.\n", "\n", - "Now let's analyze the book." + "Теперь давайте проанализируем книгу." ] }, { @@ -1260,7 +1260,7 @@ "id": "2676e2fb", "metadata": {}, "source": [ - "We can look up any word and find the words that can follow it." + "Мы можем искать любое слово и найти слова, которые могут следовать ему." ] }, { @@ -1286,7 +1286,7 @@ "id": "7b777a9c", "metadata": {}, "source": [ - "In this list of successors, notice that the word `'to'` appears three times -- the other successors only appear once." + "В этом списке преемников обратите внимание, что слово «до» появляется три раза - другие преемники появляются только один раз." ] }, { @@ -1294,18 +1294,18 @@ "id": "e8bf85fc", "metadata": {}, "source": [ - "## Generating text\n", + "## генерирование текста\n", "\n", - "We can use the results from the previous section to generate new text with the same relationships between consecutive words as in the original.\n", - "Here's how it works:\n", + "Мы можем использовать результаты из предыдущего раздела для создания нового текста с теми же отношениями между последовательными словами, что и в оригинале.\n", + "Вот как это работает:\n", "\n", - "* Starting with any word that appears in the text, we look up its possible successors and choose one at random.\n", + "* Начиная с любого слова, которое появляется в тексте, мы смотрим на его возможных преемников и выбираем его случайным образом.\n", "\n", - "* Then, using the chosen word, we look up its possible successors, and choose one at random.\n", + "* Затем, используя выбранное слово, мы смотрим его возможных преемников и выбираем его случайным образом.\n", "\n", - "We can repeat this process to generate as many words as we want.\n", - "As an example, let's start with the word `'although'`.\n", - "Here are the words that can follow it." + "Мы можем повторить этот процесс, чтобы генерировать столько слов, сколько хотим.\n", + "В качестве примера, давайте начнем со слова «хотя».\n", + "Вот слова, которые могут следовать за ним." ] }, { @@ -1331,7 +1331,7 @@ "id": "b26a2ead", "metadata": {}, "source": [ - "We can use `choice` to choose from the list with equal probability." + "Мы можем использовать «выбор», чтобы выбрать из списка с одинаковой вероятностью." ] }, { @@ -1347,9 +1347,9 @@ "id": "9741beca", "metadata": {}, "source": [ - "If the same word appears more than once in the list, it is more likely to be selected.\n", + "Если одно и то же слово появляется более одного раза в списке, оно будет выбран.\n", "\n", - "Repeating these steps, we can use the following loop to generate a longer series." + "Повторяя эти шаги, мы можем использовать следующий цикл для создания более длинной серии." ] }, { @@ -1365,11 +1365,11 @@ "id": "38a2d79a", "metadata": {}, "source": [ - "The result sounds more like a real sentence, but it still doesn't make much sense.\n", + "Результат звучит больше как реальное предложение, но это все еще не имеет большого смысла.\n", "\n", - "We can do better using more than one word as a key in `successor_map`.\n", - "For example, we can make a dictionary that maps from each bigram -- or trigram -- to the list of words that come next.\n", - "As an exercise, you'll have a chance to implement this analysis and see what the results look like." + "Мы можем лучше использовать более одного слова в качестве ключа в `curstor_map`.\n", + "Например, мы можем сделать словарь, который карты из каждой биграм - или триграммы - в список слов, которые приходят дальше.\n", + "В качестве упражнения у вас будет возможность реализовать этот анализ и посмотреть, как выглядят результаты." ] }, { @@ -1379,32 +1379,32 @@ "tags": [] }, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "At this point we are writing more substantial programs, and you might find that you are spending more time debugging.\n", - "If you are stuck on a difficult bug, here are a few things to try:\n", + "На данный момент мы пишем более существенные программы, и вы можете обнаружить, что вы тратите больше времени на отладку.\n", + "Если вы застряли на сложной ошибке, вот несколько вещей, которые нужно попробовать:\n", "\n", - "* Reading: Examine your code, read it back to yourself, and check that it says what you meant to say.\n", + "* Чтение: проверьте свой код, прочитайте его обратно и проверьте, что он говорит то, что вы хотели сказать.\n", "\n", - "* Running: Experiment by making changes and running different versions. Often if you display the right thing at the right place in the program, the problem becomes obvious, but sometimes you have to build scaffolding.\n", + "* Запуск: Экспериментируйте, внося изменения и запустив разные версии.Часто, если вы отображаете правильные вещи в нужном месте в программе, проблема становится очевидной, но иногда вам приходится строить леса.\n", "\n", - "* Ruminating: Take some time to think! What kind of error is it: syntax, runtime,\n", - " or semantic? What information can you get from the error messages,\n", - " or from the output of the program? What kind of error could cause\n", - " the problem you're seeing? What did you change last, before the\n", - " problem appeared?\n", + "* Размышления: понадобится время, чтобы подумать!Что это за ошибка: синтаксис, время выполнения,\n", + "или семантический?Какая информация вы можете получить от сообщений об ошибках,\n", + "Или из вывода программы?Какая ошибка может вызвать\n", + "Проблема, которую вы видите?Что вы изменили в последний раз, до\n", + "Появилась проблема?\n", "\n", - "* Rubberducking: If you explain the problem to someone else, you sometimes find the\n", - " answer before you finish asking the question. Often you don't need\n", - " the other person; you could just talk to a rubber duck. And that's\n", - " the origin of the well-known strategy called **rubber duck\n", - " debugging**. I am not making this up -- see\n", - " .\n", + "* RubberDucking: Если вы объясните проблему кому -то другому, вы иногда найдете\n", + "Ответьте, прежде чем закончить задание вопроса.Часто вам не нужно\n", + "другой человек;Вы могли бы просто поговорить с резиновой уткой.И это\n", + "Происхождение известной стратегии под названием ** резиновая утка\n", + "отладка **.Я не придумываю это - вижу\n", + ".\n", "\n", - "* Retreating: At some point, the best thing to do is back up -- undoing recent\n", - " changes -- until you get to a program that works. Then you can start rebuilding.\n", - " \n", - "* Resting: If you give your brain a break, sometime it will find the problem for you." + "* Отступление: в какой -то момент лучше\n", + "Изменения - пока вы не доберетесь до программы, которая работает.Тогда вы можете начать восстановление.\n", + "\n", + "* Отдых: если вы дадите своему мозгу разрыв, иногда это найдет проблему для вас." ] }, { @@ -1412,15 +1412,15 @@ "id": "12c2cd32", "metadata": {}, "source": [ - "Beginning programmers sometimes get stuck on one of these activities and forget the others. Each activity comes with its own failure mode.\n", + "Начальные программисты иногда застряли на одном из этих действий и забывают других.Каждое действие поставляется с собственным режимом отказа.\n", "\n", - "For example, reading your code works if the problem is a typographical error, but not if the problem is a conceptual misunderstanding.\n", - "If you don't understand what your program does, you can read it 100 times and never see the error, because the error is in your head.\n", + "Например, чтение вашего кода работает, если проблема является типографской ошибкой, но не в том случае, если проблема является концептуальным недопониманием.\n", + "Если вы не понимаете, что делает ваша программа, вы можете прочитать ее 100 раз и никогда не увидеть ошибку, потому что ошибка у вас в голове.\n", "\n", - "Running experiments can work, especially if you run small, simple tests.\n", - "But if you run experiments without thinking or reading your code, it can take a long time to figure out what's happening.\n", + "Запуск экспериментов может работать, особенно если вы запускаете маленькие, простые тесты.\n", + "Но если вы запускаете эксперименты, не задумываясь и не читая свой код, может потребоваться много времени, чтобы выяснить, что происходит.\n", "\n", - "You have to take time to think. Debugging is like an experimental science. You should have at least one hypothesis about what the problem is. If there are two or more possibilities, try to think of a test that would eliminate one of them." + "Вы должны понадобиться, чтобы подумать.Отладка похожа на экспериментальную науку.У вас должна быть хотя бы одна гипотеза о том, в чем проблема.Если есть две или более возможностей, попробуйте придумать тест, который устранит один из них." ] }, { @@ -1428,18 +1428,18 @@ "id": "a55036e1", "metadata": {}, "source": [ - "But even the best debugging techniques will fail if there are too many\n", - "errors, or if the code you are trying to fix is too big and complicated.\n", - "Sometimes the best option is to retreat, simplifying the program until\n", - "you get back to something that works.\n", + "Но даже лучшие методы отладки потерпят неудачу, если их слишком много\n", + "Ошибки, или если код, который вы пытаетесь исправить, слишком большой и сложный.\n", + "Иногда лучший вариант - отступить, упрощая программу до тех пор, пока\n", + "Вы возвращаетесь к чему -то, что работает.\n", "\n", - "Beginning programmers are often reluctant to retreat because they can't\n", - "stand to delete a line of code (even if it's wrong). If it makes you\n", - "feel better, copy your program into another file before you start\n", - "stripping it down. Then you can copy the pieces back one at a time.\n", + "Начальные программисты часто неохотно отступают, потому что они не могут\n", + "Встаньте, чтобы удалить строку кода (даже если это не так).Если это заставит вас\n", + "Почувствуйте себя лучше, скопируйте свою программу в другой файл, прежде чем начать\n", + "Разбрасывая это.Тогда вы можете скопировать части обратно по одному.\n", "\n", - "Finding a hard bug requires reading, running, ruminating, retreating, and sometimes resting.\n", - "If you get stuck on one of these activities, try the others." + "Поиск жесткой ошибки требует чтения, бега, размышлений, отступления и иногда отдыха.\n", + "Если вы застряли на одном из этих действий, попробуйте другие." ] }, { @@ -1447,31 +1447,31 @@ "id": "25d091af", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**default value:**\n", - "The value assigned to a parameter if no argument is provided.\n", + "** Значение по умолчанию: **\n", + "Значение, присвоенное параметру, если аргумент не предоставлен.\n", "\n", - "**override:**\n", - " To replace a default value with an argument.\n", + "** Переопределение: **\n", + "Чтобы заменить значение по умолчанию на аргумент.\n", "\n", - "**deterministic:**\n", - " A deterministic program does the same thing each time it runs, given the same inputs.\n", + "** Детерминированный: **\n", + "Детерминистская программа делает одно и то же каждый раз, когда она работает, учитывая одинаковые входы.\n", "\n", - "**pseudorandom:**\n", - " A pseudorandom sequence of numbers appears to be random, but is generated by a deterministic program.\n", + "** псевдорандома: **\n", + "Последовательность псевдорендомов чисел, по -видимому, является случайной, но генерируется детерминистской программой.\n", "\n", - "**bigram:**\n", - "A sequence of two elements, often words.\n", + "** Bigram: **\n", + "Последовательность двух элементов, часто слова.\n", "\n", - "**trigram:**\n", - "A sequence of three elements.\n", + "** Триграмма: **\n", + "Последовательность из трех элементов.\n", "\n", - "**n-gram:**\n", - "A sequence of an unspecified number of elements.\n", + "** n-gram: **\n", + "Последовательность неустановленного числа элементов.\n", "\n", - "**rubber duck debugging:**\n", - "A way of debugging by explaining a problem aloud to an inanimate object." + "** Отладка резиновой утки: **\n", + "Способ отладки, объяснив проблему вслух неодушевленным объектам." ] }, { @@ -1479,7 +1479,7 @@ "id": "cde18229", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -1497,9 +1497,9 @@ "id": "9b0efab8", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "In `add_bigram`, the `if` statement creates a new list or appends an element to an existing list, depending on whether the key is already in the dictionary." + "В `add_bigram` оператор« if »создает новый список или добавляет элемент к существующему списку, в зависимости от того, находится ли ключ в словаре." ] }, { @@ -1515,13 +1515,13 @@ "id": "30d9e549", "metadata": {}, "source": [ - "Dictionaries provide a method called `setdefault` that we can use to do the same thing more concisely.\n", - "Ask a virtual assistant how it works, or copy `add_word` into a virtual assistant and ask \"Can you rewrite this using `setdefault`?\"\n", + "Словары предоставляют метод под названием «SetDefault», который мы можем использовать, чтобы сделать то же самое более кратко.\n", + "Спросите виртуального помощника, как это работает, или скопируйте `add_word` в виртуального помощника и спросите:« Можете ли вы переписать это, используя `setdefault`?»\n", "\n", - "In this chapter we implemented Markov chain text analysis and generation.\n", - "If you are curious, you can ask a virtual assistant for more information on the topic.\n", - "One of the things you might learn is that virtual assistants use algorithms that are similar in many ways -- but also different in important ways.\n", - "Ask a VA, \"What are the differences between large language models like GPT and Markov chain text analysis?\"" + "В этой главе мы реализовали анализ текста и генерации цепи Маркова.\n", + "Если вам любопытно, вы можете попросить виртуального помощника для получения дополнительной информации по теме.\n", + "Одна из вещей, которые вы можете узнать, заключается в том, что виртуальные помощники используют алгоритмы, которые во многих отношениях похожи, но также различны важными способами.\n", + "Спросите VA: «Каковы различия между большими языковыми моделями, такими как анализ текста GPT и марковского текста?»" ] }, { @@ -1529,12 +1529,12 @@ "id": "060c9ef6", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function that counts the number of times each trigram (sequence of three words) appears. \n", - "If you test your function with the text of _Dr. Jekyll and Mr. Hyde_, you should find that the most common trigram is \"said the lawyer\".\n", + "Напишите функцию, которая подсчитывает количество раз, когда появляется каждая триграмма (последовательность трех слов).\n", + "Если вы проверяете свою функцию с помощью текста _dr.Jekyll и Mr. Hyde_, вы должны обнаружить, что наиболее распространенной триграммой является «сказал адвокат».\n", "\n", - "Hint: Write a function called `count_trigram` that is similar to `count_bigram`. Then write a function called `process_word_trigram` that is similar to `process_word_bigram`." + "Подсказка: напишите функцию с именем `count_trigram`, которая похожа на` count_bigram`.Затем напишите функцию с именем `process_word_trigram`, которая похожа на` process_word_bigram`." ] }, { @@ -1560,7 +1560,7 @@ "tags": [] }, "source": [ - "You can use the following loop to read the book and process the words." + "Вы можете использовать следующий цикл, чтобы прочитать книгу и обработать слова." ] }, { @@ -1580,7 +1580,7 @@ "tags": [] }, "source": [ - "Then use `print_most_common` to find the most common trigrams in the book." + "Затем используйте `print_sty_common`, чтобы найти наиболее распространенные триграммы в книге." ] }, { @@ -1598,11 +1598,11 @@ "id": "4bd07bb7", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Now let's implement Markov chain text analysis with a mapping from each bigram to a list of possible successors.\n", + "Теперь давайте внедрим анализ текста цепи Маркова с отображением от каждого биграма в список возможных преемников.\n", "\n", - "Starting with `add_bigram`, write a function called `add_trigram` that takes a list of three words and either adds or updates an item in `successor_map`, using the first two words as the key and the third word as a possible successor." + "Начиная с `add_bigram`, напишите функцию с именем` add_trigram`, которая принимает список из трех слов и добавляет или обновляет элемент в `custcoror_map`, используя первые два слова в качестве ключа и третье слово в качестве возможного преемника." ] }, { @@ -1618,7 +1618,7 @@ "id": "94d683fe", "metadata": {}, "source": [ - "Here's a version of `process_word_trigram` that calls `add_trigram`." + "Вот версия `process_word_trigram`, которая вызывает` add_trigram`." ] }, { @@ -1636,7 +1636,7 @@ "tags": [] }, "source": [ - "You can use the following loop to test your function with the lyrics of \"Eric, the Half a Bee\"." + "Вы можете использовать следующий цикл, чтобы проверить свою функцию с помощью текста «Эрик, половина пчелы»." ] }, { @@ -1656,8 +1656,8 @@ "tags": [] }, "source": [ - "If your function works as intended, the predecessor `('half', 'a')` should map to a list with the single element `'bee'`.\n", - "In fact, as it happens, each bigram in this song appear only once, so all of the values in `successor_map` have a single element." + "Если ваша функция работает так, как предназначена, предшественник `(« половина », 'a')` должен составить карту в список с одним элементом `'bee''.\n", + "На самом деле, как это происходит, каждый биграм в этой песне появляется только один раз, поэтому все значения в `custcoror_map` имеют единый элемент." ] }, { @@ -1675,7 +1675,7 @@ "id": "886212b5", "metadata": {}, "source": [ - "You can use the following loop to test your function with the words from the book." + "Вы можете использовать следующий цикл, чтобы проверить свою функцию со словами из книги." ] }, { @@ -1691,7 +1691,7 @@ "id": "3e1d073e", "metadata": {}, "source": [ - "In the next exercise, you'll use the results to generate new random text." + "В следующем упражнении вы используете результаты для генерации нового случайного текста." ] }, { @@ -1699,9 +1699,9 @@ "id": "04d7a6ee", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "For this exercise, we'll assume that `successor_map` is a dictionary that maps from each bigram to the list of words that follow it." + "Для этого упражнения мы предположим, что `custoror_map` - это словарь, который отображает из каждого биграма в список слов, которые следуют за ним." ] }, { @@ -1719,7 +1719,7 @@ "id": "fb0f8f7d", "metadata": {}, "source": [ - "To generate random text, we'll start by choosing a random key from `successor_map`." + "Чтобы сгенерировать случайный текст, мы начнем с выбора случайного ключа из `customor_map`." ] }, { @@ -1735,15 +1735,15 @@ "id": "83ed6c7e", "metadata": {}, "source": [ - "Now write a loop that generates 50 more words following these steps:\n", + "Теперь напишите цикл, который генерирует еще 50 слов после этих шагов:\n", "\n", - "1. In `successor_map`, look up the list of words that can follow `bigram`.\n", + "1. В `custeror_map` найдите список слов, которые могут следовать за` bigram '.\n", "\n", - "2. Choose one of them at random and print it.\n", + "2. Выберите один из них случайным образом и распечатайте его.\n", "\n", - "3. For the next iteration, make a new bigram that contains the second word from `bigram` and the chosen successor.\n", + "3. Для следующей итерации сделайте новый биграм, который содержит второе слово от `Bigram` и выбранного преемника.\n", "\n", - "For example, if we start with the bigram `('doubted', 'if')` and choose `'from'` as its successor, the next bigram is `('if', 'from')`." + "Например, если мы начнем с Bigram `('сомневались', 'if')` и выберем `'from' 'в качестве преемника, следующий биграм - (' if ',' from ')`." ] }, { @@ -1759,9 +1759,9 @@ "id": "c71d8a89", "metadata": {}, "source": [ - "If everything is working, you should find that the generated text is recognizably similar in style to the original, and some phrases make sense, but the text might wander from one topic to another.\n", + "Если все работает, вы должны обнаружить, что сгенерированный текст узнаваемо по -настоящему похож на оригинал, а некоторые фразы имеют смысл, но текст может бродить от одной темы к другой.\n", "\n", - "As a bonus exercise, modify your solution to the last two exercises to use trigrams as keys in `successor_map`, and see what effect it has on the results." + "В качестве бонусного упражнения измените свое решение до двух последних упражнений, чтобы использовать триграммы в качестве ключей в `custormor_map`, и посмотрите, какое влияние он оказывает на результаты." ] }, { @@ -1779,13 +1779,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT] (https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik" ] } ], From dd756e5f8ebd45c50805b898842806803d560f5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:04:43 +0300 Subject: [PATCH 13/44] Translate chap13 text cells to Russian --- blank/chap13.ipynb | 502 ++++++++++++++++++++++----------------------- 1 file changed, 251 insertions(+), 251 deletions(-) diff --git a/blank/chap13.ipynb b/blank/chap13.ipynb index 69616a9..fe9efc5 100644 --- a/blank/chap13.ipynb +++ b/blank/chap13.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг*Think Python 3e*из\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon](https://www.amazon.com/_/dp/1098155432?ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325)." ] }, { @@ -27,8 +27,8 @@ "tags": [] }, "source": [ - "Credit: Photos downloaded from [Lorem Picsum](https://picsum.photos/), a service that provides placeholder images.\n", - "The name is a reference to \"lorem ipsum\", which is a name for placeholder text.\n" + "Кредит: фотографии загружены с [Lorem Picsum](https://picsum.photos/), услуга, которая предоставляет изображения заполнителей.\n", + "Название является ссылкой на «Lorem Ipsum», которая является названием для текста заполнителей." ] }, { @@ -66,19 +66,19 @@ "id": "92934cb0", "metadata": {}, "source": [ - "# Files and Databases\n", + "# Файлы и базы данных\n", "\n", - "Most of the programs we have seen so far are **ephemeral** in the sense that they run for a short time and produce output, but when they end, their data disappears.\n", - "Each time you run an ephemeral program, it starts with a clean slate.\n", + "Большинство программ, которые мы видели до сих пор, являются**эфемерными**в том смысле, что они запускаются в течение короткого времени и производят выход, но когда они заканчиваются, их данные исчезают.\n", + "Каждый раз, когда вы запускаете эфемерную программу, она начинается с чистого сланца.\n", "\n", - "Other programs are **persistent**: they run for a long time (or all the time); they keep at least some of their data in long-term storage; and if they shut down and restart, they pick up where they left off.\n", + "Другие программы**настойчивы**: они бегают в течение длительного времени (или все время);Они держат хотя бы некоторые из своих данных в долгосрочном хранении;И если они отключены и перезагружаются, они поднимают, где остановились.\n", "\n", - "A simple way for programs to maintain their data is by reading and writing text files.\n", - "A more versatile alternative is to store data in a database.\n", - "Databases are specialized files that can be read and written more efficiently than text files, and they provide additional capabilities.\n", + "Простым способом для сохранения своих данных является чтение и написание текстовых файлов.\n", + "Более универсальной альтернативой является хранение данных в базе данных.\n", + "Базы данных представляют собой специализированные файлы, которые могут быть прочитаны и написаны более эффективно, чем текстовые файлы, и они предоставляют дополнительные возможности.\n", "\n", - "In this chapter, we'll write programs that read and write text files and databases, and as an exercise you'll write a program that searches a collection of photos for duplicates.\n", - "But before you can work with a file, you have to find it, so we'll start with file names, paths, and directories." + "В этой главе мы напишем программы, которые читают и пишем текстовые файлы и базы данных, а в качестве упражнения вы напишете программу, которая ищет коллекцию фотографий для дубликатов.\n", + "Но прежде чем вы сможете работать с файлом, вы должны его найти, поэтому мы начнем с имен файлов, путей и каталогов." ] }, { @@ -86,14 +86,14 @@ "id": "75cec7ca", "metadata": {}, "source": [ - "## Filenames and paths\n", + "## имена файлов и пути\n", "\n", - "Files are organized into **directories**, also called \"folders\".\n", - "Every running program has a **current working directory**, which is the default directory for most operations.\n", - "For example, when you open a file, Python looks for it in the current working directory.\n", + "Файлы организованы в**каталоги**, также называемые «папки».\n", + "Каждая работающая программа имеет**текущий рабочий каталог**, который является каталогом по умолчанию для большинства операций.\n", + "Например, когда вы открываете файл, Python ищет его в текущем рабочем каталоге.\n", "\n", - "The `os` module provides functions for working with files and directories (\"os\" stands for \"operating system\"). \n", - "It provides a function called `getcwd` that gets the name of the current working directory." + "Модуль «OS» предоставляет функции для работы с файлами и каталогами («ОС» означает «операционная система»).\n", + "Он предоставляет функцию, называемую `getCwd`, которая получает имя текущего рабочего каталога." ] }, { @@ -119,14 +119,14 @@ "id": "6c55575f", "metadata": {}, "source": [ - "The result in this example is the home directory of a user named `dinsdale`.\n", - "A string like `'/home/dinsdale'` that identifies a file or directory is called a **path**.\n", + "Результатом этого примера является домашний каталог пользователя по имени «Dinsdale».\n", + "Строка, такая как `'/home/dinsdale'', которая идентифицирует файл или каталог, называется**Path**.\n", "\n", - "A simple filename like `'memo.txt'` is also considered a path, but it is a **relative path** because it specifies a file name relative to the current directory.\n", - "In this example, the current directory is `/home/dinsdale`, so `'memo.txt'` is equivalent to the complete path `'/home/dinsdale/memo.txt'`.\n", + "Простое имя файла, подобное «memo.txt'», также считается путем, но это**относительный путь**, потому что оно определяет имя файла относительно текущего каталога.\n", + "В этом примере текущий каталог - «/home/dinsdale», поэтому `` memo.txt'` эквивалентен полному пути `'/home/dinsdale/memo.txt'`.\n", "\n", - "A path that begins with `/` does not depend on the current directory -- it is called an **absolute path**. \n", - "To find the absolute path to a file, you can use `abspath`." + "Путь, который начинается с `/`, не зависит от текущего каталога - он называется**абсолютный путь**.\n", + "Чтобы найти абсолютный путь к файлу, вы можете использовать `abspath '." ] }, { @@ -142,9 +142,9 @@ "id": "f1a0cf04", "metadata": {}, "source": [ - "The `os` module provides other functions for working with filenames and paths.\n", - "`listdir` returns a list of the contents of the given directory, including files and other directories.\n", - "Here's an example that lists the contents of a directory named `photos`." + "Модуль `OS обеспечивает другие функции для работы с именами файлов и путей.\n", + "`listdir` возвращает список содержимого данного каталога, включая файлы и другие каталоги.\n", + "Вот пример, который перечисляет содержимое каталога под названием «Фотографии»." ] }, { @@ -160,8 +160,8 @@ "id": "ab160f29", "metadata": {}, "source": [ - "This directory contains a text file named `notes.txt` and three directories.\n", - "The directories contain image files in the JPEG format." + "Этот каталог содержит текстовый файл с именем `notes.txt` и три каталога.\n", + "Катарии содержат файлы изображений в формате JPEG." ] }, { @@ -177,7 +177,7 @@ "id": "06b27c85", "metadata": {}, "source": [ - "To check whether a file or directory exists, we can use `os.path.exists`." + "Чтобы проверить, существует ли файл или каталог, мы можем использовать `os.path.exists`." ] }, { @@ -201,7 +201,7 @@ "id": "d41f235c", "metadata": {}, "source": [ - "To check whether a path refers to a file or directory, we can use `isdir`, which return `True` if a path refers to a directory." + "Чтобы проверить, относится ли путь к файлу или каталогу, мы можем использовать `isdir`, который возвращает` true`, если путь относится к каталогу." ] }, { @@ -217,7 +217,7 @@ "id": "4bd70cc9", "metadata": {}, "source": [ - "And `isfile` which returns `True` if a path refers to a file." + "И `isfile`, который возвращает` true`, если путь относится к файлу." ] }, { @@ -233,12 +233,12 @@ "id": "c6933c18", "metadata": {}, "source": [ - "One challenge of working with paths is that they look different on different operating systems.\n", - "On macOS and UNIX systems like Linux, the directory and file names in a path are separated by a forward slash, `/`.\n", - "Windows uses a backward slash, `\\`.\n", - "So, if you you run these examples on Windows, you will see backward slashes in the paths, and you'll have to replace the forward slashes in the examples.\n", + "Одна из проблем работы с путями заключается в том, что они выглядят по -разному в различных операционных системах.\n", + "В системах MacOS и Unix, таких как Linux, имена каталога и файлов в пути разделены прямолинейной чертой, `/`.\n", + "Windows использует обратную черту, `\\`.\n", + "Так что, если вы запускаете эти примеры в Windows, вы увидите обратные черты на пути, и вам придется заменить прямые черты в примерах.\n", "\n", - "Or, to write code that works on both systems, you can use `os.path.join`, which joins directory and filenames into a path using a forward or backward slash, depending on which operating system you are using." + "Или, чтобы написать код, который работает в обеих системах, вы можете использовать `os.path.join`, который соединяет каталог и имена файлов в путь, используя прямую или обратную черту, в зависимости от того, какую операционную систему вы используете." ] }, { @@ -254,7 +254,7 @@ "id": "0a665cf9", "metadata": {}, "source": [ - "Later in this chapter we'll use these functions to search a set of directories and find all of the image files." + "Позже в этой главе мы будем использовать эти функции для поиска набора каталогов и поиск всех файлов изображений." ] }, { @@ -262,12 +262,12 @@ "id": "31a96ba4", "metadata": {}, "source": [ - "## f-strings\n", + "## F-стрит\n", "\n", - "One way for programs to store data is to write it to a text file.\n", - "For example, suppose you are a camel spotter, and you want to record the number of camels you have seen during a period of observation.\n", - "And suppose that in one and a half years, you have spotted `23` camels.\n", - "The data in your camel-spotting book might look like this." + "Один из способов для хранения программ - написать их в текстовый файл.\n", + "Например, предположим, что вы являетесь верблюжьим штрифом, и вы хотите записать количество верблюдов, которые вы видели в период наблюдения.\n", + "И предположим, что через полтора года вы заметили 23 -й верблюда.\n", + "Данные в вашей верблюжьей книге могут выглядеть так." ] }, { @@ -283,11 +283,11 @@ "id": "f652aaac", "metadata": {}, "source": [ - "To write this data to a file, you can use the `write` method, which we saw in Chapter 8.\n", - "The argument of `write` has to be a string, so if we want to put other values in a file, we have to convert them to strings.\n", - "The easiest way to do that is with the built-in function `str`.\n", + "Чтобы написать эти данные в файл, вы можете использовать метод «записать», который мы видели в главе 8.\n", + "Аргумент «write» должен быть строкой, поэтому, если мы хотим поместить другие значения в файл, мы должны преобразовать их в строки.\n", + "Самый простой способ сделать это со встроенной функцией `str`.\n", "\n", - "Here's what that looks like:" + "Вот как это выглядит:" ] }, { @@ -303,8 +303,8 @@ "id": "307c22d2", "metadata": {}, "source": [ - "That works, but `write` doesn't add a space or newline unless you include it explicitly.\n", - "If we read back the file, we see that the two numbers are run together." + "Это работает, но «написать» не добавляет пространство или новую линию, если вы не включите его явно.\n", + "Если мы прочитаем файл, мы видим, что два числа запускаются вместе." ] }, { @@ -320,11 +320,11 @@ "id": "8008ecdc", "metadata": {}, "source": [ - "At the very least, we should add whitespace between the numbers.\n", - "And while we're at it, let's add some explanatory text.\n", + "По крайней мере, мы должны добавить пробелы между числами.\n", + "И пока мы в этом, давайте добавим какой -то объяснительный текст.\n", "\n", - "To write a combination of strings and other values, we can use an **f-string**, which is a string that has the letter `f` before the opening quotation mark, and contains one or more Python expressions in curly braces.\n", - "The following f-string contains one expression, which is a variable name." + "Чтобы написать комбинацию строк и других значений, мы можем использовать**F-String**, которая представляет собой строку, которая имеет букву «f» перед первой оценкой кавычки, и содержит одно или несколько выражений Python в кудрявых скобках.\n", + "Следующая F-стринг содержит одно выражение, которое является именем переменной." ] }, { @@ -340,8 +340,8 @@ "id": "a3fb0556", "metadata": {}, "source": [ - "The result is a string where the expression has been evaluated and replaced with the result.\n", - "There can be more than one expression." + "Результатом является строка, где выражение было оценено и заменено результатом.\n", + "Там может быть более одного выражения." ] }, { @@ -357,7 +357,7 @@ "id": "bace1539", "metadata": {}, "source": [ - "And the expressions can contain operators and function calls." + "И выражения могут содержать операторы и функциональные вызовы." ] }, { @@ -373,7 +373,7 @@ "id": "bc6fa094", "metadata": {}, "source": [ - "So we could write the data to a text file like this." + "Таким образом, мы могли бы написать данные в такой текстовый файл, как это." ] }, { @@ -389,9 +389,9 @@ "id": "f916d561", "metadata": {}, "source": [ - "Both f-strings end with the sequence `\\n`, which adds a newline character.\n", + "Оба F-стрит заканчиваются последовательности `\\ n`, которая добавляет новую линию.\n", "\n", - "We can read the file back like this:" + "Мы можем прочитать файл обратно так:" ] }, { @@ -407,7 +407,7 @@ "id": "c3bf6913", "metadata": {}, "source": [ - "In an f-string, an expression in curly brace is converted to a string, so you can include lists, dictionaries, and other types." + "В F-String выражение в кудрявой скобке преобразуется в строку, поэтому вы можете включить списки, словарные и другие типы." ] }, { @@ -425,7 +425,7 @@ "tags": [] }, "source": [ - "If a f-string contains an invalid expression, the result is an error." + "Если F-стринг содержит неверное выражение, результатом является ошибка." ] }, { @@ -443,13 +443,13 @@ "id": "cbbaaed3", "metadata": {}, "source": [ - "## YAML\n", + "## yaml\n", "\n", - "One of the reasons programs read and write files is to store **configuration data**, which is information that specifies what the program should do and how.\n", + "Одна из причин, по которой программы читают и записывают файлы, заключается в хранении**данных конфигурации**, которая является информацией, которая указывает, что должна делать программа и как.\n", "\n", - "For example, in a program that searches for duplicate photos, we might have a dictionary called `config` that contains the name of the directory to search, the name of another directory where it should store the results, and a list of file extensions it should use to identify image files.\n", + "Например, в программе, которая ищет дубликаты фотографий, у нас может быть словарь под названием «config», который содержит имя каталога для поиска, имя другого каталога, где он должен сохранить результаты, и список расширений файлов, которые он должен использовать для идентификации файлов изображений.\n", "\n", - "Here's what it might look like:" + "Вот как это может выглядеть:" ] }, { @@ -465,11 +465,11 @@ "id": "1667bb96", "metadata": {}, "source": [ - "To write this data in a text file, we could use f-strings, as in the previous section. But it is easier to use a module called `yaml` that is designed for just this sort of thing.\n", + "Чтобы написать эти данные в текстовом файле, мы могли бы использовать F-строки, как в предыдущем разделе.Но легче использовать модуль под названием «Yaml», который предназначен только для такого рода вещей.\n", "\n", - "The `yaml` module provides functions to work with YAML files, which are text files formatted to be easy for humans *and* programs to read and write.\n", + "Модуль `yaml` предоставляет функции для работы с файлами YAML, которые представляют собой текстовые файлы, отформатированные для того, чтобы люди были простыми для людей и*программ для чтения и записи.\n", "\n", - "Here's an example that uses the `dump` function to write the `config` dictionary to a YAML file. " + "Вот пример, который использует функцию `dump` для записи словаря« config »в файл YAML." ] }, { @@ -495,7 +495,7 @@ "id": "92d1b7ff", "metadata": {}, "source": [ - "If we read back the contents of the file, we can see what the YAML format looks like." + "Если мы прочитаем содержимое файла, мы увидим, как выглядит формат YAML." ] }, { @@ -511,7 +511,7 @@ "id": "33cdfd2c", "metadata": {}, "source": [ - "Now, we can use `safe_load` to read back the YAML file." + "Теперь мы можем использовать `safe_load`, чтобы прочитать файл YAML." ] }, { @@ -527,7 +527,7 @@ "id": "ca55764f", "metadata": {}, "source": [ - "The result is new dictionary that contains the same information as the original, but it is not the same dictionary." + "Результатом является новый словарь, который содержит ту же информацию, что и оригинал, но это не тот же словарь." ] }, { @@ -543,9 +543,9 @@ "id": "969ad306", "metadata": {}, "source": [ - "Converting an object like a dictionary to a string is called **serialization**.\n", - "Converting the string back to an object is called **deserialization**.\n", - "If you serialize and then deserialize an object, the result should be equivalent to the original." + "Преобразование объекта, такого как словарь в строку, называется**сериализация**.\n", + "Преобразование строки обратно в объект называется**Deserialization**.\n", + "Если вы сериализуете, а затем десериализуете объект, результат должен быть эквивалентен оригиналу." ] }, { @@ -553,16 +553,16 @@ "id": "5e130cf8", "metadata": {}, "source": [ - "## Shelve\n", + "## retve\n", "\n", - "So far we've been reading and writing text files -- now let's consider databases.\n", - "A **database** is a file that is organized for storing data.\n", - "Some databases are organized like a table with rows and columns of information.\n", - "Others are organized like a dictionary that maps from keys to values; they are sometimes called **key-value stores**.\n", + "До сих пор мы читали и писали текстовые файлы - теперь давайте рассмотрим базы данных.\n", + "База данных**- это файл, который организован для хранения данных.\n", + "Некоторые базы данных организованы как таблица с рядами и столбцами информации.\n", + "Другие организованы как словарь, который карты от ключей к ценностям;Их иногда называют**хранилищами ключей**.\n", "\n", - "The `shelve` module provides functions for creating and updating a key-value store called a \"shelf\".\n", - "As an example, we'll create a shelf to contain captions for the figures in the `photos` directory.\n", - "We'll use the `config` dictionary to get the name of the directory where we should put the shelf." + "Модуль `shelve` предоставляет функции для создания и обновления магазина ключей, называемого« полкой ».\n", + "Например, мы создадим полку, чтобы сдержать подписи для фигур в каталоге «Фотографии».\n", + "Мы будем использовать словарь «config», чтобы получить имя каталога, где мы должны положить полку." ] }, { @@ -578,7 +578,7 @@ "id": "3e6cfb65", "metadata": {}, "source": [ - "We can use `os.makedirs` to create this directory, if it doesn't already exist." + "Мы можем использовать `os.madkedirs` для создания этого каталога, если его еще не существует." ] }, { @@ -594,7 +594,7 @@ "id": "6352f83f", "metadata": {}, "source": [ - "And `os.path.join` to make a path that includes the name of the directory and the name of the shelf file, `captions`." + "И `os.path.join`, чтобы сделать путь, который включает имя каталога, и имя файла полки,` Quiptions '." ] }, { @@ -610,8 +610,8 @@ "id": "cbb08679", "metadata": {}, "source": [ - "Now we can use `shelve.open` to open the shelf file.\n", - "The argument `c` indicates that the file should be created if necessary." + "Теперь мы можем использовать `shelve.open`, чтобы открыть файл полки.\n", + "Аргумент `c` указывает, что файл должен быть создан при необходимости." ] }, { @@ -627,10 +627,10 @@ "id": "0e4a2fb3", "metadata": {}, "source": [ - "The return value is officially a `DbfilenameShelf` object, more casually called a shelf object.\n", + "Возвращаемое значение официально представляет собой объект «dbfilenameShelf», более случайно называемый объектом на полке.\n", "\n", - "The shelf object behaves in many ways like a dictionary.\n", - "For example, we can use the bracket operator to add an item, which is a mapping from a key to a value." + "Объект шельфа ведет себя во многих отношениях, как словарь.\n", + "Например, мы можем использовать оператор кронштейна для добавления элемента, который является отображением из ключа к значению." ] }, { @@ -646,9 +646,9 @@ "id": "36fd5e3a", "metadata": {}, "source": [ - "In this example, the key is the path to an image file and the value is a string that describes the image.\n", + "В этом примере ключ - это путь к файлу изображения, а значение - это строка, которая описывает изображение.\n", "\n", - "We also use the bracket operator to look up a key and get the corresponding value." + "Мы также используем оператор кронштейна, чтобы найти ключ и получить соответствующее значение." ] }, { @@ -664,7 +664,7 @@ "id": "e9b252a7", "metadata": {}, "source": [ - "If you make another assignment to an existing key, `shelve` replaces the old value." + "Если вы сделаете другое назначение существующему ключу, «Shelve» заменяет старое значение." ] }, { @@ -680,7 +680,7 @@ "id": "003eacbc", "metadata": {}, "source": [ - "Some dictionary methods, like `keys`, `values` and `items`, also work with shelf objects." + "Некоторые методы словаря, такие как «Keys», `values 'и` элементы', также работают с объектами SHELK." ] }, { @@ -704,7 +704,7 @@ "id": "056e0bd9", "metadata": {}, "source": [ - "We can use the `in` operator to check whether a key appears in the shelf." + "Мы можем использовать оператора `in`, чтобы проверить, появляется ли ключ на полке." ] }, { @@ -720,7 +720,7 @@ "id": "982740b4", "metadata": {}, "source": [ - "And we can use a `for` statement to loop through the keys." + "И мы можем использовать оператор «for», чтобы пройти через ключи." ] }, { @@ -736,7 +736,7 @@ "id": "b67a0ddc", "metadata": {}, "source": [ - "As with other files, you should close the database when you are done." + "Как и в случае с другими файлами, вы должны закрыть базу данных, когда вы закончите." ] }, { @@ -752,7 +752,7 @@ "id": "a1e08b41", "metadata": {}, "source": [ - "Now if we list the contents of the data directory, we see two files." + "Теперь, если мы перечислим содержимое каталога данных, мы увидим два файла." ] }, { @@ -778,9 +778,9 @@ "id": "97453006", "metadata": {}, "source": [ - "`captions.dat` contains the data we just stored.\n", - "`captions.dir` contains information about the organization of the database that makes it more efficient to access.\n", - "The suffix `dir` stands for \"directory\", but it has nothing to do with the directories we've been working with that contain files." + "`captions.dat` содержит данные, которые мы только что хранили.\n", + "`captions.dir` содержит информацию об организации базы данных, которая делает ее более эффективной для доступа.\n", + "Суффикс «Dir` обозначает\" каталог \", но он не имеет ничего общего с каталогами, с которыми мы работали, содержащие файлы." ] }, { @@ -790,17 +790,17 @@ "tags": [] }, "source": [ - "## Storing data structures\n", + "## хранение структур данных\n", "\n", - "In the previous example, the keys and values in the shelf are strings.\n", - "But we can also use a shelf to contain data structures like lists and dictionaries.\n", + "В предыдущем примере ключи и значения на полке являются строками.\n", + "Но мы также можем использовать полку, чтобы содержать структуры данных, такие как списки и словари.\n", "\n", - "As an example, let's revisit the anagram example from an exercise in [Chapter 11](section_exercise_11).\n", - "Recall that we made a dictionary that maps from a sorted string of letters to the\n", - "list of words that can be spelled with those letters.\n", - "For example, the key `'opst'` maps to the list `['opts', 'post', 'pots', 'spot', 'stop', 'tops']`.\n", + "В качестве примера, давайте вернемся к примеру Anagram из упражнения в [Глава 11](section_exercise_11).\n", + "Напомним, что мы сделали словарь, который карты из отсортированной строки букв в\n", + "Список слов, которые могут быть написаны этими буквами.\n", + "Например, ключ «opst» отображает в список `['opts', 'post', 'pots', 'spot', 'stop', 'tops']`.\n", "\n", - "We'll use the following function to sort the letters in a word." + "Мы будем использовать следующую функцию, чтобы сортировать буквы одним словом." ] }, { @@ -816,7 +816,7 @@ "id": "8c24316c", "metadata": {}, "source": [ - "And here's an example." + "И вот пример." ] }, { @@ -832,8 +832,8 @@ "id": "7c5d7555", "metadata": {}, "source": [ - "Now let's open a shelf called `anagram_map`.\n", - "The argument `'n'` means we should always create a new, empty shelf, even if one already exists." + "Теперь давайте откроем полку под названием `anagram_map`.\n", + "Аргумент «n'» означает, что мы всегда должны создавать новую пустую полку, даже если он уже существует." ] }, { @@ -849,7 +849,7 @@ "id": "6b495e79", "metadata": {}, "source": [ - "Now we can add an item to the shelf like this." + "Теперь мы можем добавить элемент на полку, как это." ] }, { @@ -865,9 +865,9 @@ "id": "f058dff1", "metadata": {}, "source": [ - "In this item, the key is a string and the value is a list of strings.\n", + "В этом элементе ключ - это строка, а значение - это список строк.\n", "\n", - "Now suppose we find another word that contains the same letters, like `tops`" + "Теперь предположим, что мы находим другое слово, которое содержит те же буквы, например, «вершины»" ] }, { @@ -883,8 +883,8 @@ "id": "a215367d", "metadata": {}, "source": [ - "The key is the same as in the previous example, so we want to append a second word to the same list of strings.\n", - "Here's how we would do it if `db` were a dictionary." + "Ключ такой же, как в предыдущем примере, поэтому мы хотим добавить второе слово к тому же списку строк.\n", + "Вот как мы бы сделали это, если бы «db» был словарем." ] }, { @@ -900,7 +900,7 @@ "id": "e1a83f39", "metadata": {}, "source": [ - "But if we run that and then look up the key in the shelf, it looks like it has not been updated." + "Но если мы запустим это, а затем посмотрим на ключ на полке, похоже, что он не был обновлен." ] }, { @@ -916,8 +916,8 @@ "id": "32a56de9", "metadata": {}, "source": [ - "Here's the problem: when we look up the key, we get a list of strings, but if we modify the list of strings, it does not affect the shelf.\n", - "If we want to update the shelf, we have to read the old value, update it, and then write the new value back to the shelf." + "Вот проблема: когда мы смотрим ключ, мы получаем список строк, но если мы изменим список строк, это не влияет на полку.\n", + "Если мы хотим обновить полку, мы должны прочитать старое значение, обновить его, а затем написать новое значение обратно на полку." ] }, { @@ -933,7 +933,7 @@ "id": "a054f537", "metadata": {}, "source": [ - "Now the value in the shelf is updated." + "Теперь значение на полке обновляется." ] }, { @@ -949,7 +949,7 @@ "id": "ca02c0d7", "metadata": {}, "source": [ - "As an exercise, you can finish this example by reading the word list and storing all of the anagrams in a shelf." + "В качестве упражнения вы можете закончить этот пример, прочитав список слов и сохранив все анаграммы на полке." ] }, { @@ -969,15 +969,15 @@ "tags": [] }, "source": [ - "## Checking for equivalent files\n", + "## Проверка эквивалентных файлов\n", "\n", - "Now let's get back to the goal of this chapter: searching for different files that contain the same data.\n", - "One way to check is to read the contents of both files and compare.\n", + "Теперь давайте вернемся к цели этой главы: поиск различных файлов, которые содержат одинаковые данные.\n", + "Один из способов проверить - прочитать содержимое обоих файлов и сравнить.\n", "\n", - "If the files contain images, we have to open them with mode `'rb'`, where `'r'` means we want to read the contents and `'b'` indicates **binary mode**.\n", - "In binary mode, the contents are not interpreted as text -- they are treated as a sequence of bytes.\n", + "Если файлы содержат изображения, мы должны открыть их в режиме `'rb'', где« r'»означает, что мы хотим прочитать содержимое, а« b »указывает**двоичный режим**.\n", + "В двоичном режиме содержимое не интерпретируется как текст - они рассматриваются как последовательность байтов.\n", "\n", - "Here's an example that opens and reads an image file." + "Вот пример, который открывает и считывает файл изображения." ] }, { @@ -993,10 +993,10 @@ "id": "36687da2", "metadata": {}, "source": [ - "The result from `read` is a `bytes` object -- as the name suggests, it contains a sequence of bytes.\n", + "Результатом `reading` является объект` байтов ' - как следует из названия, он содержит последовательность байтов.\n", "\n", - "In general the contents of an image file and not human-readable.\n", - "But if we read the contents from a second file, we can use the `==` operator to compare." + "В целом содержимое файла изображения, а не читаемого на человеке.\n", + "Но если мы прочитаем содержимое из второго файла, мы можем использовать оператор `==` для сравнения." ] }, { @@ -1012,9 +1012,9 @@ "id": "36006cd4", "metadata": {}, "source": [ - "These two files are not equivalent.\n", + "Эти два файла не эквивалентны.\n", "\n", - "Let's encapsulate what we have so far in a function." + "Давайте инкапсулируем то, что у нас есть в функции." ] }, { @@ -1030,16 +1030,16 @@ "id": "b4e08850", "metadata": {}, "source": [ - "If we have only two files, this function is a good option.\n", - "But suppose we have a large number of files and we want to know whether any two of them contain the same data.\n", - "It would be inefficient to compare every pair of files.\n", + "Если у нас есть только два файла, эта функция является хорошим вариантом.\n", + "Но предположим, что у нас есть большое количество файлов, и мы хотим знать, содержат ли какие -либо два из них одни и те же данные.\n", + "Было бы неэффективно сравнить каждую пару файлов.\n", "\n", - "An alternative is to use a **hash function**, which takes the contents of a file and computes a **digest**, which is usually a large integer.\n", - "If two files contain the same data, they will have the same digest.\n", - "If two files differ, they will *almost always* have different digests.\n", + "Альтернативой является использование**хэш -функции**, которая принимает содержимое файла и вычисляет**Digest**, который обычно является большим целым числом.\n", + "Если два файла содержат одинаковые данные, они будут иметь одинаковый дайджест.\n", + "Если два файла отличаются, они*почти всегда*будут иметь разные дайджесты.\n", "\n", - "The `hashlib` module provides several hash functions -- the one we'll use is called `md5`.\n", - "We'll start by using `hashlib.md5` to create a `HASH` object." + "Модуль `hashlib` обеспечивает несколько хэш -функций - то, что мы используем, называется` md5`.\n", + "Мы начнем с использования `hashlib.md5` для создания объекта` hash '." ] }, { @@ -1055,7 +1055,7 @@ "id": "a8e480f0", "metadata": {}, "source": [ - "The `HASH` object provides an `update` method that takes the contents of the file as an argument." + "Объект `hash 'предоставляет метод« обновления », который принимает содержимое файла в качестве аргумента." ] }, { @@ -1071,7 +1071,7 @@ "id": "86bd6bc0", "metadata": {}, "source": [ - "Now we can use `hexdigest` to get the digest as a string of hexadecimal digits that represent an integer in base 16." + "Теперь мы можем использовать `hexdigest`, чтобы получить дайджест в качестве цепочки шестнадцатеричных цифр, которые представляют целое число в базе 16." ] }, { @@ -1087,7 +1087,7 @@ "id": "b9b4b347", "metadata": {}, "source": [ - "The following function encapsulates these steps." + "Следующая функция инкапсулирует эти шаги." ] }, { @@ -1103,7 +1103,7 @@ "id": "914b85b2", "metadata": {}, "source": [ - "If we hash the contents of a different file, we can confirm that we get a different digest." + "Если мы хэмем содержимое другого файла, мы можем подтвердить, что мы получим другой дайджест." ] }, { @@ -1119,8 +1119,8 @@ "id": "deeabdde", "metadata": {}, "source": [ - "Now we have almost everything we need to find equivalent files.\n", - "The last step is to search a directory and find all of the images files." + "Теперь у нас есть почти все, что нам нужно, чтобы найти эквивалентные файлы.\n", + "Последним шагом является поиск в каталоге и найти все файлы изображений." ] }, { @@ -1130,12 +1130,12 @@ "tags": [] }, "source": [ - "## Walking directories\n", + "## каталоги ходьбы\n", "\n", - "The following function takes as an argument the directory we want to search.\n", - "It uses `listdir` to loop through the contents of the directory.\n", - "When it finds a file, it prints its complete path.\n", - "When it finds a directory, it calls itself recursively to search the subdirectory." + "Следующая функция принимает в качестве аргумента каталог, который мы хотим искать.\n", + "Он использует `listdir`, чтобы пройти через содержимое каталога.\n", + "Когда он находит файл, он печатает свой полный путь.\n", + "Когда он находит каталог, он вызывает себя рекурсивно для поиска подкаталории." ] }, { @@ -1151,7 +1151,7 @@ "id": "faaf5b25", "metadata": {}, "source": [ - "We can use it like this:" + "Мы можем использовать это так:" ] }, { @@ -1167,7 +1167,7 @@ "id": "897c66bf", "metadata": {}, "source": [ - "The order of the results depends on details of the operating system." + "Порядок результатов зависит от деталей операционной системы." ] }, { @@ -1175,12 +1175,12 @@ "id": "c7853f18", "metadata": {}, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "When you are reading and writing files, you might run into problems with whitespace.\n", - "These errors can be hard to debug because whitespace characters are normally invisible.\n", - "For example, here's a string that contains spaces, a tab represented by the sequence `\\t`, and a newline represented by the sequence `\\n`.\n", - "When we print it, we don't see the whitespace characters." + "Когда вы читаете и пишете файлы, вы можете столкнуться с проблемами с пробелом.\n", + "Эти ошибки могут быть трудно отлаживать, потому что персонажи пробелов обычно невидимы.\n", + "Например, вот строка, которая содержит пространства, вкладку, представленную последовательности `\\ t`, и новая линия, представленная последовательности` \\ n`.\n", + "Когда мы печатаем его, мы не видим персонажей пробелов." ] }, { @@ -1196,8 +1196,8 @@ "id": "49bbebe6", "metadata": {}, "source": [ - "The built-in function `repr` can help. It takes any object as an argument and returns a string representation of the object.\n", - "For strings, it represents whitespace characters with backslash sequences." + "Встроенная функция `repr` может помочь.Он принимает любой объект в качестве аргумента и возвращает строковое представление объекта.\n", + "Для строк он представляет персонажи пробелов с последовательностями BackSlash." ] }, { @@ -1213,15 +1213,15 @@ "id": "790cf8dd", "metadata": {}, "source": [ - "This can be helpful for debugging.\n", + "Это может быть полезно для отладки.\n", "\n", - "One other problem you might run into is that different systems use different characters to indicate the end of a line. Some systems use a newline, represented `\\n`. Others use a return character, represented `\\r`. \n", - "Some use both. If you move files between different systems, these\n", - "inconsistencies can cause problems.\n", + "Еще одна проблема, с которой вы можете столкнуться, это то, что разные системы используют разные символы, чтобы указать конец линии.Некоторые системы используют новую линию, представленную `\\ n`.Другие используют возвращающийся символ, представленного `\\ r`.\n", + "Некоторые используют оба.Если вы перемещаете файлы между различными системами, это\n", + "Несоответствия могут вызвать проблемы.\n", "\n", - "File name capitalization is another issue you might encounter if you work with different operating systems.\n", - "In macOS and UNIX, file names can contain lowercase and uppercase letters, digits, and most symbols.\n", - "But many Windows applications ignore the difference between lowercase and uppercase letters, and several symbols that are allowed in macOS and UNIX are not allowed in Windows." + "Имя файла Капитализация - это еще одна проблема, с которой вы можете столкнуться, если вы работаете с различными операционными системами.\n", + "В MacOS и Unix имена файлов могут содержать строчные и верхние буквы, цифры и большинство символов.\n", + "Но многие приложения Windows игнорируют разницу между строчными и прописными буквами, и в Windows не допускаются несколько символов, которые разрешены в MacOS и UNIX." ] }, { @@ -1229,55 +1229,55 @@ "id": "cf063639", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**ephemeral:**\n", - "An ephemeral program typically runs for a short time and, when it ends, its data are lost.\n", + "**эфемерный:**\n", + "Эфемерная программа обычно работает в течение короткого времени, и, когда она заканчивается, ее данные теряются.\n", "\n", - "**persistent:**\n", - " A persistent program runs indefinitely and keeps at least some of its data in permanent storage.\n", + "**настойчивый:**\n", + "Постоянная программа работает на неопределенный срок и хранит, по крайней мере, некоторые из своих данных в постоянном хранении.\n", "\n", - "**directory:**\n", - "A collection of files and other directories.\n", + "**Справочник:**\n", + "Сборник файлов и других каталогов.\n", "\n", - "**current working directory:**\n", - "The default directory used by a program unless another directory is specified.\n", + "**Текущий рабочий каталог:**\n", + "Каталог по умолчанию, используемый программой, если не указан другой каталог.\n", "\n", - "**path:**\n", - " A string that specifies a sequence of directories, often leading to a file.\n", + "**путь:**\n", + "Строка, которая указывает последовательность каталогов, часто приводящих к файлу.\n", "\n", - "**relative path:**\n", - "A path that starts from the current working directory, or some other specified directory.\n", + "**относительный путь:**\n", + "Путь, который начинается с текущего рабочего каталога или какого -либо другого указанного каталога.\n", "\n", - "**absolute path:**\n", - "A path that does not depend on the current directory.\n", + "**Абсолютный путь:**\n", + "Путь, который не зависит от текущего каталога.\n", "\n", - "**f-string:**\n", - "A string that has the letter `f` before the opening quotation mark, and contains one or more expressions in curly braces.\n", + "**F-String:**\n", + "Строка, которая имеет букву «f» перед открытием кавычки, и содержит одно или несколько выражений в кудрявых скобках.\n", "\n", - "**configuration data:**\n", - "Data, often stored in a file, that specifies what a program should do and how.\n", + "**Данные конфигурации:**\n", + "Данные, часто хранящиеся в файле, которые указывают, что должна делать программа и как.\n", "\n", - "**serialization:**\n", - "Converting an object to a string.\n", + "**Сериализация:**\n", + "Преобразование объекта в строку.\n", "\n", - "**deserialization:**\n", - "Converting a string to an object.\n", + "**десериализация:**\n", + "Преобразование строки в объект.\n", "\n", - "**database:**\n", - " A file whose contents are organized to perform certain operations efficiently.\n", + "**База данных:**\n", + "Файл, содержимое которого организовано для эффективного выполнения определенных операций.\n", "\n", - "**key-value stores:**\n", - "A database whose contents are organized like a dictionary with keys that correspond to values.\n", + "**Магазины ключей:**\n", + "База данных, содержимое которого организовано как словарь с ключами, которые соответствуют значениям.\n", "\n", - "**binary mode:**\n", - "A way of opening a file so the contents are interpreted as sequence of bytes rather than a sequence of characters.\n", + "**двоичный режим:**\n", + "Способ открыть файл, чтобы содержимое интерпретируется как последовательность байтов, а не последовательность символов.\n", "\n", - "**hash function:**\n", - "A function that takes and object and computes an integer, which is sometimes called a digest.\n", + "**Хэш -функция:**\n", + "Функция, которая берет и объект и вычисляет целое число, которое иногда называют дайджестом.\n", "\n", - "**digest:**\n", - "The result of a hash function, especially when it is used to check whether two objects are the same." + "**Дайджест:**\n", + "Результат хэш -функции, особенно когда она используется для проверки, являются ли два объекта одинаковыми." ] }, { @@ -1285,7 +1285,7 @@ "id": "67941fdd", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -1303,32 +1303,32 @@ "id": "9a537173", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "There are several topics that came up in this chapter that I did not explain in detail.\n", - "Here are some questions you can ask a virtual assistant to get more information. \n", + "Есть несколько тем, которые появились в этой главе, которые я не объяснил подробно.\n", + "Вот несколько вопросов, которые вы можете задать виртуальному помощнику получить больше информации.\n", "\n", - "* \"What are the differences between ephemeral and persistent programs?\"\n", + "*«Каковы различия между эфемерными и постоянными программами?»\n", "\n", - "* \"What are some examples of persistent programs?\"\n", + "*Каковы примеры постоянных программ? »\n", "\n", - "* \"What's the difference between a relative path and an absolute path?\"\n", + "*«В чем разница между относительным путем и абсолютным путем?»\n", "\n", - "* \"Why does the `yaml` module have functions called `load` and `safe_load`?\"\n", + "*«Почему у модуля` yaml` есть функции, называемые `load` и` safe_load`? »\n", "\n", - "* \"When I write a Python shelf, what are the files with suffixes `dat` and `dir`?\"\n", + "*«Когда я пишу полку Python, какие файлы с суффиксами` dat` и `dir`?»\n", "\n", - "* \"Other than key-values stores, what other kinds of databases are there?\"\n", + "*«Помимо магазинов ключевых значений, какие другие виды баз данных существуют?»\n", "\n", - "* \"When I read a file, what's the difference between binary mode and text mode?\"\n", + "*«Когда я читаю файл, в чем разница между двоичным режимом и текстовым режимом?»\n", "\n", - "* \"What are the differences between a bytes object and a string?\"\n", + "*«Каковы различия между объектом байтов и строкой?»\n", "\n", - "* \"What is a hash function?\"\n", + "*\"Что такое хэш -функция?\"\n", "\n", - "* \"What is an MD5 digest?\"\n", + "*\"Что такое диварие MD5?\"\n", "\n", - "As always, if you get stuck on any of the following exercises, consider asking a VA for help. Along with your question, you might want to paste in the relevant functions from this chapter." + "Как всегда, если вы застряли в любом из следующих упражнений, подумайте о том, чтобы попросить VA о помощи.Наряду с вашим вопросом, вы можете вставить соответствующие функции из этой главы." ] }, { @@ -1336,11 +1336,11 @@ "id": "7586e1e9", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `replace_all` that takes as arguments a pattern string, a replacement string, and two filenames.\n", - "It should read the first file and write the contents into the second file (creating it if necessary).\n", - "If the pattern string appears anywhere in the contents, it should be replaced with the replacement string." + "Напишите функцию с именем `replace_all`, которая принимает в качестве аргументов строку шаблона, строку замены и два имена файлов.\n", + "Он должен прочитать первый файл и записать содержимое во второй файл (при необходимости его создает).\n", + "Если строка шаблона появляется в любом месте содержимого, ее следует заменить на запасную строку." ] }, { @@ -1350,7 +1350,7 @@ "tags": [] }, "source": [ - "Here's an outline of the function to get you started." + "Вот набросок функции, чтобы вы начали." ] }, { @@ -1374,7 +1374,7 @@ "id": "7f37245c", "metadata": {}, "source": [ - "To test your function, read the file `photos/notes.txt`, replace `'photos'` with `'images'`, and write the result to the file `photos/new_notes.txt`." + "Чтобы проверить свою функцию, прочитайте файл `photos/notes.txt`, замените« фотографии »на` '' Images »и напишите результат в файл` photos/new_notes.txt`." ] }, { @@ -1412,12 +1412,12 @@ "id": "7b2589a4", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In [a previous section](section_storing_data_structure), we used the `shelve` module to make a key-value store that maps from a sorted string of letters to a list of anagrams.\n", - "To finish the example, write a function called `add_word` that takes as arguments a string and a shelf object.\n", + "В [предыдущий раздел](section_storing_data_structure) мы использовали модуль `shelve`, чтобы сделать хранилище ключа, который карты из отсортированной строки букв в список анаграмм.\n", + "Чтобы закончить пример, напишите функцию с именем `add_word`, которая принимает в качестве аргументов строку и объект полки.\n", "\n", - "It should sort the letters of the word to make a key, then check whether the key is already in the shelf. If not, it should make a list that contains the new word and add it to the shelf. If so, it should append the new word to the existing value. " + "Он должен сортировать буквы слова, чтобы сделать ключ, а затем проверить, находится ли ключ уже на полке.Если нет, то он должен составить список, который содержит новое слово и добавить его на полку.Если это так, оно должно добавить новое слово к существующему значению." ] }, { @@ -1435,7 +1435,7 @@ "tags": [] }, "source": [ - "You can use this loop to test your function." + "Вы можете использовать этот цикл, чтобы проверить вашу функцию." ] }, { @@ -1465,7 +1465,7 @@ "tags": [] }, "source": [ - "If everything is working, you should be able to look up a key like `'opst'` and get a list of words that can be spelled with those letters." + "Если все работает, вы сможете найти ключ, такой как «Opst», и получить список слов, которые можно писать с этими буквами." ] }, { @@ -1503,23 +1503,23 @@ "id": "228e977c", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In a large collection of files, there may be more than one copy of the same file, stored in different directories or with different file names.\n", - "The goal of this exercise is to search for duplicates.\n", - "As an example, we'll work with image files in the `photos` directory.\n", + "В большой коллекции файлов может быть более одной копии одного и того же файла, хранящейся в разных каталогах или с разными именами файлов.\n", + "Цель этого упражнения - искать дубликаты.\n", + "В качестве примера мы будем работать с файлами изображений в каталоге «Фотографии».\n", "\n", - "Here's how it will work:\n", + "Вот как это будет работать:\n", "\n", - "* We'll use the `walk` function from [](section_walking_directories) to search this directory for files that end with one of the extensions in `config['extensions']`.\n", + "*Мы будем использовать функцию `walk` от [](section_walking_directories) для поиска этого каталога для файлов, которые заканчиваются одним из расширений в` config ['agensions'] `.\n", "\n", - "* For each file, we'll use `md5_digest` from [](section_md5_digest) to compute a digest of the contents.\n", + "*Для каждого файла мы используем `md5_digest` from [](section_md5_digest) для вычисления дайджеста содержимого.\n", "\n", - "* Using a shelf, we'll make a mapping from each digest to a list of paths with that digest.\n", + "*Используя полку, мы сделаем отображение из каждого дайджеста в список путей с этим дайджестом.\n", "\n", - "* Finally, we'll search the shelf for any digests that map to multiple files.\n", + "*Наконец, мы будем искать полку для любых дайджестов, которые карту в нескольких файлах.\n", "\n", - "* If we find any, we'll use `same_contents` to confirm that the files contain the same data." + "*Если мы найдем что -либо, мы будем использовать `some_contents`, чтобы подтвердить, что файлы содержат те же данные." ] }, { @@ -1527,9 +1527,9 @@ "id": "8f5365da", "metadata": {}, "source": [ - "I'll suggest some functions to write first, then we'll bring it all together.\n", + "Я предложу несколько функций, чтобы написать сначала, затем мы объединим все это.\n", "\n", - "1. To identify image files, write a function called `is_image` that takes a path and a list of file extensions, and returns `True` if the path ends with one of the extensions in the list. Hint: Use `os.path.splitext` -- or ask a virtual assistant to write this function for you." + "1. Чтобы идентифицировать файлы изображений, напишите функцию с именем `is_image`, которая берет путь и список расширений файлов, и возвращает` true`, если путь заканчивается одним из расширений в списке.Подсказка: используйте `os.path.splitext` - или попросите виртуального помощника написать эту функцию для вас." ] }, { @@ -1547,7 +1547,7 @@ "tags": [] }, "source": [ - "You can use `doctest` to test your function." + "Вы можете использовать `doctest`, чтобы проверить вашу функцию." ] }, { @@ -1565,7 +1565,7 @@ "id": "1a7c8f49", "metadata": {}, "source": [ - "2. Write a function called `add_path` that takes as arguments a path and a shelf. It should use `md5_digest` to compute a digest of the file contents. Then it should update the shelf, either creating a new item that maps from the digest to a list containing the path, or appending the path to the list if it exists." + "2. Напишите функцию с именем `add_path`, которая принимает в качестве аргументов путь и полку.Он должен использовать `md5_digest` для вычисления дадеста содержимого файла.Затем он должен обновить полку, создавая новый элемент, который карты из дайджеста в список, содержащий путь, либо добавление пути к списку, если он существует." ] }, { @@ -1581,7 +1581,7 @@ "id": "08223a21", "metadata": {}, "source": [ - "3. Write a version of `walk` called `walk_images` that takes a directory and walks through the files in the directory and its subdirectories. For each file, it should use `is_image` to check whether it's an image file and `add_path` to add it to the shelf." + "3. Напишите версию «Walk» под названием `walk_images`, которая принимает каталог и проходит через файлы в каталоге и его подкаталогах.Для каждого файла он должен использовать `is_image`, чтобы проверить, является ли это файл изображения и` add_path`, чтобы добавить его на полку." ] }, { @@ -1597,7 +1597,7 @@ "id": "1ea76a52", "metadata": {}, "source": [ - "When everything is working, you can use the following program to create the shelf, search the `photos` directory and add paths to the shelf, and then check whether there are multiple files with the same digest." + "Когда все работает, вы можете использовать следующую программу для создания полки, выполнить поиск в каталоге «Photo» и добавить пути к полке, а затем проверить, есть ли несколько файлов с одним и тем же дайджестом." ] }, { @@ -1615,8 +1615,8 @@ "id": "102d4d10", "metadata": {}, "source": [ - "You should find one pair of files that have the same digest.\n", - "Use `same_contents` to check whether they contain the same data." + "Вы должны найти одну пару файлов, которые имеют одинаковый дайджест.\n", + "Используйте `some_contents`, чтобы проверить, содержат ли они одинаковые данные." ] }, { @@ -1642,13 +1642,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание](https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik" ] } ], From 533f92c3465ff47056405f39eca3442f35d1933b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:06:13 +0300 Subject: [PATCH 14/44] Translate chap14 notebook to Russian --- blank/chap14.ipynb | 2724 +++++++++++++++++++++----------------------- 1 file changed, 1268 insertions(+), 1456 deletions(-) diff --git a/blank/chap14.ipynb b/blank/chap14.ipynb index 38aaffc..9ab3fa1 100644 --- a/blank/chap14.ipynb +++ b/blank/chap14.ipynb @@ -1,1458 +1,1270 @@ { - "cells": [ - { - "cell_type": "markdown", - "id": "1331faa1", - "metadata": {}, - "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "ae5a86f8", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "e826e661", - "metadata": {}, - "source": [ - "# Classes and Functions\n", - "\n", - "At this point you know how to use functions to organize code and how to use built-in types to organize data.\n", - "The next step is **object-oriented programming**, which uses programmer-defined types to organize both code and data.\n", - "\n", - "Object-oriented programming is a big topic, so we will proceed gradually.\n", - "In this chapter, we'll start with code that is not idiomatic -- that is, it is not the kind of code experienced programmers write -- but it is a good place to start.\n", - "In the next two chapters, we will use additional features to write more idiomatic code." - ] - }, - { - "cell_type": "markdown", - "id": "6b414d4a", - "metadata": {}, - "source": [ - "## Programmer-defined types\n", - "\n", - "We have used many of Python's built-in types -- now we will define a new type.\n", - "As a first example, we'll create a type called `Time` that represents a time of day.\n", - "A programmer-defined type is also called a **class**.\n", - "A class definition looks like this:" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "c9c99d2c", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "e2414cd2", - "metadata": {}, - "source": [ - "The header indicates that the new class is called `Time`.\n", - "The body is a docstring that explains what the class is for.\n", - "Defining a class creates a **class object**.\n", - "\n", - "The class object is like a factory for creating objects.\n", - "To create a `Time` object, you call `Time` as if it were a function." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "d318001a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "f63247d4", - "metadata": {}, - "source": [ - "The result is a new object whose type is `__main__.Time`, where `__main__` is the name of the module where `Time` is defined." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "f37d67fd", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "14d0c96a", - "metadata": {}, - "source": [ - "When you print an object, Python tells you what type it is and where it is stored in memory (the prefix `0x` means that the following number is in hexadecimal)." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "e2bd114a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "b6445414", - "metadata": {}, - "source": [ - "Creating a new object is called **instantiation**, and the object is an **instance** of the class." - ] - }, - { - "cell_type": "markdown", - "id": "4c3768ec", - "metadata": {}, - "source": [ - "## Attributes\n", - "\n", - "An object can contain variables, which are called **attributes** and pronounced with the emphasis on the first syllable, like \"AT-trib-ute\", rather than the second syllable, like \"a-TRIB-ute\".\n", - "We can create attributes using dot notation." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "e166701a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "b3fd8858", - "metadata": {}, - "source": [ - "This example creates attributes called `hour`, `minute`, and `second`, which contain the hours, minutes, and seconds of the time `11:59:01`, which is lunch time as far as I am concerned.\n", - "\n", - "The following diagram shows the state of `lunch` and its attributes after these assignments. " - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "3eb47826", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "6702a353", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "d9df5b48", - "metadata": {}, - "source": [ - "The variable `lunch` refers to a `Time` object, which contains three attributes. \n", - "Each attribute refers to an integer.\n", - "A state diagram like this -- which shows an object and its attributes -- is called an **object diagram**.\n", - "\n", - "You can read the value of an attribute using the dot operator." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "4c4eff2b", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "5ccfaea0", - "metadata": {}, - "source": [ - "You can use an attribute as part of any expression." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "7ac6db21", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "c5e6725b", - "metadata": {}, - "source": [ - "And you can use the dot operator in an expression in an f-string." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "1ecdc091", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "e70671d2", - "metadata": {}, - "source": [ - "But notice that the previous example is not in the standard format.\n", - "To fix it, we have to print the `minute` and `second` attributes with a leading zero.\n", - "We can do that by extending the expressions in curly braces with a **format specifier**.\n", - "In the following example, the format specifiers indicate that `minute` and `second` should be displayed with at least two digits and a leading zero if needed." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "a8a45573", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "bcbea13a", - "metadata": {}, - "source": [ - "We'll use this f-string to write a function that displays the value of a `Time`object.\n", - "You can pass an object as an argument in the usual way.\n", - "For example, the following function takes a `Time` object as an argument. " - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "fc77feb2", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "3b8ccbed", - "metadata": {}, - "source": [ - "When we call it, we can pass `lunch` as an argument." - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "59b7f4f4", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "18826e53", - "metadata": {}, - "source": [ - "## Objects as return values\n", - "\n", - "Functions can return objects. For example, `make_time` takes parameters called `hour`, `minute`, and `second`, stores them as attributes in a `Time` object, and returns the new object." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "fde15b59", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "d8a6acca", - "metadata": {}, - "source": [ - "It might be surprising that the parameters have the same names as the attributes, but that's a common way to write a function like this.\n", - "Here's how we use `make_time` to create a `Time` object.`" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "f4199d7f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "05720bcb", - "metadata": {}, - "source": [ - "## Objects are mutable\n", - "\n", - "Suppose you are going to a screening of a movie, like *Monty Python and the Holy Grail*, which starts at `9:20 PM` and runs for `92` minutes, which is one hour `32` minutes.\n", - "What time will the movie end?\n", - "\n", - "First, we'll create a `Time` object that represents the start time." - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "57847af3", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "001bcda9", - "metadata": {}, - "source": [ - "To find the end time, we can modify the attributes of the `Time` object, adding the duration of the movie." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "f3637b10", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "7007ab61", - "metadata": {}, - "source": [ - "The movie will be over at 10:52 PM.\n", - "\n", - "Let's encapsulate this computation in a function and generalize it to take the duration of the movie in three parameters: `hours`, `minutes`, and `seconds`." - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "3468f4d0", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "a51913e2", - "metadata": {}, - "source": [ - "Here is an example that demonstrates the effect." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "ad8177ad", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "42d7de02", - "metadata": {}, - "source": [ - "The following stack diagram shows the state of the program just before `increment_time` modifies the object." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "6f90c060", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "93a1db71", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "d1e27667", - "metadata": {}, - "source": [ - "Inside the function, `time` is an alias for `start`, so when `time` is modified, `start` changes.\n", - "\n", - "This function works, but after it runs, we're left with a variable named `start` that refers to an object that represents the *end* time, and we no longer have an object that represents the start time.\n", - "It would be better to leave `start` unchanged and make a new object to represent the end time.\n", - "We can do that by copying `start` and modifying the copy." - ] - }, - { - "cell_type": "markdown", - "id": "0128f850", - "metadata": {}, - "source": [ - "## Copying\n", - "\n", - "The `copy` module provides a function called `copy` that can duplicate any object.\n", - "We can import it like this." - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "9f74834d", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "940adbeb", - "metadata": {}, - "source": [ - "To see how it works, let's start with a new `Time` object that represents the start time of the movie." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "770c077a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "514f05b9", - "metadata": {}, - "source": [ - "And make a copy." - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "edced6e5", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "87d8956b", - "metadata": {}, - "source": [ - "Now `start` and `end` contain the same data." - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "509c3640", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "e75c1e09", - "metadata": {}, - "source": [ - "But the `is` operator confirms that they are not the same object." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "60d812f7", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "22b68a3f", - "metadata": {}, - "source": [ - "Let's see what the `==` operator does." - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "4d504362", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "78ebf931", - "metadata": {}, - "source": [ - "You might expect `==` to yield `True` because the objects contain the same data.\n", - "But for programmer-defined classes, the default behavior of the `==` operator is the same as the `is` operator -- it checks identity, not equivalence." - ] - }, - { - "cell_type": "markdown", - "id": "a3934fdd-d4cd-41e0-86e6-5bb78d0886a7", - "metadata": {}, - "source": [ - "## Pure functions\n", - "\n", - "We can use `copy` to write pure functions that don't modify their parameters.\n", - "For example, here's a function that takes a `Time` object and a duration in hours, minutes and seconds.\n", - "It makes a copy of the original object, uses `increment_time` to modify the copy, and returns it." - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "85090d3e", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "c181af12", - "metadata": {}, - "source": [ - "Here's how we use it." - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "1d9cf4da", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "54b1ca4a", - "metadata": {}, - "source": [ - "The return value is a new object representing the end time of the movie.\n", - "And we can confirm that `start` is unchanged." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "9fe30d71", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "1233b2db", - "metadata": {}, - "source": [ - "`add_time` is a **pure function** because it does not modify any of the objects passed to it as arguments and its only effect is to return a value.\n", - "\n", - "Anything that can be done with impure functions can also be done with pure functions.\n", - "In fact, some programming languages only allow pure functions.\n", - "Programs that use pure functions might be less error-prone, but impure functions are sometimes convenient and can be more efficient.\n", - "\n", - "In general, I suggest you write pure functions whenever it is reasonable and resort to impure functions only if there is a compelling advantage.\n", - "This approach might be called a **functional programming style**." - ] - }, - { - "cell_type": "markdown", - "id": "9d9fabbc", - "metadata": {}, - "source": [ - "## Prototype and patch\n", - "\n", - "In the previous example, `increment_time` and `add_time` seem to work, but if we try another example, we'll see that they are not quite correct.\n", - "\n", - "Suppose you arrive at the theater and discover that the movie starts at `9:40`, not `9:20`.\n", - "Here's what happens when we compute the updated end time." - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "57a96bf9-7d7b-4715-a4b3-2dfad1beb670", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "c712ebf7-7e52-490e-91d7-5f1c83334de0", - "metadata": {}, - "source": [ - "The result is not a valid time.\n", - "The problem is that `increment_time` does not deal with cases where the number of seconds or minutes adds up to more than `60`.\n", - "\n", - "Here's an improved version that checks whether `second` exceeds or equals `60` -- if so, it increments `minute` -- then checks whether `minute` exceeds or equals `60` -- if so, it increments `hour`." - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "5bada1df-be0a-4f6a-8fe3-d92bd937dc70", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "c133c5d8", - "metadata": {}, - "source": [ - "Fixing `increment_time` also fixes `add_time`, which uses it.\n", - "So now the previous example works correctly." - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "a139b64b", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "a2f644a6-ca43-494e-af14-6e845b3d7973", - "metadata": {}, - "source": [ - "But this function is still not correct, because the arguments might be bigger than `60`.\n", - "For example, suppose we are given the run time as `92` minutes, rather than `1` hours and `32` minutes.\n", - "We might call `add_time` like this." - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "8c9384cb", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "72e0a08b", - "metadata": {}, - "source": [ - "The result is not a valid time.\n", - "So let's try a different approach, using the `divmod` function.\n", - "We'll make a copy of `start` and modify it by incrementing the `minute` attribute." - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "47b04507", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "c56355bc", - "metadata": {}, - "source": [ - "Now `minute` is `132`, which is `2` hours and `12` minutes.\n", - "We can use `divmod` to divide by `60` and return the number of whole hours and the number of minutes left over." - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "8ce8f8bc", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "43204703", - "metadata": {}, - "source": [ - "Now `minute` is correct, and we can add the hours to `hour`." - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "90445645", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "a68ae1cd", - "metadata": {}, - "source": [ - "The result is a valid time.\n", - "We can do the same thing with `hour` and `second`, and encapsulate the whole process in a function." - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "0a9653a2", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "7437113a", - "metadata": {}, - "source": [ - "With this version of `increment_time`, `add_time` works correctly, even if the arguments exceed `60`." - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "id": "694cfdd1", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "7c6329b2", - "metadata": {}, - "source": [ - "This section demonstrates a program development plan I call **prototype and patch**.\n", - "We started with a simple prototype that worked correctly for the first example.\n", - "Then we tested it with more difficult examples -- when we found an error, we modified the program to fix it, like putting a patch on tire with a puncture.\n", - "\n", - "This approach can be effective, especially if you don't yet have a deep understanding of the problem.\n", - "But incremental corrections can generate code that is unnecessarily complicated -- since it deals with many special cases -- and unreliable -- since it is hard to know if you have\n", - "found all the errors." - ] - }, - { - "cell_type": "markdown", - "id": "39031461-49a9-4eba-a075-ef49a6f5552b", - "metadata": {}, - "source": [ - "## Design-first development\n", - "\n", - "An alternative plan is **design-first development**, which involves more planning before prototyping. In a design-first process, sometimes a high-level insight into the problem makes the programming much easier.\n", - "\n", - "In this case, the insight is that we can think of a `Time` object as a three-digit number in base 60 -- also known as sexagesimal.\n", - "The `second` attribute is the \"ones column\", the `minute` attribute is the \"sixties column\",\n", - "and the `hour` attribute is the \"thirty-six hundreds column\".\n", - "When we wrote `increment_time`, we were effectively doing addition in base 60, which is why we had to carry from one column to the next.\n", - "\n", - "This observation suggests another approach to the whole problem -- we can convert `Time` objects to integers and take advantage of the fact that Python knows how to do integer arithmetic.\n", - "\n", - "Here is a function that converts from a `Time` to an integer." - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "id": "a4427f06-10f3-478f-af4b-888297ee59ac", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "c7e7789e", - "metadata": {}, - "source": [ - "The result is the number of seconds since the beginning of the day.\n", - "For example, `01:01:01` is `1` hour, `1` minute and `1` second from the beginning of the day, with is the sum of `3600` seconds, `60` seconds, and `1` second." - ] - }, - { - "cell_type": "code", - "execution_count": 42, - "id": "e71f9661", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "6ea525c8-4547-4bde-91c3-17f45add1bf8", - "metadata": {}, - "source": [ - "And here's a function that goes in the other direction -- converting an integer to a `Time` object -- using the `divmod` function." - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "id": "7a93edcc-de21-43b1-b0a9-1bcbc7f6125c", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "4706b5df", - "metadata": {}, - "source": [ - "We can test it by converting the previous example back to a `Time`." - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "id": "967fc3c2", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "0c2b8469-d4a7-46f9-a0a1-f2a6c1595183", - "metadata": {}, - "source": [ - "Using these functions, we can write a more concise version of `add_time`." - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "id": "0278a042-9e5b-460f-bd26-2fa319e7193a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "cb560257", - "metadata": {}, - "source": [ - "The first line converts the arguments to a `Time` object called `duration`.\n", - "The second line converts `time` and `duration` to seconds and adds them.\n", - "The third line converts the sum to a `Time` object and returns it.\n", - "\n", - "Here's how it works." - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "id": "ee78ffbc", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "db762aa8-4aab-4c17-a88d-72c5048f18c0", - "metadata": {}, - "source": [ - "In some ways, converting from base 60 to base 10 and back is harder than\n", - "just dealing with times. Base conversion is more abstract; our intuition\n", - "for dealing with time values is better.\n", - "\n", - "But if we have the insight to treat times as base 60 numbers -- and invest the effort to write the conversion functions `time_to_int` and `int_to_time` -- we get a program that is shorter, easier to read and debug, and more reliable.\n", - "\n", - "It is also easier to add features later. For example, imagine subtracting two `Time` objects to find the duration between them.\n", - "The naive approach is to implement subtraction with borrowing.\n", - "Using the conversion functions is easier and more likely to be correct.\n", - "\n", - "Ironically, sometimes making a problem harder -- or more general -- makes it easier, because there are fewer special cases and fewer opportunities for error." - ] - }, - { - "cell_type": "markdown", - "id": "a0d23d08", - "metadata": { - "tags": [] - }, - "source": [ - "## Debugging\n", - "\n", - "Python provides several built-in functions that are useful for testing and debugging programs that work with objects.\n", - "For example, if you are not sure what type an object is, you can ask." - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "id": "652bee8f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "7ec0eabf", - "metadata": {}, - "source": [ - "You can also use `isinstance` to check whether an object is an instance of a particular class." - ] - }, - { - "cell_type": "code", - "execution_count": 48, - "id": "3ab974e4", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "4f453fe9", - "metadata": {}, - "source": [ - "If you are not sure whether an object has a particular attribute, you\n", - "can use the built-in function `hasattr`." - ] - }, - { - "cell_type": "code", - "execution_count": 49, - "id": "5f80e5ad", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "a0131d84", - "metadata": {}, - "source": [ - "To get all of the attributes, and their values, in a dictionary, you can use `vars`." - ] - }, - { - "cell_type": "code", - "execution_count": 50, - "id": "2a102f0f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "f1a443c8", - "metadata": {}, - "source": [ - "The `structshape` module, which we saw in [Chapter 11](section_debugging_11), also works with programmer-defined types." - ] - }, - { - "cell_type": "code", - "execution_count": 51, - "id": "b71f46d8", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 52, - "id": "1e6498a8", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "501436c0-6634-415f-be84-2d130232b2b8", - "metadata": {}, - "source": [ - "## Glossary\n", - "\n", - "**object-oriented programming:**\n", - "A style of programming that uses objects to organize code and data.\n", - "\n", - "**class:**\n", - " A programmer-defined type. A class definition creates a new class object.\n", - "\n", - "**class object:**\n", - "An object that represents a class -- it is the result of a class definition.\n", - "\n", - "**instantiation:**\n", - "The process of creating an object that belongs to a class.\n", - "\n", - "**instance:**\n", - " An object that belongs to a class.\n", - "\n", - "**attribute:**\n", - " A variable associated with an object, also called an instance variable.\n", - "\n", - "**object diagram:**\n", - "A graphical representation of an object, its attributes, and their values.\n", - "\n", - "**format specifier:**\n", - "In an f-string, a format specifier determines how a value is converted to a string.\n", - "\n", - "**pure function:**\n", - "A function that does not modify its parameters or have any effect other than returning a value.\n", - "\n", - "**functional programming style:**\n", - "A way of programming that uses pure functions whenever possible.\n", - "\n", - "**prototype and patch:**\n", - "A way of developing programs by starting with a rough draft and gradually adding features and fixing bugs.\n", - "\n", - "**design-first development:**\n", - "A way of developing programs with more careful planning that prototype and patch." - ] - }, - { - "cell_type": "markdown", - "id": "09dd41c1", - "metadata": {}, - "source": [ - "## Exercises" - ] - }, - { - "cell_type": "code", - "execution_count": 53, - "id": "ab3d0104", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "da0aea86", - "metadata": {}, - "source": [ - "### Ask a virtual assistant\n", - "\n", - "There is a lot of new vocabulary in this chapter.\n", - "A conversation with a virtual assistant can help solidify your understanding.\n", - "Consider asking:\n", - "\n", - "* \"What is the difference between a class and a type?\"\n", - "\n", - "* \"What is the difference between an object and an instance?\"\n", - "\n", - "* \"What is the difference between a variable and an attribute?\"\n", - "\n", - "* \"What are the pros and cons of pure functions compared to impure functions?\"\n", - "\n", - "Because we are just getting started with object oriented programming, the code in this chapter is not idiomatic -- it is not the kind of code experienced programmers write.\n", - "If you ask a virtual assistant for help with the exercises, you will probably see features we have not covered yet.\n", - "In particular, you are likely to see a method called `__init__` used to initialize the attributes of an instance.\n", - "\n", - "If these features make sense to you, go ahead and use them.\n", - "But if not, be patient -- we will get there soon.\n", - "In the meantime, see if you can solve the following exercises using only the features we have covered so far.\n", - "\n", - "Also, in this chapter we saw one example of a format specifier. For more information, ask \"What format specifiers can be used in a Python f-string?\"" - ] - }, - { - "cell_type": "markdown", - "id": "c85eab62", - "metadata": {}, - "source": [ - "## Exercises\n" - ] - }, - { - "cell_type": "markdown", - "id": "bcdab7d6", - "metadata": {}, - "source": [ - "### Exercise\n", - "\n", - "Write a function called `subtract_time` that takes two `Time` objects and returns the interval between them in seconds -- assuming that they are two times during the same day." - ] - }, - { - "cell_type": "markdown", - "id": "5033ee5f", - "metadata": { - "tags": [] - }, - "source": [ - "Here's an outline of the function to get you started." - ] - }, - { - "cell_type": "code", - "execution_count": 54, - "id": "7d898f43", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 55, - "id": "f1b54959", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "73334265", - "metadata": { - "tags": [] - }, - "source": [ - "You can use `doctest` to test your function." - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "id": "5a25a3de", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "c3189549", - "metadata": {}, - "source": [ - "### Exercise\n", - "\n", - "Write a function called `is_after` that takes two `Time` objects and returns `True` if the first time is later in the day than the second, and `False` otherwise." - ] - }, - { - "cell_type": "markdown", - "id": "fd4ac340", - "metadata": { - "tags": [] - }, - "source": [ - "Here's an outline of the function to get you started." - ] - }, - { - "cell_type": "code", - "execution_count": 57, - "id": "05499ffa", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 58, - "id": "12b4ad17", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "f9da8ede", - "metadata": { - "tags": [] - }, - "source": [ - "You can use `doctest` to test your function." - ] - }, - { - "cell_type": "code", - "execution_count": 59, - "id": "4e580404", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "16dff862", - "metadata": {}, - "source": [ - "### Exercise\n", - "\n", - "Here's a definition for a `Date` class that represents a date -- that is, a year, month, and day of the month." - ] - }, - { - "cell_type": "code", - "execution_count": 60, - "id": "c5de60ed", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "3311fa97", - "metadata": {}, - "source": [ - "1. Write a function called `make_date` that takes `year`, `month`, and `day` as parameters, makes a `Date` object, assigns the parameters to attributes, and returns the result the new object. Create an object that represents June 22, 1933.\n", - "\n", - "2. Write a function called `print_date` that takes a `Date` object, uses an f-string to format the attributes, and prints the result. If you test it with the `Date` you created, the result should be `1933-06-22`.\n", - "\n", - "3. Write a function called `is_after` that takes two `Date` objects as parameters and returns `True` if the first comes after the second. Create a second object that represents September 17, 1933, and check whether it comes after the first object.\n", - "\n", - "Hint: You might find it useful to write a function called `date_to_tuple` that takes a `Date` object and returns a tuple that contains its attributes in year, month, day order." - ] - }, - { - "cell_type": "markdown", - "id": "90b10ca5", - "metadata": { - "tags": [] - }, - "source": [ - "You can use this function outline to get started." - ] - }, - { - "cell_type": "code", - "execution_count": 61, - "id": "9e16bcde", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 62, - "id": "ff95300b", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "20c5edf8", - "metadata": { - "tags": [] - }, - "source": [ - "You can use these examples to test `make_date`." - ] - }, - { - "cell_type": "code", - "execution_count": 63, - "id": "62180007", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 64, - "id": "2d70104e", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "16ff5bef", - "metadata": { - "tags": [] - }, - "source": [ - "You can use this function outline to get started." - ] - }, - { - "cell_type": "code", - "execution_count": 65, - "id": "2cc0653e", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 66, - "id": "0b8f63df", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "c36c432e", - "metadata": { - "tags": [] - }, - "source": [ - "You can use this example to test `print_date`." - ] - }, - { - "cell_type": "code", - "execution_count": 67, - "id": "2d0a026d", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "17565b1e", - "metadata": { - "tags": [] - }, - "source": [ - "You can use this function outline to get started." - ] - }, - { - "cell_type": "code", - "execution_count": 68, - "id": "70413f48", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 69, - "id": "b244a057", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 70, - "id": "5fab04bd", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "d9b5dd67", - "metadata": { - "tags": [] - }, - "source": [ - "You can use these examples to test `is_after`." - ] - }, - { - "cell_type": "code", - "execution_count": 71, - "id": "59166d30", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": 72, - "id": "c33706ee", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "d6f1cc2f", - "metadata": {}, - "source": [] - }, - { - "cell_type": "markdown", - "id": "a7f4edf8", - "metadata": { - "tags": [] - }, - "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", - "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", - "\n", - "Code license: [MIT License](https://mit-license.org/)\n", - "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" - ] - } - ], - "metadata": { - "celltoolbar": "Tags", - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.11" - } - }, - "nbformat": 4, - "nbformat_minor": 5 + "cells": [ + { + "cell_type": "markdown", + "id": "1331faa1", + "metadata": {}, + "source": [ + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n[Amazon] (https://www.amazon.com/_/dp/1098155432? ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325)." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "ae5a86f8", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "e826e661", + "metadata": {}, + "source": [ + "# Классы и функции\n\nНа этом этапе вы знаете, как использовать функции для организации кода и как использовать встроенные типы для организации данных.\nСледующим шагом является ** объектно-ориентированное программирование **, в котором используются типы, определяемые программистом для организации как кода, так и данных.\n\nОбъектно-ориентированное программирование-большая тема, поэтому мы будем продолжаться постепенно.\nВ этой главе мы начнем с кода, который не является идиоматическим, то есть не тот код, которые пишут опытные программисты, но это хорошее место для начала.\nВ следующих двух главах мы будем использовать дополнительные функции для написания более идиоматического кода." + ] + }, + { + "cell_type": "markdown", + "id": "6b414d4a", + "metadata": {}, + "source": [ + "## Defermore Programmed Tipes\n\nМы использовали многие из встроенных типов Python-теперь мы определим новый тип.\nВ качестве первого примера мы создадим тип под названием «Time», который представляет время дня.\nТип, определенный программистом, также называется ** класс **.\nОпределение класса выглядит следующим образом:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "c9c99d2c", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "e2414cd2", + "metadata": {}, + "source": [ + "Заголовок указывает, что новый класс называется «Время».\nТело - это Docstring, который объясняет, для чего для класса.\nОпределение класса создает объект класса ** **.\n\nОбъект класса похож на фабрику для создания объектов.\nЧтобы создать объект «Time», вы называете «время», как будто это была функция." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "d318001a", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "f63247d4", + "metadata": {}, + "source": [ + "Результатом является новый объект, чей тип `__main __. Time`, где` __main__` - это имя модуля, где определяется `time`." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "f37d67fd", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "14d0c96a", + "metadata": {}, + "source": [ + "Когда вы печатаете объект, Python говорит вам, какой он тип и где он хранится в памяти (префикс `0x` означает, что следующее число находится в шестнадцатеричном)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "e2bd114a", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "b6445414", + "metadata": {}, + "source": [ + "Создание нового объекта называется ** Commentiation **, а объект - это ** экземпляр ** класса." + ] + }, + { + "cell_type": "markdown", + "id": "4c3768ec", + "metadata": {}, + "source": [ + "## атрибуты\n\nОбъект может содержать переменные, которые называются ** атрибутами ** и произносятся с акцентом на первый слог, как «At-Trib-ute», а не второй слог, такой как «A-Trib-ute».\nМы можем создавать атрибуты с использованием точечной нотации." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "e166701a", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "b3fd8858", + "metadata": {}, + "source": [ + "Этот пример создает атрибуты, называемые «час», «минута» и «второй», которые содержат часы, минуты и секунды времени `11: 59: 01`, которое, насколько я обеспокоен.\n\nНа следующей диаграмме показано состояние «ланча» и его атрибуты после этих заданий." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "3eb47826", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "6702a353", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "d9df5b48", + "metadata": {}, + "source": [ + "Переменная «обед» относится к объекту «время», который содержит три атрибута. \nКаждый атрибут относится к целому числу.\nТакая диаграмма состояния, которая показывает объект и его атрибуты - называется ** объектной диаграммой **.\n\nВы можете прочитать значение атрибута с помощью оператора DOT." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "4c4eff2b", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "5ccfaea0", + "metadata": {}, + "source": [ + "Вы можете использовать атрибут как часть любого выражения." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "7ac6db21", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c5e6725b", + "metadata": {}, + "source": [ + "И вы можете использовать оператор DOT в выражении в F-String." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "1ecdc091", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "e70671d2", + "metadata": {}, + "source": [ + "Но обратите внимание, что предыдущий пример не находится в стандартном формате.\nЧтобы исправить это, мы должны распечатать атрибуты «минута» и «второй» с ведущим нолью.\nМы можем сделать это, расширяя выражения в кудрявых скобках со спецификатором формата ** **.\nВ следующем примере спецификаторы формата указывают, что «минута» и «второй» должны отображаться как минимум с двумя цифрами и при необходимости ведущего нуля." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "a8a45573", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "bcbea13a", + "metadata": {}, + "source": [ + "Мы будем использовать эту F-String, чтобы написать функцию, которая отображает значение `time`Object.\nВы можете передать объект как аргумент обычным способом.\nНапример, следующая функция принимает объект «Time» в качестве аргумента." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "fc77feb2", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "3b8ccbed", + "metadata": {}, + "source": [ + "Когда мы называем это, мы можем передать «обед» в качестве спора." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "59b7f4f4", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "18826e53", + "metadata": {}, + "source": [ + "## объекты как возвращаемые значения\n\nФункции могут возвращать объекты. Например, `make_time` принимает параметры, называемые` hour`, `minute` и` second`, хранит их как атрибуты в объекте «время» и возвращает новый объект." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "fde15b59", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "d8a6acca", + "metadata": {}, + "source": [ + "Может быть, удивительно, что параметры имеют те же имена, что и атрибуты, но это общий способ написать такую функцию.\nВот как мы используем `make_time`, чтобы создать объект« время »." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "f4199d7f", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "05720bcb", + "metadata": {}, + "source": [ + "## объекты изменяются\n\nПредположим, что вы собираетесь показывать фильм, например, *Монти Пайтон и Святой Грааль *, который начинается в 9:20 вечера и работает в течение 92 `минут, что составляет один час` 32 `минут.\nВ какое время фильм закончится?\n\nВо -первых, мы создадим объект «Time», который представляет время начала." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "57847af3", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "001bcda9", + "metadata": {}, + "source": [ + "Чтобы найти время окончания, мы можем изменить атрибуты объекта «время», добавив продолжительность фильма." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "f3637b10", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "7007ab61", + "metadata": {}, + "source": [ + "Фильм будет закончен в 10:52 вечера.\n\nДавайте инкапсулируем это вычисление в функцию и обобщаем его, чтобы взять продолжительность фильма в трех параметрах: «Часы», «Минут» и «Секунды»." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "3468f4d0", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "a51913e2", + "metadata": {}, + "source": [ + "Вот пример, который демонстрирует эффект." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "ad8177ad", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "42d7de02", + "metadata": {}, + "source": [ + "Следующая диаграмма стека показывает состояние программы незадолго до `increment_time` -изменение объекта." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "6f90c060", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "93a1db71", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "d1e27667", + "metadata": {}, + "source": [ + "Внутри функции «Time» является псевдонимом для `start ', поэтому, когда` time' изменяется, `start 'изменяется.\n\nЭта функция работает, но после того, как она работает, у нас осталась переменная с именем «Start», которая относится к объекту, который представляет время * end *, и у нас больше нет объекта, который представляет время начала.\nБыло бы лучше оставить `start 'без изменений и сделать новый объект, чтобы представлять время окончания.\nМы можем сделать это, копировав `start 'и изменив копию." + ] + }, + { + "cell_type": "markdown", + "id": "0128f850", + "metadata": {}, + "source": [ + "## копирование\n\nМодуль `copy` предоставляет функцию с именем` copy`, которая может дублировать любой объект.\nМы можем импортировать его так." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "9f74834d", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "940adbeb", + "metadata": {}, + "source": [ + "Чтобы увидеть, как это работает, давайте начнем с нового объекта «Time», который представляет время начала фильма." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "770c077a", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "514f05b9", + "metadata": {}, + "source": [ + "И сделать копию." + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "edced6e5", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "87d8956b", + "metadata": {}, + "source": [ + "Теперь `start` и` end 'содержат те же данные." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "509c3640", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "e75c1e09", + "metadata": {}, + "source": [ + "Но оператор IS 'подтверждает, что они не один и тот же объект." + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "60d812f7", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "22b68a3f", + "metadata": {}, + "source": [ + "Посмотрим, что делает оператор `==`." + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "4d504362", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "78ebf931", + "metadata": {}, + "source": [ + "Вы можете ожидать, что `==` позволит `true`, потому что объекты содержат одни и те же данные.\nНо для определенных программиста классов поведение оператора `==` совпадает с оператором `is`-он проверяет идентичность, а не эквивалентность." + ] + }, + { + "cell_type": "markdown", + "id": "a3934fdd-d4cd-41e0-86e6-5bb78d0886a7", + "metadata": {}, + "source": [ + "## чистые функции\n\nМы можем использовать `copy` для написания чистых функций, которые не изменяют их параметры.\nНапример, вот функция, которая занимает объект «время» и продолжительность часа, минуты и секунды.\nОн делает копию исходного объекта, использует `urment_time` для изменения копии и возвращает ее." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "85090d3e", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c181af12", + "metadata": {}, + "source": [ + "Вот как мы его используем." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "1d9cf4da", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "54b1ca4a", + "metadata": {}, + "source": [ + "Возвращаемое значение - это новый объект, представляющий время окончания фильма.\nИ мы можем подтвердить, что `start 'не изменился." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "9fe30d71", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "1233b2db", + "metadata": {}, + "source": [ + "`add_time` - это ** чистая функция **, потому что она не изменяет ни один из объектов, передаваемых ему в качестве аргументов, и его единственный эффект - вернуть значение.\n\nВсе, что можно сделать с нечистыми функциями, также может быть сделано с помощью чистых функций.\nНа самом деле, некоторые языки программирования позволяют только чистые функции.\nПрограммы, которые используют чистые функции, могут быть менее подверженными ошибкам, но нечистые функции иногда удобны и могут быть более эффективными.\n\nВ целом, я предлагаю вам написать чистые функции всякий раз, когда это разумно, и прибегать к нечистым функциям, только если есть убедительное преимущество.\nЭтот подход можно назвать ** функциональным стилем программирования **." + ] + }, + { + "cell_type": "markdown", + "id": "9d9fabbc", + "metadata": {}, + "source": [ + "## Прототип и патч\n\nВ предыдущем примере `increment_time` и` add_time`, кажется, работают, но если мы попробуем другой пример, мы увидим, что они не совсем правы.\n\nПредположим, вы приходите в театр и обнаружите, что фильм начинается в 9: 40 `, а не« 9: 20 `.\nВот что происходит, когда мы вычисляем обновленное время окончания." + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "57a96bf9-7d7b-4715-a4b3-2dfad1beb670", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c712ebf7-7e52-490e-91d7-5f1c83334de0", + "metadata": {}, + "source": [ + "Результат не является достоверным временем.\nПроблема заключается в том, что `increment_time` не касается случаев, когда количество секунд или минут наносит более чем« 60 ».\n\nВот улучшенная версия, которая проверяет, превышает ли «второе» или равняется `60` - если да, то увеличивает` minute` - затем проверяет, превышает ли `minute` или равно` 60` - если это так, это увеличивает `час" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "5bada1df-be0a-4f6a-8fe3-d92bd937dc70", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c133c5d8", + "metadata": {}, + "source": [ + "Исправление `increment_time` также исправляет` add_time`, который использует его.\nТак что теперь предыдущий пример работает правильно." + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "a139b64b", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "a2f644a6-ca43-494e-af14-6e845b3d7973", + "metadata": {}, + "source": [ + "Но эта функция все еще не верна, потому что аргументы могут быть больше, чем `60 '.\nНапример, предположим, что нам дают время выполнения как «92» минуты, а не «1» и «32» минуты.\nМы могли бы назвать «add_time»." + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "8c9384cb", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "72e0a08b", + "metadata": {}, + "source": [ + "Результат не является достоверным временем.\nИтак, давайте попробуем другой подход, используя функцию «divmod».\nМы сделаем копию «Start» и изменим ее, увеличив атрибут `Minute '." + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "47b04507", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c56355bc", + "metadata": {}, + "source": [ + "Теперь `minute` -` 132`, что составляет `2` часы и `12 'минут.\nМы можем использовать «divmod», чтобы разделить на `60 'и вернуть количество целых часов и количество оставшихся минут." + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "8ce8f8bc", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "43204703", + "metadata": {}, + "source": [ + "Теперь «минута» верна, и мы можем добавить часы к «часу»." + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "90445645", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "a68ae1cd", + "metadata": {}, + "source": [ + "Результат - достоверное время.\nМы можем сделать то же самое с «Часом» и «вторым» и инкапсулировать весь процесс в функцию." + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "0a9653a2", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "7437113a", + "metadata": {}, + "source": [ + "С этой версией `urment_time`` add_time` работает правильно, даже если аргументы превышают `60 '." + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "694cfdd1", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "7c6329b2", + "metadata": {}, + "source": [ + "Этот раздел демонстрирует план разработки программы, который я называю ** прототипом и патч **.\nМы начали с простого прототипа, который работал правильно для первого примера.\nЗатем мы проверили его с более сложными примерами - когда мы нашли ошибку, мы изменили программу, чтобы исправить ее, например, нанести патч на шину с прокол.\n\nЭтот подход может быть эффективным, особенно если у вас еще нет глубокого понимания проблемы.\nНо постепенные исправления могут генерировать код, который излишне сложный - поскольку он имеет дело со многими особыми случаями - и ненадежным - поскольку трудно понять, есть ли у вас\nНашел все ошибки." + ] + }, + { + "cell_type": "markdown", + "id": "39031461-49a9-4eba-a075-ef49a6f5552b", + "metadata": {}, + "source": [ + "## Design-Pirst Development\n\nАльтернативным планом является ** проектирование-первое развитие **, которое включает в себя больше планирования перед прототипированием. В процессе первого дизайна иногда высокое понимание проблемы облегчает программирование.\n\nВ этом случае понимание состоит в том, что мы можем думать о объекте «Время» как о трехзначном числе в базе 60, также известном как сексмальный.\nАтрибут «второй» - это «столбец», атрибут `Minute` -« столбец шестидесятых »,\nА атрибут «часа»-это «тридцать шесть сотни сотни столбцов».\nКогда мы написали `urment_time`, мы эффективно делали дополнение в базе 60, поэтому мы должны были перенести из одного столбца в другой.\n\nЭто наблюдение предлагает другой подход ко всей проблеме - мы можем преобразовать объекты «время» в целые числа и воспользоваться тем фактом, что Python знает, как выполнять целочисленную арифметику.\n\nВот функция, которая преобразуется из «времени» в целое число." + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "id": "a4427f06-10f3-478f-af4b-888297ee59ac", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c7e7789e", + "metadata": {}, + "source": [ + "Результатом является количество секунд с начала дня.\nНапример, `01: 01: 01` - 1` час, `1` минута и` 1` секунды с начала дня, с суммой `3600` секунды, `60` секунды и `1` второй." + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "id": "e71f9661", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "6ea525c8-4547-4bde-91c3-17f45add1bf8", + "metadata": {}, + "source": [ + "А вот функция, которая идет в другом направлении - преобразование целого числа в объект «время» - с использованием функции «divmod»." + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "id": "7a93edcc-de21-43b1-b0a9-1bcbc7f6125c", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "4706b5df", + "metadata": {}, + "source": [ + "Мы можем проверить его, преобразив предыдущий пример обратно в «время»." + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "967fc3c2", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "0c2b8469-d4a7-46f9-a0a1-f2a6c1595183", + "metadata": {}, + "source": [ + "Используя эти функции, мы можем написать более краткую версию `add_time`." + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "id": "0278a042-9e5b-460f-bd26-2fa319e7193a", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "cb560257", + "metadata": {}, + "source": [ + "Первая строка преобразует аргументы в объект «время», называемый «продолжительность».\nВторая строка преобразует «время» и «продолжительность» в секунды и добавляет их.\nТретья строка преобразует сумму в объект «время» и возвращает ее.\n\nВот как это работает." + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "id": "ee78ffbc", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "db762aa8-4aab-4c17-a88d-72c5048f18c0", + "metadata": {}, + "source": [ + "В некотором смысле преобразование из базы 60 в основание 10 и назад сложнее, чем\nПросто дело со временем. Базовое преобразование более абстрактно; наша интуиция\nДля работы с временными значениями лучше.\n\nНо если у нас есть понимание, чтобы рассматривать время как базовые 60 чисел - и инвестировать усилия, чтобы написать функции преобразования `time_to_int` и` int_to_time` - мы получаем программу, которая легче, проще для чтения и отладка и более надежных.\n\nТакже легче добавить функции позже. Например, представьте, что вы вычитаете два объекта «время», чтобы найти продолжительность между ними.\nНаивный подход заключается в реализации вычитания с заимствованием.\nИспользование функций преобразования проще и с большей вероятностью будет правильным.\n\nПо иронии судьбы, иногда усложняет проблему - или более общий - облегчает, потому что существует меньше особых случаев и меньше возможностей для ошибок." + ] + }, + { + "cell_type": "markdown", + "id": "a0d23d08", + "metadata": { + "tags": [] + }, + "source": [ + "## отладка\n\nPython предоставляет несколько встроенных функций, которые полезны для тестирования и программ отладки, которые работают с объектами.\nНапример, если вы не уверены, какой тип объект, вы можете спросить." + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "id": "652bee8f", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "7ec0eabf", + "metadata": {}, + "source": [ + "Вы также можете использовать `isInstance`, чтобы проверить, является ли объект экземпляром определенного класса." + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "id": "3ab974e4", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "4f453fe9", + "metadata": {}, + "source": [ + "Если вы не уверены, есть ли у объекта определенный атрибут, вы\nможет использовать встроенную функцию `hasattr`." + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "id": "5f80e5ad", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "a0131d84", + "metadata": {}, + "source": [ + "Чтобы получить все атрибуты и их значения в словаре, вы можете использовать «vars»." + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "id": "2a102f0f", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "f1a443c8", + "metadata": {}, + "source": [ + "Модуль Structshape`, который мы видели в [Глава 11] (section_debugging_11), также работает с типами, определенными программистом." + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "id": "b71f46d8", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 52, + "id": "1e6498a8", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "501436c0-6634-415f-be84-2d130232b2b8", + "metadata": {}, + "source": [ + "## Глоссарий\n\n** Объектно-ориентированное программирование: **\nСтиль программирования, который использует объекты для организации кода и данных.\n\n**сорт:**\n Определяемый программистом тип. Определение класса создает новый объект класса.\n\n** Объект класса: **\nОбъект, который представляет класс - это результат определения класса.\n\n** экземпляр: **\nПроцесс создания объекта, который принадлежит классу.\n\n**пример:**\n Объект, который принадлежит классу.\n\n**атрибут:**\n Переменная, связанная с объектом, также называемой переменной экземпляра.\n\n** Диаграмма объектов: **\nГрафическое представление объекта, его атрибутов и его значений.\n\n** Спецификатор формата: **\nВ F-String спецификатор формата определяет, как значение преобразуется в строку.\n\n** Чистая функция: **\nФункция, которая не изменяет свои параметры или не имеет какого -либо эффекта, кроме возврата значения.\n\n** Стиль функционального программирования: **\nСпособ программирования, который использует чистые функции, когда это возможно.\n\n** Прототип и патч: **\nСпособ разработки программ, начиная с черновой черновики и постепенно добавляя функции и исправляя ошибки.\n\n** Проектирование-первая разработка: **\nСпособ разработки программ с более тщательным планированием этого прототипа и патча." + ] + }, + { + "cell_type": "markdown", + "id": "09dd41c1", + "metadata": {}, + "source": [ + "## Упражнения" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "id": "ab3d0104", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "da0aea86", + "metadata": {}, + "source": [ + "### Спросите виртуального помощника\n\nВ этой главе много нового словаря.\nРазговор с виртуальным помощником может помочь укрепить ваше понимание.\nПодумайте о том, чтобы спросить:\n\n* «В чем разница между классом и типом?»\n\n* «В чем разница между объектом и экземпляром?»\n\n* «В чем разница между переменной и атрибутом?»\n\n* «Каковы плюсы и минусы чистых функций по сравнению с нечистыми функциями?»\n\nПоскольку мы только начинаем с объектно -ориентированным программированием, код в этой главе не является идиоматическим - это не тот код, которые пишут опытные программисты.\nЕсли вы попросите виртуального помощника о помощи с упражнениями, вы, вероятно, увидите функции, которые мы еще не покрыли.\nВ частности, вы, вероятно, увидите метод, называемый `__init__`, используемый для инициализации атрибутов экземпляра.\n\nЕсли эти функции имеют смысл для вас, продолжайте и используйте их.\nНо если нет, будьте терпеливы - мы скоро доберемся.\nВ то же время, посмотрите, сможете ли вы решить следующие упражнения, используя только те функции, которые мы рассмотрели до сих пор.\n\nКроме того, в этой главе мы увидели один пример спецификатора формата. Для получения дополнительной информации спросите: «Какие спецификаторы формата можно использовать в Fython F-String?»" + ] + }, + { + "cell_type": "markdown", + "id": "c85eab62", + "metadata": {}, + "source": [ + "## Упражнения" + ] + }, + { + "cell_type": "markdown", + "id": "bcdab7d6", + "metadata": {}, + "source": [ + "### Упражнение\n\nНапишите функцию, называемую `suptract_time`, которая занимает два объекта« Time »и возвращает интервал между ними за считанные секунды - при условии, что они два раза в тот же день." + ] + }, + { + "cell_type": "markdown", + "id": "5033ee5f", + "metadata": { + "tags": [] + }, + "source": [ + "Вот набросок функции, чтобы вы начали." + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "id": "7d898f43", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 55, + "id": "f1b54959", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "73334265", + "metadata": { + "tags": [] + }, + "source": [ + "Вы можете использовать `doctest`, чтобы проверить вашу функцию." + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "id": "5a25a3de", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c3189549", + "metadata": {}, + "source": [ + "### Упражнение\n\nНапишите функцию, называемую `is_after`, которая занимает два объекта« Time »и возвращает` true`, если в первый раз в первый раз, как второй, и `false 'в противном случае." + ] + }, + { + "cell_type": "markdown", + "id": "fd4ac340", + "metadata": { + "tags": [] + }, + "source": [ + "Вот набросок функции, чтобы вы начали." + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "id": "05499ffa", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 58, + "id": "12b4ad17", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "f9da8ede", + "metadata": { + "tags": [] + }, + "source": [ + "Вы можете использовать `doctest`, чтобы проверить вашу функцию." + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "id": "4e580404", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "16dff862", + "metadata": {}, + "source": [ + "### Упражнение\n\nВот определение для класса «Дата», которое представляет собой дату, то есть год, месяц и день месяца." + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "id": "c5de60ed", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "3311fa97", + "metadata": {}, + "source": [ + "1. Напишите функцию, называемую «make_date», которая занимает `year`,` month` и `day 'как параметры, делает объект` date', назначает параметры атрибутам и возвращает результат новый объект. Создайте объект, который представляет 22 июня 1933 года.\n\n2. Напишите функцию с именем `print_date`, которая принимает объект` date`, использует F-String для форматирования атрибутов, и печатает результат. Если вы тестируете его с созданной вами датой, результатом должен быть `1933-06-22 '.\n\n3. Напишите функцию с именем `is_after`, которая принимает два объекта` date` в виде параметров и возвращает `true`, если первый появится после второго. Создайте второй объект, который представляет 17 сентября 1933 года, и проверьте, наступает ли он после первого объекта.\n\nПодсказка: вы можете найти полезное написание функции с именем `date_to_tuple`, которая принимает объект` date` и возвращает кортеж, который содержит свои атрибуты в год, месяц, дневной заказ." + ] + }, + { + "cell_type": "markdown", + "id": "90b10ca5", + "metadata": { + "tags": [] + }, + "source": [ + "Вы можете использовать этот контур функции, чтобы начать." + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "id": "9e16bcde", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 62, + "id": "ff95300b", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "20c5edf8", + "metadata": { + "tags": [] + }, + "source": [ + "Вы можете использовать эти примеры для проверки `make_date`." + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "id": "62180007", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 64, + "id": "2d70104e", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "16ff5bef", + "metadata": { + "tags": [] + }, + "source": [ + "Вы можете использовать этот контур функции, чтобы начать." + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "id": "2cc0653e", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 66, + "id": "0b8f63df", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c36c432e", + "metadata": { + "tags": [] + }, + "source": [ + "Вы можете использовать этот пример для проверки `print_date`." + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "id": "2d0a026d", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "17565b1e", + "metadata": { + "tags": [] + }, + "source": [ + "Вы можете использовать этот контур функции, чтобы начать." + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "id": "70413f48", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 69, + "id": "b244a057", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 70, + "id": "5fab04bd", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "d9b5dd67", + "metadata": { + "tags": [] + }, + "source": [ + "Вы можете использовать эти примеры для проверки `is_after`." + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "id": "59166d30", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 72, + "id": "c33706ee", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "d6f1cc2f", + "metadata": {}, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "a7f4edf8", + "metadata": { + "tags": [] + }, + "source": [ + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n\nCopyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n\nЛицензия кода: [Лицензия MIT] (https://mit-license.org/)\n\nТекстовая лицензия: [Creative Commons attribution-noncommercial-sharealik" + ] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.11" + } + }, + "nbformat": 4, + "nbformat_minor": 5 } From 2ce773085e08127381dd9d1b33a69c81774a14bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:06:46 +0300 Subject: [PATCH 15/44] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=B5?= =?UTF-8?q?=D0=B4=D0=B5=D0=BD=D1=8B=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=D1=8B=D0=B5=20=D1=8F=D1=87=D0=B5=D0=B9=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=B2=20chap15?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blank/chap15.ipynb | 308 ++++++++++++++++++++++----------------------- 1 file changed, 154 insertions(+), 154 deletions(-) diff --git a/blank/chap15.ipynb b/blank/chap15.ipynb index 2ffde33..81b600d 100644 --- a/blank/chap15.ipynb +++ b/blank/chap15.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432?ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325)." ] }, { @@ -25,19 +25,19 @@ "id": "fa22117f", "metadata": {}, "source": [ - "# Classes and Methods\n", + "# Классы и методы\n", "\n", - "Python is an **object-oriented language** -- that is, it provides features that support object-oriented programming, which has these defining characteristics:\n", + "Python-это ** объектно-ориентированный язык **, то есть он предоставляет функции, которые поддерживают объектно-ориентированное программирование, которое имеет эти определяющие характеристики:\n", "\n", - "- Most of the computation is expressed in terms of operations on objects.\n", + "- Большая часть вычислений выражена с точки зрения операций на объектах.\n", "\n", - "- Objects often represent things in the real world, and methods often correspond to the ways things in the real world interact.\n", + "- Объекты часто представляют вещи в реальном мире, и методы часто соответствуют способам взаимодействия вещей в реальном мире.\n", "\n", - "- Programs include class and method definitions.\n", + "- Программы включают определения класса и метода.\n", "\n", - "For example, in the previous chapter we defined a `Time` class that corresponds to the way people record the time of day, and we defined functions that correspond to the kinds of things people do with times.\n", - "But there was no explicit connection between the definition of the `Time` class and the function definitions that follow.\n", - "We can make the connection explicit by rewriting a function as a **method**, which is defined inside a class definition." + "Например, в предыдущей главе мы определили класс `Time`, который соответствует тому, как люди записывают время суток, и мы определили функции, которые соответствуют тому, что люди делают со временем.\n", + "Но не было явного соединения между определением класса `Time` и следующими определениями функций.\n", + "Мы можем явно сделать соединение, переписывая функцию как ** метод **, который определяется внутри определения класса." ] }, { @@ -45,9 +45,9 @@ "id": "9857823a", "metadata": {}, "source": [ - "## Defining methods\n", + "## определение методов\n", "\n", - "In the previous chapter we defined a class named `Time` and wrote a function named `print_time` that displays a time of day." + "В предыдущей главе мы определили класс с именем `Time` и написали функцию с именем `print_time`, которая отображает время суток." ] }, { @@ -63,12 +63,12 @@ "id": "a89ddf58", "metadata": {}, "source": [ - "To make `print_time` a method, all we have to do is move the function\n", - "definition inside the class definition. Notice the change in\n", - "indentation.\n", + "Чтобы сделать метод `print_time`, все, что нам нужно сделать, это переместить функцию\n", + "Определение внутри определения класса.Обратите внимание на изменение в\n", + "отступление.\n", "\n", - "At the same time, we'll change the name of the parameter from `time` to `self`.\n", - "This change is not necessary, but it is conventional for the first parameter of a method to be named `self`." + "В то же время мы изменим имя параметра с `time` на `self`.\n", + "Это изменение не является необходимым, но оно является обычным для первого параметра метода, который будет назван `self`." ] }, { @@ -84,8 +84,8 @@ "id": "8da4079c", "metadata": {}, "source": [ - "To call this method, you have to pass a `Time` object as an argument.\n", - "Here's the function we'll use to make a `Time` object." + "Чтобы назвать этот метод, вы должны передать объект `Time` в качестве аргумента.\n", + "Вот функция, которую мы используем для создания объекта `Time`." ] }, { @@ -101,7 +101,7 @@ "id": "c6ad4e12", "metadata": {}, "source": [ - "And here's a `Time` instance." + "А вот экземпляр `Time`." ] }, { @@ -117,8 +117,8 @@ "id": "bbbcd333", "metadata": {}, "source": [ - "Now there are two ways to call `print_time`. The first (and less common)\n", - "way is to use function syntax." + "Теперь есть два способа позвонить в `print_time`.Первый (и менее распространен)\n", + "способ использовать синтаксис функций." ] }, { @@ -134,8 +134,8 @@ "id": "2eb0847e", "metadata": {}, "source": [ - "In this version, `Time` is the name of the class, `print_time` is the name of the method, and `start` is passed as a parameter.\n", - "The second (and more idiomatic) way is to use method syntax:" + "В этой версии `Time` является именем класса, `print_time` - это имя метода, а `start` передается в качестве параметра.\n", + "Второй (и более идиоматический) способ - использовать синтаксис метода:" ] }, { @@ -151,10 +151,10 @@ "id": "c80c40f0", "metadata": {}, "source": [ - "In this version, `start` is the object the method is invoked on, which is called the **receiver**, based on the analogy that invoking a method is like sending a message to an object.\n", + "В этой версии `start` - это объект, на который используется метод, который называется ** приемник **, основанный на аналогии, которая ссылается на метод, похожа на отправку сообщения объекту.\n", "\n", - "Regardless of the syntax, the behavior of the method is the same.\n", - "The receiver is assigned to the first parameter, so inside the method, `self` refers to the same object as `start`." + "Независимо от синтаксиса, поведение метода одинаково.\n", + "Приемник назначен первым параметрам, поэтому внутри метода `self` относится к тому же объекту, что и `start`." ] }, { @@ -162,9 +162,9 @@ "id": "8deb6c34", "metadata": {}, "source": [ - "## Another method\n", + "## Другой метод\n", "\n", - "Here's the `time_to_int` function from the previous chapter." + "Вот функция `time_to_int` из предыдущей главы." ] }, { @@ -180,7 +180,7 @@ "id": "144e043f", "metadata": {}, "source": [ - "And here's a version rewritten as a method.\n" + "А вот версия, переписанная как метод." ] }, { @@ -196,14 +196,14 @@ "id": "e3a721ab", "metadata": {}, "source": [ - "The first line uses the special command `add_method_to`, which adds a method to a previously-defined class.\n", - "This command works in a Jupyter notebook, but it is not part of Python, so it won't work in other environments.\n", - "Normally, all methods of a class are inside the class definition, so they get defined at the same time as the class.\n", - "But for this book, it is helpful to define one method at a time.\n", + "В первой строке используется специальная команда `add_method_to`, которая добавляет метод в ранее определенный класс.\n", + "Эта команда работает в ноутбуке Jupyter, но она не является частью Python, поэтому она не будет работать в других средах.\n", + "Обычно все методы класса находятся внутри определения класса, поэтому они определяются одновременно с классом.\n", + "Но для этой книги полезно определить один метод за раз.\n", "\n", - "As in the previous example, the method definition is indented and the name of the parameter is `self`.\n", - "Other than that, the method is identical to the function.\n", - "Here's how we invoke it." + "Как и в предыдущем примере, определение метода является отступом, а имя параметра - `self`.\n", + "Кроме этого, метод идентичен функции.\n", + "Вот как мы это призываем." ] }, { @@ -219,7 +219,7 @@ "id": "14565505", "metadata": {}, "source": [ - "It is common to say that we \"call\" a function and \"invoke\" a method, but they mean the same thing." + "Обычно говорить, что мы «называем» функцию и «вызовы» методом, но они означают одно и то же." ] }, { @@ -227,10 +227,10 @@ "id": "7bc24683", "metadata": {}, "source": [ - "## Static methods\n", + "## статические методы\n", "\n", - "As another example, let's consider the `int_to_time` function.\n", - "Here's the version from the previous chapter." + "В качестве другого примера, давайте рассмотрим функцию `int_to_time`.\n", + "Вот версия из предыдущей главы." ] }, { @@ -246,12 +246,12 @@ "id": "2b77c2a0", "metadata": {}, "source": [ - "This function takes `seconds` as a parameter and returns a new `Time` object.\n", - "If we transform it into a method of the `Time` class, we have to invoke it on a `Time` object.\n", - "But if we're trying to create a new `Time` object, what are we supposed to invoke it on?\n", + "Эта функция принимает `seconds` в качестве параметра и возвращает новый объект `Time`.\n", + "Если мы преобразуем его в метод класса `Time`, мы должны вызвать его на объекте `Time`.\n", + "Но если мы пытаемся создать новый объект `Time`, на чем мы должны его вызвать?\n", "\n", - "We can solve this chicken-and-egg problem using a **static method**, which is a method that does not require an instance of the class to be invoked.\n", - "Here's how we rewrite this function as a static method." + "Мы можем решить эту проблему с курицей и яйцом, используя ** статический метод **, который является методом, который не требует применения класса.\n", + "Вот как мы переписываем эту функцию как статический метод." ] }, { @@ -267,8 +267,8 @@ "id": "a7e2e788", "metadata": {}, "source": [ - "Because it is a static method, it does not have `self` as a parameter.\n", - "To invoke it, we use `Time`, which is the class object." + "Поскольку это статический метод, он не имеет `self` в качестве параметра.\n", + "Чтобы вызвать его, мы используем `Time`, который является объектом класса." ] }, { @@ -284,7 +284,7 @@ "id": "d2f4fd5a", "metadata": {}, "source": [ - "The result is a new object that represents 9:40." + "Результатом является новый объект, который представляет 9:40." ] }, { @@ -300,8 +300,8 @@ "id": "e6a18c76", "metadata": {}, "source": [ - "Now that we have `Time.from_seconds`, we can use it to write `add_time` as a method.\n", - "Here's the function from the previous chapter." + "Теперь, когда у нас есть `Time.from_seconds`, мы можем использовать его для написания `add_time` в качестве метода.\n", + "Вот функция из предыдущей главы." ] }, { @@ -317,7 +317,7 @@ "id": "8e56da48", "metadata": {}, "source": [ - "And here's a version rewritten as a method." + "А вот версия, переписанная как метод." ] }, { @@ -333,9 +333,9 @@ "id": "b784a4ea", "metadata": {}, "source": [ - "`add_time` has `self` as a parameter because it is not a static method.\n", - "It is an ordinary method -- also called an **instance method**.\n", - "To invoke it, we need a `Time` instance." + "`add_time` имеет `self` в качестве параметра, поскольку он не является статическим методом.\n", + "Это обычный метод, также называемый методом ** экземпляра **.\n", + "Чтобы вызвать это, нам нужен экземпляр `Time`." ] }, { @@ -351,10 +351,10 @@ "id": "f1c806a9", "metadata": {}, "source": [ - "## Comparing Time objects\n", + "## Сравнение объектов времени\n", "\n", - "As one more example, let's write `is_after` as a method.\n", - "Here's the `is_after` function, which is a solution to an exercise in the previous chapter." + "В качестве еще одного примера, давайте напишем `is_after` в качестве метода.\n", + "Вот функция `is_after`, которая является решением упражнения в предыдущей главе." ] }, { @@ -370,7 +370,7 @@ "id": "8e7153e8", "metadata": {}, "source": [ - "And here it is as a method." + "И вот это как метод." ] }, { @@ -386,9 +386,9 @@ "id": "50815aec", "metadata": {}, "source": [ - "Because we're comparing two objects, and the first parameter is `self`, we'll call the second parameter `other`.\n", - "To use this method, we have to invoke it on one object and pass the\n", - "other as an argument." + "Поскольку мы сравниваем два объекта, а первый параметр - `self`, мы вызовым второй параметр `other`.\n", + "Чтобы использовать этот метод, мы должны вызвать его на один объект и передать\n", + "Другое как аргумент." ] }, { @@ -404,8 +404,8 @@ "id": "cf97e358", "metadata": {}, "source": [ - "One nice thing about this syntax is that it almost reads like a question,\n", - "\"`end` is after `start`?\"" + "Одна хорошая вещь в этом синтаксисе - это то, что он почти читается как вопрос,\n", + "\"`end` после `start`?\"" ] }, { @@ -413,12 +413,12 @@ "id": "15a17fce", "metadata": {}, "source": [ - "## The `__str__` method\n", + "## метод `__str__`\n", "\n", - "When you write a method, you can choose almost any name you want.\n", - "However, some names have special meanings.\n", - "For example, if an object has a method named `__str__`, Python uses that method to convert the object to a string.\n", - "For example, here is a `__str__` method for a time object." + "Когда вы пишете метод, вы можете выбрать практически любое имя, которое вы хотите.\n", + "Однако некоторые имена имеют особые значения.\n", + "Например, если у объекта есть метод с именем `__str__`, Python использует этот метод для преобразования объекта в строку.\n", + "Например, вот метод `__str__` для объекта времени." ] }, { @@ -434,9 +434,9 @@ "id": "b056b729", "metadata": {}, "source": [ - "This method is similar to `print_time`, from the previous chapter, except that it returns the string rather than printing it.\n", + "Этот метод аналогичен `print_time`, из предыдущей главы, за исключением того, что он возвращает строку, а не печатает ее.\n", "\n", - "You can invoke this method in the usual way." + "Вы можете вызвать этот метод обычным способом." ] }, { @@ -452,8 +452,8 @@ "id": "76092a0c", "metadata": {}, "source": [ - "But Python can also invoke it for you.\n", - "If you use the built-in function `str` to convert a `Time` object to a string, Python uses the `__str__` method in the `Time` class." + "Но Python также может вызвать его для вас.\n", + "Если вы используете встроенную функцию `str` для преобразования объекта `Time` в строку, Python использует метод `__str__` в классе `Time`." ] }, { @@ -469,7 +469,7 @@ "id": "8a26caa8", "metadata": {}, "source": [ - "And it does the same if you print a `Time` object." + "И это делает то же самое, если вы печатаете объект `Time`." ] }, { @@ -485,8 +485,8 @@ "id": "97eb30c2", "metadata": {}, "source": [ - "Methods like `__str__` are called **special methods**.\n", - "You can identify them because their names begin and end with two underscores." + "Методы, такие как `__str__`, называются ** Специальные методы **.\n", + "Вы можете идентифицировать их, потому что их имена начинаются и заканчиваются двумя подставками." ] }, { @@ -494,10 +494,10 @@ "id": "e01e9673", "metadata": {}, "source": [ - "## The __init__ method\n", + "## метод __init__\n", "\n", - "The most special of the special methods is `__init__`, so-called because it initializes the attributes of a new object.\n", - "An `__init__` method for the `Time` class might look like this:" + "Самым особенным из специальных методов является `__init__`, так называемый, потому что он инициализирует атрибуты нового объекта.\n", + "Метод `__init__` для класса `Time` может выглядеть так:" ] }, { @@ -513,8 +513,8 @@ "id": "8ba624c3", "metadata": {}, "source": [ - "Now when we instantiate a `Time` object, Python invokes `__init__`, and passes along the arguments.\n", - "So we can create an object and initialize the attributes at the same time." + "Теперь, когда мы создаем создание объекта `Time`, Python вызывает `__init__` и проходит по аргументам.\n", + "Таким образом, мы можем создать объект и одновременно инициализировать атрибуты." ] }, { @@ -530,8 +530,8 @@ "id": "55e0e296", "metadata": {}, "source": [ - "In this example, the parameters are optional, so if you call `Time` with no arguments,\n", - "you get the default values." + "В этом примере параметры являются необязательными, поэтому, если вы звоните `Time` без аргументов,\n", + "Вы получаете значения по умолчанию." ] }, { @@ -547,7 +547,7 @@ "id": "bacb036d", "metadata": {}, "source": [ - "If you provide one argument, it overrides `hour`:" + "Если вы предоставите один аргумент, он переопределяет `hour`:" ] }, { @@ -563,7 +563,7 @@ "id": "37edb221", "metadata": {}, "source": [ - "If you provide two arguments, they override `hour` and `minute`." + "Если вы предоставите два аргумента, они переопределяют `hour` и `minute`." ] }, { @@ -579,10 +579,10 @@ "id": "277de217", "metadata": {}, "source": [ - "And if you provide three arguments, they override all three default\n", - "values.\n", + "И если вы предоставите три аргумента, они переопределяют все три по умолчанию\n", + "ценности.\n", "\n", - "When I write a new class, I almost always start by writing `__init__`, which makes it easier to create objects, and `__str__`, which is useful for debugging." + "Когда я пишу новый класс, я почти всегда начинаю с написания `__init__`, что облегчает создание объектов, и `__str__`, что полезно для отладки." ] }, { @@ -590,14 +590,14 @@ "id": "94bbbd7d", "metadata": {}, "source": [ - "## Operator overloading\n", + "## перегрузка оператора\n", "\n", - "By defining other special methods, you can specify the behavior of\n", - "operators on programmer-defined types. For example, if you define a\n", - "method named `__add__` for the `Time` class, you can use the `+`\n", - "operator on Time objects.\n", + "Определяя другие специальные методы, вы можете указать поведение\n", + "Операторы на определяемых программистом типах.Например, если вы определите\n", + "Метод с именем `__add__` для класса `Time`, вы можете использовать `+`\n", + "Оператор на временных объектах.\n", "\n", - "Here is an `__add__` method." + "Вот метод `__add__`." ] }, { @@ -613,7 +613,7 @@ "id": "0221c9ad", "metadata": {}, "source": [ - "We can use it like this." + "Мы можем использовать это так." ] }, { @@ -629,16 +629,16 @@ "id": "7cc7866e", "metadata": {}, "source": [ - "There is a lot happening when we run these three lines of code:\n", + "Когда мы запускаем эти три строки кода, многое происходит:\n", "\n", - "* When we instantiate a `Time` object, the `__init__` method is invoked.\n", + "* Когда мы создаем создание объекта `Time`, используется метод `__init__`.\n", "\n", - "* When we use the `+` operator with a `Time` object, its `__add__` method is invoked.\n", + "* Когда мы используем оператор `+` с объектом `Time`, его метод `__add__` вызывается.\n", "\n", - "* And when we print a `Time` object, its `__str__` method is invoked.\n", + "* И когда мы печатаем объект `Time`, его метод `__str__` вызывается.\n", "\n", - "Changing the behavior of an operator so that it works with programmer-defined types is called **operator overloading**.\n", - "For every operator, like `+`, there is a corresponding special method, like `__add__`. " + "Изменение поведения оператора, так что он работает с типами, определенными программистом, называется ** Оператор перегрузка **.\n", + "Для каждого оператора, как `+`, существует соответствующий специальный метод, например, `__add__`." ] }, { @@ -646,15 +646,15 @@ "id": "b7299e62", "metadata": {}, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "A `Time` object is valid if the values of `minute` and `second` are between `0` and `60` -- including `0` but not `60` -- and if `hour` is positive.\n", - "Also, `hour` and `minute` should be integer values, but we might allow `second` to have a fraction part.\n", - "Requirements like these are called **invariants** because they should always be true.\n", - "To put it a different way, if they are not true, something has gone wrong.\n", + "Объект `Time` действителен, если значения `minute` и `second` находятся между `0` и `60` - включая `0`, но не `60` - и если `hour` положительно.\n", + "Кроме того, `hour` и `minute` должны быть целочисленными значениями, но мы можем разрешить `second` иметь часть дробной части.\n", + "Требования, подобные этим, называются ** инвариантами **, потому что они всегда должны быть правдой.\n", + "Чтобы выразить это по -другому, если они неправда, что -то пошло не так.\n", "\n", - "Writing code to check invariants can help detect errors and find their causes.\n", - "For example, you might have a method like `is_valid` that takes a Time object and returns `False` if it violates an invariant." + "Написание кода для проверки инвариантов может помочь обнаружить ошибки и найти их причины.\n", + "Например, у вас может быть метод, такой как `minute`1, который занимает объект времени и возвращает `False`, если он нарушает инвариант." ] }, { @@ -670,7 +670,7 @@ "id": "a10ad3db", "metadata": {}, "source": [ - "Then, at the beginning of each method you can check the arguments to make sure they are valid." + "Затем, в начале каждого метода, вы можете проверить аргументы, чтобы убедиться, что они действительны." ] }, { @@ -686,8 +686,8 @@ "id": "e7c78e9a", "metadata": {}, "source": [ - "The `assert` statement evaluates the expression that follows. If the result is `True`, it does nothing; if the result is `False`, it causes an `AssertionError`.\n", - "Here's an example." + "Заявление `assert` оценивает следующее выражение.Если результат `True`, он ничего не делает;Если результат `False`, он вызывает `AssertionError`.\n", + "Вот пример." ] }, { @@ -713,7 +713,7 @@ "id": "18bd34ad", "metadata": {}, "source": [ - "`assert` statements are useful because they distinguish code that deals with normal conditions from code that checks for errors." + "`assert` операторы полезны, потому что они различают код, который касается нормальных условий от кода, который проверяет ошибки." ] }, { @@ -721,31 +721,31 @@ "id": "58b86fbe", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**object-oriented language:**\n", - "A language that provides features to support object-oriented programming, notably user-defined types.\n", + "** объектно-ориентированный язык: **\n", + "Язык, который предоставляет функции для поддержки объектно-ориентированного программирования, особенно определяемых пользователями типов.\n", "\n", - "**method:**\n", - "A function that is defined inside a class definition and is invoked on instances of that class.\n", + "** Метод: **\n", + "Функция, которая определяется внутри определения класса и вызывается в случаях этого класса.\n", "\n", - "**receiver:**\n", - "The object a method is invoked on.\n", + "** приемник: **\n", + "Объект, на который используется метод.\n", "\n", - "**static method:**\n", - "A method that can be invoked without an object as receiver.\n", + "** Статический метод: **\n", + "Метод, который можно вызвать без объекта в качестве приемника.\n", "\n", - "**instance method:**\n", - "A method that must be invoked with an object as receiver.\n", + "** Метод экземпляра: **\n", + "Метод, который должен быть вызван объектом в качестве приемника.\n", "\n", - "**special method:**\n", - "A method that changes the way operators and some functions work with an object.\n", + "** Специальный метод: **\n", + "Метод, который меняет способ работы операторов и некоторых функций с объектом.\n", "\n", - "**operator overloading:**\n", - "The process of using special methods to change the way operators with with user-defined types.\n", + "** Оператор перегрузка: **\n", + "Процесс использования специальных методов для изменения способа операторов с пользовательскими типами.\n", "\n", - "**invariant:**\n", - " A condition that should always be true during the execution of a program." + "** инвариант: **\n", + "Условие, которое всегда должно быть правдой во время выполнения программы." ] }, { @@ -753,7 +753,7 @@ "id": "796adf5c", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -771,20 +771,20 @@ "id": "25cd6888", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "For more information about static methods, ask a virtual assistant:\n", + "Для получения дополнительной информации о статических методах, спросите виртуального помощника:\n", "\n", - "* \"What's the difference between an instance method and a static method?\"\n", + "* «В чем разница между методом экземпляра и статическим методом?»\n", "\n", - "* \"Why are static methods called static?\"\n", + "* Почему статические методы называются статичными? »\n", "\n", - "If you ask a virtual assistant to generate a static method, the result will probably begin with `@staticmethod`, which is a \"decorator\" that indicates that it is a static method.\n", - "Decorators are not covered in this book, but if you are curious, you can ask a VA for more information.\n", + "Если вы попросите виртуального помощника создать статический метод, результат, вероятно, начнется с `@staticmethod`, который является «декоратором», который указывает на то, что это статический метод.\n", + "Декораторы не рассматриваются в этой книге, но если вам любопытно, вы можете попросить VA для получения дополнительной информации.\n", "\n", - "In this chapter we rewrote several functions as methods.\n", - "Virtual assistants are generally good at this kind of code transformation.\n", - "As an example, paste the following function into a VA and ask it, \"Rewrite this function as a method of the `Time` class.\"" + "В этой главе мы переписываем несколько функций в качестве методов.\n", + "Виртуальные помощники, как правило, хороши в таком преобразовании кода.\n", + "В качестве примера вставьте следующую функцию в VA и спросите ее: «Перепишите эту функцию как метод класса `Time`»." ] }, { @@ -800,20 +800,20 @@ "id": "fc9f135b-e242-4ef6-83eb-8e028235c07b", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In the previous chapter, a series of exercises asked you to write a `Date` class and several functions that work with `Date` objects.\n", - "Now let's practice rewriting those functions as methods.\n", + "В предыдущей главе серия упражнений попросила вас написать класс `Date` и несколько функций, которые работают с объектами `Date`.\n", + "Теперь давайте практиковать переписывание этих функций в качестве методов.\n", "\n", - "1. Write a definition for a `Date` class that represents a date -- that is, a year, month, and day of the month.\n", + "1. Напишите определение для класса `Date`, который представляет дату, то есть год, месяц и день месяца.\n", "\n", - "2. Write an `__init__` method that takes `year`, `month`, and `day` as parameters and assigns the parameters to attributes. Create an object that represents June 22, 1933.\n", + "2. Напишите метод `__init__`, который принимает `year`, `month` и `day` в качестве параметров и назначает параметры атрибутам.Создайте объект, который представляет 22 июня 1933 года.\n", "\n", - "2. Write `__str__` method that uses an f-string to format the attributes and returns the result. If you test it with the `Date` you created, the result should be `1933-06-22`.\n", + "2. Напишите метод `__str__`, который использует F-String для форматирования атрибутов и возвращает результат.Если вы тестируете его с созданным вами 1`Date`, результат должен быть `1933-06-22`.\n", "\n", - "3. Write a method called `is_after` that takes two `Date` objects and returns `True` if the first comes after the second. Create a second object that represents September 17, 1933, and check whether it comes after the first object.\n", + "3. Напишите метод под названием `is_after`, который принимает два объекта `Date`1 и возвращает `True`, если первый появляется после второго.Создайте второй объект, который представляет 17 сентября 1933 года, и проверьте, наступает ли он после первого объекта.\n", "\n", - "Hint: You might find it useful write a method called `to_tuple` that returns a tuple that contains the attributes of a `Date` object in year-month-day order." + "Подсказка: вы можете найти его полезным написать метод под названием `to_tuple`, который возвращает кортеж, который содержит атрибуты объекта `Date` в порядке в течение года." ] }, { @@ -831,7 +831,7 @@ "tags": [] }, "source": [ - "You can use these examples to test your solution." + "Вы можете использовать эти примеры для проверки вашего решения." ] }, { @@ -889,13 +889,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT] (https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik" ] } ], @@ -921,4 +921,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 459d17e7390a3a07a29c69628201a0551c300d75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:07:20 +0300 Subject: [PATCH 16/44] Translate chapter 16 notebook --- blank/chap16.ipynb | 358 ++++++++++++++++++++++----------------------- 1 file changed, 179 insertions(+), 179 deletions(-) diff --git a/blank/chap16.ipynb b/blank/chap16.ipynb index 4309183..0d8145c 100644 --- a/blank/chap16.ipynb +++ b/blank/chap16.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432?ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325).\n" ] }, { @@ -25,15 +25,15 @@ "id": "e826e661", "metadata": {}, "source": [ - "# Classes and Objects\n", + "# Классы и объекты\n", "\n", - "At this point we have defined classes and created objects that represent the time of day and the day of the year.\n", - "And we've defined methods that create, modify, and perform computations with these objects.\n", + "На этом этапе мы определили классы и создали объекты, которые представляют время дня и день года.\n", + "И мы определили методы, которые создают, изменяют и выполняют вычисления с этими объектами.\n", "\n", - "In this chapter we'll continue our tour of object-oriented programming (OOP) by defining classes that represent geometric objects, including points, lines, rectangles, and circles.\n", - "We'll write methods that create and modify these objects, and we'll use the `jupyturtle` module to draw them.\n", + "В этой главе мы продолжим наш тур по объектно-ориентированному программированию (ООП), определяя классы, которые представляют геометрические объекты, включая точки, линии, прямоугольники и круги.\n", + "Мы напишем методы, которые создают и изменяем эти объекты, и мы будем использовать модуль `jupyturtle ', чтобы нарисовать их.\n", "\n", - "I'll use these classes to demonstrate OOP topics including object identity and equivalence, shallow and deep copying, and polymorphism." + "Я буду использовать эти классы, чтобы продемонстрировать темы ООП, включая идентичность объекта и эквивалентность, неглубокое и глубокое копирование, а также полиморфизм.\n" ] }, { @@ -43,22 +43,22 @@ "tags": [] }, "source": [ - "## Creating a Point\n", + "## Создание точки\n", "\n", - "In computer graphics a location on the screen is often represented using a pair of coordinates in an `x`-`y` plane.\n", - "By convention, the point `(0, 0)` usually represents the upper-left corner of the screen, and `(x, y)` represents the point `x` units to the right and `y` units down from the origin.\n", - "Compared to the Cartesian coordinate system you might have seen in a math class, the `y` axis is upside-down.\n", + "В компьютерной графике местоположение на экране часто представлено с использованием пары координат в плоскости ``-`y.\n", + "По согласованию точка `(0, 0)` обычно представляет верхний левый угол экрана, а `(x, y)` представляет единицы точки `x` вправо и единицы` y` вниз от начала начала.\n", + "По сравнению с декартовой системой координат, которую вы могли увидеть в математическом классе, ось «Y» перевернута.\n", "\n", - "There are several ways we might represent a point in Python:\n", + "Есть несколько способов, которыми мы могли бы представить точку в Python:\n", "\n", - "- We can store the coordinates separately in two variables, `x` and `y`.\n", + "- Мы можем хранить координаты отдельно в двух переменных, `x` и` y`.\n", "\n", - "- We can store the coordinates as elements in a list or tuple.\n", + "- Мы можем хранить координаты в виде элементов в списке или кортеже.\n", "\n", - "- We can create a new type to represent points as objects.\n", + "- Мы можем создать новый тип, чтобы представлять точки в качестве объектов.\n", "\n", - "In object-oriented programming, it would be most idiomatic to create a new type.\n", - "To do that, we'll start with a class definition for `Point`." + "В объектно-ориентированном программировании было бы наиболее идиоматическим создавать новый тип.\n", + "Для этого мы начнем с определения класса для `point '.\n" ] }, { @@ -74,10 +74,10 @@ "id": "3d35a095", "metadata": {}, "source": [ - "The `__init__` method takes the coordinates as parameters and assigns them to attributes `x` and `y`.\n", - "The `__str__` method returns a string representation of the `Point`.\n", + "Метод «__init__» принимает координаты как параметры и назначает их атрибутам `x` и` y`.\n", + "Метод `__str__` возвращает строковое представление` point '.\n", "\n", - "Now we can instantiate and display a `Point` object like this." + "Теперь мы можем создать экземпляр и отобразить такой объект «точка».\n" ] }, { @@ -93,7 +93,7 @@ "id": "b3fd8858", "metadata": {}, "source": [ - "The following diagram shows the state of the new object. " + "На следующей диаграмме показано состояние нового объекта.\n" ] }, { @@ -121,9 +121,9 @@ "id": "713b7410", "metadata": {}, "source": [ - "As usual, a programmer-defined type is represented by a box with the name of the type outside and the attributes inside.\n", + "Как обычно, тип, определенный программистом, представлен коробкой с именем типа снаружи и атрибутами внутри.\n", "\n", - "In general, programmer-defined types are mutable, so we can write a method like `translate` that takes two numbers, `dx` and `dy`, and adds them to the attributes `x` and `y`." + "В целом, определяемые программистами типы являются измененными, поэтому мы можем написать метод, такой как «Translate», который принимает два числа, `dx` и` dy`, и добавляет их к атрибутам `x` и` y`.\n" ] }, { @@ -139,8 +139,8 @@ "id": "4d183292", "metadata": {}, "source": [ - "This function translates the `Point` from one location in the plane to another.\n", - "If we don't want to modify an existing `Point`, we can use `copy` to copy the original object and then modify the copy." + "Эта функция переводит «точку» из одного места в плоскости в другое.\n", + "Если мы не хотим изменять существующую `point ', мы можем использовать` copy` для копирования исходного объекта, а затем изменить копию.\n" ] }, { @@ -156,7 +156,7 @@ "id": "562567c2", "metadata": {}, "source": [ - "We can encapsulate those steps in another method called `translated`." + "Мы можем инкапсулировать эти шаги в другой метод, называемый «переведен».\n" ] }, { @@ -172,9 +172,9 @@ "id": "a7a635ee", "metadata": {}, "source": [ - "In the same way that the built in function `sort` modifies a list, and the `sorted` function creates a new list, now we have a `translate` method that modifies a `Point` and a `translated` method that creates a new one.\n", + "Точно так же, как встроенная функция `sort` изменяет список, а функция« сортированная »создает новый список, теперь у нас есть метод« translate », который изменяет метод« точка »и« переведенный », который создает новый.\n", "\n", - "Here's an example:" + "Вот пример:\n" ] }, { @@ -190,7 +190,7 @@ "id": "923362d2", "metadata": {}, "source": [ - "In the next section, we'll use these points to define and draw a line." + "В следующем разделе мы будем использовать эти точки для определения и проведения линии.\n" ] }, { @@ -198,10 +198,10 @@ "id": "837f98fd", "metadata": {}, "source": [ - "## Creating a Line\n", + "## Создание строки\n", "\n", - "Now let's define a class that represents the line segment between two points.\n", - "As usual, we'll start with an `__init__` method and a `__str__` method." + "Теперь давайте определим класс, который представляет сегмент линии между двумя точками.\n", + "Как обычно, мы начнем с метода `__init__` и метода` __str__`.\n" ] }, { @@ -217,7 +217,7 @@ "id": "d7dad30e", "metadata": {}, "source": [ - "With those two methods, we can instantiate and display a `Line` object we'll use to represent the `x` axis." + "С этими двумя методами мы можем создать экземпляр и отобразить объект `line`, который мы используем для представления оси` x`.\n" ] }, { @@ -233,16 +233,16 @@ "id": "e7b5fd9a", "metadata": {}, "source": [ - "When we call `print` and pass `line` as a parameter, `print` invokes `__str__` on `line`.\n", - "The `__str__` method uses an f-string to create a string representation of the `line`. \n", + "Когда мы называем `print` и передаем` line` как параметр, `print` вызывает` __str__` на `line`.\n", + "Метод `__str__` использует F-строчку для создания строкового представления` line '.\n", "\n", - "The f-string contains two expressions in curly braces, `self.p1` and `self.p2`.\n", - "When those expressions are evaluated, the results are `Point` objects.\n", - "Then, when they are converted to strings, the `__str__` method from the `Point` class gets invoked.\n", + "F-String содержит два выражения в кудрявых скобках, `self.p1` и` self.p2`.\n", + "Когда эти выражения оцениваются, результатами являются объекты «точка».\n", + "Затем, когда они преобразуются в строки, метод `__str__` из класса« точка »вызывается.\n", "\n", - "That's why, when we display a `Line`, the result contains the string representations of the `Point` objects.\n", + "Вот почему, когда мы отображаем `line ', результат содержит строки представлений объектов` point'.\n", "\n", - "The following object diagram shows the state of this `Line` object." + "На следующей диаграмме объектов показана состояние этого объекта `line`.\n" ] }, { @@ -270,17 +270,17 @@ "id": "079859b5", "metadata": {}, "source": [ - "String representations and object diagrams are useful for debugging, but the point of this example is to generate graphics, not text!\n", - "So we'll use the `jupyturtle` module to draw lines on the screen.\n", + "Строковые представления и диаграммы объектов полезны для отладки, но точка этого примера состоит в том, чтобы генерировать графику, а не текст!\n", + "Итак, мы будем использовать модуль `jupyturtle`, чтобы нарисовать линии на экране.\n", "\n", - "As we did in [Chapter 4](section_turtle_module), we'll use `make_turtle` to create a `Turtle` object and a small canvas where it can draw.\n", - "To draw lines, we'll use two new functions from the `jupyturtle` module:\n", + "Как мы делали в [Глава 4] (section_turtle_module), мы будем использовать `make_turtle`, чтобы создать объект« черепахи »и небольшой холст, где он может рисовать.\n", + "Чтобы нарисовать линии, мы будем использовать две новые функции из модуля `jupyturtle`:\n", "\n", - "* `jumpto`, which takes two coordinates and moves the `Turtle` to the given location without drawing a line, and \n", + "* `jumpto`, который берет две координаты и перемещает« черепаху »в данное место, не проведя линию, и\n", "\n", - "* `moveto`, which moves the `Turtle` from its current location to the given location, and draws a line segment between them.\n", + "* `moveto`, который перемещает« черепаху »от своей текущего местоположения в данное местоположение и протягивает сегмент линии между ними.\n", "\n", - "Here's how we import them." + "Вот как мы их импортируем.\n" ] }, { @@ -296,7 +296,7 @@ "id": "9d2dd88f", "metadata": {}, "source": [ - "And here's a method that draws a `Line`." + "А вот метод, который рисует `line '.\n" ] }, { @@ -312,7 +312,7 @@ "id": "2341f0e0", "metadata": {}, "source": [ - "To show how it's used, I'll create a second line that represents the `y` axis." + "Чтобы показать, как это используется, я создам вторую строку, которая представляет ось `y`.\n" ] }, { @@ -328,7 +328,7 @@ "id": "d7450736", "metadata": {}, "source": [ - "And then draw the axes." + "А затем нарисуйте топоры.\n" ] }, { @@ -344,8 +344,8 @@ "id": "473c156f", "metadata": {}, "source": [ - "As we define and draw more objects, we'll use these lines again.\n", - "But first let's talk about object equivalence and identity." + "Когда мы определяем и нарисуем больше объектов, мы снова будем использовать эти линии.\n", + "Но сначала давайте поговорим о эквивалентности объекта и идентичности.\n" ] }, { @@ -353,9 +353,9 @@ "id": "950da673", "metadata": {}, "source": [ - "## Equivalence and identity\n", + "## эквивалентность и идентичность\n", "\n", - "Suppose we create two points with the same coordinates." + "Предположим, мы создаем две точки с одинаковыми координатами.\n" ] }, { @@ -371,7 +371,7 @@ "id": "82b14526", "metadata": {}, "source": [ - "If we use the `==` operator to compare them, we get the default behavior for programmer-defined types -- the result is `True` only if they are the same object, which they are not." + "Если мы используем оператор `==` для их сравнения, мы получаем поведение по умолчанию для типов, определенных программистом-результат-«true», только если они являются одним и тем же объектом, что они не являются.\n" ] }, { @@ -387,7 +387,7 @@ "id": "96be0ff8", "metadata": {}, "source": [ - "If we want to change that behavior, we can provide a special method called `__eq__` that defines what it means for two `Point` objects to be equal." + "Если мы хотим изменить это поведение, мы можем предоставить специальный метод под названием «__eq__`, который определяет, что это значит для двух объектов` point`, чтобы быть равными.\n" ] }, { @@ -403,8 +403,8 @@ "id": "7f4409de", "metadata": {}, "source": [ - "This definition considers two `Points` to be equal if their attributes are equal.\n", - "Now when we use the `==` operator, it invokes the `__eq__` method, which indicates that `p1` and `p2` are considered equal." + "Это определение считает, что две «точки» равны, если их атрибуты равны.\n", + "Теперь, когда мы используем оператор `==`, он вызывает метод `__EQ__`, который указывает, что` P1` и `P2` считаются равными.\n" ] }, { @@ -420,7 +420,7 @@ "id": "52662e6a", "metadata": {}, "source": [ - "But the `is` operator still indicates that they are different objects." + "Но оператор is 'все еще указывает на то, что это разные объекты.\n" ] }, { @@ -436,9 +436,9 @@ "id": "c008d3dd", "metadata": {}, "source": [ - "It's not possible to override the `is` operator -- it always checks whether the objects are identical.\n", - "But for programmer-defined types, you can override the `==` operator so it checks whether the objects are equivalent.\n", - "And you can define what equivalent means." + "Невозможно переопределить оператора `is` - он всегда проверяет, являются ли объекты идентичными.\n", + "Но для определяемых программистом типы вы можете переопределить оператора `==`, чтобы он проверял, являются ли объекты эквивалентными.\n", + "И вы можете определить, что означает эквивалент.\n" ] }, { @@ -446,20 +446,20 @@ "id": "893a8cab", "metadata": {}, "source": [ - "## Creating a Rectangle\n", + "## Создание прямоугольника\n", "\n", - "Now let's define a class that represents and draws rectangles.\n", - "To keep things simple, we'll assume that the rectangles are either vertical or horizontal, not at an angle.\n", - "What attributes do you think we should use to specify the location and size of a rectangle?\n", + "Теперь давайте определим класс, который представляет и рисует прямоугольники.\n", + "Чтобы все было просто, мы предположим, что прямоугольники являются либо вертикальными, либо горизонтальными, а не под углом.\n", + "Как вы думаете, какие атрибуты мы должны использовать для указания местоположения и размера прямоугольника?\n", "\n", - "There are at least two possibilities:\n", + "Есть как минимум две возможности:\n", "\n", - "- You could specify the width and height of the rectangle and the location of one corner.\n", + "- Вы можете указать ширину и высоту прямоугольника и расположение одного угла.\n", "\n", - "- You could specify two opposing corners.\n", + "- Вы можете указать два противоположных угла.\n", "\n", - "At this point it's hard to say whether either is better than the other, so let's implement the first one.\n", - "Here is the class definition." + "На данный момент трудно сказать, лучше ли другой, поэтому давайте реализуем первый.\n", + "Вот определение класса.\n" ] }, { @@ -475,8 +475,8 @@ "id": "df2852f3", "metadata": {}, "source": [ - "As usual, the `__init__` method assigns the parameters to attributes and the `__str__` returns a string representation of the object.\n", - "Now we can instantiate a `Rectangle` object, using a `Point` as the location of the upper-left corner." + "Как обычно, метод `__init__` назначает параметры атрибутам, а` __str__` возвращает строковое представление объекта.\n", + "Теперь мы можем создать экземпляр объекта «прямоугольник», используя «точку» в качестве местоположения верхнего левого угла.\n" ] }, { @@ -492,7 +492,7 @@ "id": "a9e0b5ec", "metadata": {}, "source": [ - "The following diagram shows the state of this object." + "На следующей диаграмме показано состояние этого объекта.\n" ] }, { @@ -520,7 +520,7 @@ "id": "bb54e6b5", "metadata": {}, "source": [ - "To draw a rectangle, we'll use the following method to make four `Point` objects to represent the corners." + "Чтобы нарисовать прямоугольник, мы будем использовать следующий метод, чтобы сделать четыре объекта «точка» для представления углов.\n" ] }, { @@ -536,7 +536,7 @@ "id": "20dbe0cb", "metadata": {}, "source": [ - "Then we'll make four `Line` objects to represent the sides." + "Тогда мы сделаем четыре объекта `line`, чтобы представлять стороны.\n" ] }, { @@ -552,7 +552,7 @@ "id": "30fe41cc", "metadata": {}, "source": [ - "Then we'll draw the sides." + "Тогда мы нарисуем стороны.\n" ] }, { @@ -568,7 +568,7 @@ "id": "390ba3e7", "metadata": {}, "source": [ - "Here's an example." + "Вот пример.\n" ] }, { @@ -584,7 +584,7 @@ "id": "532a4f69", "metadata": {}, "source": [ - "The figure includes two lines to represent the axes." + "Рисунок включает в себя две линии для представления оси.\n" ] }, { @@ -592,13 +592,13 @@ "id": "0e713a90", "metadata": {}, "source": [ - "## Changing rectangles\n", + "## Изменение прямоугольников\n", "\n", - "Now let's consider two methods that modify rectangles, `grow` and `translate`.\n", - "We'll see that `grow` works as expected, but `translate` has a subtle bug.\n", - "See if you can figure it out before I explain.\n", + "Теперь давайте рассмотрим два метода, которые изменяют прямоугольники, «Grow» и «transtate».\n", + "Мы увидим, что «Grow» работает, как и ожидалось, но «Translate» имеет тонкую ошибку.\n", + "Посмотрите, сможете ли вы понять это, прежде чем я объясню.\n", "\n", - "`grow` takes two numbers, `dwidth` and `dheight`, and adds them to the `width` and `height` attributes of the rectangle." + "`grow 'принимает два числа:` dwidth` и `dheight', и добавляет их к атрибутам` width 'и `hiep' прямоугольника.\n" ] }, { @@ -614,7 +614,7 @@ "id": "a51913e2", "metadata": {}, "source": [ - "Here's an example that demonstrates the effect by making a copy of `box1` and invoking `grow` on the copy." + "Вот пример, который демонстрирует эффект, создавая копию «Box1» и вызывая «Grow» на копию.\n" ] }, { @@ -630,7 +630,7 @@ "id": "6d74da62", "metadata": {}, "source": [ - "If we draw `box1` and `box2`, we can confirm that `grow` works as expected." + "Если мы нарисуем `box1` и` box2`, мы можем подтвердить, что «Grow» работает, как и ожидалось.\n" ] }, { @@ -646,8 +646,8 @@ "id": "0c940008", "metadata": {}, "source": [ - "Now let's see about `translate`.\n", - "It takes two numbers, `dx` and `dy`, and moves the rectangle the given distances in the `x` and `y` directions. " + "Теперь давайте посмотрим о `transtate '.\n", + "Требуется два числа, `dx` и` dy`, и перемещает прямоугольник на заданных расстояниях в направлениях `x` и` y`.\n" ] }, { @@ -663,7 +663,7 @@ "id": "c27fe91d", "metadata": {}, "source": [ - "To demonstrate the effect, we'll translate `box2` to the right and down." + "Чтобы продемонстрировать эффект, мы переведем `box2` вправо и вниз.\n" ] }, { @@ -679,7 +679,7 @@ "id": "e01badbc", "metadata": {}, "source": [ - "Now let's see what happens if we draw `box1` and `box2` again." + "Теперь давайте посмотрим, что произойдет, если мы снова нарисуем `box1` и` box2`.\n" ] }, { @@ -695,8 +695,8 @@ "id": "5310bdd7", "metadata": {}, "source": [ - "It looks like both rectangles moved, which is not what we intended!\n", - "The next section explains what went wrong." + "Похоже, что оба прямоугольника перемещаются, что не то, что мы намеревались!\n", + "В следующем разделе объясняется, что пошло не так.\n" ] }, { @@ -704,10 +704,10 @@ "id": "940adbeb", "metadata": {}, "source": [ - "## Deep copy\n", + "## Глубокая копия\n", "\n", - "When we use `copy` to duplicate `box1`, it copies the `Rectangle` object but not the `Point` object it contains.\n", - "So `box1` and `box2` are different objects, as intended." + "Когда мы используем `copy` для дублирования` box1`, он копирует объект `rectangle ', но не объект` point', который он содержит.\n", + "Таким образом, `box1` и` box2` - это разные объекты, как предполагалось.\n" ] }, { @@ -723,7 +723,7 @@ "id": "eac5309b", "metadata": {}, "source": [ - "But their `corner` attributes refer to the same object." + "Но их атрибуты «угол» относятся к тому же объекту.\n" ] }, { @@ -739,7 +739,7 @@ "id": "f0cc51b5", "metadata": {}, "source": [ - "The following diagram shows the state of these objects." + "На следующей диаграмме показано состояние этих объектов.\n" ] }, { @@ -767,14 +767,14 @@ "id": "35f3e7e1", "metadata": {}, "source": [ - "What `copy` does is called a **shallow copy** because it copies the object but not the objects it contains.\n", - "As a result, changing the `width` or `height` of one `Rectangle` does not affect the other, but changing the attributes of the shared `Point` affects both!\n", - "This behavior is confusing and error-prone.\n", + "То, что делает Copy`, называется ** неглубокая копия **, потому что он копирует объект, но не объекты, которые он содержит.\n", + "В результате изменение «ширины» или «высота» одного «прямоугольника» не влияет на другую, но изменение атрибутов общей точки «точка» влияет на оба!\n", + "Такое поведение сбивает с толку и подвержено ошибкам.\n", "\n", - "Fortunately, the `copy` module provides another function, called `deepcopy`, that copies not only the object but also the objects it refers to, and the objects *they* refer to, and so on. \n", - "This operation is called a **deep copy**.\n", + "К счастью, модуль «Copy» предоставляет другую функцию, называемую «DeepCopy», которая копирует не только объект, но и объекты, на которые он ссылается, и объекты * они * ссылаются, и так далее.\n", + "Эта операция называется ** глубокая копия **.\n", "\n", - "To demonstrate, let's start with a new `Rectangle` that contains a new `Point`." + "Чтобы продемонстрировать, давайте начнем с нового «прямоугольника», который содержит новую «точку».\n" ] }, { @@ -790,7 +790,7 @@ "id": "ff9ee872", "metadata": {}, "source": [ - "And we'll make a deep copy." + "И мы сделаем глубокую копию.\n" ] }, { @@ -806,7 +806,7 @@ "id": "7efd0e6a", "metadata": {}, "source": [ - "We can confirm that the two `Rectangle` objects refer to different `Point` objects." + "Мы можем подтвердить, что два объекта «прямоугольник» относятся к различным объектам «точка».\n" ] }, { @@ -822,8 +822,8 @@ "id": "ca925206", "metadata": {}, "source": [ - "Because `box3` and `box4` are completely separate objects, we can modify one without affecting the other.\n", - "To demonstrate, we'll move `box3` and grow `box4`." + "Поскольку `box3` и` box4` являются совершенно отдельными объектами, мы можем изменить один, не влияя на другого.\n", + "Чтобы продемонстрировать, мы переместим `box3` и вырасту` box4`.\n" ] }, { @@ -839,7 +839,7 @@ "id": "3ff31c7c", "metadata": {}, "source": [ - "And we can confirm that the effect is as expected." + "И мы можем подтвердить, что эффект, как и ожидалось.\n" ] }, { @@ -855,10 +855,10 @@ "id": "67051d62", "metadata": {}, "source": [ - "## Polymorphism\n", + "## Полиморфизм\n", "\n", - "In the previous example, we invoked the `draw` method on two `Line` objects and two `Rectangle` objects.\n", - "We can do the same thing more concisely by making a list of objects." + "В предыдущем примере мы призвали метод «Draw» на двух объектах `line 'и два объекта` rectangle'.\n", + "Мы можем сделать то же самое более кратко, составив список объектов.\n" ] }, { @@ -874,7 +874,7 @@ "id": "773955dd", "metadata": {}, "source": [ - "The elements of this list are different types, but they all provide a `draw` method, so we can loop through the list and invoke `draw` on each one." + "Элементы этого списка являются разными типами, но все они предоставляют метод «Draw», поэтому мы можем пройти через список и вызвать «Draw» на каждого.\n" ] }, { @@ -890,17 +890,17 @@ "id": "a1ae190c", "metadata": {}, "source": [ - "The first and second time through the loop, `shape` refers to a `Line` object, so when `draw` is invoked, the method that runs is the one defined in the `Line` class.\n", + "Первый и второй раз через петлю, «Shape» относится к объекту `line`, поэтому, когда используется` drait\n", "\n", - "The third and fourth time through the loop, `shape` refers to a `Rectangle` object, so when `draw` is invoked, the method that runs is the one defined in the `Rectangle` class.\n", + "Третий и четвертый раз через петлю, «Shape» относится к объекту «прямоугольник», поэтому, когда вызывается `drait\n", "\n", - "In a sense, each object knows how to draw itself.\n", - "This feature is called **polymorphism**.\n", - "The word comes from Greek roots that mean \"many shaped\".\n", - "In object-oriented programming, polymorphism is the ability of different types to provide the same methods, which makes it possible to perform many computations -- like drawing shapes -- by invoking the same method on different types of objects.\n", + "В некотором смысле каждый объект знает, как рисовать.\n", + "Эта функция называется ** полиморфизм **.\n", + "Слово происходит от греческих корней, которые означают «много форм».\n", + "В объектно-ориентированном программировании полиморфизм-это способность различных типов предоставлять одинаковые методы, что позволяет выполнять множество вычислений, таких как формы рисования,-вызывая один и тот же метод на различных типах объектов.\n", "\n", - "As an exercise at the end of this chapter, you'll define a new class that represents a circle and provides a `draw` method.\n", - "Then you can use polymorphism to draw lines, rectangles, and circles." + "В качестве упражнения в конце этой главы вы определите новый класс, который представляет круг и предоставляет метод «Draw».\n", + "Затем вы можете использовать полиморфизм для рисования линий, прямоугольников и кругов.\n" ] }, { @@ -908,15 +908,15 @@ "id": "74d1b48f", "metadata": {}, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "In this chapter, we ran into a subtle bug that happened because we created a `Point` that was shared by two `Rectangle` objects, and then we modified the `Point`.\n", - "In general, there are two ways to avoid problems like this: you can avoid sharing objects or you can avoid modifying them.\n", + "В этой главе мы столкнулись с тонкой ошибкой, которая произошла, потому что мы создали «точку», которая была разделена двумя объектами «прямоугольника», а затем мы изменили «точку».\n", + "В целом, есть два способа избежать таких проблем, как это: вы можете избежать обмена объектами, или вы можете избежать их изменения.\n", "\n", - "To avoid sharing objects, you can use deep copy, as we did in this chapter.\n", + "Чтобы избежать обмена объектами, вы можете использовать Deep Copy, как мы делали в этой главе.\n", "\n", - "To avoid modifying objects, consider replacing impure functions like `translate` with pure functions like `translated`.\n", - "For example, here's a version of `translated` that creates a new `Point` and never modifies its attributes." + "Чтобы избежать изменения объектов, рассмотрите возможность замены нечистых функций, таких как `translate` на чистые функции, такие как` transted`.\n", + "Например, вот версия `translated`, которая создает новую« точку »и никогда не изменяет свои атрибуты.\n" ] }, { @@ -932,11 +932,11 @@ "id": "76972167", "metadata": {}, "source": [ - "Python provides features that make it easier to avoid modifying objects.\n", - "They are beyond the scope of this book, but if you are curious, ask a virtual assistant, \"How do I make a Python object immutable?\"\n", + "Python предоставляет функции, которые облегчают избегать изменения объектов.\n", + "Они выходят за рамки этой книги, но если вам любопытно, спросите виртуального помощника: «Как сделать объект Python неизменным?»\n", "\n", - "Creating a new object takes more time than modifying an existing one, but the difference seldom matters in practice.\n", - "Programs that avoid shared objects and impure functions are often easier to develop, test, and debug -- and the best kind of debugging is the kind you don't have to do." + "Создание нового объекта занимает больше времени, чем изменение существующего, но разница редко имеет значение на практике.\n", + "Программы, которые избегают общих объектов и нечистых функций, часто проще в разработке, тестировании и отладке - и лучший вид отладки - это тот вид, который вам не нужно делать.\n" ] }, { @@ -944,16 +944,16 @@ "id": "02106995", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**shallow copy:**\n", - "A copy operation that does not copy nested objects.\n", + "** мелкая копия: **\n", + "Операция копирования, которая не копирует вложенные объекты.\n", "\n", - "**deep copy:**\n", - "A copy operation that also copies nested objects.\n", + "** Глубокая копия: **\n", + "Операция копирования, которая также копирует вложенные объекты.\n", "\n", - "**polymorphism:**\n", - "The ability of a method or operator to work with multiple types of objects." + "**полиморфизм:**\n", + "Способность метода или оператора работать с несколькими типами объектов.\n" ] }, { @@ -961,7 +961,7 @@ "id": "09dd41c1", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения\n" ] }, { @@ -979,10 +979,10 @@ "id": "da0aea86", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "For all of the following exercises, consider asking a virtual assistant for help.\n", - "If you do, you'll want include as part of the prompt the class definitions for `Point`, `Line`, and `Rectangle` -- otherwise the VA will make a guess about their attributes and functions, and the code it generates won't work." + "Для всех следующих упражнений подумайте о том, чтобы попросить виртуального помощника за помощью.\n", + "Если вы это сделаете, вы захотите включить как часть подсказки определения класса для `point`,` line 'и `rectangle' - в противном случае VA догадается об их атрибутах и функциях, и код, который он генерирует, не будет работать.\n" ] }, { @@ -990,9 +990,9 @@ "id": "7721e47b", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write an `__eq__` method for the `Line` class that returns `True` if the `Line` objects refer to `Point` objects that are equivalent, in either order." + "Напишите метод `__eq__` для класса` line`, который возвращает `true`, если объекты` line 'относятся к объектам `point`, которые эквивалентны, в любом порядке.\n" ] }, { @@ -1002,7 +1002,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Вы можете использовать следующий план, чтобы начать.\n" ] }, { @@ -1032,7 +1032,7 @@ "tags": [] }, "source": [ - "You can use these examples to test your code." + "Вы можете использовать эти примеры для проверки вашего кода.\n" ] }, { @@ -1052,7 +1052,7 @@ "tags": [] }, "source": [ - "This example should be `True` because the `Line` objects refer to `Point` objects that are equivalent, in the same order." + "Этот пример должен быть «true», потому что объекты `line 'относятся к объектам« точка », которые эквивалентны, в том же порядке.\n" ] }, { @@ -1072,7 +1072,7 @@ "tags": [] }, "source": [ - "This example should be `True` because the `Line` objects refer to `Point` objects that are equivalent, in reverse order." + "Этот пример должен быть «true», потому что объекты `line 'относятся к объектам« точка », которые эквивалентны в обратном порядке.\n" ] }, { @@ -1092,7 +1092,7 @@ "tags": [] }, "source": [ - "Equivalence should always be transitive -- that is, if `line_a` and `line_b` are equivalent, and `line_a` and `line_c` are equivalent, then `line_b` and `line_c` should also be equivalent." + "Эквивалентность всегда должна быть переходной - то есть, если `line_a` и` line_b` эквивалентны, а `line_a` и` line_c` эквивалентны, тогда также должны быть эквивалентны `line_b` и` line_c`.\n" ] }, { @@ -1112,7 +1112,7 @@ "tags": [] }, "source": [ - "This example should be `False` because the `Line` objects refer to `Point` objects that are not equivalent." + "Этот пример должен быть «false», потому что объекты `line 'относятся к объектам« точка », которые не являются эквивалентными.\n" ] }, { @@ -1130,9 +1130,9 @@ "id": "0e629491", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a `Line` method called `midpoint` that computes the midpoint of a line segment and returns the result as a `Point` object." + "Напишите метод `line` с именем` midpoint`, который вычисляет среднюю точку сегмента линии и возвращает результат как объект `point '.\n" ] }, { @@ -1142,7 +1142,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Вы можете использовать следующий план, чтобы начать.\n" ] }, { @@ -1172,7 +1172,7 @@ "tags": [] }, "source": [ - "You can use the following examples to test your code and draw the result." + "Вы можете использовать следующие примеры для проверки вашего кода и набрать результат.\n" ] }, { @@ -1230,9 +1230,9 @@ "id": "0518c200", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a `Rectangle` method called `midpoint` that find the point in the center of a rectangle and returns the result as a `Point` object." + "Напишите метод «прямоугольник», называемый «Midpoint», который находит точку в центре прямоугольника и возвращает результат в качестве объекта «точка».\n" ] }, { @@ -1242,7 +1242,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Вы можете использовать следующий план, чтобы начать.\n" ] }, { @@ -1272,7 +1272,7 @@ "tags": [] }, "source": [ - "You can use the following example to test your code." + "Вы можете использовать следующий пример для проверки вашего кода.\n" ] }, { @@ -1320,15 +1320,15 @@ "id": "00cbc4d9", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a `Rectangle` method called `make_cross` that:\n", + "Напишите метод `rectangle 'с именем` make_cross`, который:\n", "\n", - "1. Uses `make_lines` to get a list of `Line` objects that represent the four sides of the rectangle.\n", + "1. использует `make_lines`, чтобы получить список объектов` line`, которые представляют четыре стороны прямоугольника.\n", "\n", - "2. Computes the midpoints of the four lines.\n", + "2. Вычисляет средние точки четырех линий.\n", "\n", - "3. Makes and returns a list of two `Line` objects that represent lines connecting opposite midpoints, forming a cross through the middle of the rectangle." + "3. составляет и возвращает список из двух объектов `line`, которые представляют строки, соединяющие противоположные средние точки, образуя крест через середину прямоугольника.\n" ] }, { @@ -1338,7 +1338,7 @@ "tags": [] }, "source": [ - "You can use this outline to get started." + "Вы можете использовать этот контур, чтобы начать.\n" ] }, { @@ -1368,7 +1368,7 @@ "tags": [] }, "source": [ - "You can use the following example to test your code." + "Вы можете использовать следующий пример для проверки вашего кода.\n" ] }, { @@ -1406,10 +1406,10 @@ "id": "0f707fe3", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a definition for a class named `Circle` with attributes `center` and `radius`, where `center` is a Point object and `radius` is a number.\n", - "Include special methods `__init__` and a `__str__`, and a method called `draw` that uses `jupyturtle` functions to draw the circle." + "Напишите определение для класса с именем `circle` с атрибутами` center` и `radius`, где` center ' - это точечный объект, а `radius` - это число.\n", + "Включите специальные методы `__init__` и` __str__`, и метод, называемый `draw`, который использует функции` jupyturtle` для рисования круга.\n" ] }, { @@ -1419,7 +1419,7 @@ "tags": [] }, "source": [ - "You can use the following function, which is a version of the `circle` function we wrote in Chapter 4." + "Вы можете использовать следующую функцию, которая является версией функции `Circle ', которую мы написали в главе 4.\n" ] }, { @@ -1447,8 +1447,8 @@ "tags": [] }, "source": [ - "You can use the following example to test your code.\n", - "We'll start with a square `Rectangle` with width and height `100`." + "Вы можете использовать следующий пример для проверки вашего кода.\n", + "Мы начнем с квадратной `rectangle 'с шириной и высотой` 100'.\n" ] }, { @@ -1468,7 +1468,7 @@ "tags": [] }, "source": [ - "The following code should create a `Circle` that fits inside the square." + "Следующий код должен создать «кружок», который вписывается в квадрат.\n" ] }, { @@ -1488,7 +1488,7 @@ "tags": [] }, "source": [ - "If everything worked correctly, the following code should draw the circle inside the square (touching on all four sides)." + "Если все сработало правильно, следующий код должен нарисовать круг внутри квадрата (касаясь всех четырех сторон).\n" ] }, { @@ -1516,13 +1516,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT] (https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik\n" ] } ], @@ -1548,4 +1548,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From d3858d7f40161968ed36f53322978a1fab77df67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:11:47 +0300 Subject: [PATCH 17/44] Translate first markdown cells in chap06 --- blank/chap06.ipynb | 111 ++++++++++++++++++++++----------------------- 1 file changed, 55 insertions(+), 56 deletions(-) diff --git a/blank/chap06.ipynb b/blank/chap06.ipynb index 7fadc4e..63985b4 100644 --- a/blank/chap06.ipynb +++ b/blank/chap06.ipynb @@ -5,8 +5,7 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Печатную и электронную версии книги *Think Python 3e* можно заказать на [Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -25,16 +24,16 @@ "id": "88ecc443", "metadata": {}, "source": [ - "# Return Values\n", + "# Возвращаемые значения\n", "\n", - "In previous chapters, we've used built-in functions -- like `abs` and `round` -- and functions in the math module -- like `sqrt` and `pow`.\n", - "When you call one of these functions, it returns a value you can assign to a variable or use as part of an expression.\n", + "В предыдущих главах мы использовали встроенные функции, такие как `abs` и `round`, а также функции из модуля math, например `sqrt` и `pow`.\n", + "Вызывая такую функцию, мы получаем значение, которое можно присвоить переменной или использовать в выражении.\n", "\n", - "The functions we have written so far are different.\n", - "Some use the `print` function to display values, and some use turtle functions to draw figures.\n", - "But they don't return values we assign to variables or use in expressions.\n", + "Функции, написанные нами до сих пор, отличаются.\n", + "Некоторые используют `print` для вывода значений, а другие рисуют фигуры с помощью turtle.\n", + "Но они не возвращают значения, которые можно присвоить переменным или использовать в выражениях.\n", "\n", - "In this chapter, we'll see how to write functions that return values." + "В этой главе мы узнаем, как писать функции, которые возвращают значения." ] }, { @@ -42,10 +41,10 @@ "id": "6cf2cf80", "metadata": {}, "source": [ - "## Some functions have return values\n", + "## Некоторые функции возвращают значения\n", "\n", - "When you call a function like `math.sqrt`, the result is called a **return value**.\n", - "If the function call appears at the end of a cell, Jupyter displays the return value immediately." + "Когда вы вызываете функцию вроде `math.sqrt`, результат называется **возвращаемым значением**.\n", + "Если вызов функции стоит в конце ячейки, Jupyter сразу выводит возвращаемое значение." ] }, { @@ -61,7 +60,7 @@ "id": "4b4885c2", "metadata": {}, "source": [ - "If you assign the return value to a variable, it doesn't get displayed." + "Если присвоить возвращаемое значение переменной, оно не отображается." ] }, { @@ -77,7 +76,7 @@ "id": "196c692b", "metadata": {}, "source": [ - "But you can display it later." + "Но его можно вывести позже." ] }, { @@ -93,7 +92,7 @@ "id": "257b28d5", "metadata": {}, "source": [ - "Or you can use the return value as part of an expression." + "Или можно использовать возвращаемое значение как часть выражения." ] }, { @@ -109,7 +108,7 @@ "id": "23ed47ab", "metadata": {}, "source": [ - "Here's an example of a function that returns a value." + "Вот пример функции, которая возвращает значение." ] }, { @@ -125,11 +124,11 @@ "id": "273acabc", "metadata": {}, "source": [ - "`circle_area` takes `radius` as a parameter and computes the area of a circle with that radius.\n", + "`circle_area` принимает параметр `radius` и вычисляет площадь круга с этим радиусом.\n", "\n", - "The last line is a `return` statement that returns the value of `area`.\n", + "Последняя строка — это оператор `return`, который возвращает значение `area`.\n", "\n", - "If we call the function like this, Jupyter displays the return value.\n" + "Если вызвать функцию так, Jupyter покажет возвращаемое значение.\n" ] }, { @@ -145,7 +144,7 @@ "id": "4f28bfd6", "metadata": {}, "source": [ - "We can assign the return value to a variable." + "Мы можем присвоить возвращаемое значение переменной." ] }, { @@ -161,7 +160,7 @@ "id": "3f82fe70", "metadata": {}, "source": [ - "Or use it as part of an expression." + "Или использовать его в составе выражения." ] }, { @@ -177,7 +176,7 @@ "id": "15122fd2", "metadata": {}, "source": [ - "Later we can display the value of the variable we assigned the result to." + "Позже мы можем вывести значение переменной, в которую сохранили результат." ] }, { @@ -193,7 +192,7 @@ "id": "a3f6dcae", "metadata": {}, "source": [ - "But we can't access `area`." + "Но мы не можем обратиться к `area`." ] }, { @@ -211,7 +210,7 @@ "id": "f8ace9ce", "metadata": {}, "source": [ - "`area` is a local variable in a function, so we can't access it from outside the function." + "`area` — это локальная переменная функции, поэтому извне мы к ней обратиться не можем." ] }, { @@ -219,10 +218,10 @@ "id": "41a4f03f", "metadata": {}, "source": [ - "## And some have None\n", + "## А некоторые возвращают None\n", "\n", - "If a function doesn't have a `return` statement, it returns `None`, which is a special value like `True` and `False`.\n", - "For example, here's the `repeat` function from Chapter 3." + "Если в функции нет оператора `return`, она возвращает `None` — специальное значение вроде `True` и `False`.\n", + "Например, вот функция `repeat` из главы 3." ] }, { @@ -238,7 +237,7 @@ "id": "6ada19cf", "metadata": {}, "source": [ - "If we call it like this, it displays the first line of the Monty Python song \"Finland\"." + "Если вызвать её так, она выведет первую строку песни Монти Пайтона «Finland»." ] }, { @@ -254,8 +253,8 @@ "id": "fe49f5e5", "metadata": {}, "source": [ - "This function uses the `print` function to display a string, but it does not use a `return` statement to return a value.\n", - "If we assign the result to a variable, it displays the string anyway. " + "Эта функция использует `print`, чтобы вывести строку, но не содержит оператора `return`, возвращающего значение.\n", + "Если мы присвоим результат переменной, строка всё равно отобразится." ] }, { @@ -271,7 +270,7 @@ "id": "4ecabbdb", "metadata": {}, "source": [ - "And if we display the value of the variable, we get nothing." + "И если вывести значение переменной, ничего не появится." ] }, { @@ -287,8 +286,8 @@ "id": "07033959", "metadata": {}, "source": [ - "`result` actually has a value, but Jupyter doesn't show it.\n", - "However, we can display it like this." + "`result` на самом деле содержит значение, но Jupyter его не показывает.\n", + "Однако мы можем вывести его так." ] }, { @@ -304,9 +303,9 @@ "id": "379b98c5", "metadata": {}, "source": [ - "The return value from `repeat` is `None`.\n", + "Возвращаемое значение функции `repeat` — `None`.\n", "\n", - "Now here's a function similar to `repeat` except that has a return value." + "Теперь посмотрим на похожую функцию, только она возвращает значение." ] }, { @@ -322,10 +321,10 @@ "id": "db6ad3d4", "metadata": {}, "source": [ - "Notice that we can use an expression in a `return` statement, not just a variable.\n", + "Обратите внимание, что в операторе `return` можно использовать выражение, а не только переменную.\n", "\n", - "With this version, we can assign the result to a variable.\n", - "When the function runs, it doesn't display anything." + "С этой версией мы можем присвоить результат переменной.\n", + "Когда функция выполняется, она ничего не выводит." ] }, { @@ -341,7 +340,7 @@ "id": "1232cd8a", "metadata": {}, "source": [ - "But later we can display the value assigned to `line`." + "Но позже мы можем вывести значение, сохранённое в `line`." ] }, { @@ -357,7 +356,7 @@ "id": "ae02c7d2", "metadata": {}, "source": [ - "A function like this is called a **pure function** because it doesn't display anything or have any other effect -- other than returning a value." + "Такая функция называется **чистой** — она ничего не выводит и не делает ничего другого, кроме возврата значения." ] }, { @@ -365,9 +364,9 @@ "id": "567ae734", "metadata": {}, "source": [ - "## Return values and conditionals\n", + "## Возвращаемые значения и условные операторы\n", "\n", - "If Python did not provide `abs`, we could write it like this." + "Если бы в Python не было `abs`, мы могли бы написать её так." ] }, { @@ -383,12 +382,12 @@ "id": "ffd559b8", "metadata": {}, "source": [ - "If `x` is negative, the first `return` statement returns `-x` and the function ends immediately.\n", - "Otherwise, the second `return` statement returns `x` and the function ends.\n", - "So this function is correct.\n", + "Если `x` отрицателен, первый оператор `return` возвращает `-x`, и функция немедленно заканчивается.\n", + "Иначе второй `return` возвращает `x`, и функция завершается.\n", + "Так что функция работает правильно.\n", "\n", - "However, if you put `return` statements in a conditional, you have to make sure that every possible path through the program hits a `return` statement.\n", - "For example, here's an incorrect version of `absolute_value`." + "Однако, помещая `return` в условный оператор, нужно убедиться, что любая ветка программы приводит к выполнению `return`.\n", + "Например, вот некорректная версия `absolute_value`." ] }, { @@ -404,7 +403,7 @@ "id": "da3280ae", "metadata": {}, "source": [ - "Here's what happens if we call this function with `0` as an argument." + "Вот что произойдёт, если вызвать эту функцию с аргументом `0`." ] }, { @@ -420,9 +419,9 @@ "id": "5733f239", "metadata": {}, "source": [ - "We get nothing! Here's the problem: when `x` is `0`, neither condition is true, and the function ends without hitting a `return` statement, which means that the return value is `None`, so Jupyter displays nothing.\n", + "Мы ничего не получаем! В чём проблема: когда `x` равно `0`, ни одно условие не выполняется, и функция завершается без `return`, поэтому возвращается `None`, и Jupyter ничего не показывает.\n", "\n", - "As another example, here's a version of `absolute_value` with an extra `return` statement at the end." + "Вот ещё пример — версия `absolute_value` с лишним оператором `return` в конце." ] }, { @@ -438,12 +437,12 @@ "id": "cf5486fd", "metadata": {}, "source": [ - "If `x` is negative, the first `return` statement runs and the function ends.\n", - "Otherwise the second `return` statement runs and the function ends.\n", - "Either way, we never get to the third `return` statement -- so it can never run.\n", + "Если `x` отрицателен, выполняется первый `return`, и функция завершается.\n", + "Иначе выполняется второй `return`, и функция тоже завершается.\n", + "Так или иначе мы никогда не добираемся до третьего `return` — он никогда не исполнится.\n", "\n", - "Code that can never run is called **dead code**.\n", - "In general, dead code doesn't do any harm, but it often indicates a misunderstanding, and it might be confusing to someone trying to understand the program." + "Код, который никогда не выполняется, называется **мёртвым кодом**.\n", + "Обычно он не приносит вреда, но часто указывает на недопонимание и может сбивать с толку тех, кто пытается разобраться в программе." ] }, { @@ -1694,4 +1693,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 66a163b147bde0cd5c269fa3908826e7a36d9f9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:29:22 +0300 Subject: [PATCH 18/44] Translate notebook cells 50-99 in chap06 --- blank/chap06.ipynb | 202 ++++++++++++++++++++++----------------------- 1 file changed, 97 insertions(+), 105 deletions(-) diff --git a/blank/chap06.ipynb b/blank/chap06.ipynb index 63985b4..0c0c90f 100644 --- a/blank/chap06.ipynb +++ b/blank/chap06.ipynb @@ -452,22 +452,21 @@ "tags": [] }, "source": [ - "## Incremental development\n", + "## Инкрементальная разработка\n", "\n", - "As you write larger functions, you might find yourself spending more\n", - "time debugging.\n", - "To deal with increasingly complex programs, you might want to try **incremental development**, which is a way of adding and testing only a small amount of code at a time.\n", + "По мере того как вы пишете более крупные функции, вы можете заметить, что тратите все больше времени на отладку.\n", + "Чтобы справляться с всё более сложными программами, имеет смысл попробовать **инкрементальную разработку** — подход, при котором вы добавляете и проверяете лишь небольшое количество кода за один раз.\n", "\n", - "As an example, suppose you want to find the distance between two points represented by the coordinates $(x_1, y_1)$ and $(x_2, y_2)$.\n", - "By the Pythagorean theorem, the distance is:\n", + "Предположим, например, что вы хотите найти расстояние между двумя точками с координатами $(x_1, y_1)$ и $(x_2, y_2)$.\n", + "По теореме Пифагора это расстояние равно:\n", "\n", "$$\\mathrm{distance} = \\sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$$ \n", "\n", - "The first step is to consider what a `distance` function should look like in Python -- that is, what are the inputs (parameters) and what is the output (return value)?\n", + "Первый шаг — определить, как должна выглядеть функция `distance` на Python, то есть какие данные она принимает (параметры) и что возвращает (значение).\n", "\n", - "For this function, the inputs are the coordinates of the points.\n", - "The return value is the distance.\n", - "Immediately you can write an outline of the function:" + "В нашем случае параметрами будут координаты точек.\n", + "Возвращаемым значением — расстояние между ними.\n", + "Сразу можно набросать заготовку функции:" ] }, { @@ -483,10 +482,10 @@ "id": "7b384fcf", "metadata": {}, "source": [ - "This version doesn't compute distances yet -- it always returns zero.\n", - "But it is a complete function with a return value, which means that you can test it before you make it more complicated.\n", + "Эта версия ещё не вычисляет расстояние — она всегда возвращает ноль.\n", + "Тем не менее это полноценная функция с возвращаемым значением, что позволяет протестировать её до усложнения кода.\n", "\n", - "To test the new function, we'll call it with sample arguments:" + "Чтобы проверить новую функцию, вызовем её с примерными аргументами:" ] }, { @@ -502,13 +501,12 @@ "id": "13a98096", "metadata": {}, "source": [ - "I chose these values so that the horizontal distance is `3` and the\n", - "vertical distance is `4`.\n", - "That way, the result is `5`, the hypotenuse of a `3-4-5` right triangle. When testing a function, it is useful to know the right answer.\n", + "Я выбрал такие значения, чтобы горизонтальная дистанция была `3`, а вертикальная — `4`.\n", + "Тогда результат равен `5` — гипотенузе прямоугольного треугольника `3-4-5`. При тестировании функции полезно знать правильный ответ.\n", "\n", - "At this point we have confirmed that the function runs and returns a value, and we can start adding code to the body.\n", - "A good next step is to find the differences `x2 - x1` and `y2 - y1`. \n", - "Here's a version that stores those values in temporary variables and displays them." + "На этом этапе мы убедились, что функция выполняется и возвращает значение, поэтому можем начать добавлять код в её тело.\n", + "Хороший следующий шаг — вычислить разности `x2 - x1` и `y2 - y1`. \n", + "Ниже приведена версия, которая сохраняет их во временных переменных и выводит на экран." ] }, { @@ -524,10 +522,9 @@ "id": "c342a3bd", "metadata": {}, "source": [ - "If the function is working, it should display `dx is 3` and `dy is 4`.\n", - "If so, we know that the function is getting the right arguments and\n", - "performing the first computation correctly. If not, there are only a few\n", - "lines to check." + "Если функция работает правильно, она должна вывести `dx is 3` и `dy is 4`.\n", + "В этом случае мы уверены, что функция получает верные аргументы и\n", + "корректно выполняет первый расчёт. Если нет — проверять придётся лишь несколько строк кода." ] }, { @@ -543,7 +540,7 @@ "id": "9424eca9", "metadata": {}, "source": [ - "Good so far. Next we compute the sum of squares of `dx` and `dy`:" + "Пока всё хорошо. Далее вычислим сумму квадратов `dx` и `dy`:" ] }, { @@ -559,7 +556,7 @@ "id": "e28262f9", "metadata": {}, "source": [ - "Again, we can run the function and check the output, which should be `25`. " + "Снова запускаем функцию и проверяем вывод — он должен быть равен `25`." ] }, { @@ -575,7 +572,7 @@ "id": "c09f0ddc", "metadata": {}, "source": [ - "Finally, we can use `math.sqrt` to compute the distance:" + "Наконец, используем `math.sqrt`, чтобы вычислить расстояние:" ] }, { @@ -591,7 +588,7 @@ "id": "f27902ac", "metadata": {}, "source": [ - "And test it." + "И протестируем её." ] }, { @@ -607,9 +604,9 @@ "id": "8ad2e626", "metadata": {}, "source": [ - "The result is correct, but this version of the function displays the result rather than returning it, so the return value is `None`.\n", + "Результат правильный, но эта версия функции выводит его, а не возвращает, поэтому значение функции — `None`.\n", "\n", - "We can fix that by replacing the `print` function with a `return` statement." + "Исправить это можно, заменив `print` на оператор `return`." ] }, { @@ -625,8 +622,8 @@ "id": "f3a13a14", "metadata": {}, "source": [ - "This version of `distance` is a pure function.\n", - "If we call it like this, only the result is displayed." + "Эта версия `distance` является чистой функцией.\n", + "Если вызвать её так, будет выведен только результат." ] }, { @@ -642,7 +639,7 @@ "id": "7db8cf86", "metadata": {}, "source": [ - "And if we assign the result to a variable, nothing is displayed." + "А если присвоить результат переменной, ничего не будет выведено." ] }, { @@ -658,20 +655,20 @@ "id": "0c3b8829", "metadata": {}, "source": [ - "The `print` statements we wrote are useful for debugging, but once the function is working, we can remove them. \n", - "Code like that is called **scaffolding** because it is helpful for building the program but is not part of the final product.\n", + "Инструкции `print`, которые мы писали, полезны при отладке, но когда функция начинает работать, их можно убрать. \n", + "Такой код называют **строительными лесами** (scaffolding): он помогает при разработке, но не нужен в итоговой версии программы.\n", "\n", - "This example demonstrates incremental development.\n", - "The key aspects of this process are:\n", + "Этот пример демонстрирует инкрементальную разработку.\n", + "Основные её моменты:\n", "\n", - "1. Start with a working program, make small changes, and test after every change.\n", + "1. Начинайте с рабочей программы, вносите небольшие изменения и проверяйте их после каждого шага.\n", "\n", - "2. Use variables to hold intermediate values so you can display and check them.\n", + "2. Используйте переменные для хранения промежуточных значений, чтобы их можно было вывести и проверить.\n", "\n", - "3. Once the program is working, remove the scaffolding.\n", + "3. Когда программа заработает, удалите «строительные леса».\n", "\n", - "At any point, if there is an error, you should have a good idea where it is.\n", - "Incremental development can save you a lot of debugging time." + "В любой момент при появлении ошибки вы должны хорошо представлять, где она может быть.\n", + "Инкрементальная разработка может сэкономить вам много времени на отладку." ] }, { @@ -679,10 +676,10 @@ "id": "3dd7514f", "metadata": {}, "source": [ - "## Boolean functions\n", + "## Логические функции\n", "\n", - "Functions can return the boolean values `True` and `False`, which is often convenient for encapsulating a complex test in a function.\n", - "For example, `is_divisible` checks whether `x` is divisible by `y` with no remainder." + "Функции могут возвращать логические значения `True` и `False`, что удобно, когда нужно заключить сложную проверку в отдельную функцию.\n", + "Например, `is_divisible` определяет, делится ли `x` на `y` без остатка." ] }, { @@ -698,7 +695,7 @@ "id": "f3a58afb", "metadata": {}, "source": [ - "Here's how we use it." + "Вот как её можно использовать." ] }, { @@ -722,8 +719,7 @@ "id": "e9103ece", "metadata": {}, "source": [ - "Inside the function, the result of the `==` operator is a boolean, so we can write the\n", - "function more concisely by returning it directly." + "Внутри функции результат оператора `==` — логическое значение, поэтому код можно сократить, просто возвращая его." ] }, { @@ -739,7 +735,7 @@ "id": "4d82dae5", "metadata": {}, "source": [ - "Boolean functions are often used in conditional statements." + "Логические функции часто используются в условных операторах." ] }, { @@ -755,7 +751,7 @@ "id": "9e232afc", "metadata": {}, "source": [ - "It might be tempting to write something like this:" + "Может возникнуть соблазн написать так:" ] }, { @@ -771,7 +767,7 @@ "id": "ff9e5160", "metadata": {}, "source": [ - "But the comparison is unnecessary." + "Но такое сравнение лишнее." ] }, { @@ -779,27 +775,27 @@ "id": "a932a966", "metadata": {}, "source": [ - "## Recursion with return values\n", + "## Рекурсия с возвращаемым значением\n", "\n", - "Now that we can write functions with return values, we can write recursive functions with return values, and with that capability, we have passed an important threshold -- the subset of Python we have is now **Turing complete**, which means that we can perform any computation that can be described by an algorithm.\n", + "Теперь, когда мы умеем писать функции, возвращающие значения, мы можем писать и рекурсивные функции с возвращаемыми значениями. Благодаря этому мы преодолели важный порог — доступное нам подмножество Python стало **тюринг-полным**, то есть способным выполнять любой алгоритм.\n", "\n", - "To demonstrate recursion with return values, we'll evaluate a few recursively defined mathematical functions.\n", - "A recursive definition is similar to a circular definition, in the sense that the definition refers to the thing being defined. A truly circular definition is not very useful:\n", + "Чтобы показать рекурсию с возвращаемым значением, вычислим несколько рекурсивно определённых математических функций.\n", + "Рекурсивное определение похоже на круговое, поскольку в нём говорится о самом определяемом объекте. Настоящее круговое определение бесполезно:\n", "\n", - "> vorpal: An adjective used to describe something that is vorpal.\n", + "> vorpal: прилагательное, описывающее нечто vorpal.\n", "\n", - "If you saw that definition in the dictionary, you might be annoyed. \n", - "On the other hand, if you looked up the definition of the factorial function, denoted with the symbol $!$, you might get something like this: \n", + "Увидев такое определение в словаре, вы, возможно, расстроитесь. \n", + "С другой стороны, если вы откроете определение факториала, обозначаемого символом $!$, то увидите примерно следующее: \n", "\n", "$$\\begin{aligned}\n", - "0! &= 1 \\\\\n", + "0! &= 1 \\\n", "n! &= n~(n-1)!\n", "\\end{aligned}$$ \n", "\n", - "This definition says that the factorial of $0$ is $1$, and the factorial of any other value, $n$, is $n$ multiplied by the factorial of $n-1$.\n", + "Это определение говорит, что факториал числа $0$ равен $1$, а факториал любого другого $n$ равен $n$, умноженному на факториал $n-1$.\n", "\n", - "If you can write a recursive definition of something, you can write a Python program to evaluate it. \n", - "Following an incremental development process, we'll start with a function that take `n` as a parameter and always returns `0`." + "Если вы можете дать рекурсивное определение, то можете написать и программу на Python, вычисляющую его. \n", + "Следуя принципам инкрементальной разработки, начнём с функции, которая принимает `n` и всегда возвращает `0`." ] }, { @@ -815,7 +811,7 @@ "id": "ee1f63b8", "metadata": {}, "source": [ - "Now let's add the first part of the definition -- if the argument happens to be `0`, all we have to do is return `1`:" + "Теперь добавим первую часть определения: если аргумент равен `0`, нужно просто вернуть `1`:" ] }, { @@ -831,8 +827,7 @@ "id": "4f2fd7c7", "metadata": {}, "source": [ - "Now let's fill in the second part -- if `n` is not `0`, we have to make a recursive\n", - "call to find the factorial of `n-1` and then multiply the result by `n`:" + "Теперь заполним вторую часть: если `n` не равно `0`, нужно вызвать функцию рекурсивно, чтобы найти факториал `n-1`, а затем умножить результат на `n`:" ] }, { @@ -848,32 +843,29 @@ "id": "da3d1595", "metadata": {}, "source": [ - "The flow of execution for this program is similar to the flow of `countdown` in Chapter 5.\n", - "If we call `factorial` with the value `3`:\n", + "Ход выполнения этой программы похож на то, как работала `countdown` в Главе 5.\n", + "Если вызвать `factorial` со значением `3`:\n", "\n", - "Since `3` is not `0`, we take the second branch and calculate the factorial\n", - "of `n-1`\\...\n", + "Поскольку `3` не равно `0`, выбирается вторая ветка и вычисляется факториал `n-1`...\n", "\n", - "> Since `2` is not `0`, we take the second branch and calculate the\n", - "> factorial of `n-1`\\...\n", + "> Так как `2` не равно `0`, снова выбирается вторая ветка и вычисляется\n", + "> факториал `n-1`...\n", ">\n", - "> > Since `1` is not `0`, we take the second branch and calculate the\n", - "> > factorial of `n-1`\\...\n", + "> > Поскольку `1` не равно `0`, мы опять выбираем вторую ветку и вычисляем\n", + "> > факториал `n-1`...\n", "> >\n", - "> > > Since `0` equals `0`, we take the first branch and return `1` without\n", - "> > > making any more recursive calls.\n", + "> > > Так как `0` равно `0`, выполняется первая ветка и возвращается `1` без\n", + "> > > дальнейших рекурсивных вызовов.\n", "> >\n", - "> > The return value, `1`, is multiplied by `n`, which is `1`, and the\n", - "> > result is returned.\n", + "> > Возвращённое значение `1` умножается на `n`, которое равно `1`, и результат\n", + "> > возвращается.\n", ">\n", - "> The return value, `1`, is multiplied by `n`, which is `2`, and the result\n", - "> is returned.\n", + "> Возвращённое значение `1` умножается на `n`, которое равно `2`, и результат\n", + "> возвращается.\n", "\n", - "The return value `2` is multiplied by `n`, which is `3`, and the result,\n", - "`6`, becomes the return value of the function call that started the whole\n", - "process.\n", + "Значение `2` умножается на `n`, равное `3`, и итог `6` становится возвращаемым значением из самого первого вызова функции.\n", "\n", - "The following figure shows the stack diagram for this sequence of function calls." + "На следующем рисунке показана диаграмма стека для этой последовательности вызовов." ] }, { @@ -901,10 +893,10 @@ "id": "f924c539", "metadata": {}, "source": [ - "The return values are shown being passed back up the stack.\n", - "In each frame, the return value is the product of `n` and `recurse`.\n", + "На диаграмме видно, как возвращаемые значения передаются обратно вверх по стеку.\n", + "В каждом кадре возвращаемое значение — это произведение `n` и `recurse`.\n", "\n", - "In the last frame, the local variable `recurse` does not exist because the branch that creates it does not run." + "В последнем кадре локальной переменной `recurse` нет, потому что ветка, в которой она создаётся, не выполнялась." ] }, { @@ -912,20 +904,20 @@ "id": "acea9dc1", "metadata": {}, "source": [ - "## Leap of faith\n", + "## Прыжок веры\n", "\n", - "Following the flow of execution is one way to read programs, but it can quickly become overwhelming. An alternative is what I call the \"leap of faith\". When you come to a function call, instead of following the flow of execution, you *assume* that the function works correctly and returns the right result.\n", + "Прослеживать ход выполнения — один из способов читать программы, но он быстро становится непосильным. Альтернативой является то, что я называю «прыжком веры». Когда вы сталкиваетесь с вызовом функции, вместо того чтобы следовать за исполнением, вы *предполагаете*, что функция работает правильно и возвращает нужный результат.\n", "\n", - "In fact, you are already practicing this leap of faith when you use built-in functions.\n", - "When you call `abs` or `math.sqrt`, you don't examine the bodies of those functions -- you just assume that they work.\n", + "На самом деле вы уже практикуете этот прыжок веры, когда пользуетесь встроенными функциями.\n", + "Вызывая `abs` или `math.sqrt`, вы не заглядываете в их тела — просто считаете, что они корректны.\n", "\n", - "The same is true when you call one of your own functions. For example, earlier we wrote a function called `is_divisible` that determines whether one number is divisible by another. Once we convince ourselves that this function is correct, we can use it without looking at the body again.\n", + "То же самое относится и к вашим собственным функциям. Например, ранее мы написали функцию `is_divisible`, определяющую, делится ли одно число на другое. Убедившись, что она верна, можно использовать её, больше не заглядывая внутрь.\n", "\n", - "The same is true of recursive programs.\n", - "When you get to the recursive call, instead of following the flow of execution, you should assume that the recursive call works and then ask yourself, \"Assuming that I can compute the factorial of $n-1$, can I compute the factorial of $n$?\"\n", - "The recursive definition of factorial implies that you can, by multiplying by $n$.\n", + "Так же обстоит дело и с рекурсивными программами.\n", + "Добравшись до рекурсивного вызова, вместо следования за исполнением стоит предположить, что он сработает, и спросить себя: «Если я умею вычислять факториал $(n-1)$, смогу ли я вычислить факториал $n$?»\n", + "Рекурсивное определение факториала утверждает, что сможем — нужно просто умножить на $n$.\n", "\n", - "Of course, it's a bit strange to assume that the function works correctly when you haven't finished writing it, but that's why it's called a leap of faith!" + "Конечно, немного странно предполагать корректность функции, которую вы ещё не дописали, но именно поэтому это и называется прыжком веры!" ] }, { @@ -935,17 +927,17 @@ "tags": [] }, "source": [ - "## Fibonacci\n", + "## Фибоначчи\n", "\n", - "After `factorial`, the most common example of a recursive function is `fibonacci`, which has the following definition: \n", + "После факториала самым известным примером рекурсивной функции является `fibonacci`, определяемая так:\n", "\n", "$$\\begin{aligned}\n", - "\\mathrm{fibonacci}(0) &= 0 \\\\\n", - "\\mathrm{fibonacci}(1) &= 1 \\\\\n", + "\\mathrm{fibonacci}(0) &= 0 \\\n", + "\\mathrm{fibonacci}(1) &= 1 \\\n", "\\mathrm{fibonacci}(n) &= \\mathrm{fibonacci}(n-1) + \\mathrm{fibonacci}(n-2)\n", "\\end{aligned}$$ \n", "\n", - "Translated into Python, it looks like this:" + "В переводе на Python это выглядит так:" ] }, { @@ -961,11 +953,11 @@ "id": "69d56a0b", "metadata": {}, "source": [ - "If you try to follow the flow of execution here, even for small values of $n$, your head explodes.\n", - "But according to the leap of faith, if you assume that the two recursive calls work correctly, you can be confident that the last `return` statement is correct.\n", + "Если попытаться проследить ход выполнения здесь, даже при небольших значениях $n$, голова кругом пойдёт.\n", + "Но согласно \"прыжку веры\", если предположить, что два рекурсивных вызова работают правильно, можно быть уверенным и в корректности последнего оператора `return`.\n", "\n", - "As an aside, this way of computing Fibonacci numbers is very inefficient.\n", - "In [Chapter 10](section_memos) I'll explain why and suggest a way to improve it." + "Замечу, что такой способ вычисления чисел Фибоначчи крайне неэффективен.\n", + "В [главе 10](section_memos) я объясню почему и покажу, как его улучшить." ] }, { @@ -973,9 +965,9 @@ "id": "26d9706b", "metadata": {}, "source": [ - "## Checking types\n", + "## Проверка типов\n", "\n", - "What happens if we call `factorial` and give it `1.5` as an argument?" + "Что произойдёт, если вызвать `factorial` и передать ему аргумент `1.5`?" ] }, { From 54fd4965cbfcc297638e495baca77f9595c31839 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:38:17 +0300 Subject: [PATCH 19/44] Translate Debugging section through end of chapter --- chapters/chap18.ipynb | 149 +++++++++--------------------------------- 1 file changed, 32 insertions(+), 117 deletions(-) diff --git a/chapters/chap18.ipynb b/chapters/chap18.ipynb index 41d5fc1..73e3199 100644 --- a/chapters/chap18.ipynb +++ b/chapters/chap18.ipynb @@ -1765,11 +1765,7 @@ "id": "e046e382", "metadata": {}, "source": [ - "## Debugging\n", - "\n", - "In previous chapters, we used `doctest` to test functions.\n", - "For example, here's a function called `add` that takes two numbers and returns their sum.\n", - "In includes a doctest that checks whether `2 + 2` is `4`." + "## Отладка\n\nВ предыдущих главах мы использовали `doctest` для тестирования функций.\nНапример, функция `add` принимает два числа и возвращает их сумму.\nВ её строке документа есть doctest, проверяющий, что `2 + 2` равно `4`.\n" ] }, { @@ -1793,7 +1789,7 @@ "id": "a5e332d3", "metadata": {}, "source": [ - "This function takes a function object and runs its doctests." + "Эта функция принимает объект функции и запускает её doctest-тесты.\n" ] }, { @@ -1814,7 +1810,7 @@ "id": "2d752a40", "metadata": {}, "source": [ - "So we can test `add` like this." + "Поэтому протестировать `add` можно так.\n" ] }, { @@ -1832,10 +1828,7 @@ "id": "77d36e9b", "metadata": {}, "source": [ - "There's no output, which means all tests passed.\n", - "\n", - "Python provides another tool for running automated tests, called `unittest`.\n", - "It is a little more complicated to use, but here's an example." + "Выходных данных нет, что означает успешное прохождение всех тестов.\n\nВ Python есть ещё один инструмент для автоматизированного тестирования — `unittest`.\nПользоваться им немного сложнее, но вот пример.\n" ] }, { @@ -1859,15 +1852,7 @@ "id": "59b4212a", "metadata": {}, "source": [ - "First we import `TestCase`, which is a class in the `unittest` module.\n", - "To use it, we have to define a new class that inherits from `TestCase` and provides at least one test method.\n", - "The name of the test method must begin with `test` and should indicate which function it tests.\n", - "\n", - "In this example, `test_add` tests the `add` function by calling it, saving the result, and invoking `assertEqual`, which is inherited from `TestCase`.\n", - "`assertEqual` takes two arguments and checks whether they are equal.\n", - "\n", - "In order to run this test method, we have to run a function in `unittest` called `main` and provide several keyword arguments.\n", - "The following function shows the details -- if you are curious, you can ask a virtual assistant to explain how it works." + "Сначала мы импортируем `TestCase` — класс из модуля `unittest`.\nЧтобы воспользоваться им, нужно определить новый класс, наследующий `TestCase`, и добавить хотя бы один метод теста.\nИмя метода теста должно начинаться с `test` и отражать, какую функцию он проверяет.\n\nВ нашем примере `test_add` вызывает `add`, сохраняет результат и использует унаследованный от `TestCase` метод `assertEqual`.\n`assertEqual` принимает два аргумента и проверяет, равны ли они.\n\nЧтобы запустить этот тест, нужно вызвать функцию `main` из `unittest`, передав ей несколько именованных аргументов.\nСледующая функция показывает детали — если интересно, попросите виртуального помощника объяснить, как она работает.\n" ] }, { @@ -1888,11 +1873,7 @@ "id": "5409ea0c", "metadata": {}, "source": [ - "`run_unittest` does not take `TestExample` as an argument -- instead, it searches for classes that inherit from `TestCase`.\n", - "Then it searches for methods that begin with `test` and runs them.\n", - "This process is called **test discovery**.\n", - "\n", - "Here's what happens when we call `run_unittest`." + "`run_unittest` не принимает `TestExample` как аргумент — вместо этого она ищет классы, наследующие `TestCase`.\nЗатем она находит методы, начинающиеся с `test`, и выполняет их.\nЭтот процесс называется **обнаружением тестов**.\n\nПосмотрим, что произойдёт при вызове `run_unittest`.\n" ] }, { @@ -1910,10 +1891,7 @@ "id": "7775304a", "metadata": {}, "source": [ - "`unittest.main` reports the number of tests it ran and the results.\n", - "In this case `OK` indicates that the tests passed.\n", - "\n", - "To see what happens when a test fails, we'll add an incorrect test method to `TestExample`." + "`unittest.main` сообщает, сколько тестов было выполнено, и их результат.\nЗдесь `OK` означает, что все тесты прошли.\n\nЧтобы увидеть, что бывает при сбое теста, добавим в `TestExample` ошибочный метод.\n" ] }, { @@ -1935,7 +1913,7 @@ "id": "96810614", "metadata": {}, "source": [ - "Here's what happens when we run the tests." + "Вот что происходит при запуске тестов.\n" ] }, { @@ -1953,10 +1931,7 @@ "id": "64b743cb", "metadata": {}, "source": [ - "The report includes the test method that failed and an error message showing where.\n", - "The summary indicates that two tests ran and one failed.\n", - "\n", - "In the exercises below, I'll suggest some prompts you can use to ask a virtual assistant for more information about `unittest`." + "В отчёте указано, какой тестовый метод провалился, и приведено сообщение об ошибке.\nВ сводке указано, что было запущено два теста и один из них не прошёл.\n\nВ упражнениях ниже я предложу подсказки, с помощью которых можно спросить у виртуального ассистента больше о `unittest`.\n" ] }, { @@ -1964,22 +1939,7 @@ "id": "7d0fb256", "metadata": {}, "source": [ - "## Glossary\n", - "\n", - "**factory:**\n", - " A function used to create objects, often passed as a parameter to a function.\n", - "\n", - "**conditional expression:**\n", - "An expression that uses a conditional to select one of two values.\n", - "\n", - "**list comprehension:**\n", - "A concise way to loop through a sequence and create a list.\n", - "\n", - "**generator expression:**\n", - "Similar to a list comprehension except that it does not create a list.\n", - "\n", - "**test discovery:**\n", - "A process used to find and run tests." + "## Глоссарий\n\n**фабрика:**\n Функция, создающая объекты; её часто передают как параметр.\n\n**тернарное выражение:**\nВыражение, использующее условие для выбора одного из двух значений.\n\n**списковое включение:**\nКраткий способ пройти по последовательности и создать список.\n\n**генераторное выражение:**\nПохоже на списковое включение, но не создаёт список.\n\n**обнаружение тестов:**\nПроцесс поиска и запуска тестов.\n" ] }, { @@ -1987,7 +1947,7 @@ "id": "bc03f15d", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения\n" ] }, { @@ -2010,27 +1970,7 @@ "id": "fe10415e", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", - "\n", - "There are a few topics in this chapter you might want to learn about.\n", - "\n", - "* \"What are the methods and operators of Python's set class?\"\n", - "\n", - "* \"What are the methods and operators of Python's Counter class?\"\n", - "\n", - "* \"What is the difference between a Python list comprehension and a generator expression?\"\n", - "\n", - "* \"When should I use Python's `namedtuple` rather than define a new class?\"\n", - "\n", - "* \"What are some uses of packing and unpacking keyword arguments?\"\n", - "\n", - "* \"How does `unittest` do test discovery?\"\n", - "\n", - "* \"Along with `assertEqual`, what are the most commonly used methods in `unittest.TestCase`?\"\n", - "\n", - "* \"What are the pros and cons of `doctest` and `unittest`?\"\n", - "\n", - "For the following exercises, consider asking a virtual assistant for help, but as always, remember to test the results." + "### Вопросы виртуальному помощнику\n\nЕсть несколько тем из этой главы, о которых вы можете узнать подробнее.\n\n* «Какие методы и операторы есть у класса `set` в Python?»\n\n* «Какие методы и операторы есть у класса `Counter`?»\n\n* «Чем списковое включение отличается от генераторного выражения?»\n\n* «Когда стоит использовать `namedtuple` вместо создания нового класса?»\n\n* «Для чего применяется упаковка и распаковка именованных аргументов?»\n\n* «Как `unittest` выполняет обнаружение тестов?»\n\n* «Какие методы, помимо `assertEqual`, чаще всего используются в `unittest.TestCase`?»\n\n* «Каковы плюсы и минусы `doctest` и `unittest`?»\n\nВ оставшихся упражнениях при необходимости можете обращаться к виртуальному помощнику, но не забывайте проверять полученные ответы.\n" ] }, { @@ -2038,9 +1978,7 @@ "id": "c61ecde2", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "One of the exercises in Chapter 7 asks for a function called `uses_none` that takes a word and a string of forbidden letters, and returns `True` if the word does not use any of the letters. Here's a solution." + "### Упражнение\n\nВ одной из задач главы 7 предлагалось написать функцию `uses_none`, которая принимает слово и строку запрещённых букв и возвращает `True`, если слово не содержит ни одной из них. Ниже приведено решение.\n" ] }, { @@ -2062,8 +2000,7 @@ "id": "b558b8b3", "metadata": {}, "source": [ - "Write a version of this function that uses `set` operations instead of a `for` loop.\n", - "Hint: ask a VA, \"How do I compute the intersection of Python sets?\"" + "Напишите вариант этой функции, использующий операции множеств вместо цикла `for`.\nПодсказка: спросите у виртуального помощника: «Как найти пересечение множеств в Python?»\n" ] }, { @@ -2073,7 +2010,7 @@ "tags": [] }, "source": [ - "You can use this outline to get started." + "Можете воспользоваться этой заготовкой.\n" ] }, { @@ -2140,12 +2077,7 @@ "id": "d2d670cf", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "Scrabble is a board game where the objective is to use letter tiles to spell words.\n", - "For example, if we have tiles with the letters `T`, `A`, `B`, `L`, `E`, we can spell `BELT` and `LATE` using a subset of the tiles -- but we can't spell `BEET` because we don't have two `E`s.\n", - "\n", - "Write a function that takes a string of letters and a word, and checks whether the letters can spell the word, taking into account how many times each letter appears." + "### Упражнение\n\nScrabble — настольная игра, в которой нужно составлять слова из буквенных фишек.\nНапример, имея фишки `T`, `A`, `B`, `L`, `E`, можно составить слова `BELT` и `LATE`, используя подмножество фишек, но слово `BEET` не получится — у нас только одна буква `E`.\n\nНапишите функцию, которая принимает строку букв и слово и проверяет, можно ли ими составить слово с учётом количества каждой буквы.\n" ] }, { @@ -2155,7 +2087,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Для начала можно использовать следующую заготовку.\n" ] }, { @@ -2207,9 +2139,7 @@ "id": "de2dc099", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "In one of the exercises from [Chapter 17](chapter_inheritance), my solution to `has_straightflush` uses the following method, which partitions a `PokerHand` into a list of four hands, where each hand contains cards of the same suit." + "### Упражнение\n\nВ одном из заданий [главы 17](chapter_inheritance) моё решение функции `has_straightflush` использует метод, который разбивает `PokerHand` на список из четырёх рук, каждая из которых содержит карты одной масти.\n" ] }, { @@ -2236,7 +2166,7 @@ "id": "cd04a7a3", "metadata": {}, "source": [ - "Write a simplified version of this function using a `defaultdict`." + "Напишите упрощённую версию этой функции, используя `defaultdict`.\n" ] }, { @@ -2246,7 +2176,7 @@ "tags": [] }, "source": [ - "Here's an outline of the `PokerHand` class and the `partition_suits` function you can use to get started." + "Ниже приведена заготовка класса `PokerHand` и функции `partition_suits`, которую можно взять за основу.\n" ] }, { @@ -2281,7 +2211,7 @@ "tags": [] }, "source": [ - "To test your code, we'll make a deck and shuffle it." + "Чтобы проверить код, создадим колоду и перемешаем её.\n" ] }, { @@ -2305,7 +2235,7 @@ "tags": [] }, "source": [ - "Then create a `PokerHand` and add seven cards to it." + "Затем создайте `PokerHand` и добавьте в неё семь карт.\n" ] }, { @@ -2333,7 +2263,7 @@ "tags": [] }, "source": [ - "If you invoke `partition` and print the results, each hand should contain cards of one suit only." + "Если вызвать `partition` и вывести результаты, каждая рука должна содержать карты лишь одной масти.\n" ] }, { @@ -2357,9 +2287,7 @@ "id": "218798e3", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "Here's the function from Chapter 11 that computes Fibonacci numbers." + "### Упражнение\n\nНиже приведена функция из главы 11, вычисляющая числа Фибоначчи.\n" ] }, { @@ -2384,7 +2312,7 @@ "id": "6acab624", "metadata": {}, "source": [ - "Write a version of this function with a single return statement that use two conditional expressions, one nested inside the other." + "Напишите вариант этой функции с единственным оператором `return`, используя два тернарных выражения, одно внутри другого.\n" ] }, { @@ -2426,9 +2354,7 @@ "id": "2deb0e1f", "metadata": {}, "source": [ - "### Exercise\n", - "The following is a function that computes the binomial coefficient\n", - "recursively." + "### Упражнение\nНиже показана рекурсивная функция для вычисления биномиального коэффициента.\n" ] }, { @@ -2460,10 +2386,7 @@ "id": "656c61f6", "metadata": {}, "source": [ - "Rewrite the body of the function using nested conditional expressions.\n", - "\n", - "This function is not very efficient because it ends up computing the same values over and over.\n", - "Make it more efficient by memoizing it, as described in [Chapter 10](section_memos)." + "Перепишите тело функции, используя вложенные тернарные выражения.\n\nЭта версия не слишком эффективна, потому что многократно вычисляет одни и те же значения.\nСделайте её быстрее, применив мемоизацию, как описано в [главе 10](section_memos).\n" ] }, { @@ -2491,9 +2414,7 @@ "id": "921719dc", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "Here's the `__str__` method from the `Deck` class in [Chapter 17](section_print_deck)." + "### Упражнение\n\nНиже показан метод `__str__` из класса `Deck` в [главе 17](section_print_deck).\n" ] }, { @@ -2517,7 +2438,7 @@ "id": "27f189cf", "metadata": {}, "source": [ - "Write a more concise version of this method with a list comprehension or generator expression." + "Напишите более лаконичную версию этого метода, используя списковое или генераторное выражение.\n" ] }, { @@ -2539,7 +2460,7 @@ "tags": [] }, "source": [ - "You can use this example to test your solution." + "Этим примером можно воспользоваться для проверки решения.\n" ] }, { @@ -2571,13 +2492,7 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", - "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", - "\n", - "Code license: [MIT License](https://mit-license.org/)\n", - "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "[Think Python: 3-е издание](https://allendowney.github.io/ThinkPython/index.html)\n\n© 2024 [Allen B. Downey](https://allendowney.com)\n\nЛицензия на код: [MIT License](https://mit-license.org/)\n\nЛицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -2603,4 +2518,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 8a79f4050a123f3fab8d1059fec74d6732eff15f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:47:22 +0300 Subject: [PATCH 20/44] translate first markdown cells in chap17 --- blank/chap17.ipynb | 71 +++++++--------------------------------------- 1 file changed, 11 insertions(+), 60 deletions(-) diff --git a/blank/chap17.ipynb b/blank/chap17.ipynb index bc6b43e..99f4a20 100644 --- a/blank/chap17.ipynb +++ b/blank/chap17.ipynb @@ -5,9 +5,7 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n[Amazon] (https://www.amazon.com/_/dp/1098155432?ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325)." ] }, { @@ -27,12 +25,7 @@ "tags": [] }, "source": [ - "# Inheritance\n", - "\n", - "The language feature most often associated with object-oriented programming is **inheritance**.\n", - "Inheritance is the ability to define a new class that is a modified version of an existing class.\n", - "In this chapter I demonstrate inheritance using classes that represent playing cards, decks of cards, and poker hands.\n", - "If you don't play poker, don't worry -- I'll tell you what you need to know." + "# Наследование\n\nЯзыковая особенность чаще всего связана с объектно-ориентированным программированием,-это ** наследование **.\nНаследование - это способность определить новый класс, который является модифицированной версией существующего класса.\nВ этой главе я демонстрирую наследование, используя классы, которые представляют воспроизводимые карты, колоды карт и покерные руки.\nЕсли вы не играете в покер, не волнуйтесь - я скажу вам, что вам нужно знать." ] }, { @@ -40,21 +33,7 @@ "id": "b19c4dae", "metadata": {}, "source": [ - "## Representing cards\n", - "\n", - "There are 52 playing cards in a standard deck -- each of them belongs to one of four suits and one of thirteen ranks. \n", - "The suits are Spades, Hearts, Diamonds, and Clubs.\n", - "The ranks are Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King.\n", - "Depending on which game you are playing, an Ace can be higher than King or lower than 2.\n", - "\n", - "If we want to define a new object to represent a playing card, it is obvious what the attributes should be: `rank` and `suit`.\n", - "It is less obvious what type the attributes should be.\n", - "One possibility is to use strings like `'Spade'` for suits and `'Queen'` for ranks.\n", - "A problem with this implementation is that it would not be easy to compare cards to see which had a higher rank or suit.\n", - "\n", - "An alternative is to use integers to **encode** the ranks and suits.\n", - "In this context, \"encode\" means that we are going to define a mapping between numbers and suits, or between numbers and ranks.\n", - "This kind of encoding is not meant to be a secret (that would be \"encryption\")." + "## представлять карты\n\nВ стандартной колоде есть 52 игральных карт - каждый из них принадлежит одному из четырех костюмов и одной из тринадцати рангов.\nКостюмы - пики, сердца, бриллианты и клубы.\nРанги - туз, 2, 3, 4, 5, 6, 7, 8, 9, 10, Джек, королева и король.\nВ зависимости от того, в какой игре вы играете, туз может быть выше короля или ниже 2.\n\nЕсли мы хотим определить новый объект для представления игровой карты, очевидно, какими должны быть атрибуты: `rank 'и` костюм.\nМенее очевидно, какой тип должен быть атрибуты.\nОдна возможность состоит в том, чтобы использовать струны, такие как «Spade» для костюмов и «Queen» для рядов.\nПроблема с этой реализацией заключается в том, что было бы нелегко сравнить карты, чтобы увидеть, что имело более высокий ранг или костюм.\n\nАльтернативой является использование целых чисел для ** кодировать ** ранги и костюмы.\nВ этом контексте «кодирование» означает, что мы собираемся определить отображение между числами и костюмами или между числами и рангами.\nЭтот вид кодировки не предназначен для того, чтобы быть секретом (это будет «шифрование»)." ] }, { @@ -62,17 +41,7 @@ "id": "a9bafecf", "metadata": {}, "source": [ - "For example, this table shows the suits and the corresponding integer codes:\n", - "\n", - "\n", - "| Suit | Code |\n", - "| --- | --- |\n", - "| Spades | 3 |\n", - "| Hearts | 2 |\n", - "| Diamonds | 1 |\n", - "| Clubs | 0 |\n", - "\n", - "With this encoding, we can compare suits by comparing their codes." + "Например, в этой таблице показаны подходящие и соответствующие целочисленные коды:\n\n\n|Костюм |Код |\n|--- |--- |\n|Spades |3 |\n|Сердца |2 |\n|Бриллианты |1 |\n|Клубы |0 |\n\nС помощью этого кодирования мы можем сравнить костюмы, сравнивая их коды." ] }, { @@ -80,21 +49,7 @@ "id": "a1b46b1a", "metadata": {}, "source": [ - "To encode the ranks, we'll use the integer `2` to represent the rank `2`, `3` to represent `3`, and so on up to `10`.\n", - "The following table shows the codes for the face cards.\n", - "\n", - " \n", - "| Rank | Code |\n", - "| --- | --- |\n", - "| Jack | 11 |\n", - "| Queen | 12 |\n", - "| King | 13 |\n", - "\n", - "And we can use either `1` or `14` to represent an Ace, depending on whether we want it to be considered lower or higher than the other ranks.\n", - "\n", - "To represent these encodings, we will use two lists of strings, one with the names of the suits and the other with the names of the ranks.\n", - "\n", - "Here's a definition for a class that represents a playing card, with these lists of strings as **class variables**, which are variables defined inside a class definition, but not inside a method." + "Чтобы кодировать ранги, мы будем использовать целое число `2`, чтобы представить ранг` 2`, `3`, чтобы представлять` 3` и т. Д. до `10`.\nВ следующей таблице показаны коды для карт лица.\n\n\n|Ранг |Код |\n|--- |--- |\n|Джек |11 |\n|Королева |12 |\n|Король |13 |\n\nИ мы можем использовать либо `1`, либо« 14 », чтобы представлять ACE, в зависимости от того, хотим ли мы считаться ниже или выше, чем другие ранги.\n\nЧтобы представить эти кодировки, мы будем использовать два списка строк, один с именами костюмов, а другой с именами рангов.\n\nВот определение для класса, который представляет собой игровую карту, с этими списками строк как ** переменные класса **, которые являются переменными, определенными внутри определения класса, но не внутри метода." ] }, { @@ -110,9 +65,7 @@ "id": "d63f798a", "metadata": {}, "source": [ - "The first element of `rank_names` is `None` because there is no card with rank zero. By including `None` as a place-keeper, we get a list with the nice property that the index `2` maps to the string `'2'`, and so on.\n", - "\n", - "Class variables are associated with the class, rather than an instance of the class, so we can access them like this." + "Первым элементом `rank_names` является« нет », потому что нет карты с ноль.Включив «нет» в качестве хранителя, мы получаем список со свойством хорошего, что индекс `2` отображает на строку` '2'' и так далее.\n\nПеременные класса связаны с классом, а не с экземпляром класса, поэтому мы можем получить к ним доступ к ним." ] }, { @@ -128,7 +81,7 @@ "id": "c837fff6", "metadata": {}, "source": [ - "We can use `suit_names` to look up a suit and get the corresponding string." + "Мы можем использовать `suit_names`, чтобы найти костюм и получить соответствующую строку." ] }, { @@ -144,7 +97,7 @@ "id": "a59d905e", "metadata": {}, "source": [ - "And `rank_names` to look up a rank." + "И `rank_names`, чтобы посмотреть ранг." ] }, { @@ -160,9 +113,7 @@ "id": "50dda19b", "metadata": {}, "source": [ - "## Card attributes\n", - "\n", - "Here's an `__init__` method for the `Card` class -- it takes `suit` and `rank` as parameters and assigns them to attributes with the same names." + "## Карточные атрибуты\n\nВот метод `__init__` для класса` card` - он принимает `костюм 'и` rank' в качестве параметров и назначает их атрибутам с одинаковыми именами." ] }, { @@ -178,7 +129,7 @@ "id": "31a2782d", "metadata": {}, "source": [ - "Now we can create a `Card` object like this." + "Теперь мы можем создать такой объект «карты»." ] }, { @@ -2142,4 +2093,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From f761c6f908bdf52989226dfad2a40231ce725ed1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 13:48:49 +0300 Subject: [PATCH 21/44] Translate chap19 text cells to Russian --- blank/chap19.ipynb | 103 ++++++++++++++++++++++----------------------- 1 file changed, 51 insertions(+), 52 deletions(-) diff --git a/blank/chap19.ipynb b/blank/chap19.ipynb index 4d86fb8..cc69e6f 100644 --- a/blank/chap19.ipynb +++ b/blank/chap19.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать печатную и электронную версии *Think Python 3e* на\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -15,7 +15,7 @@ "id": "171aca73", "metadata": {}, "source": [ - "# Final thoughts" + "# Заключительные мысли" ] }, { @@ -23,13 +23,13 @@ "id": "4d551c99", "metadata": {}, "source": [ - "Learning to program is not easy, but if you made it this far, you are off to a good start.\n", - "Now I have some suggestions for ways you can keep learning and apply what you have learned.\n", + "Учиться программировать непросто, но если вы дошли до этого места, у вас уже хороший старт.\n", + "Теперь несколько советов, как продолжать учиться и применять полученные знания.\n", "\n", - "This book is meant to be a general introduction to programming, so we have not focused on specific applications.\n", - "Depending on your interests, there are any number of areas where you can apply your new skills.\n", + "Эта книга является общим введением в программирование, поэтому мы не сосредоточились на конкретных приложениях.\n", + "В зависимости от ваших интересов существует множество областей, где вы можете применить новые навыки.\n", "\n", - "If you are interested in Data Science, there are three books of mine you might like:\n", + "Если вас интересует Data Science, вам могут понравиться три мои книги:\n", "\n", "* *Think Stats: Exploratory Data Analysis*, O'Reilly Media, 2014.\n", "\n", @@ -43,13 +43,13 @@ "id": "cceabe36", "metadata": {}, "source": [ - "If you are interested in physical modeling and complex systems, you might like:\n", + "Если вас интересует физическое моделирование и сложные системы, вам могут понравиться следующие книги:\n", "\n", "* *Modeling and Simulation in Python: An Introduction for Scientists and Engineers*, No Starch Press, 2023.\n", "\n", "* *Think Complexity: Complexity Science and Computational Modeling*, O'Reilly Media, 2018.\n", "\n", - "These use NumPy, SciPy, pandas, and other Python libraries for data science and scientific computing." + "В них используются NumPy, SciPy, pandas и другие библиотеки Python для науки о данных и научных вычислений." ] }, { @@ -57,13 +57,13 @@ "id": "54a39121", "metadata": {}, "source": [ - "This book tries to find a balance between general principles of programming and details of Python.\n", - "As a result, it does not include every feature of the Python language.\n", - "For more about Python, and good advice about how to use it, I recommend *Fluent Python: Clear, Concise, and Effective Programming*, second edition by Luciano Ramalho, O'Reilly Media, 2022.\n", + "Эта книга пытается найти баланс между общими принципами программирования и деталями Python.\n", + "В результате она не включает каждую возможность языка Python.\n", + "Чтобы узнать больше о Python и получить рекомендации по его применению, я советую книгу *Fluent Python: Clear, Concise, and Effective Programming*, второе издание, Лучиано Рамальо, O'Reilly Media, 2022.\n", "\n", - "After an introduction to programming, a common next step is to learn about data structures and algorithms.\n", - "I have a work in progress on this topic, called *Data Structures and Information Retrieval in Python*.\n", - "A free electronic version is available from Green Tea Press at ." + "После введения в программирование обычным следующим шагом является изучение структур данных и алгоритмов.\n", + "У меня есть работа в процессе на эту тему под названием *Data Structures and Information Retrieval in Python*.\n", + "Бесплатная электронная версия доступна в Green Tea Press по адресу ." ] }, { @@ -71,11 +71,11 @@ "id": "a1598510", "metadata": {}, "source": [ - "As you work on more complex programs, you will encounter new challenges.\n", - "You might find it helpful to review the sections in this book about debugging.\n", - "In particular, remember the Six R's of debugging from [Chapter 12](section_debugging_12): reading, running, ruminating, rubber-ducking, retreating, and resting.\n", + "По мере того как вы будете писать более сложные программы, вы столкнетесь с новыми вызовами.\n", + "Возможно, вам будет полезно перечитать разделы этой книги о отладке.\n", + "В частности, помните о шести R отладки из [главы 12](section_debugging_12): чтение, запуск, размышление, 'резиновая уточка', отход и отдых.\n", "\n", - "This book suggests tools to help with debugging, including the `print` and `repr` functions, the `structshape` function in [Chapter 11](section_debugging_11) -- and the built-in functions `isinstance`, `hasattr`, and `vars` in [Chapter 14](section_debugging_14)." + "В этой книге также предлагаются инструменты для отладки, включая функции `print` и `repr`, функцию `structshape` из [главы 11](section_debugging_11), а также встроенные функции `isinstance`, `hasattr` и `vars` из [главы 14](section_debugging_14)." ] }, { @@ -83,12 +83,12 @@ "id": "fb4dd345", "metadata": {}, "source": [ - "It also suggests tools for testing programs, including the `assert` statement, the `doctest` module, and the `unittest` module.\n", - "Including tests in your programs is one of the best ways to prevent and detect errors, and save time debugging.\n", + "Также предлагаются инструменты для тестирования программ: оператор `assert`, модуль `doctest` и модуль `unittest`.\n", + "Включение тестов в программу — один из лучших способов предотвратить и обнаружить ошибки, сэкономив время на отладке.\n", "\n", - "But the best kind of debugging is the kind you don't have to do.\n", - "If you use an incremental development process as described in [Chapter 6](section_incremental) -- and test as you go -- you will make fewer errors and find them more quickly when you do.\n", - "Also, remember encapsulation and generalization from [Chapter 4](section_encapsulation), which is particularly useful when you are developing code in Jupyter notebooks." + "Но лучший вид отладки — это тот, который вам не приходится делать.\n", + "Если вы используете процесс инкрементальной разработки, описанный в [главе 6](section_incremental), и тестируете по ходу дела, ошибок будет меньше и вы будете быстрее их находить.\n", + "Также помните об инкапсуляции и обобщении из [главы 4](section_encapsulation), что особенно полезно при разработке кода в Jupyter-ноутбуках." ] }, { @@ -96,16 +96,15 @@ "id": "0d29933e", "metadata": {}, "source": [ - "Throughout this book, I've suggested ways to use virtual assistants to help you learn, program, and debug.\n", - "I hope you are finding these tools useful.\n", + "На протяжении этой книги я предлагал способы использовать виртуальных ассистентов для обучения, программирования и отладки.\n", + "Надеюсь, эти инструменты оказались полезными.\n", "\n", - "In additional to virtual assistants like ChatGPT, you might also want to use a tool like Copilot that autocompletes code as you type.\n", - "I did not recommend using these tools, initially, because they can be overwhelming for beginners.\n", - "But you might want to explore them now.\n", + "Помимо ассистентов вроде ChatGPT, вы также можете попробовать такие средства, как Copilot, которое дополняет код по мере набора.\n", + "Изначально я не рекомендовал использовать их, так как они могут перегружать новичков, но сейчас вы можете их изучить.\n", "\n", - "Using AI tools effectively requires some experimentation and reflection to find a flow that works for you.\n", - "If you think it's a nuisance to copy code from ChatGPT to Jupyter, you might prefer something like Copilot.\n", - "But the cognitive work you do to compose a prompt and interpret the response can be as valuable as the code the tool generates, in the same vein as rubber duck debugging." + "Эффективное применение ИИ-инструментов требует экспериментов и размышлений, чтобы найти подходящий вам рабочий процесс.\n", + "Если вам неудобно копировать код из ChatGPT в Jupyter, возможно, вам подойдет Copilot.\n", + "Но умственная работа, которую вы проделываете, формулируя запрос и интерпретируя ответ, может быть не менее ценной, чем сам код, который генерирует инструмент, в духе резиновой уточки." ] }, { @@ -113,17 +112,17 @@ "id": "c28d6815", "metadata": {}, "source": [ - "As you gain programming experience, you might want to explore other development environments.\n", - "I think Jupyter notebooks are a good place to start, but they are relatively new and not as widely-used as conventional integrated development environments (IDE).\n", - "For Python, the most popular IDEs include PyCharm and Spyder -- and Thonny, which is often recommended for beginners.\n", - "Other IDEs, like Visual Studio Code and Eclipse, work with other programming languages as well.\n", - "Or, as a simpler alternative, you can write Python programs using any text editor you like.\n", - "\n", - "As you continue your programming journey, you don't have to go alone!\n", - "If you live in or near a city, there's a good chance there is a Python user group you can join.\n", - "These groups are usually friendly to beginners, so don't be afraid.\n", - "If there is no group near you, you might be able to join events remotely.\n", - "Also, keep an eye out for regional Python conferences." + "Набираясь опыта программирования, вы можете захотеть опробовать другие среды разработки.\n", + "Я считаю Jupyter-ноутбуки хорошим местом для начала, но они относительно новы и не так широко распространены, как традиционные интегрированные среды разработки (IDE).\n", + "Для Python наиболее популярны PyCharm и Spyder, а также Thonny, который часто рекомендуют новичкам.\n", + "Другие IDE, такие как Visual Studio Code и Eclipse, поддерживают и другие языки программирования.\n", + "Или, в качестве более простого варианта, вы можете писать программы на Python в любом текстовом редакторе.\n", + "\n", + "Продолжая путь программиста, не оставайтесь одни!\n", + "Если вы живёте в городе или рядом, скорее всего там есть группа пользователей Python, к которой можно присоединиться.\n", + "Эти сообщества обычно дружелюбны к новичкам, поэтому не бойтесь.\n", + "Если рядом нет такой группы, возможно, вы сможете участвовать в событиях удаленно.\n", + "Также обращайте внимание на региональные конференции по Python." ] }, { @@ -131,12 +130,12 @@ "id": "28cb22bf", "metadata": {}, "source": [ - "One of the best ways to improve your programming skills is to learn another language.\n", - "If you are interested in statistics and data science, you might want to learn R.\n", - "But I particularly recommend learning a functional language like Racket or Elixir.\n", - "Functional programming requires a different kind of thinking, which changes the way you think about programs.\n", + "Один из лучших способов улучшить навыки программирования — выучить другой язык.\n", + "Если вас интересует статистика и Data Science, возможно, вам стоит изучить R.\n", + "Но особенно рекомендую изучить функциональный язык, например Racket или Elixir.\n", + "Функциональное программирование требует иного образа мышления, который меняет восприятие программ.\n", "\n", - "Good luck!" + "Удачи!" ] }, { @@ -154,13 +153,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3-е издание](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], From 98e0ab7b3814b5eba46bf16abf8194c171a3c9a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 14:00:48 +0300 Subject: [PATCH 22/44] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20=D0=BE=D1=81=D1=82=D0=B0=D0=B2=D1=88=D0=B5=D0=B3=D0=BE?= =?UTF-8?q?=D1=81=D1=8F=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=D0=B0=20=D0=B2=20?= =?UTF-8?q?=D0=B3=D0=BB=D0=B0=D0=B2=D0=B5=206?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blank/chap06.ipynb | 175 ++++++++++++++++++++------------------------- 1 file changed, 79 insertions(+), 96 deletions(-) diff --git a/blank/chap06.ipynb b/blank/chap06.ipynb index 0c0c90f..cb64a24 100644 --- a/blank/chap06.ipynb +++ b/blank/chap06.ipynb @@ -985,17 +985,16 @@ "id": "0bec7ba4", "metadata": {}, "source": [ - "It looks like an infinite recursion. How can that be? The function has a\n", - "base case -- when `n == 0`.\n", - "But if `n` is not an integer, we can *miss* the base case and recurse forever.\n", + "Выглядит так, будто рекурсия бесконечна. Как же так? У функции есть базовый случай — когда `n == 0`.\n", + "Но если `n` не целое число, мы можем *пропустить* базовый случай и зациклиться.\n", "\n", - "In this example, the initial value of `n` is `1.5`.\n", - "In the first recursive call, the value of `n` is `0.5`.\n", - "In the next, it is `-0.5`. \n", - "From there, it gets smaller (more negative), but it will never be `0`.\n", + "В этом примере начальное значение `n` равно `1.5`.\n", + "В первом рекурсивном вызове `n` равно `0.5`.\n", + "В следующем — `-0.5`.\n", + "Дальше значение становится всё меньше (более отрицательным), но никогда не будет `0`.\n", "\n", - "To avoid infinite recursion we can use the built-in function `isinstance` to check the type of the argument.\n", - "Here's how we check whether a value is an integer." + "Чтобы избежать бесконечной рекурсии, можно использовать встроенную функцию `isinstance`, проверяющую тип аргумента.\n", + "Так мы проверяем, является ли значение целым числом.\n" ] }, { @@ -1019,7 +1018,7 @@ "id": "b0017b42", "metadata": {}, "source": [ - "Now here's a version of `factorial` with error-checking." + "Теперь версия `factorial` с проверками на ошибки.\n" ] }, { @@ -1035,9 +1034,8 @@ "id": "0561e3f5", "metadata": {}, "source": [ - "First it checks whether `n` is an integer.\n", - "If not, it displays an error message and returns `None`.\n", - "\n" + "Сначала проверяем, целое ли `n`.\n", + "Если нет, выводим сообщение об ошибке и возвращаем `None`.\n" ] }, { @@ -1053,8 +1051,8 @@ "id": "10b00a39", "metadata": {}, "source": [ - "Then it checks whether `n` is negative.\n", - "If so, it displays an error message and returns `None.`" + "Затем проверяем, не отрицательно ли `n`.\n", + "Если да, выводим сообщение об ошибке и возвращаем `None`.\n" ] }, { @@ -1070,8 +1068,8 @@ "id": "96aa1403", "metadata": {}, "source": [ - "If we get past both checks, we know that `n` is a non-negative integer, so we can be confident the recursion will terminate.\n", - "Checking the parameters of a function to make sure they have the correct types and values is called **input validation**." + "Если обе проверки пройдены, значит `n` — неотрицательное целое число, и можно быть уверенным, что рекурсия завершится.\n", + "Проверку параметров функции на корректность типа и значения называют **валидацией ввода**.\n" ] }, { @@ -1081,27 +1079,27 @@ "tags": [] }, "source": [ - "## Debugging\n", + "## Отладка\n", "\n", - "Breaking a large program into smaller functions creates natural checkpoints for debugging.\n", - "If a function is not working, there are three possibilities to consider:\n", + "Разбиение большой программы на функции создаёт естественные точки проверки при отладке.\n", + "Если функция работает неправильно, возможны три варианта:\n", "\n", - "- There is something wrong with the arguments the function is getting -- that is, a precondition is violated.\n", + "- Проблема с аргументами, которые получает функция, то есть нарушено предположение (precondition).\n", "\n", - "- There is something wrong with the function -- that is, a postcondition is violated.\n", + "- Проблема в самой функции, то есть нарушено постусловие (postcondition).\n", "\n", - "- The caller is doing something wrong with the return value.\n", + "- Вызывающий неверно использует возвращаемое значение.\n", "\n", - "To rule out the first possibility, you can add a `print` statement at the beginning of the function that displays the values of the parameters (and maybe their types).\n", - "Or you can write code that checks the preconditions explicitly.\n", + "Чтобы исключить первую возможность, можно добавить в начало функции оператор `print`, выводящий значения параметров (а при необходимости и их типы).\n", + "Или написать код, который явно проверяет предусловия.\n", "\n", - "If the parameters look good, you can add a `print` statement before each `return` statement and display the return value.\n", - "If possible, call the function with arguments that make it easy check the result. \n", + "Если параметры выглядят корректно, можно добавить оператор `print` перед каждым `return` и вывести возвращаемое значение.\n", + "По возможности вызывайте функцию с аргументами, для которых легко проверить результат.\n", "\n", - "If the function seems to be working, look at the function call to make sure the return value is being used correctly -- or used at all!\n", + "Если функция вроде бы работает, посмотрите на вызов, чтобы убедиться, что возвращаемое значение используется правильно — или используется вообще!\n", "\n", - "Adding `print` statements at the beginning and end of a function can help make the flow of execution more visible.\n", - "For example, here is a version of `factorial` with print statements:" + "Добавление операторов `print` в начале и конце функции помогает лучше видеть ход выполнения.\n", + "Например, вот версия `factorial` с такими выводами:\n" ] }, { @@ -1117,8 +1115,7 @@ "id": "0c044111", "metadata": {}, "source": [ - "`space` is a string of space characters that controls the indentation of\n", - "the output. Here is the result of `factorial(3)` :" + "`space` — строка из пробелов, задающая отступы в выводе. Вот результат `factorial(3)`:\n" ] }, { @@ -1134,8 +1131,8 @@ "id": "43b3e408", "metadata": {}, "source": [ - "If you are confused about the flow of execution, this kind of output can be helpful.\n", - "It takes some time to develop effective scaffolding, but a little bit of scaffolding can save a lot of debugging." + "Если вы запутались во взаимосвязи вызовов, такой вывод может помочь.\n", + "Нужна практика, чтобы эффективно использовать подобные подпорки, но немного дополнительных сообщений может сэкономить много времени на отладку.\n" ] }, { @@ -1143,29 +1140,28 @@ "id": "b7c3962f", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**return value:**\n", - "The result of a function. If a function call is used as an expression, the return value is the value of the expression.\n", + "**возвращаемое значение:**\n", + "Результат функции. Если вызов используется как выражение, возвращаемое значение становится значением выражения.\n", "\n", - "**pure function:**\n", - "A function that does not display anything or have any other effect, other than returning a return value.\n", + "**чистая функция:**\n", + "Функция, которая ничего не выводит и не делает ничего, кроме возврата значения.\n", "\n", + "**мёртвый код:**\n", + "Часть программы, которая никогда не выполняется, часто потому, что находится после оператора `return`.\n", "\n", - "**dead code:**\n", - "Part of a program that can never run, often because it appears after a `return` statement.\n", + "**инкрементальная разработка:**\n", + "План разработки программы, позволяющий избегать отладки за счёт добавления и тестирования лишь небольших фрагментов кода.\n", "\n", - "**incremental development:**\n", - "A program development plan intended to avoid debugging by adding and testing only a small amount of code at a time.\n", + "**подпорки:**\n", + "Код, используемый во время разработки программы, но не входящий в финальную версию.\n", "\n", - "**scaffolding:**\n", - " Code that is used during program development but is not part of the final version.\n", + "**Тьюринг-полнота:**\n", + "Язык или его подмножество называется Тьюринг-полным, если на нём можно описать любой алгоритм.\n", "\n", - "**Turing complete:**\n", - "A language, or subset of a language, is Turing complete if it can perform any computation that can be described by an algorithm.\n", - "\n", - "**input validation:**\n", - "Checking the parameters of a function to make sure they have the correct types and values" + "**валидация ввода:**\n", + "Проверка параметров функции на корректность типа и значения.\n" ] }, { @@ -1173,7 +1169,7 @@ "id": "ff7b1edf", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения\n" ] }, { @@ -1191,9 +1187,9 @@ "id": "0da2daaf", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "In this chapter, we saw an incorrect function that can end without returning a value." + "В этой главе мы видели некорректную функцию, которая может завершиться без возврата значения.\n" ] }, { @@ -1209,7 +1205,7 @@ "id": "69563d4b", "metadata": {}, "source": [ - "And a version of the same function that has dead code at the end." + "А также версию той же функции, в которой в конце остаётся мёртвый код.\n" ] }, { @@ -1225,7 +1221,7 @@ "id": "9fe8ae2e", "metadata": {}, "source": [ - "And we saw the following example, which is correct but not idiomatic." + "Мы также видели следующий пример, который работает правильно, но написан не идиоматично.\n" ] }, { @@ -1241,9 +1237,9 @@ "id": "14f52688", "metadata": {}, "source": [ - "Ask a virtual assistant what's wrong with each of these functions and see if it can spot the errors or improve the style.\n", + "Спросите у виртуального помощника, что не так с каждой из этих функций, и может ли он исправить ошибки или улучшить стиль.\n", "\n", - "Then ask \"Write a function that takes coordinates of two points and computes the distance between them.\" See if the result resembles the version of `distance` we wrote in this chapter." + "Потом попросите: \"Напиши функцию, которая принимает координаты двух точек и вычисляет расстояние между ними.\" Посмотрите, будет ли результат похож на версию `distance`, написанную в этой главе.\n" ] }, { @@ -1251,14 +1247,14 @@ "id": "fd23bb60", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Use incremental development to write a function called `hypot` that returns the length of the hypotenuse of a right triangle given the lengths of the other two legs as arguments.\n", + "Используя инкрементальную разработку, напишите функцию `hypot`, которая возвращает длину гипотенузы прямоугольного треугольника по длинам двух катетов.\n", "\n", - "Note: There's a function in the math module called `hypot` that does the same thing, but you should not use it for this exercise!\n", + "Замечание: в модуле `math` есть функция `hypot`, делающая то же самое, но в этом упражнении её использовать не нужно!\n", "\n", - "Even if you can write the function correctly on the first try, start with a function that always returns `0` and practice making small changes, testing as you go.\n", - "When you are done, the function should only return a value -- it should not display anything." + "Даже если вы можете сразу написать правильную функцию, начните с версии, которая всегда возвращает `0`, и постепенно вносите небольшие изменения, каждый раз тестируя код.\n", + "Когда закончите, функция должна только возвращать значение и ничего не выводить.\n" ] }, { @@ -1346,10 +1342,9 @@ "id": "0a66d82a", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a boolean function, `is_between(x, y, z)`, that returns `True` if $x < y < z$ or if \n", - "$z < y < x$, and`False` otherwise." + "Напишите логическую функцию `is_between(x, y, z)`, которая возвращает `True`, если $x < y < z$ или $z < y < x$, и `False` в противном случае.\n" ] }, { @@ -1367,7 +1362,7 @@ "tags": [] }, "source": [ - "You can use these examples to test your function." + "Вы можете использовать эти примеры для проверки функции.\n" ] }, { @@ -1415,20 +1410,15 @@ "id": "57f06466", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "The Ackermann function, $A(m, n)$, is defined:\n", + "Функция Аккермана, $A(m, n)$, определяется так:\n", "\n", "$$\\begin{aligned}\n", - "A(m, n) = \\begin{cases} \n", - " n+1 & \\mbox{if } m = 0 \\\\ \n", - " A(m-1, 1) & \\mbox{if } m > 0 \\mbox{ and } n = 0 \\\\ \n", - "A(m-1, A(m, n-1)) & \\mbox{if } m > 0 \\mbox{ and } n > 0.\n", - "\\end{cases} \n", - "\\end{aligned}$$ \n", + "A(m, n) = \\begin{cases}\\n n+1 & \\mbox{if } m = 0 \\\\ \\n A(m-1, 1) & \\mbox{if } m > 0 \\mbox{ and } n = 0 \\\\ \\nA(m-1, A(m, n-1)) & \\mbox{if } m > 0 \\mbox{ and } n > 0.\\n\\end{cases}\\n\\end{aligned}$$\n", "\n", - "Write a function named `ackermann` that evaluates the Ackermann function.\n", - "What happens if you call `ackermann(5, 5)`?" + "Напишите функцию `ackermann`, которая вычисляет функцию Аккермана.\n", + "Что произойдёт, если вызвать `ackermann(5, 5)`?\n" ] }, { @@ -1446,7 +1436,7 @@ "tags": [] }, "source": [ - "You can use these examples to test your function." + "Вы можете использовать эти примеры для проверки функции.\n" ] }, { @@ -1486,7 +1476,7 @@ "tags": [] }, "source": [ - "If you call this function with values bigger than 4, you get a `RecursionError`." + "Если вызвать эту функцию с аргументами больше 4, возникнет `RecursionError`.\n" ] }, { @@ -1506,7 +1496,7 @@ "tags": [] }, "source": [ - "To see why, add a print statement to the beginning of the function to display the values of the parameters, and then run the examples again." + "Чтобы понять почему, добавьте в начало функции оператор `print`, выводящий значения параметров, и снова выполните примеры.\n" ] }, { @@ -1516,12 +1506,9 @@ "tags": [] }, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "A number, $a$, is a power of $b$ if it is divisible by $b$ and $a/b$ is\n", - "a power of $b$. Write a function called `is_power` that takes parameters\n", - "`a` and `b` and returns `True` if `a` is a power of `b`. Note: you will\n", - "have to think about the base case." + "Число $a$ является степенью $b$, если оно делится на $b$ и $a/b$ тоже является степенью $b$. Напишите функцию `is_power`, которая принимает параметры `a` и `b` и возвращает `True`, если $a$ является степенью $b$. Подумайте, как должен выглядеть базовый случай.\n" ] }, { @@ -1539,7 +1526,7 @@ "tags": [] }, "source": [ - "You can use these examples to test your function." + "Вы можете использовать эти примеры для проверки функции.\n" ] }, { @@ -1587,17 +1574,13 @@ "id": "a33bbd07", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "The greatest common divisor (GCD) of $a$ and $b$ is the largest number\n", - "that divides both of them with no remainder.\n", + "Наибольший общий делитель (НОД) чисел $a$ и $b$ — это наибольшее число, которое делит их без остатка.\n", "\n", - "One way to find the GCD of two numbers is based on the observation that\n", - "if $r$ is the remainder when $a$ is divided by $b$, then $gcd(a,\n", - "b) = gcd(b, r)$. As a base case, we can use $gcd(a, 0) = a$.\n", + "Один из способов найти НОД двух чисел основан на наблюдении, что если остаток от деления $a$ на $b$ равен $r$, то $gcd(a, b) = gcd(b, r)$. В качестве базового случая можно использовать $gcd(a, 0) = a$.\n", "\n", - "Write a function called `gcd` that takes parameters `a` and `b` and\n", - "returns their greatest common divisor." + "Напишите функцию `gcd`, которая принимает параметры `a` и `b` и возвращает их наибольший общий делитель.\n" ] }, { @@ -1615,7 +1598,7 @@ "tags": [] }, "source": [ - "You can use these examples to test your function." + "Вы можете использовать эти примеры для проверки функции.\n" ] }, { @@ -1657,9 +1640,9 @@ "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)\n" ] } ], From 83562c113e3e5022498c9ae4d2b7b7d5281f8eeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 14:16:23 +0300 Subject: [PATCH 23/44] Translate chapter 17 notebook to Russian --- blank/chap17.ipynb | 391 ++++++++++++++++++--------------------------- 1 file changed, 156 insertions(+), 235 deletions(-) diff --git a/blank/chap17.ipynb b/blank/chap17.ipynb index 99f4a20..a8bb6a2 100644 --- a/blank/chap17.ipynb +++ b/blank/chap17.ipynb @@ -145,7 +145,7 @@ "id": "85e5cf5d", "metadata": {}, "source": [ - "We can use the new instance to access the attributes." + "Мы можем использовать новый экземпляр для доступа к атрибутам.\n" ] }, { @@ -161,7 +161,7 @@ "id": "449225d3", "metadata": {}, "source": [ - "It is also legal to use the instance to access the class variables." + "Также допустимо использовать экземпляр, чтобы обращаться к переменным класса.\n" ] }, { @@ -177,7 +177,7 @@ "id": "97232ffa", "metadata": {}, "source": [ - "But if you use the class, it is clearer that they are class variables, not attributes." + "Но если использовать сам класс, то яснее, что это именно переменные класса, а не атрибуты.\n" ] }, { @@ -185,9 +185,9 @@ "id": "7a0a79ae", "metadata": {}, "source": [ - "## Printing cards\n", + "## Вывод карт\n", "\n", - "Here's a `__str__` method for `Card` objects." + "Ниже приведён метод `__str__` для объектов `Card`.\n" ] }, { @@ -203,7 +203,7 @@ "id": "d6c51352", "metadata": {}, "source": [ - "When we print a `Card`, Python calls the `__str__` method to get a human-readable representation of the card." + "Когда мы печатаем объект `Card`, Python вызывает метод `__str__`, чтобы получить удобное для чтения представление карты.\n" ] }, { @@ -219,10 +219,7 @@ "id": "76044b9e", "metadata": {}, "source": [ - "The following is a diagram of the `Card` class object and the Card instance.\n", - "`Card` is a class object, so its type is `type`.\n", - "`queen` is an instance of `Card`, so its type is `Card`.\n", - "To save space, I didn't draw the contents of `suit_names` and `rank_names`." + "Ниже показана диаграмма объекта класса `Card` и экземпляра `Card`. `Card` является объектом класса, поэтому его тип — `type`. `queen` — экземпляр `Card`, поэтому его тип — `Card`. Чтобы сэкономить место, я не изобразил содержимое `suit_names` и `rank_names`.\n" ] }, { @@ -250,7 +247,7 @@ "id": "ccb8e41d", "metadata": {}, "source": [ - "Every `Card` instance has its own `suit` and `rank` attributes, but there is only one `Card` class object, and only one copy of the class variables `suit_names` and `rank_names`." + "У каждого экземпляра `Card` есть собственные атрибуты `suit` и `rank`, но объект класса `Card` только один, как и единственные копии переменных класса `suit_names` и `rank_names`.\n" ] }, { @@ -258,9 +255,9 @@ "id": "98c6508d", "metadata": {}, "source": [ - "## Comparing cards\n", + "## Сравнение карт\n", "\n", - "Suppose we create a second `Card` object with the same suit and rank." + "Предположим, мы создаём второй объект `Card` с тем же мастью и рангом.\n" ] }, { @@ -276,7 +273,7 @@ "id": "3c92779c", "metadata": {}, "source": [ - "If we use the `==` operator to compare them, it checks whether `queen` and `queen2` refer to the same object." + "Если использовать оператор `==`, он проверит, ссылаются ли `queen` и `queen2` на один и тот же объект.\n" ] }, { @@ -292,8 +289,7 @@ "id": "278d8abe", "metadata": {}, "source": [ - "They don't, so it returns `False`.\n", - "We can change this behavior by defining the special method `__eq__`." + "Так как это не так, результатом будет `False`. Мы можем изменить это поведение, определив специальный метод `__eq__`.\n" ] }, { @@ -309,10 +305,7 @@ "id": "bd66a9d3", "metadata": {}, "source": [ - "`__eq__` takes two `Card` objects as parameters and returns `True` if they have the same suit and rank, even if they are not the same object.\n", - "In other words, it checks whether they are equivalent, even if they are not identical.\n", - "\n", - "When we use the `==` operator with `Card` objects, Python calls the `__eq__` method." + "`__eq__` принимает два объекта `Card` и возвращает `True`, если у них одинаковые масть и ранг, даже если это разные объекты. Другими словами, он проверяет, эквивалентны ли карты, даже если они не идентичны. Когда мы применяем к объектам `Card` оператор `==`, Python вызывает метод `__eq__`.\n" ] }, { @@ -328,7 +321,7 @@ "id": "23d99d3e", "metadata": {}, "source": [ - "As a second test, let's create a card with the same suit and a different rank." + "Для второго теста создадим карту с той же мастью, но другим рангом.\n" ] }, { @@ -344,7 +337,7 @@ "id": "c5f66404", "metadata": {}, "source": [ - "We can confirm that `queen` and `six` are not equivalent." + "Мы можем убедиться, что `queen` и `six` не эквивалентны.\n" ] }, { @@ -360,8 +353,7 @@ "id": "1dcb561f", "metadata": {}, "source": [ - "If we use the `!=` operator, Python invokes a special method called `__ne__`, if it exists.\n", - "Otherwise it invokes`__eq__` and inverts the result -- so if `__eq__` returns `True`, the result of the `!=` operator is `False`." + "Если использовать оператор `!=`, Python вызывает специальный метод `__ne__`, если он определён. В противном случае вызывается `__eq__`, а его результат инвертируется — поэтому, если `__eq__` вернул `True`, оператор `!=` даст `False`.\n" ] }, { @@ -385,8 +377,7 @@ "id": "77c48464", "metadata": {}, "source": [ - "Now suppose we want to compare two cards to see which is bigger.\n", - "If we use one of the relational operators, we get a `TypeError`." + "Теперь предположим, что нам нужно определить, какая из двух карт больше. Если применить один из операторов сравнения, возникнет `TypeError`.\n" ] }, { @@ -404,11 +395,7 @@ "id": "4db0ad52", "metadata": {}, "source": [ - "To change the behavior of the `<` operator, we can define a special method called `__lt__`, which is short for \"less than\".\n", - "For the sake of this example, let's assume that suit is more important than rank -- so all Spades outrank all Hearts, which outrank all Diamonds, and so on.\n", - "If two cards have the same suit, the one with the higher rank wins.\n", - "\n", - "To implement this logic, we'll use the following method, which returns a tuple containing a card's suit and rank, in that order." + "Чтобы изменить поведение оператора `<`, можно определить специальный метод `__lt__` (от англ. «less than»). Для примера будем считать, что масть важнее ранга: все пики старше червей, черви старше бубен и т.д. Если масти одинаковы, выигрывает карта с большим рангом. Для реализации этой логики используем метод, возвращающий кортеж из масти и ранга карты в таком порядке.\n" ] }, { @@ -424,7 +411,7 @@ "id": "d5062348", "metadata": {}, "source": [ - "We can use this method to write `__lt__`." + "Используя этот метод, мы можем написать `__lt__`.\n" ] }, { @@ -440,10 +427,7 @@ "id": "bd9ef8f5", "metadata": {}, "source": [ - "Tuple comparison compares the first elements from each tuple, which represent the suits.\n", - "If they are the same, it compares the second elements, which represent the ranks.\n", - "\n", - "Now if we use the `<` operator, it invokes the `__lt__` method." + "При сравнении кортежей сначала сопоставляются первые элементы, то есть масти. Если они совпадают, сравниваются вторые элементы — ранги. Теперь при использовании оператора `<` будет вызываться метод `__lt__`.\n" ] }, { @@ -459,8 +443,7 @@ "id": "83289a77", "metadata": {}, "source": [ - "If we use the `>` operator, it invokes a special method called `__gt__`, if it exists.\n", - "Otherwise it invokes `__lt__` with the arguments in the opposite order." + "Если применить оператор `>`, Python вызовет специальный метод `__gt__`, если он есть. Иначе используется `__lt__`, но с аргументами в обратном порядке.\n" ] }, { @@ -484,7 +467,7 @@ "id": "5d0a91de", "metadata": {}, "source": [ - "Finally, if we use the `<=` operator, it invokes a special method called `__le__`." + "Наконец, оператор `<=` вызывает специальный метод `__le__`.\n" ] }, { @@ -500,7 +483,7 @@ "id": "6c85ac69", "metadata": {}, "source": [ - "So we can check whether one card is less than or equal to another." + "Таким образом можно проверить, что одна карта меньше либо равна другой.\n" ] }, { @@ -524,7 +507,7 @@ "id": "7af7b289", "metadata": {}, "source": [ - "If we use the `>=` operator, it uses `__ge__` if it exists. Otherwise, it invokes `__le__` with the arguments in the opposite order." + "Оператор `>=` использует метод `__ge__`, если он определён; иначе вызывается `__le__` с аргументами в обратном порядке.\n" ] }, { @@ -540,9 +523,7 @@ "id": "fe2a81cc", "metadata": {}, "source": [ - "As we have defined them, these methods are complete in the sense that we can compare any two `Card` objects, and consistent in the sense that results from different operators don't contradict each other.\n", - "With these two properties, we can say that `Card` objects are **totally ordered**.\n", - "And that means, as we'll see soon, that they can be sorted." + "В нашем определении эти методы позволяют сравнивать любые два объекта `Card`, причём результаты разных операторов согласованы друг с другом. При наличии этих свойств можно сказать, что объекты `Card` **полностью упорядочены**. А это значит, что их можно сортировать.\n" ] }, { @@ -550,11 +531,9 @@ "id": "199f8bfc", "metadata": {}, "source": [ - "## Decks\n", + "## Колоды\n", "\n", - "Now that we have objects that represent cards, let's define objects that represent decks.\n", - "The following is a class definition for `Deck` with\n", - "an `__init__` method takes a list of `Card` objects as a parameter and assigns it to an attribute called `cards`." + "Теперь, когда у нас есть объекты, представляющие карты, определим объекты для представления колод. Ниже приведено определение класса `Deck`, чьей метод `__init__` принимает список объектов `Card` и сохраняет его в атрибуте `cards`.\n" ] }, { @@ -570,7 +549,7 @@ "id": "2d529789", "metadata": {}, "source": [ - "To create a list that contains the 52 cards in a standard deck, we'll use the following static method." + "Чтобы создать список из 52 карт стандартной колоды, воспользуемся следующим статическим методом.\n" ] }, { @@ -586,11 +565,7 @@ "id": "47ae8f71", "metadata": {}, "source": [ - "In `make_cards`, the outer loop enumerates the suits from `0` to `3`.\n", - "The inner loop enumerates the ranks from `2` to `14` -- where `14` represents an Ace that outranks a King.\n", - "Each iteration creates a new `Card` with the current suit and rank, and appends it to `cards`.\n", - "\n", - "Here's how we make a list of cards and a `Deck` object that contains it." + "В `make_cards` внешний цикл перебирает масти от `0` до `3`, а внутренний — ранги от `2` до `14`, где `14` обозначает туза, старше короля. Каждая итерация создаёт новую `Card` с текущими мастью и рангом и добавляет её в `cards`. Так мы получаем список карт и объект `Deck`, который их содержит.\n" ] }, { @@ -606,7 +581,7 @@ "id": "032ec302", "metadata": {}, "source": [ - "It contains 52 cards, as intended." + "В нём 52 карты, как и задумано.\n" ] }, { @@ -616,9 +591,9 @@ "tags": [] }, "source": [ - "## Printing the deck\n", + "## Вывод колоды\n", "\n", - "Here is a `__str__` method for `Deck`." + "Вот метод `__str__` для `Deck`.\n" ] }, { @@ -634,9 +609,9 @@ "id": "660f18e6", "metadata": {}, "source": [ - "This method demonstrates an efficient way to accumulate a large string -- building a list of strings and then using the string method `join`. \n", + "Этот метод демонстрирует эффективный способ собрать длинную строку: сначала формируется список строк, после чего используется метод `join`.\n", "\n", - "We'll test this method with a deck that only contains two cards." + "Проверим его на колоде, содержащей всего две карты.\n" ] }, { @@ -652,7 +627,7 @@ "id": "91c7145f", "metadata": {}, "source": [ - "If we call `str`, it invokes `__str__`." + "При вызове `str` будет задействован `__str__`.\n" ] }, { @@ -668,9 +643,9 @@ "id": "00270656", "metadata": {}, "source": [ - "When Jupyter displays a string, it shows the \"representational\" form of the string, which represents a newline with the sequence `\\n`.\n", + "Когда Jupyter отображает строку, он показывает её «представительную» форму, где перевод строки обозначается последовательностью `\\n`.\n", "\n", - "However, if we print the result, Jupyter shows the \"printable\" form of the string, which prints the newline as whitespace." + "Если же мы выводим строку функцией `print`, Jupyter показывает «печатную» форму, в которой перевод строки отображается пробелами.\n" ] }, { @@ -686,7 +661,7 @@ "id": "e97810c4", "metadata": {}, "source": [ - "So the cards appear on separate lines." + "Поэтому карты выводятся каждая на своей строке.\n" ] }, { @@ -694,11 +669,9 @@ "id": "52d3d597", "metadata": {}, "source": [ - "## Add, remove, shuffle and sort\n", + "## Добавление, удаление, тасование и сортировка\n", "\n", - "To deal cards, we would like a method that removes a card from the deck\n", - "and returns it. The list method `pop` provides a convenient way to do\n", - "that." + "Чтобы раздавать карты, нужен метод, который извлекает карту из колоды и возвращает её. Для этого удобно использовать метод списка `pop`.\n" ] }, { @@ -714,7 +687,7 @@ "id": "1fcef47b", "metadata": {}, "source": [ - "Here's how we use it." + "Вот как его использовать.\n" ] }, { @@ -730,7 +703,7 @@ "id": "65427954", "metadata": {}, "source": [ - "We can confirm that there are `51` cards left in the deck." + "Можно убедиться, что в колоде осталось `51` карта.\n" ] }, { @@ -746,7 +719,7 @@ "id": "7ca3614e", "metadata": {}, "source": [ - "To add a card, we can use the list method `append`." + "Чтобы добавить карту, воспользуемся методом списка `append`.\n" ] }, { @@ -762,7 +735,7 @@ "id": "2ecd8703", "metadata": {}, "source": [ - "As an example, we can put back the card we just popped." + "Например, можно вернуть в колоду только что взятую карту.\n" ] }, { @@ -778,7 +751,7 @@ "id": "8b5af8ce", "metadata": {}, "source": [ - "To shuffle the deck, we can use the `shuffle` function from the `random` module:" + "Для перетасовки колоды воспользуемся функцией `shuffle` из модуля `random`:\n" ] }, { @@ -812,7 +785,7 @@ "id": "a8cb1a7f", "metadata": {}, "source": [ - "If we shuffle the deck and print the first few cards, we can see that they are in no apparent order." + "Если перетасовать колоду и вывести первые несколько карт, видно, что они расположены в произвольном порядке.\n" ] }, { @@ -828,7 +801,7 @@ "id": "a198dde3", "metadata": {}, "source": [ - "To sort the cards, we can use the list method `sort`, which sorts the elements \"in place\" -- that is, it modifies the list rather than creating a new list." + "Для сортировки карт применим метод `sort`, который сортирует элементы «на месте», то есть изменяет исходный список, не создавая новый.\n" ] }, { @@ -844,7 +817,7 @@ "id": "d4f017c7", "metadata": {}, "source": [ - "When we invoke `sort`, it uses the `__lt__` method to compare cards." + "При вызове `sort` для сравнения карт используется метод `__lt__`.\n" ] }, { @@ -860,7 +833,7 @@ "id": "2bb966fd", "metadata": {}, "source": [ - "If we print the first few cards, we can confirm that they are in increasing order." + "Если вывести первые карты, можно убедиться, что они расположены в порядке возрастания.\n" ] }, { @@ -876,8 +849,7 @@ "id": "5c41ce4d", "metadata": {}, "source": [ - "In this example, `Deck.sort` doesn't do anything other than invoke `list.sort`.\n", - "Passing along responsibility like this is called **delegation**." + "В данном примере `Deck.sort` лишь вызывает `list.sort`. Передачу ответственности подобным образом называют **делегированием**.\n" ] }, { @@ -885,18 +857,17 @@ "id": "0502961b", "metadata": {}, "source": [ - "## Parents and children\n", + "## Родительские и дочерние классы\n", "\n", - "Inheritance is the ability to define a new class that is a modified version of an existing class.\n", - "As an example, let's say we want a class to represent a \"hand\", that is, the cards held by one player.\n", + "Наследование позволяет определить новый класс как модифицированную версию существующего. Допустим, мы хотим класс, представляющий «руку» игрока.\n", "\n", - "* A hand is similar to a deck -- both are made up of a collection of cards, and both require operations like adding and removing cards.\n", + "* Рука похожа на колоду — это коллекция карт, для которой нужны операции добавления и удаления.\n", "\n", - "* A hand is also different from a deck -- there are operations we want for hands that don't make sense for a deck. For example, in poker we might compare two hands to see which one wins. In bridge, we might compute a score for a hand in order to make a bid.\n", + "* Рука отличается от колоды: для неё полезны операции, которые не имеют смысла для колоды. Например, в покере можно сравнивать руки, чтобы определить победителя; в бридже можно вычислять очки, чтобы сделать ставку.\n", "\n", - "This relationship between classes -- where one is a specialized version of another -- lends itself to inheritance. \n", + "Такое отношение между классами, когда один является специализированной версией другого, естественно выражается через наследование.\n", "\n", - "To define a new class that is based on an existing class, we put the name of the existing class in parentheses." + "Чтобы определить новый класс на основе существующего, имя родительского класса указывают в скобках.\n" ] }, { @@ -912,9 +883,9 @@ "id": "339295cd", "metadata": {}, "source": [ - "This definition indicates that `Hand` inherits from `Deck`, which means that `Hand` objects can access methods defined in `Deck`, like `take_card` and `put_card`.\n", + "Это определение показывает, что `Hand` наследует `Deck`, поэтому объекты `Hand` могут использовать методы `Deck`, такие как `take_card` и `put_card`.\n", "\n", - "`Hand` also inherits `__init__` from `Deck`, but if we define `__init__` in the `Hand` class, it overrides the one in the `Deck` class." + "Метод `__init__` тоже наследуется, но если определить `__init__` в классе `Hand`, он заменит родительскую версию.\n" ] }, { @@ -930,8 +901,7 @@ "id": "9b6a763a", "metadata": {}, "source": [ - "This version of `__init__` takes an optional string as a parameter, and always starts with an empty list of cards.\n", - "When we create a `Hand`, Python invokes this method, not the one in `Deck` -- which we can confirm by checking that the result has a `label` attribute." + "В этой версии `__init__` принимает необязательную строку и всегда начинает с пустого списка карт. Создавая `Hand`, Python вызывает именно этот метод, а не родительский — что можно проверить по наличию атрибута `label`.\n" ] }, { @@ -947,7 +917,7 @@ "id": "b1e2a67d", "metadata": {}, "source": [ - "To deal a card, we can use `take_card` to remove a card from a `Deck`, and `put_card` to add the card to a `Hand`." + "Чтобы раздать карту, используем `take_card` для извлечения карты из `Deck` и `put_card` — чтобы добавить её в `Hand`.\n" ] }, { @@ -963,7 +933,7 @@ "id": "dc2ce06b", "metadata": {}, "source": [ - "Let's encapsulate this code in a `Deck` method called `move_cards`." + "Заключим этот код в метод `move_cards` класса `Deck`.\n" ] }, { @@ -979,8 +949,7 @@ "id": "16e6c404", "metadata": {}, "source": [ - "This method is polymorphic -- that is, it works with more than one type: `self` and `other` can be either a `Hand` or a `Deck`.\n", - "So we can use this method to deal a card from `Deck` to a `Hand`, from one `Hand` to another, or from a `Hand` back to a `Deck`." + "Этот метод полиморфный: и `self`, и `other` могут быть как `Hand`, так и `Deck`. Поэтому с его помощью можно передавать карту из колоды в руку, из руки в руку или из руки обратно в колоду.\n" ] }, { @@ -988,18 +957,13 @@ "id": "e648a722", "metadata": {}, "source": [ - "When a new class inherits from an existing one, the existing one is called the **parent** and the new class is called the **child**. In general:\n", + "Когда один класс наследуется от другого, исходный называют **родителем**, а новый — **потомком**. В общем случае:\n", "\n", - "* Instances of the child class should have all of the attributes of the parent class, but they can have additional attributes.\n", + "* Экземпляры дочернего класса должны иметь все атрибуты родительского, но могут иметь и дополнительные.\n", + "* Дочерний класс должен наследовать все методы родителя, но также может определять свои.\n", + "* Если дочерний класс переопределяет метод родителя, новый метод должен принимать те же параметры и возвращать совместимый результат.\n", "\n", - "* The child class should have all of the methods of the parent class, but it can have additional methods.\n", - "\n", - "* If a child class overrides a method from the parent class, the new method should take the same parameters and return a compatible result.\n", - "\n", - "This set of rules is called the \"Liskov substitution principle\" after computer scientist Barbara Liskov.\n", - "\n", - "If you follow these rules, any function or method designed to work with an instance of a parent class, like a `Deck`, will also work with instances of a child class, like `Hand`.\n", - "If you violate these rules, your code will collapse like a house of cards (sorry)." + "Эти правила известны как «принцип подстановки Барбары Лисков». Если их соблюдать, любая функция, рассчитанная на экземпляры родительского класса, будет работать и с экземплярами потомка, например `Deck` и `Hand`. Нарушение этих правил приведёт к тому, что программа рассыпется как карточный домик (простите).\n" ] }, { @@ -1007,12 +971,11 @@ "id": "e80873dd", "metadata": {}, "source": [ - "## Specialization\n", + "## Специализация\n", "\n", - "Let's make a class called `BridgeHand` that represents a hand in bridge -- a widely played card game.\n", - "We'll inherit from `Hand` and add a new method called `high_card_point_count` that evaluates a hand using a \"high card point\" method, which adds up points for the high cards in the hand.\n", + "Создадим класс `BridgeHand`, представляющий руку в бридже — популярной карточной игре. Он наследует `Hand` и добавляет метод `high_card_point_count`, который оценивает руку по числу очков старших карт.\n", "\n", - "Here's a class definition that contains as a class variable a dictionary that maps from card names to their point values." + "Ниже приведено определение класса, который содержит словарь `hcp_dict`, связывающий названия карт с их ценностью.\n" ] }, { @@ -1028,7 +991,7 @@ "id": "4c038717", "metadata": {}, "source": [ - "Given the rank of a card, like `12`, we can use `Card.rank_names` to get the string representation of the rank, and then use `hcp_dict` to get its score." + "Зная ранг карты, например `12`, можно с помощью `Card.rank_names` получить его строковое представление и по `hcp_dict` узнать соответствующее количество очков.\n" ] }, { @@ -1044,7 +1007,7 @@ "id": "c3a7820d", "metadata": {}, "source": [ - "The following method loops through the cards in a `BridgeHand` and adds up their scores." + "Следующий метод проходит по картам в `BridgeHand` и суммирует их очки.\n" ] }, { @@ -1070,7 +1033,7 @@ "id": "94535d8e", "metadata": {}, "source": [ - "To test it, we'll deal a hand with five cards -- a bridge hand usually has thirteen, but it's easier to test code with small examples." + "Для теста раздадим руку из пяти карт — в бридже их обычно тринадцать, но с маленькими примерами код проверять проще.\n" ] }, { @@ -1086,7 +1049,7 @@ "id": "a1bd2521", "metadata": {}, "source": [ - "And here is the total score for the King and Queen." + "Вот общий счёт для короля и дамы.\n" ] }, { @@ -1102,8 +1065,7 @@ "id": "b4f5e107", "metadata": {}, "source": [ - "`BridgeHand` inherits the variables and methods of `Hand` and adds a class variable and a method that are specific to bridge.\n", - "This way of using inheritance is called **specialization** because it defines a new class that is specialized for a particular use, like playing bridge." + "Класс `BridgeHand` наследует переменные и методы `Hand`, добавляя при этом переменную класса и метод, специфичные для бриджа. Такой способ применения наследования называют **специализацией**, потому что он создаёт класс, адаптированный под конкретную задачу — например, игру в бридж.\n" ] }, { @@ -1111,20 +1073,13 @@ "id": "b493622d", "metadata": {}, "source": [ - "## Debugging\n", - "\n", - "Inheritance is a useful feature.\n", - "Some programs that would be repetitive without inheritance can be written more concisely with it.\n", - "Also, inheritance can facilitate code reuse, since you can customize the behavior of a parent class without having to modify it.\n", - "In some cases, the inheritance structure reflects the natural structure of the problem, which makes the design easier to understand.\n", + "## Отладка\n", "\n", - "On the other hand, inheritance can make programs difficult to read.\n", - "When a method is invoked, it is sometimes not clear where to find its definition -- the relevant code may be spread across several modules.\n", + "Наследование — полезная особенность. Некоторые программы, которые без наследования были бы повторяющимися, с ним пишутся короче. Также наследование может облегчить повторное использование кода, поскольку поведение родительского класса можно менять, не изменяя его. В некоторых случаях структура наследования отражает естественную структуру задачи, что упрощает понимание дизайна.\n", "\n", - "Any time you are unsure about the flow of execution through your program, the simplest solution is to add print statements at the beginning of the relevant methods.\n", - "If `Deck.shuffle` prints a message that says something like `Running Deck.shuffle`, then as the program runs it traces the flow of execution.\n", + "С другой стороны, наследование может осложнять чтение программ. Когда вызывается метод, не всегда ясно, где находится его определение — нужный код может быть разбросан по нескольким модулям.\n", "\n", - "As an alternative, you could use the following function, which takes an object and a method name (as a string) and returns the class that provides the definition of the method." + "Если вы не уверены в ходе выполнения программы, самый простой способ — добавить операторы печати в начало соответствующих методов. Если `Deck.shuffle` выводит сообщение вроде `Running Deck.shuffle`, то во время работы программы можно проследить ход выполнения.\n" ] }, { @@ -1140,10 +1095,7 @@ "id": "1ee8f2da", "metadata": {}, "source": [ - "`find_defining_class` uses the `mro` method to get the list of class objects (types) that will be searched for methods.\n", - "\"MRO\" stands for \"method resolution order\", which is the sequence of classes Python searches to \"resolve\" a method name -- that is, to find the function object the name refers to.\n", - "\n", - "As an example, let's instantiate a `BridgeHand` and then find the defining class of `shuffle`." + "Функция `find_defining_class` использует метод `mro`, чтобы получить список классов (типов), в которых будет искаться нужный метод. Аббревиатура MRO означает «порядок разрешения методов» — последовательность классов, которую Python просматривает, чтобы найти объект функции по имени метода. Например, давайте создадим `BridgeHand` и узнаем, в каком классе определён метод `shuffle`.\n" ] }, { @@ -1159,7 +1111,7 @@ "id": "eeb70a14", "metadata": {}, "source": [ - "The `shuffle` method for the `BridgeHand` object is the one in `Deck`." + "Метод `shuffle` у объекта `BridgeHand` — тот, что определён в `Deck`.\n" ] }, { @@ -1167,31 +1119,31 @@ "id": "07f4c4bb", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", "**inheritance:**\n", - " The ability to define a new class that is a modified version of a previously defined class.\n", + " Способность определить новый класс как модифицированную версию ранее определённого класса.\n", "\n", "**encode:**\n", - " To represent one set of values using another set of values by constructing a mapping between them.\n", + " Представлять один набор значений с помощью другого набора, задавая отображение между ними.\n", "\n", "**class variable:**\n", - "A variable defined inside a class definition, but not inside any method.\n", + "Переменная, определённая внутри определения класса, но не внутри метода.\n", "\n", "**totally ordered:**\n", - "A set of objects is totally ordered if we can compare any two elements and the results are consistent.\n", + "Набор объектов полностью упорядочен, если можно сравнить любые два элемента, и результаты согласованы.\n", "\n", "**delegation:**\n", - "When one method passes responsibility to another method to do most or all of the work.\n", + "Передача ответственности от одного метода другому для выполнения большей части работы.\n", "\n", "**parent class:**\n", - "A class that is inherited from.\n", + "Класс, от которого наследуются.\n", "\n", "**child class:**\n", - "A class that inherits from another class.\n", + "Класс, наследующий другой класс.\n", "\n", "**specialization:**\n", - "A way of using inheritance to create a new class that is a specialized version of an existing class." + "Использование наследования для создания класса, специализированного под определённую задачу.\n" ] }, { @@ -1199,7 +1151,7 @@ "id": "1aea9b2b", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения\n" ] }, { @@ -1217,25 +1169,19 @@ "id": "7913e6b1", "metadata": {}, "source": [ - "### Ask a Virtual Assistant\n", - "\n", - "When it goes well, object-oriented programming can make programs more readable, testable, and reusable.\n", - "But it can also make programs complicated and hard to maintain.\n", - "As a result, OOP is a topic of controversy -- some people love it, and some people don't.\n", - "\n", - "To learn more about the topic, ask a virtual assistant:\n", - "\n", - "* What are some pros and cons of object-oriented programming?\n", + "### Спросите виртуального ассистента\n", "\n", - "* What does it mean when people say \"favor composition over inheritance\"?\n", + "Когда объектно‑ориентированное программирование применяется правильно, программы становятся более понятными, тестируемыми и пригодными к повторному использованию. Но оно может и усложнить код, сделав его трудно поддерживаемым. Поэтому к ООП относятся по‑разному — кто-то его любит, кто-то нет.\n", "\n", - "* What is the Liskov substitution principle?\n", + "Чтобы узнать больше, спросите у виртуального помощника:\n", "\n", - "* Is Python an object-oriented language?\n", + "* Каковы плюсы и минусы объектно‑ориентированного программирования?\n", + "* Что значит принцип «предпочитайте композицию наследованию»?\n", + "* В чём заключается принцип подстановки Барбары Лисков?\n", + "* Является ли Python объектно‑ориентированным языком?\n", + "* Какие требования предъявляются к тому, чтобы множество считалось полностью упорядоченным?\n", "\n", - "* What are the requirements for a set to be totally ordered?\n", - "\n", - "And as always, consider using a virtual assistant to help with the following exercises." + "И, как всегда, не стесняйтесь обращаться к виртуальному ассистенту при выполнении следующих упражнений.\n" ] }, { @@ -1243,10 +1189,9 @@ "id": "1af81269", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In contract bridge, a \"trick\" is a round of play in which each of four players plays one card.\n", - "To represent those cards, we'll define a class that inherits from `Deck`." + "В контрактном бридже «взятка» — это раунд игры, в котором каждый из четырёх игроков кладёт по карте. Чтобы представить эти карты, мы определим класс, который наследует `Deck`.\n" ] }, { @@ -1262,10 +1207,7 @@ "id": "9916d562", "metadata": {}, "source": [ - "As an example, consider this trick, where the first player leads with the 3 of Diamonds, which means that Diamonds are the \"led suit\".\n", - "The second and third players \"follow suit\", which means they play a card with the led suit.\n", - "The fourth player plays a card of a different suit, which means they cannot win the trick.\n", - "So the winner of this trick is the third player, because they played the highest card in the led suit." + "В качестве примера рассмотрим такую взятку, где первый игрок ходит тройкой бубен, из-за чего бубны становятся \"ведущей мастью\". Второй и третий игроки \"ходят в масть\", то есть кладут карту той же масти. Четвёртый игрок кладёт карту другой масти и не может выиграть взятку. Побеждает третий игрок, так как у него самая старшая карта ведущей масти.\n" ] }, { @@ -1281,8 +1223,7 @@ "id": "c94a1337", "metadata": {}, "source": [ - "Write a `Trick` method called `find_winner` that loops through the cards in the `Trick` and returns the index of the card that wins.\n", - "In the previous example, the index of the winning card is `2`." + "Напишите метод `find_winner` класса `Trick`, который проходит по картам во взятке и возвращает индекс карты-победителя. В приведённом примере индекс выигравшей карты — `2`.\n" ] }, { @@ -1292,7 +1233,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Используйте следующий шаблон, чтобы начать.\n" ] }, { @@ -1322,7 +1263,7 @@ "tags": [] }, "source": [ - "If you test your method with the previous example, the index of the winning card should be `2`." + "Если протестировать метод на предыдущем примере, индекс выигравшей карты должен быть `2`.\n" ] }, { @@ -1340,11 +1281,9 @@ "id": "b5b9fb4b", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "The next few exercises ask to you write functions that classify poker hands.\n", - "If you are not familiar with poker, I'll explain what you need to know.\n", - "We'll use the following class to represent poker hands." + "Следующие несколько упражнений предлагают написать функции, определяющие тип покерной руки. Если вы не знакомы с покером, я расскажу всё необходимое. Для представления покерных рук будем использовать следующий класс.\n" ] }, { @@ -1360,18 +1299,14 @@ "id": "2daecced", "metadata": {}, "source": [ - "`PokerHand` provides two methods that will help with the exercises.\n", - "\n", - "* `get_suit_counts` loops through the cards in the `PokerHand`, counts the number of cards in each suit, and returns a dictionary that maps from each suit code to the number of times it appears.\n", + "`PokerHand` предоставляет два метода, которые пригодятся в упражнениях.\n", "\n", - "* `get_rank_counts` does the same thing with the ranks of the cards, returning a dictionary that maps from each rank code to the number of times it appears.\n", + "* `get_suit_counts` проходит по картам в `PokerHand`, подсчитывает количество карт каждой масти и возвращает словарь, где коду масти сопоставлено число повторений.\n", + "* `get_rank_counts` делает то же для рангов, возвращая словарь, где код ранга сопоставлен числу повторений.\n", "\n", - "All of the exercises that follow can be done using only the Python features we have learned so far, but some of them are more difficult than most of the previous exercises.\n", - "I encourage you to ask an AI for help.\n", + "Все последующие упражнения можно выполнить, используя лишь изученные возможности Python, хотя некоторые из них сложнее предыдущих. Рекомендую обращаться к ИИ за помощью.\n", "\n", - "For problems like this, it often works well to ask for general advice about strategies and algorithms.\n", - "Then you can either write the code yourself or ask for code.\n", - "If you ask for code, you might want to provide the relevant class definitions as part of the prompt." + "В подобных задачах полезно спрашивать общие советы по стратегии и алгоритмам, а затем либо писать код самостоятельно, либо просить ИИ сгенерировать его. В последнем случае стоит включить определения классов в запрос.\n" ] }, { @@ -1379,10 +1314,9 @@ "id": "ccc2d8ca", "metadata": {}, "source": [ - "As a first exercise, we'll write a method called `has_flush` that checks whether a hand has a \"flush\" -- that is, whether it contains at least five cards of the same suit.\n", + "В качестве первого упражнения напишем метод `has_flush`, который проверяет, есть ли в руке \"флеш\", то есть по крайней мере пять карт одной масти.\n", "\n", - "In most varieties of poker, a hand contains either five or seven cards, but there are some exotic variations where a hand contains other numbers of cards.\n", - "But regardless of how many cards there are in a hand, the only ones that count are the five that make the best hand." + "В большинстве разновидностей покера в руке либо пять, либо семь карт, но есть и экзотические варианты с другим количеством. При этом важны только пять карт, составляющие лучшую комбинацию.\n" ] }, { @@ -1392,7 +1326,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Можно воспользоваться следующим шаблоном.\n" ] }, { @@ -1422,7 +1356,7 @@ "tags": [] }, "source": [ - "To test this method, we'll construct a hand with five cards that are all Clubs, so it contains a flush." + "Для проверки создадим руку из пяти карт одной масти — это флеш.\n" ] }, { @@ -1442,7 +1376,7 @@ "tags": [] }, "source": [ - "If we invoke `get_suit_counts`, we can confirm that the rank code `0` appears `5` times." + "Если вызвать `get_suit_counts`, убедимся, что код масти `0` встречается `5` раз.\n" ] }, { @@ -1462,7 +1396,7 @@ "tags": [] }, "source": [ - "So `has_flush` should return `True`." + "Следовательно, `has_flush` должен вернуть `True`.\n" ] }, { @@ -1482,7 +1416,7 @@ "tags": [] }, "source": [ - "As a second test, we'll construct a hand with three Clubs and two other suits." + "Для второго теста соберём руку из трёх карт треф и двух других мастей.\n" ] }, { @@ -1502,7 +1436,7 @@ "tags": [] }, "source": [ - "So `has_flush` should return `False`." + "Теперь `has_flush` должен вернуть `False`.\n" ] }, { @@ -1520,13 +1454,11 @@ "id": "ad716880", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a method called `has_straight` that checks whether a hand contains a straight, which is a set of five cards with consecutive ranks.\n", - "For example, if a hand contains ranks `5`, `6`, `7`, `8`, and `9`, it contains a straight.\n", + "Напишите метод `has_straight`, который проверяет, содержит ли рука стрит — пять карт с последовательными рангами. Например, если в руке есть ранги `5`, `6`, `7`, `8` и `9`, это стрит.\n", "\n", - "An Ace can come before a two or after a King, so `Ace`, `2`, `3`, `4`, `5` is a straight and so it `10`, `Jack`, `Queen`, `King`, `Ace`.\n", - "But a straight cannot \"wrap around\", so `King`, `Ace`, `2`, `3`, `4` is not a straight." + "Туз может стоять как перед двойкой, так и после короля, поэтому `Ace`, `2`, `3`, `4`, `5` — это стрит, как и `10`, `Jack`, `Queen`, `King`, `Ace`. Но стрит не может «заворачиваться», так что `King`, `Ace`, `2`, `3`, `4` стритом не считается.\n" ] }, { @@ -1536,8 +1468,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started.\n", - "It includes a few lines of code that count the number of Aces -- represented with the code `1` or `14` -- and store the total in both locations of the counter." + "Можно использовать следующий шаблон. В нём есть несколько строк кода, которые подсчитывают количество тузов — представленных кодами `1` или `14` — и сохраняют его в обоих местах счётчика.\n" ] }, { @@ -1567,8 +1498,7 @@ "tags": [] }, "source": [ - "`good_hand`, which we created for the previous exercise, contains a straight.\n", - "If we use `get_rank_counts`, we can confirm that it has at least one card with each of five consecutive ranks." + "`good_hand`, созданная в предыдущем упражнении, содержит стрит. Если вызвать `get_rank_counts`, можно убедиться, что в ней есть по крайней мере одна карта каждого из пяти последовательных рангов.\n" ] }, { @@ -1588,7 +1518,7 @@ "tags": [] }, "source": [ - "So `has_straight` should return `True`." + "Поэтому `has_straight` должен вернуть `True`.\n" ] }, { @@ -1608,7 +1538,7 @@ "tags": [] }, "source": [ - "`bad_hand` does not contain a straight, so `has_straight` should return `False`." + "`bad_hand` не содержит стрита, поэтому `has_straight` должна вернуть `False`.\n" ] }, { @@ -1626,10 +1556,9 @@ "id": "c1ecebd3", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "A hand has a straight flush if it contains a set of five cards that are both a straight and a flush -- that is, five cards of the same suit with consecutive ranks.\n", - "Write a `PokerHand` method that checks whether a hand has a straight flush." + "Рука имеет стрит‑флеш, если в ней есть пять карт одной масти с последовательными рангами. Напишите метод `PokerHand`, который проверяет наличие стрит‑флеша.\n" ] }, { @@ -1639,7 +1568,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Можно воспользоваться следующим шаблоном.\n" ] }, { @@ -1679,7 +1608,7 @@ "tags": [] }, "source": [ - "Use the following examples to test your method." + "Используйте следующие примеры для тестирования метода.\n" ] }, { @@ -1709,8 +1638,7 @@ "tags": [] }, "source": [ - "Note that it is not enough to check whether a hand has a straight and a flush.\n", - "To see why, consider the following hand." + "Недостаточно просто проверить, есть ли в руке стрит и флеш. Чтобы понять почему, рассмотрим следующую руку.\n" ] }, { @@ -1730,7 +1658,7 @@ "tags": [] }, "source": [ - "This hand contains a straight and a flush, but they are not the same five cards." + "В этой руке есть и стрит, и флеш, но это не одни и те же пять карт.\n" ] }, { @@ -1750,7 +1678,7 @@ "tags": [] }, "source": [ - "So it does not contain a straight flush." + "Следовательно, стрит‑флеша здесь нет.\n" ] }, { @@ -1768,10 +1696,9 @@ "id": "dd742401", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "A poker hand has a pair if it contains two or more cards with the same rank.\n", - "Write a `PokerHand` method that checks whether a hand contains a pair." + "Пара — это наличие как минимум двух карт одного ранга. Напишите метод `PokerHand`, который проверяет, содержит ли рука пару.\n" ] }, { @@ -1781,7 +1708,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Можно использовать следующий шаблон.\n" ] }, { @@ -1819,7 +1746,7 @@ "id": "9f001207", "metadata": {}, "source": [ - "To test your method, here's a hand that has a pair." + "Для проверки используйте руку, в которой есть пара.\n" ] }, { @@ -1859,10 +1786,9 @@ "id": "c4180a64", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "A hand has a full house if it contains three cards of one rank and two cards of another rank.\n", - "Write a `PokerHand` method that checks whether a hand has a full house." + "Фул‑хаус — это три карты одного ранга и две карты другого. Напишите метод `PokerHand`, который проверяет, есть ли у руки фул‑хаус.\n" ] }, { @@ -1872,7 +1798,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Можно воспользоваться следующим шаблоном.\n" ] }, { @@ -1902,7 +1828,7 @@ "tags": [] }, "source": [ - "You can use this hand to test your method." + "Этой рукой можно проверить ваш метод.\n" ] }, { @@ -1950,10 +1876,9 @@ "id": "666340c1", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "This exercise is a cautionary tale about a common error that can be difficult to debug.\n", - "Consider the following class definition." + "Это упражнение — предостережение о распространённой ошибке, которую бывает сложно отладить. Рассмотрим следующее определение класса.\n" ] }, { @@ -1969,14 +1894,13 @@ "id": "1e349832", "metadata": {}, "source": [ - "`__init__` takes two parameters: `name` is required, but `contents` is optional -- if it's not provided, the default value is an empty list.\n", + "Метод `__init__` принимает два параметра: обязательное `name` и необязательное `contents`; если его не указать, по умолчанию используется пустой список.\n", "\n", - "`__str__` returns a string representation of the object that includes the name and the contents of the pouch.\n", + "Метод `__str__` возвращает строку с именем и содержимым сумки.\n", "\n", - "`put_in_pouch` takes any object and appends it to `contents`.\n", + "`put_in_pouch` добавляет в `contents` любой объект.\n", "\n", - "Now let's see how this class works.\n", - "We'll create two `Kangaroo` objects with the names `'Kanga'` and `'Roo'`." + "Посмотрим, как работает этот класс. Создадим два объекта `Kangaroo` с именами 'Kanga' и 'Roo'.\n" ] }, { @@ -1992,7 +1916,7 @@ "id": "533982d1", "metadata": {}, "source": [ - "To Kanga's pouch we'll add two strings and Roo." + "В сумку Кенги положим две строки и `roo`.\n" ] }, { @@ -2008,7 +1932,7 @@ "id": "41cd6d6e", "metadata": {}, "source": [ - "If we print `kanga`, it seems like everything worked." + "Если вывести `kanga`, кажется, что всё в порядке.\n" ] }, { @@ -2024,7 +1948,7 @@ "id": "0ba26163", "metadata": {}, "source": [ - "But what happens if we print `roo`?" + "Но что произойдёт, если напечатать `roo`?\n" ] }, { @@ -2040,10 +1964,7 @@ "id": "a2aef813", "metadata": {}, "source": [ - "Roo's pouch contains the same contents as Kanga's, including a reference to `roo`!\n", - "\n", - "See if you can figure out what went wrong.\n", - "Then ask a virtual assistant, \"What's wrong with the following program?\" and paste in the definition of `Kangaroo`." + "Оказывается, сумка `roo` содержит то же содержимое, что и у `kanga`, включая ссылку на самого `roo`! Попробуйте понять, в чём ошибка. Затем спросите у виртуального ассистента: «Что не так в этой программе?» и вставьте определение `Kangaroo`.\n" ] }, { @@ -2061,13 +1982,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3-е издание](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Лицензия текста: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)\n" ] } ], From 1a26f1a35ec0971a159f425d45c19fc53df5d784 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 14:38:18 +0300 Subject: [PATCH 24/44] Translate early markdown cells in chapter 18 --- blank/chap18.ipynb | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/blank/chap18.ipynb b/blank/chap18.ipynb index 6a069c1..7334312 100644 --- a/blank/chap18.ipynb +++ b/blank/chap18.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать печатную и электронную версии книги *Think Python 3e* на\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -27,7 +27,7 @@ "tags": [] }, "source": [ - "Here are versions of the `Card`, `Deck`, and `Hand` classes from Chapter 17, which we will use in some examples in this chapter." + "Ниже приведены версии классов `Card`, `Deck` и `Hand` из главы 17, которые мы будем использовать в примерах этой главы." ] }, { @@ -65,14 +65,14 @@ "id": "27e8d827", "metadata": {}, "source": [ - "# Python Extras\n", + "# Дополнительные возможности Python\n", "\n", - "One of my goals for this book has been to teach you as little Python as possible. \n", - "When there were two ways to do something, I picked one and avoided mentioning the other.\n", - "Or sometimes I put the second one into an exercise.\n", + "Одной из целей этой книги было научить вас как можно меньшему количеству особенностей Python.\n", + "Когда что-то можно было сделать двумя способами, я выбирал один и не упоминал другой.\n", + "Иногда я переносил второй способ в упражнение.\n", "\n", - "Now I want to go back for some of the good bits that got left behind.\n", - "Python provides a number of features that are not really necessary -- you can write good code without them -- but with them you can write code that's more concise, readable, or efficient, and sometimes all three." + "Теперь я хочу вернуться к полезным вещам, которые мы пропустили.\n", + "Python предлагает ряд возможностей, без которых можно обойтись — вы сможете писать хороший код и без них, — но с ними код становится короче, понятнее и эффективнее, а иногда совмещает все эти качества." ] }, { @@ -80,10 +80,10 @@ "id": "7ddcece8", "metadata": {}, "source": [ - "## Sets\n", + "## Множества\n", "\n", - "Python provides a class called `set` that represents a collection of unique elements.\n", - "To create an empty set, we can use the class object like a function." + "Python предоставляет класс `set`, который представляет коллекцию уникальных элементов.\n", + "Чтобы создать пустое множество, можно вызвать этот класс как функцию." ] }, { @@ -99,7 +99,7 @@ "id": "904e2071", "metadata": {}, "source": [ - "We can use the `add` method to add elements." + "Для добавления элементов можно использовать метод `add`." ] }, { @@ -115,7 +115,7 @@ "id": "beee02fc", "metadata": {}, "source": [ - "Or we can pass any kind of sequence to `set`." + "Или можно передать в `set` любую последовательность." ] }, { @@ -131,8 +131,8 @@ "id": "42f99153", "metadata": {}, "source": [ - "An element can only appear once in a `set`.\n", - "If you add an element that's already there, it has no effect." + "Элемент может встречаться в `set` только один раз.\n", + "Если добавить уже существующий элемент, ничего не произойдёт." ] }, { @@ -148,7 +148,7 @@ "id": "9b0a82ee", "metadata": {}, "source": [ - "Or if you create a set with a sequence that contains duplicates, the result contains only unique elements." + "Если создать множество из последовательности с повторяющимися элементами, в результате останутся только уникальные значения." ] }, { @@ -164,8 +164,8 @@ "id": "328e2009", "metadata": {}, "source": [ - "Some of the exercises in this book can be done concisely and efficiently with sets. \n", - "For example, here is a solution to an exercise in Chapter 11 that uses a dictionary to check whether there are any duplicate elements in a sequence." + "Некоторые упражнения в этой книге можно решить более лаконично и эффективно, используя множества.\n", + "Например, вот решение задачи из главы 11, где словарь применяется для проверки наличия повторяющихся элементов в последовательности." ] }, { @@ -181,8 +181,8 @@ "id": "0b250e58", "metadata": {}, "source": [ - "This version adds the element of `t` as keys in a dictionary, and then checks whether there are fewer keys than elements.\n", - "Using sets, we can write the same function like this." + "Эта версия добавляет элементы `t` в словарь в качестве ключей и затем проверяет, стало ли ключей меньше, чем элементов.\n", + "Используя множества, мы можем написать ту же функцию так." ] }, { @@ -2085,4 +2085,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 82a8fbed7a4b4112421ca827c8d1fb3c72bf422b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 14:38:24 +0300 Subject: [PATCH 25/44] Translate section in chapter 18 --- blank/chap18.ipynb | 58 +++++++++++++++++++------------------------ chapters/chap18.ipynb | 56 +++++++++++++++++++---------------------- 2 files changed, 51 insertions(+), 63 deletions(-) diff --git a/blank/chap18.ipynb b/blank/chap18.ipynb index 6a069c1..c45f63e 100644 --- a/blank/chap18.ipynb +++ b/blank/chap18.ipynb @@ -208,11 +208,11 @@ "id": "30cf3158", "metadata": {}, "source": [ - "An element can only appear in a set once, so if an element in `t` appears more than once, the set will be smaller than `t`.\n", - "If there are no duplicates, the set will be the same size as `t`.\n", + "Элемент может появиться в множестве только один раз, поэтому если элемент из `t` встречается более одного раза, множество будет меньше, чем `t`.\n", + "Если дубликатов нет, множество будет того же размера, что и `t`.\n", "\n", - "`set` objects provide methods that perform set operations.\n", - "For example, `union` computes the union of two sets, which is a new set that contains all elements that appear in either set." + "Объекты `set` предоставляют методы для выполнения операций над множествами.\n", + "Например, метод `union` вычисляет объединение двух множеств, создавая новое множество, содержащее все элементы, присутствующие хотя бы в одном из них.\n" ] }, { @@ -228,8 +228,8 @@ "id": "57b1d50c", "metadata": {}, "source": [ - "Some arithmetic operators work with sets.\n", - "For example, the `-` operator performs set subtraction -- the result is a new set that contains all elements from the first set that are _not_ in the second set." + "Некоторые арифметические операторы работают с множествами.\n", + "Например, оператор `-` выполняет вычитание множеств — результатом будет новое множество, содержащее все элементы из первого множества, которые *не* входят во второе.\n" ] }, { @@ -245,8 +245,8 @@ "id": "5099226c", "metadata": {}, "source": [ - "In [Chapter 12](section_dictionary_subtraction) we used dictionaries to find the words that appear in a document but not in a word list.\n", - "We used the following function, which takes two dictionaries and returns a new dictionary that contains only the keys from the first that don't appear in the second." + "В [главе 12](section_dictionary_subtraction) мы использовали словари, чтобы найти слова, которые встречаются в документе, но отсутствуют в словаре слов.\n", + "Мы написали следующую функцию, которая принимает два словаря и возвращает новый словарь, содержащий только те ключи из первого, которые не встречаются во втором.\n" ] }, { @@ -262,8 +262,8 @@ "id": "455c3e34", "metadata": {}, "source": [ - "With sets, we don't have to write this function ourselves.\n", - "If `word_counter` is a dictionary that contains the unique words in the document and `word_list` is a list of valid words, we can compute the set difference like this." + "Используя множества, нам не нужно писать эту функцию самостоятельно.\n", + "Если `word_counter` — словарь с уникальными словами из документа, а `word_list` — список допустимых слов, то разность множеств можно вычислить так.\n" ] }, { @@ -291,10 +291,10 @@ "id": "91efe708", "metadata": {}, "source": [ - "The result is a set that contains the words in the document that don't appear in the word list.\n", + "Результатом будет множество слов, встречающихся в документе, но отсутствующих в словаре слов.\n", "\n", - "The relational operators work with sets.\n", - "For example, `<=` checks whether one set is a subset of another, including the possibility that they are equal." + "Отношения между множествами проверяются при помощи операторов сравнения.\n", + "Например, оператор `<=` проверяет, является ли одно множество подмножеством другого, включая случай равенства.\n" ] }, { @@ -310,8 +310,7 @@ "id": "74d4d824", "metadata": {}, "source": [ - "With these operators, we can use sets to do some of the exercises in Chapter 7.\n", - "For example, here's a version of `uses_only` that uses a loop." + "С помощью этих операторов можно решить некоторые упражнения из главы 7. Например, ниже показана версия функции `uses_only`, использующая цикл.\n" ] }, { @@ -327,8 +326,8 @@ "id": "58c1da26", "metadata": {}, "source": [ - "`uses_only` checks whether all letters in `word` are in `available`.\n", - "With sets, we can rewrite it like this." + "Функция `uses_only` проверяет, входят ли все буквы из `word` в `available`.\n", + "С использованием множеств её можно переписать так.\n" ] }, { @@ -344,7 +343,7 @@ "id": "01ce8cff", "metadata": {}, "source": [ - "If the letters in `word` are a subset of the letters in `available`, that means that `word` uses only letters in `available`." + "Если буквы из `word` образуют подмножество букв в `available`, это означает, что `word` использует только буквы из `available`.\n" ] }, { @@ -352,14 +351,12 @@ "id": "d7c22ef5", "metadata": {}, "source": [ - "## Counters\n", + "## Счётчики\n", "\n", - "A `Counter` is like a set, except that if an element appears more than once, the `Counter` keeps track of how many times it appears.\n", - "If you are familiar with the mathematical idea of a \"multiset\", a `Counter` is a\n", - "natural way to represent a multiset.\n", + "`Counter` похож на множество, за исключением того, что если элемент встречается более одного раза, `Counter` хранит, сколько раз он появился.\n", + "Если вам знакома математическая идея «мультимножества», то `Counter` — естественное его представление.\n", "\n", - "The `Counter` class is defined in a module called `collections`, so you have to import it.\n", - "Then you can use the class object as a function and pass as an argument a string, list, or any other kind of sequence." + "Класс `Counter` определён в модуле `collections`, поэтому его нужно импортировать. Затем можно использовать этот класс как функцию, передавая строку, список или любую другую последовательность.\n" ] }, { @@ -383,12 +380,9 @@ "id": "8da28fe5", "metadata": {}, "source": [ - "A `Counter` object is like a dictionary that maps from each key to the number of times it appears.\n", - "As in dictionaries, the keys have to be hashable.\n", + "Объект `Counter` похож на словарь, сопоставляющий каждому ключу количество его появлений. Как и в словарях, ключи должны быть хешируемыми.\n", "\n", - "Unlike dictionaries, `Counter` objects don't raise an exception if you access an\n", - "element that doesn't appear.\n", - "Instead, they return `0`." + "В отличие от словарей, объекты `Counter` не вызывают исключение при обращении к отсутствующему элементу. Вместо этого возвращается `0`.\n" ] }, { @@ -404,9 +398,9 @@ "id": "9bb2b650", "metadata": {}, "source": [ - "We can use `Counter` objects to solve one of the exercises from Chapter 10, which asks for a function that takes two words and checks whether they are anagrams -- that is, whether the letters from one can be rearranged to spell the other.\n", + "Мы можем использовать объекты `Counter` для решения одного из упражнений из главы 10, в котором требуется функция, проверяющая, являются ли два слова анаграммами — то есть можно ли переставить буквы одного слова, чтобы получилось другое.\n", "\n", - "Here's a solution using `Counter` objects." + "Ниже приведено решение с использованием `Counter`.\n" ] }, { @@ -2085,4 +2079,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/chapters/chap18.ipynb b/chapters/chap18.ipynb index 73e3199..030202a 100644 --- a/chapters/chap18.ipynb +++ b/chapters/chap18.ipynb @@ -299,11 +299,11 @@ "id": "30cf3158", "metadata": {}, "source": [ - "An element can only appear in a set once, so if an element in `t` appears more than once, the set will be smaller than `t`.\n", - "If there are no duplicates, the set will be the same size as `t`.\n", + "Элемент может появиться в множестве только один раз, поэтому если элемент из `t` встречается более одного раза, множество будет меньше, чем `t`.\n", + "Если дубликатов нет, множество будет того же размера, что и `t`.\n", "\n", - "`set` objects provide methods that perform set operations.\n", - "For example, `union` computes the union of two sets, which is a new set that contains all elements that appear in either set." + "Объекты `set` предоставляют методы для выполнения операций над множествами.\n", + "Например, метод `union` вычисляет объединение двух множеств, создавая новое множество, содержащее все элементы, присутствующие хотя бы в одном из них.\n" ] }, { @@ -321,8 +321,8 @@ "id": "57b1d50c", "metadata": {}, "source": [ - "Some arithmetic operators work with sets.\n", - "For example, the `-` operator performs set subtraction -- the result is a new set that contains all elements from the first set that are _not_ in the second set." + "Некоторые арифметические операторы работают с множествами.\n", + "Например, оператор `-` выполняет вычитание множеств — результатом будет новое множество, содержащее все элементы из первого множества, которые *не* входят во второе.\n" ] }, { @@ -340,8 +340,8 @@ "id": "5099226c", "metadata": {}, "source": [ - "In [Chapter 12](section_dictionary_subtraction) we used dictionaries to find the words that appear in a document but not in a word list.\n", - "We used the following function, which takes two dictionaries and returns a new dictionary that contains only the keys from the first that don't appear in the second." + "В [главе 12](section_dictionary_subtraction) мы использовали словари, чтобы найти слова, которые встречаются в документе, но отсутствуют в словаре слов.\n", + "Мы написали следующую функцию, которая принимает два словаря и возвращает новый словарь, содержащий только те ключи из первого, которые не встречаются во втором.\n" ] }, { @@ -364,8 +364,8 @@ "id": "455c3e34", "metadata": {}, "source": [ - "With sets, we don't have to write this function ourselves.\n", - "If `word_counter` is a dictionary that contains the unique words in the document and `word_list` is a list of valid words, we can compute the set difference like this." + "Используя множества, нам не нужно писать эту функцию самостоятельно.\n", + "Если `word_counter` — словарь с уникальными словами из документа, а `word_list` — список допустимых слов, то разность множеств можно вычислить так.\n" ] }, { @@ -401,10 +401,10 @@ "id": "91efe708", "metadata": {}, "source": [ - "The result is a set that contains the words in the document that don't appear in the word list.\n", + "Результатом будет множество слов, встречающихся в документе, но отсутствующих в словаре слов.\n", "\n", - "The relational operators work with sets.\n", - "For example, `<=` checks whether one set is a subset of another, including the possibility that they are equal." + "Отношения между множествами проверяются при помощи операторов сравнения.\n", + "Например, оператор `<=` проверяет, является ли одно множество подмножеством другого, включая случай равенства.\n" ] }, { @@ -422,8 +422,7 @@ "id": "74d4d824", "metadata": {}, "source": [ - "With these operators, we can use sets to do some of the exercises in Chapter 7.\n", - "For example, here's a version of `uses_only` that uses a loop." + "С помощью этих операторов можно решить некоторые упражнения из главы 7. Например, ниже показана версия функции `uses_only`, использующая цикл.\n" ] }, { @@ -445,8 +444,8 @@ "id": "58c1da26", "metadata": {}, "source": [ - "`uses_only` checks whether all letters in `word` are in `available`.\n", - "With sets, we can rewrite it like this." + "Функция `uses_only` проверяет, входят ли все буквы из `word` в `available`.\n", + "С использованием множеств её можно переписать так.\n" ] }, { @@ -465,7 +464,7 @@ "id": "01ce8cff", "metadata": {}, "source": [ - "If the letters in `word` are a subset of the letters in `available`, that means that `word` uses only letters in `available`." + "Если буквы из `word` образуют подмножество букв в `available`, это означает, что `word` использует только буквы из `available`.\n" ] }, { @@ -473,14 +472,12 @@ "id": "d7c22ef5", "metadata": {}, "source": [ - "## Counters\n", + "## Счётчики\n", "\n", - "A `Counter` is like a set, except that if an element appears more than once, the `Counter` keeps track of how many times it appears.\n", - "If you are familiar with the mathematical idea of a \"multiset\", a `Counter` is a\n", - "natural way to represent a multiset.\n", + "`Counter` похож на множество, за исключением того, что если элемент встречается более одного раза, `Counter` хранит, сколько раз он появился.\n", + "Если вам знакома математическая идея «мультимножества», то `Counter` — естественное его представление.\n", "\n", - "The `Counter` class is defined in a module called `collections`, so you have to import it.\n", - "Then you can use the class object as a function and pass as an argument a string, list, or any other kind of sequence." + "Класс `Counter` определён в модуле `collections`, поэтому его нужно импортировать. Затем можно использовать этот класс как функцию, передавая строку, список или любую другую последовательность.\n" ] }, { @@ -515,12 +512,9 @@ "id": "8da28fe5", "metadata": {}, "source": [ - "A `Counter` object is like a dictionary that maps from each key to the number of times it appears.\n", - "As in dictionaries, the keys have to be hashable.\n", + "Объект `Counter` похож на словарь, сопоставляющий каждому ключу количество его появлений. Как и в словарях, ключи должны быть хешируемыми.\n", "\n", - "Unlike dictionaries, `Counter` objects don't raise an exception if you access an\n", - "element that doesn't appear.\n", - "Instead, they return `0`." + "В отличие от словарей, объекты `Counter` не вызывают исключение при обращении к отсутствующему элементу. Вместо этого возвращается `0`.\n" ] }, { @@ -538,9 +532,9 @@ "id": "9bb2b650", "metadata": {}, "source": [ - "We can use `Counter` objects to solve one of the exercises from Chapter 10, which asks for a function that takes two words and checks whether they are anagrams -- that is, whether the letters from one can be rearranged to spell the other.\n", + "Мы можем использовать объекты `Counter` для решения одного из упражнений из главы 10, в котором требуется функция, проверяющая, являются ли два слова анаграммами — то есть можно ли переставить буквы одного слова, чтобы получилось другое.\n", "\n", - "Here's a solution using `Counter` objects." + "Ниже приведено решение с использованием `Counter`.\n" ] }, { From 95ed2f39c02baacd36326c8ff85c8072566d3e01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 14:38:26 +0300 Subject: [PATCH 26/44] Translate part of chapter 18 --- blank/chap18.ipynb | 47 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/blank/chap18.ipynb b/blank/chap18.ipynb index 6a069c1..22553bb 100644 --- a/blank/chap18.ipynb +++ b/blank/chap18.ipynb @@ -422,9 +422,9 @@ "id": "6907f368", "metadata": {}, "source": [ - "If two words are anagrams, they contain the same letters with the same counts, so their `Counter` objects are equivalent.\n", + "Если два слова являются анаграммами, то они содержат одни и те же буквы в одинаковом количестве, поэтому их объекты `Counter` эквивалентны.\n", "\n", - "`Counter` provides a method called `most_common` that returns a list of value-frequency pairs, sorted from most common to least." + "`Counter` предоставляет метод `most_common`, который возвращает список пар «значение-частота», отсортированный от наиболее частых к наименее частым." ] }, { @@ -440,10 +440,10 @@ "id": "b02b7dff", "metadata": {}, "source": [ - "They also provide methods and operators to perform set-like operations, including addition, subtraction, union and intersection.\n", - "For example, the `+` operator combines two `Counter` objects and creates a new `Counter` that contains the keys from both and the sums of the counts.\n", + "Модуль также предоставляет методы и операторы для выполнения операций, подобных множествам, включая сложение, вычитание, объединение и пересечение.\n", + "Например, оператор `+` объединяет два объекта `Counter` и создаёт новый `Counter`, содержащий ключи из обоих и суммы их счётчиков.\n", "\n", - "We can test it by making a `Counter` with the letters from `'bans'` and adding it to the letters from `'banana'`." + "Мы можем проверить это, создав `Counter` из букв слова `'bans'` и добавив его к буквам из `'banana'`." ] }, { @@ -459,7 +459,7 @@ "id": "5461328e", "metadata": {}, "source": [ - "You'll have a chance to explore other `Counter` operations in the exercises at the end of this chapter." + "В упражнениях в конце этой главы у вас будет возможность изучить другие операции с `Counter`." ] }, { @@ -469,13 +469,13 @@ "source": [ "## defaultdict\n", "\n", - "The `collections` module also provides `defaultdict`, which is like a dictionary except that if you access a key that doesn't exist, it generates a new value automatically.\n", + "Модуль `collections` также предоставляет `defaultdict`, который похож на словарь, но если обратиться к несуществующему ключу, он автоматически создаёт новое значение.\n", "\n", - "When you create a `defaultdict`, you provide a function that's used to create new values.\n", - "A function that create objects is sometimes called a **factory**.\n", - "The built-in functions that create lists, sets, and other types can be used as factories.\n", + "Когда вы создаёте `defaultdict`, вы передаёте функцию, которая используется для создания новых значений.\n", + "Функцию, которая создаёт объекты, иногда называют **фабрикой**.\n", + "Встроенные функции, создающие списки, множества и другие типы, можно использовать как фабрики.\n", "\n", - "For example, here's a `defaultdict` that creates a new `list` when needed. " + "Например, вот `defaultdict`, который при необходимости создаёт новый `list`. " ] }, { @@ -491,8 +491,8 @@ "id": "9f43d537", "metadata": {}, "source": [ - "Notice that the argument is `list`, which is a class object, not `list()`, which is a function call that creates a new list.\n", - "The factory function doesn't get called unless we access a key that doesn't exist." + "Обратите внимание, что аргументом является `list`, это объект класса, а не вызов функции `list()`, создающей новый список.\n", + "Фабричная функция вызывается только если мы обращаемся к несуществующему ключу." ] }, { @@ -508,8 +508,8 @@ "id": "01f87415", "metadata": {}, "source": [ - "The new list, which we're calling `t`, is also added to the dictionary.\n", - "So if we modify `t`, the change appears in `d`:" + "Новый список, который мы называем `t`, также добавляется в словарь.\n", + "Поэтому, если мы изменим `t`, изменение отразится и в `d`:" ] }, { @@ -525,12 +525,11 @@ "id": "3e5d0151", "metadata": {}, "source": [ - "If you are making a dictionary of lists, you can often write simpler\n", - "code using `defaultdict`. \n", + "Если вы создаёте словарь списков, часто можно написать более простой код, используя `defaultdict`.\n", "\n", - "In one of the exercises in [Chapter 11](chapter_tuples), I made a dictionary that maps from a sorted string of letters to the list of words that can be spelled with those letters.\n", - "For example, the string `'opst'` maps to the list `['opts', 'post', 'pots', 'spot', 'stop', 'tops']`.\n", - "Here's the original code." + "В одном из упражнений в [Главе 11](chapter_tuples) я сделал словарь, который сопоставляет отсортированную строку букв со списком слов, которые можно составить из этих букв.\n", + "Например, строка `'opst'` сопоставляется со списком `['opts', 'post', 'pots', 'spot', 'stop', 'tops']`.\n", + "Вот исходный код." ] }, { @@ -546,7 +545,7 @@ "id": "8e9a0a2b", "metadata": {}, "source": [ - "And here's a simpler version using a `defaultdict`." + "А вот более простая версия с использованием `defaultdict`." ] }, { @@ -562,7 +561,7 @@ "id": "cccdd46c", "metadata": {}, "source": [ - "In the exercises at the end of the chapter, you'll have a chance to practice using `defaultdict` objects." + "В упражнениях в конце главы у вас будет возможность попрактиковаться в работе с объектами `defaultdict`." ] }, { @@ -578,9 +577,9 @@ "id": "610359c1", "metadata": {}, "source": [ - "## Conditional expressions\n", + "## Условные выражения\n", "\n", - "Conditional statements are often used to choose one of two values, like this:" + "Условные операторы часто используются, чтобы выбрать одно из двух значений, например так:" ] }, { From 92313ed76c7217183cdd806c3449e1aecf72c919 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 14:59:55 +0300 Subject: [PATCH 27/44] Translate chapter 18 notebook --- blank/chap18.ipynb | 287 +++++++++++---------------------------------- 1 file changed, 71 insertions(+), 216 deletions(-) diff --git a/blank/chap18.ipynb b/blank/chap18.ipynb index a7ca31f..5dbfca3 100644 --- a/blank/chap18.ipynb +++ b/blank/chap18.ipynb @@ -609,11 +609,7 @@ "id": "2c5fc3dd", "metadata": {}, "source": [ - "This statement checks whether `x` is positive. If so, it computes its logarithm. \n", - "If not, `math.log` would raise a ValueError.\n", - "To avoid stopping the program, we generate a `NaN`, which is a special floating-point value that represents \"Not a Number\".\n", - "\n", - "We can write this statement more concisely using a **conditional expression**." + "Это утверждение проверяет, является ли `x` положительным.Если так, то он вычисляет его логарифм.\nЕсли нет, то `math.log` поднимет стоимость.\nЧтобы избежать остановки программы, мы генерируем «NAN», который является специальным значением с плавающей запятой, которая представляет «не число».\n\nМы можем написать это утверждение более кратко, используя ** условное выражение **." ] }, { @@ -639,10 +635,7 @@ "id": "6a7cf27b", "metadata": {}, "source": [ - "You can almost read this line like English: \"`y` gets log-`x` if `x` is greater than 0; otherwise it gets `NaN`\".\n", - "\n", - "Recursive functions can sometimes be written concisely using conditional expressions. \n", - "For example, here is a version of `factorial` with a conditional _statement_." + "Вы можете почти прочитать эту строку, как английский: «y` получает log- `x`, если` x` больше 0; в противном случае он получает `nan`».\n\nРекурсивные функции иногда можно писать кратко с использованием условных выражений.\nНапример, вот версия `factorial` с условным _statement_." ] }, { @@ -658,7 +651,7 @@ "id": "56052b5c", "metadata": {}, "source": [ - "And here's a version with a conditional _expression_." + "А вот версия с условной _expression_." ] }, { @@ -674,8 +667,7 @@ "id": "d53fbc15", "metadata": {}, "source": [ - "Another use of conditional expressions is handling optional arguments.\n", - "For example, here is class definition with an `__init__` method that uses a conditional statement to check a parameter with a default value." + "Другим использованием условных выражений является обработка дополнительных аргументов.\nНапример, вот определение класса с методом `__init__`, который использует условное операцию для проверки параметра со значением по умолчанию." ] }, { @@ -691,7 +683,7 @@ "id": "655bfc46", "metadata": {}, "source": [ - "Here's a version that uses a conditional expression." + "Вот версия, которая использует условное выражение." ] }, { @@ -707,7 +699,7 @@ "id": "fef85229", "metadata": {}, "source": [ - "In general, you can replace a conditional statement with a conditional expression if both branches contain a single expression and no statements." + "В целом, вы можете заменить условное утверждение на условное выражение, если обе ветви содержат одно выражение и отсутствие операторов." ] }, { @@ -715,10 +707,7 @@ "id": "45d3b306", "metadata": {}, "source": [ - "## List comprehensions\n", - "\n", - "In previous chapters, we've seen a few examples where we start with an empty list and add elements, one at a time, using the `append` method.\n", - "For example, suppose we have a string that contains the title of a movie, and we want to capitalize all of the words." + "## Список понимания\n\nВ предыдущих главах мы видели несколько примеров, когда мы начинаем с пустого списка и добавляем элементы по одному, используя метод «Приложение».\nНапример, предположим, что у нас есть строка, которая содержит название фильма, и мы хотим извлечь выгоду из всех слов." ] }, { @@ -734,7 +723,7 @@ "id": "9eeb45a6", "metadata": {}, "source": [ - "We can split it into a list of strings, loop through the strings, capitalize them, and append them to a list." + "Мы можем разделить его на список строк, проходить через строки, использовать их и добавить их в список." ] }, { @@ -750,7 +739,7 @@ "id": "b96197c2", "metadata": {}, "source": [ - "We can do the same thing more concisely using a **list comprehension**:" + "Мы можем сделать то же самое более кратко, используя ** Понимание списка **:" ] }, { @@ -766,13 +755,7 @@ "id": "e5b565ad", "metadata": {}, "source": [ - "The bracket operators indicate that we are constructing a new list.\n", - "The expression inside the brackets specifies the elements of the list, and the `for` clause indicates what sequence we are looping through.\n", - "\n", - "The syntax of a list comprehension might seem strange, because the loop variable -- `word` in this example -- appears in the expression before we get to its definition.\n", - "But you get used to it.\n", - "\n", - "As another example, in [Chapter 9](section_word_list) we used this loop to read words from a file and append them to a list." + "Операторы кронштейнов указывают, что мы строим новый список.\nВыражение внутри кронштейнов определяет элементы списка, а пункт «for» указывает на то, через какую последовательность мы проводим.\n\nСинтаксис понимания списка может показаться странным, потому что переменная цикла - `word` в этом примере - появляется в выражении, прежде чем мы достигнем его определения.\nНо вы привыкаете к этому.\n\nВ качестве другого примера, в [Глава 9] (section_word_list) мы использовали этот цикл для чтения слов из файла и добавления их в список." ] }, { @@ -808,7 +791,7 @@ "id": "2d1df49b", "metadata": {}, "source": [ - "Here's how we can write that as a list comprehension." + "Вот как мы можем написать это как понимание списка." ] }, { @@ -834,8 +817,7 @@ "id": "92d856ba", "metadata": {}, "source": [ - "A list comprehension can also have an `if` clause that determines which elements are included in the list.\n", - "For example, here's a `for` loop we used in [Chapter 10](section_palindrome_list) to make a list of only the words in `word_list` that are palindromes." + "Понимание списка также может иметь пункт «если», который определяет, какие элементы включены в список.\nНапример, вот `for` -цикл, который мы использовали в [главе 10] (section_palindrome_list), чтобы составить список только слов в` word_list`, которые являются палиндромами." ] }, { @@ -871,7 +853,7 @@ "id": "151621d8", "metadata": {}, "source": [ - "Here's how we can do the same thing with an list comprehension." + "Вот как мы можем сделать то же самое с пониманием списка." ] }, { @@ -897,9 +879,7 @@ "id": "5fc4eab1", "metadata": {}, "source": [ - "When a list comprehension is used as an argument to a function, we can often omit the brackets.\n", - "For example, suppose we want to add up $1 / 2^n$ for values of $n$ from 0 to 9.\n", - "We can use a list comprehension like this." + "Когда понимание списка используется в качестве аргумента для функции, мы часто можем опустить кронштейны.\nНапример, предположим, что мы хотим сложить $ 1/2^n $ для значений $ n $ от 0 до 9.\nМы можем использовать подобное понимание списка." ] }, { @@ -915,7 +895,7 @@ "id": "2ee312e0", "metadata": {}, "source": [ - "Or we can leave out the brackets like this." + "Или мы можем оставить такие кронштейны." ] }, { @@ -931,17 +911,7 @@ "id": "3d56d584", "metadata": {}, "source": [ - "In this example, the argument is technically a **generator expression**, not a list comprehension, and it never actually makes a list.\n", - "But other than that, the behavior is the same.\n", - "\n", - "List comprehensions and generator expressions are concise and easy to read, at least for simple expressions.\n", - "And they are usually faster than the equivalent for loops, sometimes much faster.\n", - "So if you are mad at me for not mentioning them earlier, I understand.\n", - "\n", - "But, in my defense, list comprehensions are harder to debug because you can't put a print statement inside the loop.\n", - "I suggest you use them only if the computation is simple enough that you are likely to get it\n", - "right the first time.\n", - "Or consider writing and debugging a `for` loop and then converting it to a list comprehension." + "В этом примере аргумент технически является ** генераторным выражением **, а не пониманием списка, и он никогда не составляет список.\nНо кроме этого поведение одинаково.\n\nСписок понимания и выражения генератора кратко и легко читают, по крайней мере, для простых выражений.\nИ они обычно быстрее, чем эквивалент для петель, иногда намного быстрее.\nТак что, если вы злитесь на меня за то, что я не упоминал их раньше, я понимаю.\n\nНо в моей защите, понимание списка труднее отладить, потому что вы не можете поместить печатное заявление в цикл.\nЯ предлагаю вам использовать их, только если вычисление достаточно просты, чтобы вы его получили\nПравильно в первый раз.\nИли рассмотрите возможность написания и отладки цикла «для», а затем преобразовать его в понимание списка." ] }, { @@ -949,9 +919,7 @@ "id": "f9fac860", "metadata": {}, "source": [ - "## `any` and `all`\n", - "\n", - "Python provides a built-in function, `any`, that takes a sequence of boolean values and returns `True` if any of the values are `True`." + "## `any 'и` all\n\nPython обеспечивает встроенную функцию, «любой», которая принимает последовательность логических значений и возвращает `true`, если какое-либо из значений является« true »." ] }, { @@ -967,7 +935,7 @@ "id": "43217186", "metadata": {}, "source": [ - "`any` is often used with generator expressions." + "«Любой» часто используется с выражениями генератора." ] }, { @@ -983,8 +951,7 @@ "id": "22395487", "metadata": {}, "source": [ - "That example isn't very useful because it does the same thing as the `in` operator. \n", - "But we could use `any` to write concise solutions to some of the exercises in [Chapter 7](chapter_search). For example, we can write `uses_none` like this." + "Этот пример не очень полезен, потому что он делает то же самое, что и оператор «в».\nНо мы могли бы использовать «любое», чтобы написать краткие решения для некоторых упражнений в [Глава 7] (глава_SEARCH).Например, мы можем написать `change_none` как это." ] }, { @@ -1020,11 +987,7 @@ "id": "fbefe3c1", "metadata": {}, "source": [ - "This function loops through the letters in `word` and checks whether any of them are in `forbidden`.\n", - "Using `any` with a generator expression is efficient because it stops immediately if it finds a `True` value, so it doesn't have to loop through the whole sequence.\n", - "\n", - "Python provides another built-in function, `all`, that returns `True` if every element of the sequence is `True`.\n", - "We can use it to write a concise version of `uses_all`." + "Эта функция проходит через буквы в «Word» и проверяет, находятся ли какие -либо из них в «запрещенном».\nИспользование «любого» с выражением генератора является эффективным, потому что оно немедленно останавливается, если оно находит значение «истинного», поэтому он не должен проходить через всю последовательность.\n\nPython предоставляет еще одну встроенную функцию, «All», которая возвращает `true`, если каждый элемент последовательности` true '.\nМы можем использовать его, чтобы написать краткую версию `using_all`." ] }, { @@ -1060,7 +1023,7 @@ "id": "8d9f7364", "metadata": {}, "source": [ - "Expressions using `any` and `all` can be concise, efficient, and easy to read." + "Выражения с использованием «any» и «all» могут быть кратким, эффективным и простым в чтении." ] }, { @@ -1068,11 +1031,7 @@ "id": "911857a3", "metadata": {}, "source": [ - "## Named tuples\n", - "\n", - "The `collections` module provides a function called `namedtuple` that can be used to create simple classes.\n", - "For example, the `Point` object in [Chapter 16](section_create_point) has only two attributes, `x` and `y`.\n", - "Here's how we defined it." + "## назван кулак\n\nМодуль «Коллекции» предоставляет функцию, называемую `nameTuple`, которую можно использовать для создания простых классов.\nНапример, объект `point` в [Глава 16] (section_create_point) имеет только два атрибута:` x` и `y`.\nВот как мы это определили." ] }, { @@ -1088,8 +1047,7 @@ "id": "36f08927", "metadata": {}, "source": [ - "That's a lot of code to convey a small amount of information.\n", - "`namedtuple` provides a more concise way to define classes like this." + "Это много кода, чтобы передать небольшое количество информации.\n`nameTuple` обеспечивает более краткий способ определить такие занятия." ] }, { @@ -1105,12 +1063,7 @@ "id": "942a0877", "metadata": {}, "source": [ - "The first argument is the name of the class you want to create. The\n", - "second is a list of the attributes `Point` objects should have.\n", - "The result is a class object, which is why it is assigned to a capitalized variable name.\n", - "\n", - "A class created with `namedtuple` provides an `__init__` method that assigns values to the attributes and a `__str__` that displays the object in a readable form.\n", - "So we can create and display a `Point` object like this." + "Первый аргумент - это имя класса, который вы хотите создать.А\nВо -вторых, это список объектов атрибутов `point`, которые должны иметь.\nРезультатом является объект класса, поэтому он назначен капитализированным именем переменной.\n\nКласс, созданный с помощью `nameTuple`, предоставляет метод` __init__`, который присваивает значения атрибутам и «__str__`, который отображает объект в читаемой форме.\nТаким образом, мы можем создавать и отобразить такой объект «точка»." ] }, { @@ -1126,7 +1079,7 @@ "id": "b42ee9a2", "metadata": {}, "source": [ - "`Point` also provides an `__eq__` method that checks whether two `Point` objects are equivalent -- that is, whether their attributes are the same." + "`Point` также предоставляет метод` __eq__`, который проверяет, эквивалентны ли два объекта «точка», то есть, являются ли их атрибуты одинаковыми." ] }, { @@ -1142,7 +1095,7 @@ "id": "9bcf275a", "metadata": {}, "source": [ - "You can access the elements of a named tuple by name or by index." + "Вы можете получить доступ к элементам названного кортежа по имени или по индексу." ] }, { @@ -1166,7 +1119,7 @@ "id": "0768ff41", "metadata": {}, "source": [ - "You can also treat a named tuple as a tuple, as in this assignment." + "Вы также можете рассматривать названный кортеж как кортеж, как в этом задании." ] }, { @@ -1182,8 +1135,7 @@ "id": "964aa3bd", "metadata": {}, "source": [ - "But `namedtuple` objects are immutable.\n", - "After the attributes are initialized, they can't be changed." + "Но объекты `nameTuple 'неизменны.\nПосле того, как атрибуты инициализированы, их нельзя изменить." ] }, { @@ -1211,10 +1163,7 @@ "id": "f2db7783", "metadata": {}, "source": [ - "`namedtuple` provides a quick way to define simple classes.\n", - "The drawback is that simple classes don't always stay simple.\n", - "You might decide later that you want to add methods to a named tuple.\n", - "In that case, you can define a new class that inherits from the named tuple." + "`nameTuple` обеспечивает быстрый способ определения простых классов.\nНедостаток в том, что простые занятия не всегда остаются простыми.\nПозже вы можете решить, что хотите добавить методы в названный кортеж.\nВ этом случае вы можете определить новый класс, который наследует от названного корпуса." ] }, { @@ -1230,7 +1179,7 @@ "id": "805475ce", "metadata": {}, "source": [ - "Or at that point you could switch to a conventional class definition." + "Или в этот момент вы можете перейти на обычное определение класса." ] }, { @@ -1238,9 +1187,7 @@ "id": "4f3713a0", "metadata": {}, "source": [ - "## Packing keyword arguments\n", - "\n", - "In [Chapter 11](section_argument_pack), we wrote a function that packs its arguments into a tuple." + "## Упаковывать аргументы ключевого слова\nВ [Глава 11] (пакет аргументов в разделе) мы пишем функцию, которая упаковывает ее аргументы в кортеж." ] }, { @@ -1256,7 +1203,7 @@ "id": "71e3b049", "metadata": {}, "source": [ - "You can call this function with any number of arguments." + "Вы можете вызвать эту функцию с любым количеством аргументов." ] }, { @@ -1272,8 +1219,7 @@ "id": "486a690f", "metadata": {}, "source": [ - "But the `*` operator doesn't pack keyword arguments.\n", - "So calling this function with a keyword argument causes an error." + "Но оператор `*` не упаковывает аргументы ключевых слов.\nТаким образом, вызов этой функции с помощью аргумента ключевого слова вызывает ошибку." ] }, { @@ -1291,7 +1237,7 @@ "id": "eb7f9281", "metadata": {}, "source": [ - "To pack keyword arguments, we can use the `**` operator:" + "Чтобы упаковать аргументы ключевого слова, мы можем использовать оператор `**`:" ] }, { @@ -1307,8 +1253,7 @@ "id": "067bf7c4", "metadata": {}, "source": [ - "The keyword-packing parameter can have any name, but `kwargs` is a common choice.\n", - "The result is a dictionary that maps from keywords to values." + "Параметр по составлению ключевых слов может иметь любое имя, но `kwargs 'является общим выбором.\nРезультатом является словарь, который отображает от ключевых слов к значениям." ] }, { @@ -1324,10 +1269,7 @@ "id": "07be77f3", "metadata": {}, "source": [ - "In this example, the value of `kwargs` is printed, but otherwise is has no effect.\n", - "\n", - "But the `**` operator can also be used in an argument list to unpack a dictionary.\n", - "For example, here's a version of `mean` that packs any keyword arguments it gets and then unpacks them as keyword arguments for `sum`." + "В этом примере значение «kwargs» напечатано, но в противном случае не имеет никакого эффекта.\n\nНо оператор `** также может быть использован в списке аргументов для распаковки словаря.\nНапример, вот версия `ead`, в которой есть какие -либо аргументы ключевых слов, которые он получает, а затем распаковывает их как аргументы ключевых слов для` sum '." ] }, { @@ -1343,8 +1285,7 @@ "id": "ba00858c", "metadata": {}, "source": [ - "Now if we call `mean` with `start` as a keyword argument, it gets passed along to sum, which uses it as the starting point of the summation.\n", - "In the following example `start=3` adds `3` to the sum before computing the mean, so the sum is `6` and the result is `3`." + "Теперь, если мы назовут «ead» с «start» в качестве аргумента ключевого слова, он передается на сумму, который использует его в качестве отправной точки суммирования.\nВ следующем примере `start = 3` добавляет` 3` к сумме перед вычислением среднего, поэтому сумма равен `6`, а результат -` 3`." ] }, { @@ -1360,7 +1301,7 @@ "id": "949a2ca3", "metadata": {}, "source": [ - "As another example, if we have a dictionary with keys `x` and `y`, we can use it with the unpack operator to create a `Point` object." + "В качестве другого примера, если у нас есть словарь с клавишами `x` и` y`, мы можем использовать его с оператором распаковки для создания объекта «точка»." ] }, { @@ -1376,7 +1317,7 @@ "id": "8aaf128a", "metadata": {}, "source": [ - "Without the unpack operator, `d` is treated as a single positional argument, so it gets assigned to `x`, and we get a `TypeError` because there's no second argument to assign to `y`." + "Без оператора распаков, «D` рассматривается как единый позиционный аргумент, поэтому он назначается« X », и мы получаем« typeerror », потому что нет второго аргумента, чтобы назначить` y`." ] }, { @@ -1394,7 +1335,7 @@ "id": "e8acb958", "metadata": {}, "source": [ - "When you are working with functions that have a large number of keyword arguments, it is often useful to create and pass around dictionaries that specify frequently used options." + "Когда вы работаете с функциями, которые имеют большое количество аргументов ключевых слов, часто полезно создавать и разобраться в словари, которые указывают часто используемые параметры." ] }, { @@ -1410,11 +1351,7 @@ "id": "e046e382", "metadata": {}, "source": [ - "## Debugging\n", - "\n", - "In previous chapters, we used `doctest` to test functions.\n", - "For example, here's a function called `add` that takes two numbers and returns their sum.\n", - "In includes a doctest that checks whether `2 + 2` is `4`." + "## отладка\n\nВ предыдущих главах мы использовали «doctest» для тестирования функций.\nНапример, вот функция, называемая `add`, которая занимает два числа и возвращает их сумму.\nВ включает в себя документ, который проверяет, является ли `2 + 2`` 4`." ] }, { @@ -1430,7 +1367,7 @@ "id": "a5e332d3", "metadata": {}, "source": [ - "This function takes a function object and runs its doctests." + "Эта функция принимает функциональный объект и запускает его Doctests." ] }, { @@ -1446,7 +1383,7 @@ "id": "2d752a40", "metadata": {}, "source": [ - "So we can test `add` like this." + "Таким образом, мы можем проверить `добавить как это." ] }, { @@ -1462,10 +1399,7 @@ "id": "77d36e9b", "metadata": {}, "source": [ - "There's no output, which means all tests passed.\n", - "\n", - "Python provides another tool for running automated tests, called `unittest`.\n", - "It is a little more complicated to use, but here's an example." + "Там нет вывода, что означает, что все тесты прошли.\n\nPython предоставляет еще один инструмент для запуска автоматических тестов, называемый «Unittest».\nЭто немного сложнее использовать, но вот пример." ] }, { @@ -1481,15 +1415,7 @@ "id": "59b4212a", "metadata": {}, "source": [ - "First we import `TestCase`, which is a class in the `unittest` module.\n", - "To use it, we have to define a new class that inherits from `TestCase` and provides at least one test method.\n", - "The name of the test method must begin with `test` and should indicate which function it tests.\n", - "\n", - "In this example, `test_add` tests the `add` function by calling it, saving the result, and invoking `assertEqual`, which is inherited from `TestCase`.\n", - "`assertEqual` takes two arguments and checks whether they are equal.\n", - "\n", - "In order to run this test method, we have to run a function in `unittest` called `main` and provide several keyword arguments.\n", - "The following function shows the details -- if you are curious, you can ask a virtual assistant to explain how it works." + "Сначала мы импортируем `testcase`, который является классом в модуле` neittest.\nЧтобы использовать его, мы должны определить новый класс, который наследует от `testcase` и предоставляет хотя бы один метод испытаний.\nИмя метода испытаний должно начинаться с `test` и должно указывать, какую функцию он тестирует.\n\nВ этом примере `test_add` проверяет функцию` add`, вызывая ее, сохраняя результат и вызывая `assertequal`, которая унаследована от` testcase '.\n`assertequal 'принимает два аргумента и проверяет, равны ли они.\n\nЧтобы запустить этот метод испытаний, мы должны запустить функцию в `Unittest`, который называется« Main »и предоставить несколько аргументов ключевых слов.\nСледующая функция показывает детали - если вам любопытно, вы можете попросить виртуального помощника объяснить, как это работает." ] }, { @@ -1505,11 +1431,7 @@ "id": "5409ea0c", "metadata": {}, "source": [ - "`run_unittest` does not take `TestExample` as an argument -- instead, it searches for classes that inherit from `TestCase`.\n", - "Then it searches for methods that begin with `test` and runs them.\n", - "This process is called **test discovery**.\n", - "\n", - "Here's what happens when we call `run_unittest`." + "`run_unittest` не принимает` testexample` в качестве аргумента - вместо этого он ищет классы, которые наследуют от `testcase '.\nЗатем он ищет методы, которые начинаются с «теста» и запускают их.\nЭтот процесс называется ** Тест -обнаружение **.\n\nВот что происходит, когда мы называем `run_unittest`." ] }, { @@ -1525,10 +1447,7 @@ "id": "7775304a", "metadata": {}, "source": [ - "`unittest.main` reports the number of tests it ran and the results.\n", - "In this case `OK` indicates that the tests passed.\n", - "\n", - "To see what happens when a test fails, we'll add an incorrect test method to `TestExample`." + "`Unittest.main\nВ этом случае `ok` указывает, что тесты прошли.\n\nЧтобы увидеть, что произойдет, когда тест не пройдет, мы добавим неверный метод испытаний в `testexample`." ] }, { @@ -1544,7 +1463,7 @@ "id": "96810614", "metadata": {}, "source": [ - "Here's what happens when we run the tests." + "Вот что происходит, когда мы запускаем тесты." ] }, { @@ -1560,10 +1479,7 @@ "id": "64b743cb", "metadata": {}, "source": [ - "The report includes the test method that failed and an error message showing where.\n", - "The summary indicates that two tests ran and one failed.\n", - "\n", - "In the exercises below, I'll suggest some prompts you can use to ask a virtual assistant for more information about `unittest`." + "Отчет включает в себя метод испытаний, который не удался, и сообщение об ошибке, показывающее, где.\nРезюме указывает, что два теста проходили, а один не удался.\n\nВ приведенных ниже упражнениях я предложу несколько подсказок, которые вы можете использовать, чтобы попросить виртуального помощника для получения дополнительной информации о «Unittest»." ] }, { @@ -1571,22 +1487,7 @@ "id": "7d0fb256", "metadata": {}, "source": [ - "## Glossary\n", - "\n", - "**factory:**\n", - " A function used to create objects, often passed as a parameter to a function.\n", - "\n", - "**conditional expression:**\n", - "An expression that uses a conditional to select one of two values.\n", - "\n", - "**list comprehension:**\n", - "A concise way to loop through a sequence and create a list.\n", - "\n", - "**generator expression:**\n", - "Similar to a list comprehension except that it does not create a list.\n", - "\n", - "**test discovery:**\n", - "A process used to find and run tests." + "## Глоссарий\n\n**фабрика:**\nФункция, используемая для создания объектов, часто передаваемой как параметр для функции.\n\n** условное выражение: **\nВыражение, которое использует условное для выбора одного из двух значений.\n\n** Понимание списка: **\nКраткий способ пройти последовательность и создать список.\n\n** выражение генератора: **\nАналогично пониманию списка, за исключением того, что он не создает список.\n\n** Испытание на обнаружение: **\nПроцесс, используемый для поиска и запуска тестов." ] }, { @@ -1594,7 +1495,7 @@ "id": "bc03f15d", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -1612,28 +1513,7 @@ "id": "fe10415e", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", - "\n", - "There are a few topics in this chapter you might want to learn about.\n", - "Here are some question to ask an AI.\n", - "\n", - "* \"What are the methods and operators of Python's set class?\"\n", - "\n", - "* \"What are the methods and operators of Python's Counter class?\"\n", - "\n", - "* \"What is the difference between a Python list comprehension and a generator expression?\"\n", - "\n", - "* \"When should I use Python's `namedtuple` rather than define a new class?\"\n", - "\n", - "* \"What are some uses of packing and unpacking keyword arguments?\"\n", - "\n", - "* \"How does `unittest` do test discovery?\"\n", - "\n", - "\"Along with `assertEqual`, what are the most commonly used methods in `unittest.TestCase`?\"\n", - "\n", - "\"What are the pros and cons of `doctest` and `unittest`?\"\n", - "\n", - "For the following exercises, consider asking an AI for help, but as always, remember to test the results." + "### Спросите виртуального помощника\n\nВ этой главе есть несколько тем, о которых вы можете узнать.\nВот какой -то вопрос, чтобы задать ИИ.\n\n* «Каковы методы и операторы класса Set Python?»\n\n* «Каковы методы и операторы Counter -класса Python?»\n\n* В чем разница между пониманием списка Python и выражением генератора? »\n\n* «Когда я должен использовать Python's` nameTuple`, а не определять новый класс? »\n\n* «Каковы некоторые использование упаковки и распаковки аргументов ключевых слов?»\n\n* \"Как« Unittest »делает тестирование обнаружения?»\n\n«Наряду с« assertequal », какие наиболее часто используемые методы в` unittest.testcase`? »\n\n«Каковы плюсы и минусы« doctest »и« Unittest »?»\n\nДля следующих упражнений подумайте о том, чтобы попросить ИИ о помощи, но, как всегда, не забудьте проверить результаты." ] }, { @@ -1641,9 +1521,7 @@ "id": "c61ecde2", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "One of the exercises in Chapter 7 asks for a function called `uses_none` that takes a word and a string of forbidden letters, and returns `True` if the word does not use any of the letters. Here's a solution." + "### Упражнение\n\nВ одном из упражнений в главе 7 просит функцию, называемую `users_none`, которая берет слово и строку запрещенных букв, и возвращает` true`, если слово не использует ни одной из букв.Вот решение." ] }, { @@ -1659,8 +1537,7 @@ "id": "b558b8b3", "metadata": {}, "source": [ - "Write a version of this function that uses `set` operations instead of a `for` loop.\n", - "Hint: ask an AI \"How do I compute the intersection of Python sets?\"" + "Напишите версию этой функции, которая использует операции «SET» вместо цикла «для».\nПодсказка: Спросите AI \"Как вычислить пересечение наборов Python?\"" ] }, { @@ -1670,7 +1547,7 @@ "tags": [] }, "source": [ - "You can use this outline to get started." + "Вы можете использовать этот контур, чтобы начать." ] }, { @@ -1716,12 +1593,7 @@ "id": "d2d670cf", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "Scrabble is a board game where the objective is to use letter tiles to spell words.\n", - "For example, if we have tiles with the letters `T`, `A`, `B`, `L`, `E`, we can spell `BELT` and `LATE` using a subset of the tiles -- but we can't spell `BEET` because we don't have two `E`s.\n", - "\n", - "Write a function that takes a string of letters and a word, and checks whether the letters can spell the word, taking into account how many times each letter appears." + "### Упражнение\n\nScrabble - это настольная игра, в которой цель состоит в том, чтобы использовать буквенную плитку для написания слов.\nНапример, если у нас есть плитка с буквами `t`,` a`, `b`,` l`, `e`, мы можем написать` belt` и `поздний ', используя подмножество плиток - но мы не можем пишется« свеккостью », потому что у нас нет двух` e`s.\n\nНапишите функцию, которая принимает ряд букв и слова, и проверяет, могут ли буквы писать слово, учитывая, сколько раз появляется каждая буква." ] }, { @@ -1731,7 +1603,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Вы можете использовать следующий план, чтобы начать." ] }, { @@ -1767,9 +1639,7 @@ "id": "de2dc099", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "In one of the exercises from [Chapter 17](chapter_inheritance), my solution to `has_straightflush` uses the following method, which partitions a `PokerHand` into a list of four hands, where each hand contains cards of the same suit." + "### Упражнение\n\nВ одном из упражнений из [Глава 17] (Глава_INHERITANCE) в моем решении «has_straightflush» используется следующий метод, который разделяет «покерханд» в список из четырех рук, где каждая рука содержит карты одного и того же костюма." ] }, { @@ -1785,7 +1655,7 @@ "id": "cd04a7a3", "metadata": {}, "source": [ - "Write a simplified version of this function using a `defaultdict`." + "Напишите упрощенную версию этой функции, используя `defaultDict." ] }, { @@ -1795,7 +1665,7 @@ "tags": [] }, "source": [ - "Here's an outline of the `PokerHand` class and the `partition_suits` function you can use to get started." + "Вот схема класса «PokerHand» и функцию `partition_suits`, которую вы можете использовать для начала." ] }, { @@ -1823,7 +1693,7 @@ "tags": [] }, "source": [ - "To test your code, we'll make a deck and shuffle it." + "Чтобы проверить ваш код, мы сделаем колоду и перетасоваем ее." ] }, { @@ -1843,7 +1713,7 @@ "tags": [] }, "source": [ - "Then create a `PokerHand` and add seven cards to it." + "Затем создайте `PokerHand 'и добавьте в него семь карт." ] }, { @@ -1863,7 +1733,7 @@ "tags": [] }, "source": [ - "If you invoke `partition` and print the results, each hand should contain cards of one suit only." + "Если вы вызовыте «раздел» и распечатаете результаты, каждая рука должна содержать карты только одного костюма." ] }, { @@ -1881,9 +1751,7 @@ "id": "218798e3", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "Here's the function from Chapter 11 that computes Fibonacci numbers." + "### Упражнение\n\nВот функция из главы 11, которая вычисляет числа Фибоначчи." ] }, { @@ -1899,7 +1767,7 @@ "id": "6acab624", "metadata": {}, "source": [ - "Write a version of this function with a single return statement that use two conditional expressions, one nested inside the other." + "Напишите версию этой функции с одним ответным оператором, в котором используются два условных выражения, одно вложенное внутри другого." ] }, { @@ -1935,9 +1803,7 @@ "id": "2deb0e1f", "metadata": {}, "source": [ - "### Exercise\n", - "The following is a function that computes the binomial coefficient\n", - "recursively." + "### Упражнение\nНиже приведена функция, которая вычисляет биномиальный коэффициент\nрекурсивно." ] }, { @@ -1953,10 +1819,7 @@ "id": "656c61f6", "metadata": {}, "source": [ - "Rewrite the body of the function using nested conditional expressions.\n", - "\n", - "This function is not very efficient because it ends up computing the same values over and over.\n", - "Make it more efficient by memoizing it, as described in [Chapter 10](section_memos)." + "Перепишите тело функции, используя вложенные условные выражения.\n\nЭта функция не очень эффективна, потому что она в конечном итоге вычисляет одни и те же значения снова и снова.\nСделайте его более эффективным, запомнив его, как описано в [Глава 10] (section_memos)." ] }, { @@ -1980,9 +1843,7 @@ "id": "921719dc", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "Here's the `__str__` method from the `Deck` class in [Chapter 17](section_print_deck)." + "### Упражнение\n\nВот метод `__str__` из класса« Deck »в [Глава 17] (section_print_deck)." ] }, { @@ -1998,7 +1859,7 @@ "id": "27f189cf", "metadata": {}, "source": [ - "Write a more concise version of this method with a list comprehension or generator expression." + "Напишите более краткую версию этого метода с помощью понимания списка или выражения генератора." ] }, { @@ -2018,7 +1879,7 @@ "tags": [] }, "source": [ - "You can use this example to test your solution." + "Вы можете использовать этот пример для проверки вашего решения." ] }, { @@ -2046,13 +1907,7 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", - "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", - "\n", - "Code license: [MIT License](https://mit-license.org/)\n", - "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n\nCopyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n\nЛицензия кода: [Лицензия MIT] (https://mit-license.org/)\n\nТекстовая лицензия: [Creative Commons attribution-noncommercial-sharealik" ] } ], From 2755365739f856fdd7dbbad7ed72166f8b492040 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:16:57 +0300 Subject: [PATCH 28/44] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20=D1=8F=D1=87=D0=B5=D0=B5=D0=BA=20=D0=BD=D0=B0=20=D1=80?= =?UTF-8?q?=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9=20=D0=B2=20=D0=B3=D0=BB?= =?UTF-8?q?=D0=B0=D0=B2=D0=B5=200?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- chapters/chap00.ipynb | 201 +++++++++++++++++++++--------------------- 1 file changed, 99 insertions(+), 102 deletions(-) diff --git a/chapters/chap00.ipynb b/chapters/chap00.ipynb index b42d9c0..1cc0316 100644 --- a/chapters/chap00.ipynb +++ b/chapters/chap00.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать печатную и электронную версии *Think Python 3e* на\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -15,7 +15,7 @@ "id": "d9724920", "metadata": {}, "source": [ - "# Preface\n", + "# Предисловие\n", "\n" ] }, @@ -24,21 +24,21 @@ "id": "b76f38c6", "metadata": {}, "source": [ - "## Who Is This Book For?\n", + "## Для кого эта книга?\n", "\n", - "If you want to learn to program, you have come to the right place.\n", - "Python is one of the best programming languages for beginners -- and it is also one of the most in-demand skills.\n", + "Если вы хотите научиться программировать, вы пришли по адресу.\n", + "Python — один из лучших языков программирования для новичков и одновременно одна из самых востребованных компетенций.\n", "\n", - "You have also come at the right time, because learning to program now is probably easier than ever.\n", - "With virtual assistants like ChatGPT, you don't have to learn alone.\n", - "Throughout this book, I'll suggest ways you can use these tools to accelerate your learning.\n", + "Вы также выбрали удачное время, потому что сейчас учиться программировать, вероятно, легче, чем когда-либо.\n", + "С виртуальными ассистентами вроде ChatGPT вам не придётся учиться в одиночку.\n", + "На протяжении всей книги я буду предлагать способы, как использовать эти инструменты, чтобы ускорить обучение.\n", "\n", - "This book is primarily for people who have never programmed before and people who have some experience in another programming language.\n", - "If you have substantial experience in Python, you might find the first few chapters too slow.\n", + "Книга рассчитана прежде всего на тех, кто никогда не программировал, а также на читателей с опытом в других языках программирования.\n", + "Если у вас уже есть значительный опыт в Python, первые главы могут показаться слишком медленными.\n", "\n", - "One of the challenges of learning to program is that you have to learn *two* languages: one is the programming language itself; the other is the vocabulary we use to talk about programs.\n", - "If you learn only the programming language, you are likely to have problems when you need to interpret an error message, read documentation, talk to another person, or use virtual assistants.\n", - "If you have done some programming, but you have not also learned this second language, I hope you find this book helpful." + "Одна из сложностей изучения программирования состоит в том, что приходится осваивать *два* языка: сам язык программирования и словарь терминов, которыми мы пользуемся, говоря о программах.\n", + "Если изучать только язык программирования, могут возникать трудности с пониманием сообщений об ошибках, чтением документации, общением с другими людьми или использованием виртуальных ассистентов.\n", + "Если вы уже немного программировали, но не освоили этот второй язык, надеюсь, эта книга будет вам полезна.\n" ] }, { @@ -46,21 +46,21 @@ "id": "b4dd57bc", "metadata": {}, "source": [ - "## Goals of the Book\n", + "## Цели книги\n", "\n", - "Writing this book, I tried to be careful with the vocabulary.\n", - "I define each term when it first appears.\n", - "And there is a glossary that the end of each chapter that reviews the terms that were introduced.\n", + "Пишa эту книгу, я старался аккуратно обращаться с терминологией.\n", + "Я определяю каждый термин в момент первого появления.\n", + "В конце каждой главы есть глоссарий, где повторяются введённые термины.\n", "\n", - "I also tried to be concise.\n", - "The less mental effort it takes to read the book, the more capacity you will have for programming.\n", + "Я также стремился быть лаконичным.\n", + "Чем меньше умственных усилий требуется на чтение, тем больше их остаётся на программирование.\n", "\n", - "But you can't learn to program just by reading a book -- you have to practice.\n", - "For that reason, this book includes exercises at the end of every chapter where you can practice what you have learned.\n", + "Но программированию нельзя научиться, лишь читая книгу — нужно практиковаться.\n", + "Поэтому в конце каждой главы есть упражнения, в которых вы можете закрепить материал.\n", "\n", - "If you read carefully and work on exercises consistently, you will make progress.\n", - "But I'll warn you now -- learning to program is not easy, and even for experienced programmers it can be frustrating.\n", - "As we go, I will suggest strategies to help you write correct programs and fix incorrect ones." + "Если читать внимательно и регулярно выполнять упражнения, вы будете продвигаться вперёд.\n", + "Но предупреждаю: учиться программировать нелегко, и даже опытные программисты порой испытывают разочарование.\n", + "По ходу дела я буду предлагать стратегии, которые помогут писать правильные программы и исправлять ошибки.\n" ] }, { @@ -68,31 +68,31 @@ "id": "6516d914", "metadata": {}, "source": [ - "## Navigating the Book\n", + "## Как работать с книгой\n", "\n", - "Each chapter in this book builds on the previous ones, so you should read them in order and take time to work on the exercises before you move on.\n", + "Каждая глава строится на предыдущих, поэтому читайте их по порядку и выполняйте упражнения, прежде чем переходить дальше.\n", "\n", - "The first six chapters introduce basic elements like arithmetic, conditionals, and loops.\n", - "They also introduce the most important concept in programming, functions, and a powerful way to use them, recursion.\n", + "В первых шести главах рассматриваются базовые элементы: арифметика, условные операторы и циклы.\n", + "Там же вводится важнейшее понятие программирования — функции, а также мощный способ их применения — рекурсия.\n", "\n", - "Chapters 7 and 8 introduce strings -- which can represent letter, words, and sentences -- and algorithms for working with them.\n", + "В главах 7 и 8 разбираются строки — они могут представлять буквы, слова и предложения — и алгоритмы работы с ними.\n", "\n", - "Chapters 9 through 12 introduce Python's core data structures -- lists, dictionaries, and tuples -- which are powerful tools for writing efficient programs.\n", - "Chapter 12 presents algorithms for analyzing text and randomly generating new text.\n", - "Algorithms like these are at the core of large language models (LLMs), so this chapter will give you an idea of how tools like ChatGPT work.\n", + "В главах с 9 по 12 мы знакомимся с основными структурами данных Python — списками, словарями и кортежами, которые позволяют писать эффективные программы.\n", + "В 12 главе приводятся алгоритмы анализа текста и случайного его порождения.\n", + "Такие алгоритмы лежат в основе больших языковых моделей (LLM), поэтому эта глава поможет понять, как работают инструменты вроде ChatGPT.\n", "\n", - "Chapter 13 is about ways to store data in long-term storage -- files and databases.\n", - "As an exercise, you can write a program that searches a file system and finds duplicate files.\n", + "Глава 13 посвящена способам долговременного хранения данных — файлам и базам данных.\n", + "В качестве упражнения вы напишете программу, которая ищет в файловой системе дубликаты файлов.\n", "\n", - "Chapters 14 through 17 introduce object-oriented programming (OOP), which is a way to organize programs and the data they work with.\n", - "Many Python libraries are written in object-oriented style, so these chapters will help you understand their design -- and define your own objects.\n", + "В главах с 14 по 17 вводится объектно-ориентированное программирование (ООП) — способ организации программ и данных, с которыми они работают.\n", + "Многие библиотеки Python написаны в объектно-ориентированном стиле, поэтому эти главы помогут понять их устройство и создавать собственные объекты.\n", "\n", - "The goal of this book is not to cover the entire Python language.\n", - "Rather, I focus on a subset of the language that provides the greatest capability with the fewest concepts.\n", - "Nevertheless, Python has a lot of features you can use to solve common problems efficiently.\n", - "Chapter 18 presents some of these features.\n", + "Цель этой книги — не охватить весь язык Python.\n", + "Я сосредоточился на подмножестве языка, которое даёт наибольшие возможности при минимуме понятий.\n", + "Тем не менее у Python есть множество средств для эффективного решения типовых задач.\n", + "О некоторых из них рассказывается в 18 главе.\n", "\n", - "Finally, Chapter 19 presents my parting thoughts and suggestions for continuing your programming journey." + "Наконец, в 19 главе я делюсь завершающими мыслями и советами по продолжению изучения программирования.\n" ] }, { @@ -100,38 +100,38 @@ "id": "23013838", "metadata": {}, "source": [ - "## What's new in the third edition?\n", + "## Что нового в третьем издании?\n", "\n", - "The biggest changes in this edition were driven by two new technologies -- Jupyter notebooks and virtual assistants.\n", + "Наибольшие изменения в этой версии связаны с двумя новыми технологиями — Jupyter-ноутбуками и виртуальными ассистентами.\n", "\n", - "Each chapter of this book is a Jupyter notebook, which is a document that contains both ordinary text and code.\n", - "For me, that makes it easier to write the code, test it, and keep it consistent with the text.\n", - "For you, it means you can run the code, modify it, and work on the exercises, all in one place.\n", - "Instructions for working with the notebooks are in the first chapter.\n", + "Каждая глава этой книги — это Jupyter-ноутбук, документ, содержащий обычный текст и код.\n", + "Мне так легче писать код, тестировать его и поддерживать соответствие тексту.\n", + "Вам это позволит запускать код, изменять его и выполнять задания в одном месте.\n", + "Инструкции по работе с ноутбуками приведены в первой главе.\n", "\n", - "The other big change is that I've added advice for working with virtual assistants like ChatGPT and using them to accelerate your learning.\n", - "When the previous edition of this book was published in 2016, the predecessors of these tools were far less useful and most people were unaware of them. \n", - "Now they are a standard tool for software engineering, and I think they will be a transformational tool for learning to program -- and learning a lot of other things, too.\n", + "Другая крупная новинка — советы по использованию виртуальных ассистентов вроде ChatGPT, которые помогут вам учиться быстрее.\n", + "Когда предыдущее издание вышло в 2016 году, предшественники этих инструментов были гораздо менее полезны, и большинство людей о них не знали.\n", + "Теперь они стали стандартным инструментом разработки программного обеспечения, и, на мой взгляд, станут революционным средством обучения программированию и многому другому.\n", "\n", - "The other changes in the book were motivated by my regrets about the second edition.\n", + "Остальные изменения книги связаны с моими сожалениями о втором издании.\n", "\n", - "The first is that I did not emphasize software testing.\n", - "That was already a regrettable omission in 2016, but with the advent of virtual assistants, automated testing has become even more important.\n", - "So this edition presents Python's most widely-used testing tools, `doctest` and `unittest`, and includes several exercises where you can practice working with them.\n", + "Во-первых, я недостаточно уделил внимания тестированию программ.\n", + "Уже в 2016 году это было упущением, а с появлением виртуальных ассистентов автоматизированное тестирование стало ещё важнее.\n", + "Поэтому в этом издании представлены наиболее популярные средства тестирования Python — `doctest` и `unittest`, а также несколько упражнений для практики работы с ними.\n", "\n", - "My other regret is that the exercises in the second edition were uneven -- some were more interesting than others and some were too hard.\n", - "Moving to Jupyter notebooks helped me develop and test a more engaging and effective sequence of exercises.\n", + "Во-вторых, задания во втором издании были неравномерными: одни получились интереснее, другие оказались слишком сложными.\n", + "Перевод книги в формат Jupyter-ноутбуков помог мне разработать и проверить более последовательный и эффективный набор упражнений.\n", "\n", - "In this revision, the sequence of topics is almost the same, but I rearranged a few of the chapters and compressed two short chapters into one.\n", - "Also, I expanded the coverage of strings to include regular expressions.\n", + "В этой редакции последовательность тем почти не изменилась, но я переставил несколько глав и объединил две короткие главы в одну.\n", + "Кроме того, я расширил раздел о строках, добавив регулярные выражения.\n", "\n", - "A few chapters use turtle graphics.\n", - "In previous editions, I used Python's `turtle` module, but unfortunately it doesn't work in Jupyter notebooks.\n", - "So I replaced it with a new turtle module that should be easier to use.\n", + "В нескольких главах используются черепашья графика.\n", + "В прежних изданиях я применял модуль `turtle` из стандартной библиотеки, но, к сожалению, он не работает в Jupyter-ноутбуках.\n", + "Поэтому я заменил его новым модулем turtle, который должен быть проще в использовании.\n", "\n", - "Finally, I rewrote a substantial fraction of the text, clarifying places that needed it and cutting back in places where I was not as concise as I could be.\n", + "Наконец, я переписал значительную часть текста, уточняя и сокращая его там, где это было нужно.\n", "\n", - "I am very proud of this new edition -- I hope you like it!" + "Я очень горжусь этим изданием и надеюсь, оно вам понравится!\n" ] }, { @@ -139,27 +139,27 @@ "id": "bfb779bb", "metadata": {}, "source": [ - "## Getting started\n", + "## Начало работы\n", "\n", - "For most programming languages, including Python, there are many tools you can use to write and run programs. \n", - "These tools are called integrated development environments (IDEs).\n", - "In general, there are two kinds of IDEs:\n", + "Для большинства языков программирования, включая Python, существует много инструментов для написания и запуска программ.\n", + "Эти инструменты называются интегрированными средами разработки (IDE).\n", + "В общих чертах IDE бывают двух типов:\n", "\n", - "* Some work with files that contain code, so they provide tools for editing and running these files.\n", + "* Одни работают с файлами кода и предоставляют средства для их редактирования и запуска.\n", "\n", - "* Others work primarily with notebooks, which are documents that contain text and code.\n", + "* Другие в основном работают с ноутбуками — документами, содержащими текст и код.\n", "\n", - "For beginners, I recommend starting with a notebook development environment like Jupyter.\n", + "Новичкам я рекомендую начать с ноутбучной среды разработки, такой как Jupyter.\n", "\n", - "The notebooks for this book are available from an online repository at .\n", + "Ноутбуки этой книги доступны в онлайн‑репозитории по адресу .\n", "\n", - "There are two ways to use them:\n", + "Существует два способа их использовать:\n", "\n", - "* You can download the notebooks and run them on your own computer. In that case, you have to install Python and Jupyter, which is not hard, but if you want to learn Python, it can be frustrating to spend a lot of time installing software.\n", + "* Можно скачать ноутбуки и запускать их на своём компьютере. В этом случае придётся установить Python и Jupyter; это несложно, но если вы хотите учить Python, бывает досадно тратить много времени на установку ПО.\n", "\n", - "* An alternative is to run the notebooks on Colab, which is a Jupyter environment that runs in a web browser, so you don't have to install anything. Colab is operated by Google, and it is free to use.\n", + "* Альтернативный вариант — работать с ноутбуками на Colab, это среда Jupyter, которая запускается в веб‑браузере, так что ничего устанавливать не нужно. Colab работает под управлением Google и бесплатен.\n", "\n", - "If you are just getting started, I strongly recommend you start with Colab." + "Если вы только начинаете, настоятельно рекомендую стартовать с Colab.\n" ] }, { @@ -167,17 +167,17 @@ "id": "2ebd2412", "metadata": {}, "source": [ - "## Resources for Teachers\n", + "## Ресурсы для преподавателей\n", "\n", - "If you are teaching with this book, here are some resources you might find useful.\n", + "Если вы преподаёте по этой книге, вот несколько ресурсов, которые могут пригодиться.\n", "\n", - "* You can find notebooks with solutions to the exercises at , along with links to the additional resources below.\n", + "* На можно найти ноутбуки с решениями упражнений и ссылки на дополнительные материалы.\n", "\n", - "* Quizzes for each chapter, and a summative quiz for the whole book, are available on request.\n", + "* По запросу доступны контрольные работы для каждой главы и итоговый тест по всей книге.\n", "\n", - "* *Teaching and Learning with Jupyter* is an online book with suggestions for using Jupyter effectively in the classroom. You can read the book at \n", + "* *Teaching and Learning with Jupyter* — это онлайн‑книга с рекомендациями по эффективному применению Jupyter в учебном процессе. Её можно прочитать на \n", "\n", - "* One of the best ways to use notebooks is live coding, where an instructor writes code and students follow along in their own notebooks. To learn about live coding -- and get other great advice about teaching programming -- I recommend the instructor training provided by The Carpentries, at " + "* Один из лучших способов использовать ноутбуки — это кодирование вживую, когда преподаватель пишет код, а студенты повторяют за ним в своих ноутбуках. Узнать больше о такой методике и получить другие советы по обучению программированию можно на тренинге для инструкторов от организации The Carpentries: \n" ] }, { @@ -185,29 +185,26 @@ "id": "28e7de55", "metadata": {}, "source": [ - "## Acknowledgments\n", + "## Благодарности\n", "\n", - "Many thanks to Jeff Elkner, who translated my Java book into Python,\n", - "which got this project started and introduced me to what has turned out\n", - "to be my favorite language.\n", - "Thanks also to Chris Meyers, who contributed several sections to *How to Think Like a Computer Scientist*.\n", + "Большое спасибо Джеффу Элкнеру, который перевёл мою книгу по Java на Python,\n", + "именно с этого начался проект и я познакомился со своим любимым языком.\n", + "Также благодарю Криса Майерса, который написал несколько разделов для *How to Think Like a Computer Scientist*.\n", "\n", - "Thanks to the Free Software Foundation for developing the GNU Free Documentation License, which helped make my collaboration with Jeff and Chris possible, and thanks to the Creative Commons for the license I am using now.\n", + "Благодарю Фонд свободного программного обеспечения за создание лицензии GNU FDL, которая сделала возможным моё сотрудничество с Джеффом и Крисом, а также Creative Commons за нынешнюю лицензию.\n", "\n", - "Thanks to the developers and maintainers of the Python language and the libraries I used, including the Turtle graphics module; the tools I used to develop the book, including Jupyter and JupyterBook; and the services I used, including ChatGPT, Copilot, Colab and GitHub.\n", + "Спасибо разработчикам и сопровождающим язык Python и библиотеки, которые я использовал, включая модуль Turtle; инструментам, с помощью которых я создавал книгу, таким как Jupyter и JupyterBook; и сервисам ChatGPT, Copilot, Colab и GitHub.\n", "\n", - "Thanks to the editors at Lulu who worked on *How to Think Like a Computer Scientist* and the editors at O'Reilly Media who worked on *Think Python*.\n", + "Благодарю редакторов из Lulu, работавших над *How to Think Like a Computer Scientist*, и редакторов O'Reilly Media, работавших над *Think Python*.\n", "\n", - "Special thanks to the technical reviewers for the second edition, Melissa Lewis and Luciano Ramalho, and for the third edition, Sam Lau and Luciano Ramalho (again!).\n", - "I am also grateful to Luciano for developing the turtle graphics module I use in several chapters, called `jupyturtle`.\n", + "Особая благодарность техническим редакторам второго издания, Мелиссе Льюис и Лусиано Рамалью, а также третьего издания — Сэму Лау и вновь Лусиано Рамалью.\n", + "Отдельно благодарю Лусиано за создание используемого мной в нескольких главах модуля turtle `jupyturtle`.\n", "\n", - "Thanks to all the students who worked with earlier versions of this book and all the contributors who sent in corrections and suggestions.\n", - "More than 100 sharp-eyed and thoughtful readers have sent in suggestions and corrections over the past few years. Their contributions, and enthusiasm for this project, have been a huge help.\n", + "Спасибо всем студентам, работавшим с ранними версиями книги, и всем читателям, приславшим исправления и предложения.\n", + "Более ста внимательных и небезразличных читателей за последние годы прислали замечания и исправления; их вклад и энтузиазм очень помогли.\n", "\n", - "If you have a suggestion or correction, please send email to `feedback@thinkpython.com`.\n", - "If you include at least part of the sentence the error appears in, that\n", - "makes it easy for me to search. Page and section numbers are fine, too,\n", - "but not quite as easy to work with. Thanks!" + "Если у вас есть предложения или исправления, пишите на `feedback@thinkpython.com`.\n", + "Если укажете хотя бы часть предложения, где обнаружена ошибка, мне будет проще её найти. Номера страниц и разделов тоже пригодятся, но работать с ними не так удобно. Спасибо!\n" ] }, { @@ -227,11 +224,11 @@ "source": [ "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "© 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -256,4 +253,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 6936129afb5b5a01fb999f1999b0d880eaa8c435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:17:41 +0300 Subject: [PATCH 29/44] Translate first part of Chapter 1 notebook --- chapters/chap01.ipynb | 342 +++++++++++++++++++++--------------------- 1 file changed, 171 insertions(+), 171 deletions(-) diff --git a/chapters/chap01.ipynb b/chapters/chap01.ipynb index bd3875d..44525cb 100644 --- a/chapters/chap01.ipynb +++ b/chapters/chap01.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432?ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325)." ] }, { @@ -17,14 +17,14 @@ "tags": [] }, "source": [ - "# Welcome\n", + "# Добро пожаловать\n", "\n", - "This is the Jupyter notebook for Chapter 1 of [*Think Python*, 3rd edition](https://greenteapress.com/wp/think-python-3rd-edition), by Allen B. Downey.\n", + "Это ноутбук Jupyter для главы 1 из [*Think Python*, 3-е издание] (https://greenteapress.com/wp/think-python-3rd-edition), Аллен Б. Дауни.\n", "\n", - "If you are not familiar with Jupyter notebooks,\n", - "[click here for a short introduction](https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/jupyter_intro.ipynb).\n", + "Если вы не знакомы с ноутбуками Jupyter,\n", + "[Нажмите здесь для короткого введения] (https://colab.research.google.com/github/allendowney/thinkpython/blob/v3/chapters/jupyter_intro.ipynb).\n", "\n", - "Then, if you are not already running this notebook on Colab, [click here to run this notebook on Colab](https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/chap01.ipynb)." + "Затем, если вы еще не запускаете эту записную книжку на Colab, нажмите здесь, чтобы запустить эту ноутбук на Colab] (https://colab.research.google.com/github/allendowney/thinkpython/blob/v3/chapters/chap01.ipynb)." ] }, { @@ -34,9 +34,9 @@ "tags": [] }, "source": [ - "The following cell downloads a file and runs some code that is used specifically for this book.\n", - "You don't have to understand this code yet, but you should run it before you do anything else in this notebook.\n", - "Remember that you can run the code by selecting the cell and pressing the play button (a triangle in a circle) or hold down `Shift` and press `Enter`." + "Следующая ячейка загружает файл и запускает какой -то код, который используется специально для этой книги.\n", + "Вам еще не нужно понимать этот код, но вы должны запустить его, прежде чем сделать что -то еще в этой записной книжке.\n", + "Помните, что вы можете запустить код, выбрав ячейку и нажав кнопку воспроизведения (треугольник в круге) или удерживать `shift` и нажмите« Enter »." ] }, { @@ -71,21 +71,21 @@ "tags": [] }, "source": [ - "# Programming as a way of thinking\n", + "# Программирование как способ мышления\n", "\n", - "The first goal of this book is to teach you how to program in Python.\n", - "But learning to program means learning a new way to think, so the second goal of this book is to help you think like a computer scientist.\n", - "This way of thinking combines some of the best features of mathematics, engineering, and natural science.\n", - "Like mathematicians, computer scientists use formal languages to denote ideas -- specifically computations.\n", - "Like engineers, they design things, assembling components into systems and evaluating trade-offs among alternatives.\n", - "Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.\n", + "Первая цель этой книги - научить вас программировать в Python.\n", + "Но обучение программированию означает изучение нового способа мыслить, поэтому вторая цель этой книги - помочь вам думать как компьютерный ученый.\n", + "Этот способ мышления сочетает в себе некоторые из лучших особенностей математики, инженерии и естественных наук.\n", + "Как и математики, компьютерные ученые используют формальные языки для обозначения идей - специально вычислений.\n", + "Как и инженеры, они разрабатывают вещи, собирают компоненты в системы и оценивают компромиссы между альтернативами.\n", + "Как и ученые, они наблюдают за поведением сложных систем, формируют гипотезы и тестируют прогнозы.\n", "\n", - "We will start with the most basic elements of programming and work our way up.\n", - "In this chapter, we'll see how Python represents numbers, letters, and words.\n", - "And you'll learn to perform arithmetic operations.\n", + "Мы начнем с самых основных элементов программирования и поднимитесь.\n", + "В этой главе мы посмотрим, как Python представляет цифры, буквы и слова.\n", + "И вы научитесь выполнять арифметические операции.\n", "\n", - "You will also start to learn the vocabulary of programming, including terms like operator, expression, value, and type.\n", - "This vocabulary is important -- you will need it to understand the rest of the book, to communicate with other programmers, and to use and understand virtual assistants." + "Вы также начнете изучать словарный запас программирования, включая такие термины, как оператор, выражение, ценность и тип.\n", + "Этот словарный запас важен - вам понадобится он, чтобы понять остальную часть книги, общаться с другими программистами, а также использовать и понять виртуальных помощников." ] }, { @@ -93,9 +93,9 @@ "id": "a371aea3", "metadata": {}, "source": [ - "## Arithmetic operators\n", + "## Арифметические операторы\n", "\n", - "An **arithmetic operator** is a symbol that represents an arithmetic computation. For example, the plus sign, `+`, performs addition." + "** Арифметический оператор ** является символом, который представляет арифметическое вычисление.Например, знак плюса, `+`, выполняет дополнение." ] }, { @@ -113,7 +113,7 @@ "id": "fc0e7ce8", "metadata": {}, "source": [ - "The minus sign, `-`, is the operator that performs subtraction." + "Знак минус, `-`, является оператором, который выполняет вычитание." ] }, { @@ -131,7 +131,7 @@ "id": "63e4e780", "metadata": {}, "source": [ - "The asterisk, `*`, performs multiplication." + "Звездочка, `*` выполняет умножение." ] }, { @@ -149,7 +149,7 @@ "id": "a6192d13", "metadata": {}, "source": [ - "And the forward slash, `/`, performs division:" + "И прямая смена, `/`, выполняет дивизион:" ] }, { @@ -167,16 +167,16 @@ "id": "641ad233", "metadata": {}, "source": [ - "Notice that the result of the division is `42.0` rather than `42`. That's because there are two types of numbers in Python: \n", + "Обратите внимание, что результат деления составляет `42.0`, а не« 42`.Это потому, что в Python есть два типа цифр:\n", "\n", - "* **integers**, which represent numbers with no fractional or decimal part, and \n", + "*** Целые числа **, которые представляют цифры без дробной или десятичной части, и\n", "\n", - "* **floating-point numbers**, which represent integers and numbers with a decimal point.\n", + "*** Числа с плавающей точкой **, которые представляют целые числа и числа с десятичной точкой.\n", "\n", - "If you add, subtract, or multiply two integers, the result is an integer.\n", - "But if you divide two integers, the result is a floating-point number.\n", - "Python provides another operator, `//`, that performs **integer division**.\n", - "The result of integer division is always an integer." + "Если вы добавляете, вычитаете или умножаете два целых числа, результатом является целое число.\n", + "Но если вы делите два целых числа, результатом является номер с плавающей запятой.\n", + "Python предоставляет еще одного оператора, `//`, который выполняет ** целочисленное разделение **.\n", + "Результат целочисленного подразделения всегда является целым числом." ] }, { @@ -194,7 +194,7 @@ "id": "b2a620ab", "metadata": {}, "source": [ - "Integer division is also called \"floor division\" because it always rounds down (toward the \"floor\"). " + "Целочисленное подразделение также называется «Полевой дивизией», потому что он всегда окружает (к «полу»)." ] }, { @@ -212,8 +212,8 @@ "id": "41e2886a", "metadata": {}, "source": [ - "Finally, the operator `**` performs exponentiation; that is, it raises a\n", - "number to a power:" + "Наконец, оператор `**` выполняет экспонентацию;то есть он поднимает\n", + "номер к силе:" ] }, { @@ -231,9 +231,9 @@ "id": "b2502fb6", "metadata": {}, "source": [ - "In some other languages, the caret, `^`, is used for exponentiation, but in Python\n", - "it is a bitwise operator called XOR.\n", - "If you are not familiar with bitwise operators, the result might be unexpected:" + "На некоторых других языках каретка, `^`, используется для экспоненты, но в Python\n", + "Это кусочек оператора под названием XOR.\n", + "Если вы не знакомы с битой операторов, результат может быть неожиданным:" ] }, { @@ -251,8 +251,8 @@ "id": "30078370", "metadata": {}, "source": [ - "I won't cover bitwise operators in this book, but you can read about\n", - "them at ." + "Я не буду охватывать битовые операторы в этой книге, но вы можете прочитать о\n", + "их на ." ] }, { @@ -260,11 +260,11 @@ "id": "0f5b7e97", "metadata": {}, "source": [ - "## Expressions\n", + "## выражения\n", "\n", - "A collection of operators and numbers is called an **expression**.\n", - "An expression can contain any number of operators and numbers.\n", - "For example, here's an expression that contains two operators." + "Сборник операторов и цифр называется ** выражением **.\n", + "Выражение может содержать любое количество операторов и чисел.\n", + "Например, вот выражение, которое содержит два оператора." ] }, { @@ -282,10 +282,10 @@ "id": "8e95039c", "metadata": {}, "source": [ - "Notice that exponentiation happens before addition.\n", - "Python follows the order of operations you might have learned in a math class: exponentiation happens before multiplication and division, which happen before addition and subtraction.\n", + "Обратите внимание, что экспонентация происходит до добавления.\n", + "Python следует по порядку операций, который вы могли выучить в математическом классе: экспонентация происходит до размножения и деления, которые происходят до добавления и вычитания.\n", "\n", - "In the following example, multiplication happens before addition." + "В следующем примере умножение происходит до добавления." ] }, { @@ -303,7 +303,7 @@ "id": "914a60d8", "metadata": {}, "source": [ - "If you want the addition to happen first, you can use parentheses." + "Если вы хотите, чтобы добавление произошло первым, вы можете использовать скобки." ] }, { @@ -321,8 +321,8 @@ "id": "67ae0ae9", "metadata": {}, "source": [ - "Every expression has a **value**.\n", - "For example, the expression `6 * 7` has the value `42`." + "Каждое выражение имеет ** значение **.\n", + "Например, выражение `6 * 7` имеет значение` 42`." ] }, { @@ -330,10 +330,10 @@ "id": "caebaa51", "metadata": {}, "source": [ - "## Arithmetic functions\n", + "## Арифметические функции\n", "\n", - "In addition to the arithmetic operators, Python provides a few **functions** that work with numbers.\n", - "For example, the `round` function takes a floating-point number and rounds it off to the nearest integer." + "В дополнение к арифметическим операторам, Python предоставляет несколько ** функций **, которые работают с числами.\n", + "Например, функция «круглый» берет номер с плавающей точкой и завершает его до ближайшего целого числа." ] }, { @@ -361,8 +361,8 @@ "id": "f5738b4b", "metadata": {}, "source": [ - "The `abs` function computes the absolute value of a number.\n", - "For a positive number, the absolute value is the number itself." + "Функция `abs вычисляет абсолютное значение числа.\n", + "Для положительного числа абсолютным значением является само число." ] }, { @@ -380,7 +380,7 @@ "id": "e518494a", "metadata": {}, "source": [ - "For a negative number, the absolute value is positive." + "Для отрицательного числа абсолютное значение положительное." ] }, { @@ -398,11 +398,11 @@ "id": "6969ce45", "metadata": {}, "source": [ - "When we use a function like this, we say we're **calling** the function.\n", - "An expression that calls a function is a **function call**.\n", + "Когда мы используем такую функцию, мы говорим, что мы ** вызываем ** функцию.\n", + "Выражение, которое вызывает функцию, является вызовом функции **.\n", "\n", - "When you call a function, the parentheses are required.\n", - "If you leave them out, you get an error message." + "Когда вы называете функцию, требуются скобки.\n", + "Если вы оставите их, вы получите сообщение об ошибке." ] }, { @@ -412,8 +412,8 @@ "tags": [] }, "source": [ - "NOTE: The following cell uses `%%expect`, which is a Jupyter \"magic command\" that means we expect the code in this cell to produce an error. For more on this topic, see the\n", - "[Jupyter notebook introduction](https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/jupyter_intro.ipynb)." + "ПРИМЕЧАНИЕ. В следующей ячейке используется `%% weard`, которая представляет собой« магическую команду »Юпитера, что означает, что мы ожидаем, что код в этой ячейке произведет ошибку.Для получения дополнительной информации по этой теме см. В\n", + "[Jupyter Notebook введение] (https://colab.research.google.com/github/allendowney/thinkpython/blob/v3/chapters/jupyter_intro.ipynb)." ] }, { @@ -435,13 +435,13 @@ "id": "7d356f1b", "metadata": {}, "source": [ - "You can ignore the first line of this message; it doesn't contain any information we need to understand right now.\n", - "The second line is the code that contains the error, with a caret (`^`) beneath it to indicate where the error was discovered.\n", + "Вы можете игнорировать первую строку этого сообщения;Он не содержит никакой информации, которая нам нужно понять прямо сейчас.\n", + "Вторая строка - это код, который содержит ошибку с каретой (`^`) под ним, чтобы указать, где была обнаружена ошибка.\n", "\n", - "The last line indicates that this is a **syntax error**, which means that there is something wrong with the structure of the expression.\n", - "In this example, the problem is that a function call requires parentheses.\n", + "Последняя строка указывает на то, что это ** синтаксическая ошибка **, что означает, что что -то не так со структурой выражения.\n", + "В этом примере проблема в том, что функциональный вызов требует скобок.\n", "\n", - "Let's see what happens if you leave out the parentheses *and* the value." + "Давайте посмотрим, что произойдет, если вы оставите скобки * и * значение." ] }, { @@ -459,8 +459,8 @@ "id": "94478885", "metadata": {}, "source": [ - "A function name all by itself is a legal expression that has a value.\n", - "When it's displayed, the value indicates that `abs` is a function, and it includes some additional information I'll explain later." + "Название функции само по себе является юридическим выражением, которое имеет ценность.\n", + "Когда он отображается, значение указывает на то, что «ABS» является функцией, и оно включает в себя некоторую дополнительную информацию, которую я объясню позже." ] }, { @@ -468,10 +468,10 @@ "id": "31a85d17", "metadata": {}, "source": [ - "## Strings\n", + "## струны\n", "\n", - "In addition to numbers, Python can also represent sequences of letters, which are called **strings** because the letters are strung together like beads on a necklace.\n", - "To write a string, we can put a sequence of letters inside straight quotation marks." + "В дополнение к числам, Python также может представлять последовательности букв, которые называются ** струны **, потому что буквы навязываются вместе, как бусы на ожерелье.\n", + "Чтобы написать строку, мы можем поместить последовательность букв в прямые кавычки." ] }, { @@ -489,7 +489,7 @@ "id": "d20050d8", "metadata": {}, "source": [ - "It is also legal to use double quotation marks." + "Также законно использовать двойные кавычки." ] }, { @@ -507,7 +507,7 @@ "id": "76f5edb7", "metadata": {}, "source": [ - "Double quotes make it easy to write a string that contains an apostrophe, which is the same symbol as a straight quote." + "Двойные кавычки позволяют легко написать строку, которая содержит апостроф, который является тем же символом, что и прямая цитата." ] }, { @@ -525,7 +525,7 @@ "id": "d62d4b1c", "metadata": {}, "source": [ - "Strings can also contain spaces, punctuation, and digits." + "Строки также могут содержать пробелы, пунктуацию и цифры." ] }, { @@ -543,7 +543,7 @@ "id": "9ad47f7a", "metadata": {}, "source": [ - "The `+` operator works with strings; it joins two strings into a single string, which is called **concatenation**" + "Оператор `+` работает со строками;Он соединяет две строки в одну строку, которая называется ** concatenation **" ] }, { @@ -561,7 +561,7 @@ "id": "0ad969a3", "metadata": {}, "source": [ - "The `*` operator also works with strings; it makes multiple copies of a string and concatenates them." + "Оператор `*` также работает со строками;Это делает несколько копий струны и объединяет их." ] }, { @@ -579,9 +579,9 @@ "id": "dfba16a5", "metadata": {}, "source": [ - "The other arithmetic operators don't work with strings.\n", + "Другие арифметические операторы не работают с струнами.\n", "\n", - "Python provides a function called `len` that computes the length of a string." + "Python предоставляет функцию, называемую «Len», которая вычисляет длину строки." ] }, { @@ -599,10 +599,10 @@ "id": "d91e00b3", "metadata": {}, "source": [ - "Notice that `len` counts the letters between the quotes, but not the quotes.\n", + "Обратите внимание, что «Лен» считает буквы между цитатами, но не цитаты.\n", "\n", - "When you create a string, be sure to use straight quotes.\n", - "The back quote, also known as a backtick, causes a syntax error." + "Когда вы создаете строку, обязательно используйте прямые кавычки.\n", + "Задняя цитата, также известная как обратная связь, вызывает ошибку синтаксиса." ] }, { @@ -624,7 +624,7 @@ "id": "40d893d1", "metadata": {}, "source": [ - "Smart quotes, also known as curly quotes, are also illegal." + "Умные цитаты, также известные как кудрявые цитаты, также являются незаконными." ] }, { @@ -646,21 +646,21 @@ "id": "5471d4f8", "metadata": {}, "source": [ - "## Values and types\n", + "## значения и типы\n", "\n", - "So far we've seen three kinds of values:\n", + "До сих пор мы видели три вида ценностей:\n", "\n", - "* `2` is an integer,\n", + "* `2` - целое число,\n", "\n", - "* `42.0` is a floating-point number, and \n", + "* `42.0`-это номер с плавающей запятой, и\n", "\n", - "* `'Hello'` is a string.\n", + "* `'Hello'' - это строка.\n", "\n", - "A kind of value is called a **type**.\n", - "Every value has a type -- or we sometimes say it \"belongs to\" a type.\n", + "Вид значения называется ** тип **.\n", + "Каждое значение имеет тип - или мы иногда говорим, что это «принадлежит» типу.\n", "\n", - "Python provides a function called `type` that tells you the type of any value.\n", - "The type of an integer is `int`." + "Python предоставляет функцию, называемую `type`, которая сообщает вам тип любого значения.\n", + "Тип целого числа - `int`." ] }, { @@ -678,7 +678,7 @@ "id": "b137814c", "metadata": {}, "source": [ - "The type of a floating-point number is `float`." + "Тип номера с плавающей точкой-`float`." ] }, { @@ -696,7 +696,7 @@ "id": "266dea4e", "metadata": {}, "source": [ - "And the type of a string is `str`." + "И тип строки - `str`." ] }, { @@ -714,8 +714,8 @@ "id": "76d216ed", "metadata": {}, "source": [ - "The types `int`, `float`, and `str` can be used as functions.\n", - "For example, `int` can take a floating-point number and convert it to an integer (always rounding down)." + "Типы `int`,` float` и `str` могут использоваться в качестве функций.\n", + "Например, `int` может взять номер с плавающей точкой и преобразовать его в целое число (всегда округление)." ] }, { @@ -733,7 +733,7 @@ "id": "dcd8d114", "metadata": {}, "source": [ - "And `float` can convert an integer to a floating-point value." + "И `float 'может преобразовать целое число в значение с плавающей точкой." ] }, { @@ -751,8 +751,8 @@ "id": "eda70b61", "metadata": {}, "source": [ - "Now, here's something that can be confusing.\n", - "What do you get if you put a sequence of digits in quotes?" + "Теперь, вот кое -что, что может быть запутанным.\n", + "Что вы получите, если вы поместите последовательность цифр в цитаты?" ] }, { @@ -770,7 +770,7 @@ "id": "fdded653", "metadata": {}, "source": [ - "It looks like a number, but it is actually a string." + "Это похоже на число, но на самом деле это строка." ] }, { @@ -788,7 +788,7 @@ "id": "2683ac35", "metadata": {}, "source": [ - "If you try to use it like a number, you might get an error." + "Если вы попытаетесь использовать его как номер, вы можете получить ошибку." ] }, { @@ -810,10 +810,10 @@ "id": "32c11cc4", "metadata": {}, "source": [ - "This example generates a `TypeError`, which means that the values in the expression, which are called **operands**, have the wrong type.\n", - "The error message indicates that the `/` operator does not support the types of these values, which are `str` and `int`.\n", + "Этот пример генерирует `typeerror`, что означает, что значения в выражении, которые называются ** операнды **, имеют неправильный тип.\n", + "Сообщение об ошибке указывает, что оператор `/` не поддерживает типы этих значений, которые являются `str` и` int`.\n", "\n", - "If you have a string that contains digits, you can use `int` to convert it to an integer." + "Если у вас есть строка, которая содержит цифры, вы можете использовать `int`, чтобы преобразовать ее в целое число." ] }, { @@ -831,7 +831,7 @@ "id": "86935d56", "metadata": {}, "source": [ - "If you have a string that contains digits and a decimal point, you can use `float` to convert it to a floating-point number." + "Если у вас есть строка, которая содержит цифры и десятичную точку, вы можете использовать «float», чтобы преобразовать ее в номер с плавающей точкой." ] }, { @@ -849,9 +849,9 @@ "id": "03103ef4", "metadata": {}, "source": [ - "When you write a large integer, you might be tempted to use commas\n", - "between groups of digits, as in `1,000,000`.\n", - "This is a legal expression in Python, but the result is not an integer." + "Когда вы пишете большое целое число, у вас может возникнуть соблазн использовать запятые\n", + "между группами цифр, как в 1 000 000 `.\n", + "Это юридическое выражение в Python, но результат не является целым числом." ] }, { @@ -869,10 +869,10 @@ "id": "3d24af71", "metadata": {}, "source": [ - "Python interprets `1,000,000` as a comma-separated sequence of integers.\n", - "We'll learn more about this kind of sequence later.\n", + "Python интерпретирует `1 000 000` как последовательность целых чисел, разделенную запятыми.\n", + "Позже мы узнаем больше об этой последовательности.\n", "\n", - "You can use underscores to make large numbers easier to read." + "Вы можете использовать подчеркивание, чтобы упростить чтение больших чисел." ] }, { @@ -890,13 +890,13 @@ "id": "1761cbac", "metadata": {}, "source": [ - "## Formal and natural languages\n", + "## формальные и естественные языки\n", "\n", - "**Natural languages** are the languages people speak, like English, Spanish, and French. They were not designed by people; they evolved naturally.\n", + "** Природные языки ** - это языки, которые люди говорят, как на английском, испанском и французском языках.Они не были спроектированы людьми;Они развивались естественно.\n", "\n", - "**Formal languages** are languages that are designed by people for specific applications. \n", - "For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols.\n", - "Similarly, programming languages are formal languages that have been designed to express computations." + "** Формальные языки ** - это языки, которые разработаны людьми для конкретных применений.\n", + "Например, нотация, которую используют математики, является формальным языком, который особенно хорош в обозначении отношений между числами и символами.\n", + "Точно так же языки программирования - это формальные языки, которые были разработаны для выражения вычислений." ] }, { @@ -904,19 +904,19 @@ "id": "1bf3d2dc", "metadata": {}, "source": [ - "Although formal and natural languages have some features in\n", - "common there are important differences:\n", + "Хотя формальные и природные языки имеют некоторые особенности в\n", + "Общие существуют важные различия:\n", "\n", - "* Ambiguity: Natural languages are full of ambiguity, which people deal with by\n", - " using contextual clues and other information. Formal languages are\n", - " designed to be nearly or completely unambiguous, which means that\n", - " any program has exactly one meaning, regardless of context.\n", + "* Неоднозначность: естественные языки полны двусмысленности, с которыми сталкиваются люди\n", + "Использование контекстуальных подсказок и другой информации.Формальные языки есть\n", + "спроектировано, чтобы быть почти или совершенно однозначным, что означает, что\n", + "Любая программа имеет ровное значение, независимо от контекста.\n", "\n", - "* Redundancy: In order to make up for ambiguity and reduce misunderstandings,\n", - " natural languages use redundancy. As a result, they are\n", - " often verbose. Formal languages are less redundant and more concise.\n", + "* Избыточность: чтобы компенсировать двусмысленность и уменьшить недоразумения,\n", + "Природные языки используют избыточность.В результате они\n", + "часто многослов.Формальные языки менее избыточные и более краткие.\n", "\n", - "* Literalness: Natural languages are full of idiom and metaphor. Formal languages mean exactly what they say." + "* Литеральная буква: естественные языки полны идиомы и метафоры.Формальные языки означают именно то, что они говорят." ] }, { @@ -924,12 +924,12 @@ "id": "78a1cec8", "metadata": {}, "source": [ - "Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages.\n", - "Formal languages are more dense than natural languages, so it takes longer to read them.\n", - "Also, the structure is important, so it is not always best to read from top to bottom, left to right.\n", - "Finally, the details matter. Small errors in spelling and\n", - "punctuation, which you can get away with in natural languages, can make\n", - "a big difference in a formal language." + "Поскольку мы все расти, говоря о естественных языках, иногда трудно приспособиться к формальным языкам.\n", + "Формальные языки более плотные, чем естественные языки, поэтому для их чтения требуется больше времени.\n", + "Кроме того, структура важна, поэтому не всегда лучше читать сверху вниз, слева направо.\n", + "Наконец, детали имеют значение.Небольшие ошибки в орфографии и\n", + "пунктуация, с которой вы можете сойти с рук на естественных языках, может сделать\n", + "Большая разница в формальном языке." ] }, { @@ -937,17 +937,17 @@ "id": "4358fa9a", "metadata": {}, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "Programmers make mistakes. For whimsical reasons, programming errors are called **bugs** and the process of tracking them down is called **debugging**.\n", + "Программисты делают ошибки.По причудливым причинам ошибки программирования называются ** ошибки **, а процесс их отслеживания называется ** отладка **.\n", "\n", - "Programming, and especially debugging, sometimes brings out strong emotions. If you are struggling with a difficult bug, you might feel angry, sad, or embarrassed.\n", + "Программирование, и особенно отладка, иногда выявляет сильные эмоции.Если вы боретесь с сложной ошибкой, вы можете чувствовать себя злым, грустным или смущенным.\n", "\n", - "Preparing for these reactions might help you deal with them. One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture.\n", + "Подготовка к этим реакциям может помочь вам справиться с ними.Один из подходов заключается в том, чтобы думать о компьютере как о сотруднике с определенными сильными сторонами, такими как скорость и точность, и особые слабости, такие как отсутствие сочувствия и неспособность понять общую картину.\n", "\n", - "Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses. And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.\n", + "Ваша работа - быть хорошим менеджером: найти способы воспользоваться преимуществами сильных сторон и смягчить слабые стороны.И найдите способы использовать свои эмоции, чтобы взаимодействовать с проблемой, не позволяя вашим реакциям мешать вашей способности эффективно работать.\n", "\n", - "Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming. At the end of each chapter there is a section, like this one, with my suggestions for debugging. I hope they help!" + "Обучение отладки может быть разочаровывающим, но это ценный навык, который полезен для многих действий, выходящих за рамки программирования.В конце каждой главы есть раздел, такой как этот, с моими предложениями по отладке.Надеюсь, они помогут!" ] }, { @@ -955,49 +955,49 @@ "id": "33b8ad00", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**arithmetic operator:**\n", - "A symbol, like `+` and `*`, that denotes an arithmetic operation like addition or multiplication.\n", + "** Арифметический оператор: **\n", + "Символ, например, `+` и `*`, который обозначает арифметическую операцию, такую как добавление или умножение.\n", "\n", - "**integer:**\n", - "A type that represents numbers with no fractional or decimal part.\n", + "** целое число: **\n", + "Тип, который представляет числа без дробной или десятичной части.\n", "\n", - "**floating-point:**\n", - "A type that represents integers and numbers with decimal parts.\n", + "** Плавающая точка: **\n", + "Тип, который представляет целые числа и числа с десятичными частями.\n", "\n", - "**integer division:**\n", - "An operator, `//`, that divides two numbers and rounds down to an integer.\n", + "** целочисленное подразделение: **\n", + "Оператор, `//`, который делит два числа и окружает целое число.\n", "\n", - "**expression:**\n", - "A combination of variables, values, and operators.\n", + "**выражение:**\n", + "Комбинация переменных, значений и операторов.\n", "\n", - "**value:**\n", - "An integer, floating-point number, or string -- or one of other kinds of values we will see later.\n", + "**ценить:**\n", + "Целое число, номер с плавающей точкой или строка-или один из других видов значений, которые мы увидим позже.\n", "\n", - "**function:**\n", - "A named sequence of statements that performs some useful operation.\n", - "Functions may or may not take arguments and may or may not produce a result.\n", + "** Функция: **\n", + "Названная последовательность операторов, которая выполняет некоторую полезную операцию.\n", + "Функции могут или не могут принимать аргументы и могут или не могут привести к результату.\n", "\n", - "**function call:**\n", - "An expression -- or part of an expression -- that runs a function.\n", - "It consists of the function name followed by an argument list in parentheses.\n", + "** Функциональный вызов: **\n", + "Выражение - или часть выражения - которое выполняет функцию.\n", + "Он состоит из имени функции, за которым следует список аргументов в скобках.\n", "\n", - "**syntax error:**\n", - "An error in a program that makes it impossible to parse -- and therefore impossible to run.\n", + "** Синтаксис ошибка: **\n", + "Ошибка в программе, которая делает невозможным проанализировать - и, следовательно, невозможно запустить.\n", "\n", - "**string:**\n", - " A type that represents sequences of characters.\n", + "**нить:**\n", + "Тип, который представляет последовательности символов.\n", "\n", - "**concatenation:**\n", - "Joining two strings end-to-end.\n", + "** Согласование: **\n", + "Присоединяясь к двум струнам.\n", "\n", - "**type:**\n", - "A category of values.\n", - "The types we have seen so far are integers (type `int`), floating-point numbers (type ` float`), and strings (type `str`).\n", + "**тип:**\n", + "Категория ценностей.\n", + "Типы, которые мы видели до сих пор, являются целыми числами (тип `int`), числа с плавающей точкой (тип` float`) и строки (тип `str`).\n", "\n", - "**operand:**\n", - "One of the values on which an operator operates.\n", + "**операнд:**\n", + "Одно из значений, на которых работает оператор.\n", "\n", "**natural language:**\n", "Any of the languages that people speak that evolved naturally.\n", From e8a32323fc82096c3345fed7cb3965bdc467e2d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:24:09 +0300 Subject: [PATCH 30/44] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 39a0d8b..2d18f4e 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # Think Python, 3rd edition -Jupyter notebooks and other material for the 3rd edition of *Think Python: How to Think Like a Computer Scientist* +Записные книжки Jupyter и другие материалы для 3-го издания *Think Python: Как мыслить как специалист по информатике* by Allen B. Downey -You can order print and electronic versions of *Think Python 3e* from +Вы можете заказать печатную и электронную версии *Think Python 3e* у нас [Bookshop.org](https://bookshop.org/a/98697/9781098155438) and [Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325). -The home page for the book is at [Green Tea Press](http://thinkpython.com). +Домашняя страница книги находится по адресу [Green Tea Press](http://thinkpython.com). From 4660bf1b2c4afe20c11c56ae6deebd95c418d311 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:26:31 +0300 Subject: [PATCH 31/44] Translate lines 1001-1307 of chapter 1 --- chapters/chap01.ipynb | 156 +++++++++++++++++++++--------------------- 1 file changed, 78 insertions(+), 78 deletions(-) diff --git a/chapters/chap01.ipynb b/chapters/chap01.ipynb index 44525cb..48f5317 100644 --- a/chapters/chap01.ipynb +++ b/chapters/chap01.ipynb @@ -999,18 +999,18 @@ "**операнд:**\n", "Одно из значений, на которых работает оператор.\n", "\n", - "**natural language:**\n", - "Any of the languages that people speak that evolved naturally.\n", + "**естественный язык:**\n", + "Любой из языков, на которых говорят люди и которые возникли естественным образом.\n", "\n", - "**formal language:**\n", - "Any of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs.\n", - "All programming languages are formal languages.\n", + "**формальный язык:**\n", + "Любой из языков, созданных людьми для определённых целей, например для представления математических идей или компьютерных программ.\n", + "Все языки программирования являются формальными.\n", "\n", - "**bug:**\n", - "An error in a program.\n", + "**ошибка:**\n", + "Ошибка в программе.\n", "\n", - "**debugging:**\n", - "The process of finding and correcting errors." + "**отладка:**\n", + "Процесс поиска и исправления ошибок." ] }, { @@ -1018,7 +1018,7 @@ "id": "ed4ec01b", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -1030,8 +1030,8 @@ }, "outputs": [], "source": [ - "# This cell tells Jupyter to provide detailed debugging information\n", - "# when a runtime error occurs. Run it before working on the exercises.\n", + "# Эта ячейка сообщает Jupyter выводить подробную информацию при отладке\n", + "# когда возникает ошибка во время выполнения. Запустите её перед выполнением упражнений.\n", "\n", "%xmode Verbose" ] @@ -1041,15 +1041,15 @@ "id": "23adf208", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", - "\n", - "As you work through this book, there are several ways you can use a virtual assistant or chatbot to help you learn.\n", - "\n", - "* If you want to learn more about a topic in the chapter, or anything is unclear, you can ask for an explanation.\n", - "\n", - "* If you are having a hard time with any of the exercises, you can ask for help.\n", - "\n", - "In each chapter, I'll suggest exercises you can do with a virtual assistant, but I encourage you to try things on your own and see what works for you." + "### Спросите виртуального помощника\n", + "\n", + "Пока вы работаете с этой книгой, есть несколько способов использовать виртуального помощника или чат-бота, чтобы учиться.\n", + "\n", + "* Если вы хотите узнать больше о теме главы или что-то непонятно, можно попросить объяснение.\n", + "\n", + "* Если у вас возникают трудности с каким-либо упражнением, попросите помощи.\n", + "\n", + "В каждой главе я предложу задания, которые можно выполнить с помощью виртуального помощника, но я призываю вас экспериментировать и находить то, что подходит именно вам." ] }, { @@ -1057,15 +1057,15 @@ "id": "ebf1a451", "metadata": {}, "source": [ - "Here are some topics you could ask a virtual assistant about:\n", - "\n", - "* Earlier I mentioned bitwise operators but I didn't explain why the value of `7 ^ 2` is 5. Try asking \"What are the bitwise operators in Python?\" or \"What is the value of `7 XOR 2`?\"\n", - "\n", - "* I also mentioned the order of operations. For more details, ask \"What is the order of operations in Python?\"\n", - "\n", - "* The `round` function, which we used to round a floating-point number to the nearest integer, can take a second argument. Try asking \"What are the arguments of the round function?\" or \"How do I round pi off to three decimal places?\"\n", - "\n", - "* There's one more arithmetic operator I didn't mention; try asking \"What is the modulus operator in Python?\"" + "Вот несколько тем, о которых вы можете спросить виртуального помощника:\n", + "\n", + "* Ранее я упомянул побитовые операторы, но не объяснил, почему значение `7 ^ 2` равно 5. Попробуйте спросить \"Какие побитовые операторы есть в Python?\" или \"Чему равно `7 XOR 2`?\"\n", + "\n", + "* Я также упомянул порядок выполнения операций. Чтобы узнать подробнее, спросите \"Каков порядок операций в Python?\"\n", + "\n", + "* Функция `round`, которой мы округляли число с плавающей точкой до ближайшего целого, может принимать второй аргумент. Спросите \"Какие аргументы у функции round?\" или \"Как округлить π до трёх знаков после запятой?\"\n", + "\n", + "* Есть ещё один арифметический оператор, о котором я не говорил; спросите \"Что такое оператор остатка от деления в Python?\"" ] }, { @@ -1073,9 +1073,9 @@ "id": "9be3e1c7", "metadata": {}, "source": [ - "Most virtual assistants know about Python, so they answer questions like this pretty reliably.\n", - "But remember that these tools make mistakes.\n", - "If you get code from a chatbot, test it!" + "Большинство виртуальных помощников знакомы с Python, поэтому на такие вопросы они отвечают довольно уверенно.\n", + "Но помните, что эти инструменты могут ошибаться.\n", + "Если получаете код от чат-бота, обязательно проверяйте его!" ] }, { @@ -1083,11 +1083,11 @@ "id": "03c1ef93", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "You might wonder what `round` does if a number ends in `0.5`.\n", - "The answer is that it sometimes rounds up and sometimes rounds down.\n", - "Try these examples and see if you can figure out what rule it follows." + "### Упражнение\n", + "\n", + "Возможно, вы задаётесь вопросом, что делает `round`, если число оканчивается на `0.5`.\n", + "Ответ в том, что иногда оно округляет вверх, а иногда вниз.\n", + "Попробуйте эти примеры и посмотрите, сможете ли выяснить правило." ] }, { @@ -1115,7 +1115,7 @@ "id": "dd2f890e", "metadata": {}, "source": [ - "If you are curious, ask a virtual assistant, \"If a number ends in 0.5, does Python round up or down?\"" + "Если вам интересно, спросите у виртуального помощника: \"Если число оканчивается на 0.5, Python округляет вверх или вниз?\"" ] }, { @@ -1123,17 +1123,17 @@ "id": "2cd03bcb", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "When you learn about a new feature, you should try it out and make mistakes on purpose.\n", - "That way, you learn the error messages, and when you see them again, you will know what they mean.\n", - "It is better to make mistakes now and deliberately than later and accidentally.\n", - "\n", - "1. You can use a minus sign to make a negative number like `-2`. What happens if you put a plus sign before a number? What about `2++2`?\n", - "\n", - "2. What happens if you have two values with no operator between them, like `4 2`?\n", - "\n", - "3. If you call a function like `round(42.5)`, what happens if you leave out one or both parentheses?" + "### Упражнение\n", + "\n", + "Когда вы знакомитесь с новой возможностью, стоит попробовать её и сознательно сделать пару ошибок.\n", + "Так вы увидите сообщения об ошибках и в дальнейшем будете понимать их смысл.\n", + "Лучше ошибиться сейчас специально, чем потом случайно.\n", + "\n", + "1. С помощью минуса можно получить отрицательное число, например `-2`. Что произойдёт, если поставить плюс перед числом? А как насчёт `2++2`?\n", + "\n", + "2. Что будет, если указать два значения без оператора между ними, как в `4 2`?\n", + "\n", + "3. Если вызвать функцию вроде `round(42.5)`, что произойдёт, если опустить одну или обе скобки?" ] }, { @@ -1141,11 +1141,11 @@ "id": "1fb0adfe", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "Recall that every expression has a value, every value has a type, and we can use the `type` function to find the type of any value.\n", - "\n", - "What is the type of the value of the following expressions? Make your best guess for each one, and then use `type` to find out.\n", + "### Упражнение\n", + "\n", + "Напомню, что каждое выражение имеет значение, каждое значение имеет тип, и мы можем воспользоваться функцией `type`, чтобы узнать тип любого значения.\n", + "\n", + "Какого типа значения получаются в следующих выражениях? Сначала предположите сами, а потом проверьте через `type`.\n", "\n", "* `765`\n", "\n", @@ -1169,22 +1169,22 @@ "id": "23762eec", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "The following questions give you a chance to practice writing arithmetic expressions.\n", - "\n", - "1. How many seconds are there in 42 minutes 42 seconds?\n", - "\n", - "2. How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile.\n", - "\n", - "3. If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace in seconds per mile? \n", - " \n", - "4. What is your average pace in minutes and seconds per mile?\n", - "\n", - "5. What is your average speed in miles per hour?\n", - "\n", - "If you already know about variables, you can use them for this exercise.\n", - "If you don't, you can do the exercise without them -- and then we'll see them in the next chapter." + "### Упражнение\n", + "\n", + "Следующие вопросы дадут вам возможность потренироваться в записи арифметических выражений.\n", + "\n", + "1. Сколько секунд содержится в 42 минутах 42 секундах?\n", + "\n", + "2. Сколько миль в 10 километрах? Подсказка: в одной миле 1.61 километра.\n", + "\n", + "3. Если вы пробежали 10 километров за 42 минуты 42 секунды, каков ваш средний темп в секундах на милю? \n", + " \n", + "4. Каков ваш средний темп в минутах и секундах на милю?\n", + "\n", + "5. Какова ваша средняя скорость в милях в час?\n", + "\n", + "Если вы уже знаете о переменных, можете использовать их в этом упражнении.\n", + "Если нет, выполните задание без них — мы рассмотрим их в следующей главе." ] }, { @@ -1272,13 +1272,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", - "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", - "\n", - "Code license: [MIT License](https://mit-license.org/)\n", - "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "\n", + "© 2024 [Allen B. Downey](https://allendowney.com)\n", + "\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", + "\n", + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], From 4e9d96560057da5ed88161636092eff45c0f38f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:42:51 +0300 Subject: [PATCH 32/44] =?UTF-8?q?=D0=94=D0=BE=D0=BF=D0=BE=D0=BB=D0=BD?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B2=D0=BE=D0=B4=20?= =?UTF-8?q?=D0=B3=D0=BB=D0=B0=D0=B2=D1=8B=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- chapters/chap02.ipynb | 308 ++++++++---------------------------------- 1 file changed, 59 insertions(+), 249 deletions(-) diff --git a/chapters/chap02.ipynb b/chapters/chap02.ipynb index fb2369f..c8f657d 100644 --- a/chapters/chap02.ipynb +++ b/chapters/chap02.ipynb @@ -5,9 +5,7 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать печатные и электронные версии *Think Python 3e* от\n[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, { @@ -41,12 +39,7 @@ "id": "d0286422", "metadata": {}, "source": [ - "# Variables and Statements\n", - "\n", - "In the previous chapter, we used operators to write expressions that perform arithmetic computations.\n", - "\n", - "In this chapter, you'll learn about variables and statements, the `import` statement, and the `print` function.\n", - "And I'll introduce more of the vocabulary we use to talk about programs, including \"argument\" and \"module\".\n" + "# Переменные и операторы\n\nВ предыдущей главе мы использовали операторы для написания выражений, которые выполняют арифметические вычисления.\n\nВ этой главе вы узнаете о переменных и инструкциях, инструкции `import` и функции `print`.\nИ я представлю больше лексики, которую мы используем для разговора о программах, включая «аргумент» и «модуль».\n" ] }, { @@ -54,10 +47,7 @@ "id": "4ac44f0c", "metadata": {}, "source": [ - "## Variables\n", - "\n", - "A **variable** is a name that refers to a value.\n", - "To create a variable, we can write a **assignment statement** like this." + "## Переменные\n\n**переменная** - это имя, которое ссылается на значение.\nЧтобы создать переменную, мы можем написать ** инструкцию присваивания** вот так." ] }, { @@ -75,9 +65,7 @@ "id": "52f187f1", "metadata": {}, "source": [ - "An assignment statement has three parts: the name of the variable on the left, the equals operator, `=`, and an expression on the right.\n", - "In this example, the expression is an integer.\n", - "In the following example, the expression is a floating-point number." + "Оператор присваивания состоит из трех частей: имя переменной слева, оператор равно, `=` и выражение справа.\nВ этом примере выражение представляет собой целое число.\nВ следующем примере выражение является числом с плавающей запятой." ] }, { @@ -95,7 +83,7 @@ "id": "3e27e65c", "metadata": {}, "source": [ - "And in the following example, the expression is a string." + "И в следующем примере выражение является строкой." ] }, { @@ -113,10 +101,7 @@ "id": "cb5916ea", "metadata": {}, "source": [ - "When you run an assignment statement, there is no output.\n", - "Python creates the variable and gives it a value, but the assignment statement has no visible effect.\n", - "However, after creating a variable, you can use it as an expression.\n", - "So we can display the value of `message` like this:" + "При запуске инструкции присваивания выходные данные отсутствуют.\nPython создает переменную и присваивает ей значение, но инструкция присваивания не имеет видимого эффекта.\nОднако после создания переменной вы можете использовать ее в качестве выражения.\nТаким образом, мы можем отобразить значение «message» следующим образом:" ] }, { @@ -134,7 +119,7 @@ "id": "e3fd81de", "metadata": {}, "source": [ - "You can also use a variable as part of an expression with arithmetic operators." + "Вы также можете использовать переменную как часть выражения с арифметическими операторами." ] }, { @@ -162,7 +147,7 @@ "id": "97396e7d", "metadata": {}, "source": [ - "And you can use a variable when you call a function." + "И вы можете использовать переменную при вызове функции." ] }, { @@ -190,10 +175,7 @@ "id": "397d9da3", "metadata": {}, "source": [ - "## State diagrams\n", - "\n", - "A common way to represent variables on paper is to write the name with\n", - "an arrow pointing to its value. " + "## Диаграммы состояний\n\nРаспространенный способ представления переменных на бумаге - написать имя с\nстрелка, указывающая на его значение." ] }, { @@ -239,8 +221,7 @@ "id": "6f40da93", "metadata": {}, "source": [ - "This kind of figure is called a **state diagram** because it shows what state each of the variables is in (think of it as the variable's state of mind).\n", - "We'll use state diagrams throughout the book to represent a model of how Python stores variables and their values." + "Такая фигура называется * * диаграммой состояния **, потому что она показывает, в каком состоянии находится каждая из переменных (думайте об этом как о состоянии ума переменной).\nМы будем использовать диаграммы состояний по всей книге, чтобы представить модель того, как Python хранит переменные и их значения." ] }, { @@ -248,16 +229,7 @@ "id": "ba252c85", "metadata": {}, "source": [ - "## Variable names\n", - "\n", - "Variable names can be as long as you like. They can contain both letters and numbers, but they can't begin with a number. \n", - "It is legal to use uppercase letters, but it is conventional to use only lower case for\n", - "variable names.\n", - "\n", - "The only punctuation that can appear in a variable name is the underscore character, `_`. It is often used in names with multiple words, such as `your_name` or `airspeed_of_unladen_swallow`.\n", - "\n", - "If you give a variable an illegal name, you get a syntax error.\n", - "The name `million!` is illegal because it contains punctuation." + "## Имена переменных\n\nИмена переменных могут быть любой длины. Они могут содержать буквы и цифры, но не могут начинаться с цифры. Допускается использование заглавных букв, но принято писать имена переменных в нижнем регистре.\n\nЕдинственный знак пунктуации, который может встречаться в имени переменной, — символ подчеркивания `_`. Его часто применяют в именах из нескольких слов, например `your_name` или `airspeed_of_unladen_swallow`.\n\nЕсли вы дадите переменной недопустимое имя, Python сообщит о синтаксической ошибке. Имя `million!` недопустимо, потому что содержит знак пунктуации." ] }, { @@ -279,7 +251,7 @@ "id": "a1cefe3e", "metadata": {}, "source": [ - "`76trombones` is illegal because it starts with a number." + "«76 тромбонов» является незаконным, потому что начинается с цифры." ] }, { @@ -301,7 +273,7 @@ "id": "94aa7e60", "metadata": {}, "source": [ - "`class` is also illegal, but it might not be obvious why." + "«класс» также является незаконным, но может быть неясно, почему." ] }, { @@ -323,10 +295,7 @@ "id": "784cfb5c", "metadata": {}, "source": [ - "It turns out that `class` is a **keyword**, which is a special word used to specify the structure of a program.\n", - "Keywords can't be used as variable names.\n", - "\n", - "Here's a complete list of Python's keywords:" + "Получается, что «класс» - это **ключевое слово**, которое является специальным словом, используемым для указания структуры программы.\nКлючевые слова не могут использоваться в качестве имен переменных.\n\nВот полный список ключевых слов Python:" ] }, { @@ -334,15 +303,7 @@ "id": "127c07e8", "metadata": {}, "source": [ - "```\n", - "False await else import pass\n", - "None break except in raise\n", - "True class finally is return\n", - "and continue for lambda try\n", - "as def from nonlocal while\n", - "assert del global not with\n", - "async elif if or yield\n", - "```" + "```\nЛожное ожидание другой импортный пропуск\nНет перерыва, кроме повышения\nИстинный класс, наконец, - это возврат\nи продолжите лямбда-попытку\nкак def от нелокального в то время как\nassert del global не с\nasync elif if или yield\n```" ] }, { @@ -364,9 +325,7 @@ "id": "6f14d301", "metadata": {}, "source": [ - "You don't have to memorize this list. In most development environments,\n", - "keywords are displayed in a different color; if you try to use one as a\n", - "variable name, you'll know." + "Вам не нужно запоминать этот список. В большинстве сред разработки\nключевые слова отображаются другим цветом; если вы попытаетесь использовать их в качестве\nимя переменной, вы узнаете." ] }, { @@ -374,10 +333,7 @@ "id": "c954a3b0", "metadata": {}, "source": [ - "## The import statement\n", - "\n", - "In order to use some Python features, you have to **import** them.\n", - "For example, the following statement imports the `math` module." + "## Отчет об импорте\n\nЧтобы использовать некоторые функции Python, вы должны **импортировать** их.\nНапример, следующая инструкция импортирует модуль «математика»." ] }, { @@ -395,9 +351,7 @@ "id": "ea4f75ec", "metadata": {}, "source": [ - "A **module** is a collection of variables and functions.\n", - "The math module provides a variable called `pi` that contains the value of the mathematical constant denoted $\\pi$.\n", - "We can display its value like this." + "**модуль** представляет собой набор переменных и функций.\nМатематический модуль предоставляет переменную под названием `pi`, которая содержит значение математической константы, обозначаемой $\\pi$.\nМы можем отобразить его значение таким образом." ] }, { @@ -415,10 +369,7 @@ "id": "c96106e4", "metadata": {}, "source": [ - "To use a variable in a module, you have to use the **dot operator** (`.`) between the name of the module and the name of the variable.\n", - "\n", - "The math module also contains functions.\n", - "For example, `sqrt` computes square roots." + "Чтобы использовать переменную в модуле, необходимо использовать **точечный оператор** (`.`) между именем модуля и именем переменной.\n\nМатематический модуль также содержит функции.\nНапример, `sqrt` вычисляет квадратные корни." ] }, { @@ -436,7 +387,7 @@ "id": "185e94a3", "metadata": {}, "source": [ - "And `pow` raises one number to the power of a second number." + "И «POW» повышает одно число до степени второго числа." ] }, { @@ -454,8 +405,7 @@ "id": "5df25a9a", "metadata": {}, "source": [ - "At this point we've seen two ways to raise a number to a power: we can use the `math.pow` function or the exponentiation operator, `**`.\n", - "Either one is fine, but the operator is used more often than the function." + "На данный момент мы видели два способа возведения числа в степень: мы можем использовать функцию `math.pow' или оператор возведения в степень `**`.\nЛюбой из них хорош, но оператор используется чаще, чем функция." ] }, { @@ -463,13 +413,7 @@ "id": "6538f22b", "metadata": {}, "source": [ - "## Expressions and statements\n", - "\n", - "So far, we've seen a few kinds of expressions.\n", - "An expression can be a single value, like an integer, floating-point number, or string.\n", - "It can also be a collection of values and operators.\n", - "And it can include variable names and function calls.\n", - "Here's an expression that includes several of these elements." + "## Выражения и утверждения\n\nДо сих пор мы видели несколько видов выражений.\nВыражение может быть одним значением, например целым числом, числом с плавающей запятой или строкой.\nЭто также может быть коллекция значений и операторов.\nИ он может включать имена переменных и вызовы функций.\nВот выражение, которое включает в себя несколько из этих элементов." ] }, { @@ -487,9 +431,7 @@ "id": "000dd2ba", "metadata": {}, "source": [ - "We have also seen a few kind of statements.\n", - "A **statement** is a unit of code that has an effect, but no value.\n", - "For example, an assignment statement creates a variable and gives it a value, but the statement itself has no value." + "Мы также видели несколько видов заявлений.\n**инструкция** - это единица кода, которая имеет эффект, но не имеет значения.\nНапример, инструкция присваивания создает переменную и присваивает ей значение, но сама инструкция не имеет значения." ] }, { @@ -507,7 +449,7 @@ "id": "cff0414b", "metadata": {}, "source": [ - "Similarly, an import statement has an effect -- it imports a module so we can use the variables and functions it contains -- but it has no visible effect." + "Аналогичным образом, инструкция импорта имеет эффект - она импортирует модуль, чтобы мы могли использовать содержащиеся в нем переменные и функции - но она не имеет видимого эффекта." ] }, { @@ -525,8 +467,7 @@ "id": "2aeb1000", "metadata": {}, "source": [ - "Computing the value of an expression is called **evaluation**.\n", - "Running a statement is called **execution**." + "Вычисление значения выражения называется * * вычислением**.\nВыполнение оператора называется **execution**." ] }, { @@ -534,9 +475,7 @@ "id": "f61601e4", "metadata": {}, "source": [ - "## The print function\n", - "\n", - "When you evaluate an expression, the result is displayed." + "## Функция печати\n\nКогда вы оцениваете выражение, отображается результат." ] }, { @@ -554,7 +493,7 @@ "id": "efacf0fa", "metadata": {}, "source": [ - "But if you evaluate more than one expression, only the value of the last one is displayed." + "Но если вы вычисляете более одного выражения, отображается только значение последнего." ] }, { @@ -573,7 +512,7 @@ "id": "cf2b991d", "metadata": {}, "source": [ - "To display more than one value, you can use the `print` function." + "Чтобы отобразить более одного значения, вы можете использовать функцию «печать»." ] }, { @@ -592,7 +531,7 @@ "id": "29af1f89", "metadata": {}, "source": [ - "It also works with floating-point numbers and strings." + "Он также работает с числами и строками с плавающей запятой." ] }, { @@ -611,7 +550,7 @@ "id": "8b4d7f4a", "metadata": {}, "source": [ - "You can also use a sequence of expressions separated by commas." + "Вы также можете использовать последовательность выражений, разделенных запятыми." ] }, { @@ -629,7 +568,7 @@ "id": "af447ec4", "metadata": {}, "source": [ - "Notice that the `print` function puts a space between the values." + "Обратите внимание, что функция `print` помещает пробел между значениями." ] }, { @@ -637,12 +576,7 @@ "id": "7c73a2fa", "metadata": {}, "source": [ - "## Arguments\n", - "\n", - "When you call a function, the expression in parenthesis is called an **argument**.\n", - "Normally I would explain why, but in this case the technical meaning of a term has almost nothing to do with the common meaning of the word, so I won't even try.\n", - "\n", - "Some of the functions we've seen so far take only one argument, like `int`." + "## Аргументы\n\nПри вызове функции выражение в скобках называется * * аргументом**.\nОбычно я объясняю, почему, но в этом случае техническое значение термина почти не имеет ничего общего с общим значением этого слова, поэтому я даже не буду пытаться.\n\nНекоторые из функций, которые мы видели до сих пор, принимают только один аргумент, например, «int»." ] }, { @@ -660,7 +594,7 @@ "id": "c4ad4f2c", "metadata": {}, "source": [ - "Some take two, like `math.pow`." + "Некоторые берут два, например «math.pow»." ] }, { @@ -678,8 +612,7 @@ "id": "17293749", "metadata": {}, "source": [ - "Some can take additional arguments that are optional. \n", - "For example, `int` can take a second argument that specifies the base of the number." + "Некоторые могут принимать дополнительные аргументы, которые являются необязательными. \nНапример, `int` может принимать второй аргумент, указывающий основание числа." ] }, { @@ -697,9 +630,7 @@ "id": "c95589a1", "metadata": {}, "source": [ - "The sequence of digits `101` in base 2 represents the number 5 in base 10.\n", - "\n", - "`round` also takes an optional second argument, which is the number of decimal places to round off to." + "Последовательность цифр «101» в основании 2 представляет собой число 5 в основании 10.\n\n`round` также принимает необязательный второй аргумент, который является числом знаков после запятой, до которого нужно округлить." ] }, { @@ -717,7 +648,7 @@ "id": "21e4a448", "metadata": {}, "source": [ - "Some functions can take any number of arguments, like `print`." + "Некоторые функции могут принимать любое количество аргументов, например `print`." ] }, { @@ -735,7 +666,7 @@ "id": "667cff14", "metadata": {}, "source": [ - "If you call a function and provide too many arguments, that's a `TypeError`." + "Если вы вызываете функцию и предоставляете слишком много аргументов, это `TypeError`." ] }, { @@ -757,7 +688,7 @@ "id": "5103368e", "metadata": {}, "source": [ - "If you provide too few arguments, that's also a `TypeError`." + "Если вы предоставляете слишком мало аргументов, это также `TypeError`." ] }, { @@ -779,7 +710,7 @@ "id": "5333c416", "metadata": {}, "source": [ - "And if you provide an argument with a type the function can't handle, that's a `TypeError`, too." + "И если вы предоставляете аргумент с типом, который функция не может обработать, это тоже `TypeError`." ] }, { @@ -801,7 +732,7 @@ "id": "548828af", "metadata": {}, "source": [ - "This kind of checking can be annoying when you are getting started, but it helps you detect and correct errors." + "Такая проверка может раздражать, когда вы начинаете, но она помогает обнаруживать и исправлять ошибки." ] }, { @@ -809,13 +740,7 @@ "id": "be2b6a9b", "metadata": {}, "source": [ - "## Comments\n", - "\n", - "As programs get bigger and more complicated, they get more difficult to read.\n", - "Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing and why.\n", - "\n", - "For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. \n", - "These notes are called **comments**, and they start with the `#` symbol." + "## Комментарии\n\nПо мере того, как программы становятся больше и сложнее, их становится труднее читать.\nФормальные языки плотные, и часто бывает трудно взглянуть на кусок кода и понять, что он делает и почему.\n\nПо этой причине рекомендуется добавлять заметки к своим программам, чтобы объяснить на естественном языке, что делает программа. \nЭти заметки называются * * комментариями * * и начинаются с символа #." ] }, { @@ -834,8 +759,7 @@ "id": "519c83a9", "metadata": {}, "source": [ - "In this case, the comment appears on a line by itself. You can also put\n", - "comments at the end of a line:" + "В этом случае комментарий появляется на строке сам по себе. Вы также можете поставить\nкомментарии в конце строки:" ] }, { @@ -853,13 +777,7 @@ "id": "87c8d10c", "metadata": {}, "source": [ - "Everything from the `#` to the end of the line is ignored---it has no\n", - "effect on the execution of the program.\n", - "\n", - "Comments are most useful when they document non-obvious features of the code.\n", - "It is reasonable to assume that the reader can figure out *what* the code does; it is more useful to explain *why*.\n", - "\n", - "This comment is redundant with the code and useless:" + "Все, от «#» до конца строки, игнорируется --- у него нет\nвлияние на выполнение программы.\n\nКомментарии наиболее полезны, когда они документируют неочевидные особенности кода.\nРазумно предположить, что читатель может понять *что* делает код; полезнее объяснить *почему*.\n\nЭтот комментарий лишний с кодом и бесполезный:" ] }, { @@ -877,7 +795,7 @@ "id": "eb83b14a", "metadata": {}, "source": [ - "This comment contains useful information that is not in the code:" + "Этот комментарий содержит полезную информацию, которой нет в коде:" ] }, { @@ -895,8 +813,7 @@ "id": "6cd60d4f", "metadata": {}, "source": [ - "Good variable names can reduce the need for comments, but long names can\n", - "make complex expressions hard to read, so there is a tradeoff." + "Хорошие имена переменных могут уменьшить потребность в комментариях, но длинные имена могут\nсделать сложные выражения трудными для чтения, поэтому есть компромисс." ] }, { @@ -904,16 +821,7 @@ "id": "7d61e416", "metadata": {}, "source": [ - "## Debugging\n", - "\n", - "Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors.\n", - "It is useful to distinguish between them in order to track them down more quickly.\n", - "\n", - "* **Syntax error**: \"Syntax\" refers to the structure of a program and the rules about that structure. If there is a syntax error anywhere in your program, Python does not run the program. It displays an error message immediately.\n", - "\n", - "* **Runtime error**: If there are no syntax errors in your program, it can start running. But if something goes wrong, Python displays an error message and stops. This type of error is called a runtime error. It is also called an **exception** because it indicates that something exceptional has happened.\n", - "\n", - "* **Semantic error**: The third type of error is \"semantic\", which means related to meaning. If there is a semantic error in your program, it runs without generating error messages, but it does not do what you intended. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing." + "## Отладка\n\nВ программе могут возникать три вида ошибок: синтаксические, ошибки времени выполнения и семантические ошибки. Полезно различать их, чтобы быстрее находить причину проблемы.\n\n* **Синтаксическая ошибка**: «Синтаксис» относится к структуре программы и правилам этой структуры. Если где‑то в программе есть синтаксическая ошибка, Python не запустит её и сразу покажет сообщение об ошибке.\n\n* **Ошибка времени выполнения**: если синтаксических ошибок нет, программа может начать выполняться. Но если что‑то пойдет не так, Python выведет сообщение об ошибке и остановится. Такой тип ошибок называется ошибкой времени выполнения, или **исключением**, потому что говорит о какой‑то необычной ситуации.\n\n* **Семантическая ошибка**: третий тип ошибок — «семантические», то есть связанные со смыслом. Если в программе есть семантическая ошибка, она выполняется без сообщений об ошибке, но делает не то, что вы ожидали. Найти такие ошибки бывает сложно: нужно проанализировать результаты работы программы и попытаться понять, что происходит." ] }, { @@ -921,7 +829,7 @@ "id": "6cd52721", "metadata": {}, "source": [ - "As we've seen, an illegal variable name is a syntax error." + "Как мы видели, недопустимое имя переменной является синтаксической ошибкой." ] }, { @@ -943,7 +851,7 @@ "id": "b8971d33", "metadata": {}, "source": [ - "If you use an operator with a type it doesn't support, that's a runtime error. " + "Если вы используете оператор с типом, который он не поддерживает, это ошибка времени выполнения." ] }, { @@ -965,8 +873,7 @@ "id": "e51fa6e2", "metadata": {}, "source": [ - "Finally, here's an example of a semantic error.\n", - "Suppose we want to compute the average of `1` and `3`, but we forget about the order of operations and write this:" + "Наконец, вот пример семантической ошибки.\nПредположим, мы хотим вычислить среднее значение `1` и `3`, но забываем о порядке операций и пишем так:" ] }, { @@ -984,9 +891,7 @@ "id": "0828afc0", "metadata": {}, "source": [ - "When this expression is evaluated, it does not produce an error message, so there is no syntax error or runtime error.\n", - "But the result is not the average of `1` and `3`, so the program is not correct.\n", - "This is a semantic error because the program runs but it doesn't do what's intended." + "Когда это выражение вычисляется, оно не выдает сообщение об ошибке, поэтому нет синтаксической ошибки или ошибки во время выполнения.\nНо результат не является средним из «1» и «3», поэтому программа неверна.\nЭто семантическая ошибка, потому что программа работает, но не делает то, что задумано." ] }, { @@ -994,52 +899,7 @@ "id": "07396f3d", "metadata": {}, "source": [ - "## Glossary\n", - "\n", - "**variable:**\n", - "A name that refers to a value.\n", - "\n", - "**assignment statement:**\n", - "A statement that assigns a value to a variable.\n", - "\n", - "**state diagram:**\n", - "A graphical representation of a set of variables and the values they refer to.\n", - "\n", - "**keyword:**\n", - "A special word used to specify the structure of a program.\n", - "\n", - "**import statement:**\n", - "A statement that reads a module file so we can use the variables and functions it contains.\n", - "\n", - "**module:**\n", - "A file that contains Python code, including function definitions and sometimes other statements.\n", - "\n", - "**dot operator:**\n", - "The operator, `.`, used to access a function in another module by specifying the module name followed by a dot and the function name.\n", - "\n", - "**evaluate:**\n", - "Perform the operations in an expression in order to compute a value.\n", - "\n", - "**statement:**\n", - "One or more lines of code that represent a command or action.\n", - "\n", - "**execute:**\n", - "Run a statement and do what it says.\n", - "\n", - "**argument:**\n", - "A value provided to a function when the function is called.\n", - "\n", - "**comment:**\n", - "Text included in a program that provides information about the program but has no effect on its execution.\n", - "\n", - "**runtime error:**\n", - "An error that causes a program to display an error message and exit.\n", - "\n", - "**exception:**\n", - "An error that is detected while the program is running.\n", - "\n", - "**semantic error:**\n", - "An error that causes a program to do the wrong thing, but not to display an error message." + "## Глоссарий\n\n**переменная:**\nИмя, которое ссылается на значение.\n\n**оператор присваивания:**\nИнструкция, которая присваивает переменной значение.\n\n**диаграмма состояния:**\nГрафическое представление набора переменных и значений, на которые они указывают.\n\n**ключевое слово:**\nСпециальное слово, которое задает структуру программы.\n\n**инструкция import:**\nИнструкция, читающая файл модуля, чтобы мы могли использовать содержащиеся в нем переменные и функции.\n\n**модуль:**\nФайл, содержащий код на Python, включая определения функций и иногда другие инструкции.\n\n**оператор точки:**\nОператор `.`, используемый для доступа к функции в другом модуле: указывается имя модуля, точка и имя функции.\n\n**вычислить:**\nВыполнить операции в выражении, чтобы получить значение.\n\n**инструкция:**\nОдна или несколько строк кода, представляющих команду или действие.\n\n**выполнить:**\nЗапустить инструкцию и сделать то, что в ней сказано.\n\n**аргумент:**\nЗначение, передаваемое функции при её вызове.\n\n**комментарий:**\nТекст в программе, поясняющий её работу, но не влияющий на выполнение.\n\n**ошибка времени выполнения:**\nОшибка, из-за которой программа выводит сообщение об ошибке и завершается.\n\n**исключение:**\nОшибка, обнаруженная во время работы программы.\n\n**семантическая ошибка:**\nОшибка, из-за которой программа делает не то, что нужно, но не выводит сообщение об ошибке." ] }, { @@ -1047,7 +907,7 @@ "id": "70ee273d", "metadata": {}, "source": [ - "## Exercises" + "Упражнения" ] }, { @@ -1070,20 +930,7 @@ "id": "7256a9b2", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", - "\n", - "Again, I encourage you to use a virtual assistant to learn more about any of the topics in this chapter.\n", - "\n", - "If you are curious about any of keywords I listed, you could ask \"Why is class a keyword?\" or \"Why can't variable names be keywords?\"\n", - "\n", - "You might have noticed that `int`, `float`, and `str` are not Python keywords.\n", - "They are variables that represent types, and they can be used as functions.\n", - "So it is *legal* to have a variable or function with one of those names, but it is strongly discouraged. Ask an assistant \"Why is it bad to use int, float, and str as variable names?\"\n", - "\n", - "Also ask, \"What are the built-in functions in Python?\"\n", - "If you are curious about any of them, ask for more information.\n", - "\n", - "In this chapter we imported the `math` module and used some of the variable and functions it provides. Ask an assistant, \"What variables and functions are in the math module?\" and \"Other than math, what modules are considered core Python?\"" + "### Обратитесь к виртуальному ассистенту\n\nСнова призываю вас использовать виртуального помощника, чтобы узнать больше о темах этой главы.\n\nЕсли вам интересно значение какого‑либо из упомянутых мной ключевых слов, спросите: «Почему `class` является ключевым словом?» или «Почему имена переменных не могут быть ключевыми словами?».\n\nВы могли заметить, что `int`, `float` и `str` не являются ключевыми словами Python. Это переменные, представляющие типы, и их можно использовать как функции. Поэтому технически допустимо создать переменную или функцию с одним из этих имён, но настоятельно не рекомендуется. Спросите у ассистента: «Почему плохо называть переменные int, float и str?».\n\nСпросите также: «Какие функции встроены в Python?». Если какая‑то из них заинтересует вас, уточните детали.\n\nВ этой главе мы импортировали модуль `math` и использовали некоторые переменные и функции из него. Спросите у ассистента: «Какие переменные и функции есть в модуле math?» и «Какие ещё модули, помимо math, относятся к стандартным в Python?»." ] }, { @@ -1091,20 +938,7 @@ "id": "f92afde0", "metadata": {}, "source": [ - "### Exercise\n", - "\n", - "Repeating my advice from the previous chapter, whenever you learn a new feature, you should make errors on purpose to see what goes wrong.\n", - "\n", - "- We've seen that `n = 17` is legal. What about `17 = n`?\n", - "\n", - "- How about `x = y = 1`?\n", - "\n", - "- In some languages every statement ends with a semi-colon (`;`). What\n", - " happens if you put a semi-colon at the end of a Python statement?\n", - "\n", - "- What if you put a period at the end of a statement?\n", - "\n", - "- What happens if you spell the name of a module wrong and try to import `maath`?" + "### Упражнение\n\nПовторю совет из предыдущей главы: когда изучаете новую конструкцию, специально допускайте ошибки, чтобы увидеть, что пойдёт не так.\n\n- Мы видели, что `n = 17` допустимо. А что будет с `17 = n`?\n\n- А как насчёт `x = y = 1`?\n\n- В некоторых языках каждое выражение заканчивается точкой с запятой (`;`). Что произойдёт, если поставить точку с запятой в конце строки Python?\n\n- Что если поставить точку в конце строки?\n\n- Что будет, если ошибиться в имени модуля и попытаться импортировать `maath`?" ] }, { @@ -1112,11 +946,7 @@ "id": "9d562609", "metadata": {}, "source": [ - "### Exercise\n", - "Practice using the Python interpreter as a calculator:\n", - "\n", - "**Part 1.** The volume of a sphere with radius $r$ is $\\frac{4}{3} \\pi r^3$.\n", - "What is the volume of a sphere with radius 5? Start with a variable named `radius` and then assign the result to a variable named `volume`. Display the result. Add comments to indicate that `radius` is in centimeters and `volume` in cubic centimeters." + "### Упражнение\nПрактика использования интерпретатора Python в качестве калькулятора:\n\n**Часть 1.** Объем сферы с радиусом $r $ равен $\\frac {4}{3} \\pi r^3 $.\nКаков объем сферы с радиусом 5? Начните с переменной с именем «RADIUS», а затем назначьте результат переменной с именем «Volume». Отображение результата. Добавьте комментарии, чтобы указать, что «радиус» указан в сантиметрах, а «объем» - в кубических сантиметрах." ] }, { @@ -1134,12 +964,7 @@ "id": "6449b12b", "metadata": {}, "source": [ - "**Part 2.** A rule of trigonometry says that for any value of $x$, $(\\cos x)^2 + (\\sin x)^2 = 1$. Let's see if it's true for a specific value of $x$ like 42.\n", - "\n", - "Create a variable named `x` with this value.\n", - "Then use `math.cos` and `math.sin` to compute the sine and cosine of $x$, and the sum of their squared.\n", - "\n", - "The result should be close to 1. It might not be exactly 1 because floating-point arithmetic is not exact---it is only approximately correct." + "**Часть 2.** Правило тригонометрии гласит, что для любого значения $x $, $(\\cos x)^2 + (\\sin x)^2 = 1 $. Давайте посмотрим, верно ли это для определенного значения $x$, например 42.\n\nСоздайте переменную с именем `x` с этим значением.\nЗатем используйте `math.cos` и 'math.sin` для вычисления синуса и косинуса $x$ и суммы их квадрата.\n\nРезультат должен быть близок к 1. Это может быть не совсем 1, потому что арифметика с плавающей точкой не является точной --- это только приблизительно правильно." ] }, { @@ -1157,16 +982,7 @@ "id": "4986801f", "metadata": {}, "source": [ - "**Part 3.** In addition to `pi`, the other variable defined in the `math` module is `e`, which represents the base of the natural logarithm, written in math notation as $e$. If you are not familiar with this value, ask a virtual assistant \"What is `math.e`?\" Now let's compute $e^2$ three ways:\n", - "\n", - "* Use `math.e` and the exponentiation operator (`**`).\n", - "\n", - "* Use `math.pow` to raise `math.e` to the power `2`.\n", - "\n", - "* Use `math.exp`, which takes as an argument a value, $x$, and computes $e^x$.\n", - "\n", - "You might notice that the last result is slightly different from the other two.\n", - "See if you can find out which is correct." + "**Часть 3.** Помимо `pi`, в модуле `math` определена переменная `e`, представляющая основание натурального логарифма. Если вы не знакомы с этим значением, спросите у виртуального помощника: «Что такое `math.e`?» Теперь вычислим $e^2$ тремя способами:\n\n* Используем `math.e` и оператор возведения в степень (`**`).\n\n* Используем `math.pow`, чтобы возвести `math.e` во вторую степень.\n\n* Используем `math.exp`, который принимает аргумент $x$ и вычисляет $e^x$.\n\nВы можете заметить, что последний результат немного отличается от первых двух. Попробуйте выяснить, какой из них верный." ] }, { @@ -1214,13 +1030,7 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", - "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", - "\n", - "Code license: [MIT License](https://mit-license.org/)\n", - "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n\nАвторское право 2024 [Аллен Б. Дауни](https://allendowney.com)\n\nЛицензия на код: [Лицензия MIT](https://mit-license.org/)\n\nТекстовая лицензия: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -1251,4 +1061,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From fb95069ea9ea07ddb26d9d145831eb10c4c98fa2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:44:22 +0300 Subject: [PATCH 33/44] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20Markdown=20=D0=B2=20=D0=B3=D0=BB=D0=B0=D0=B2=D0=B5=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- chapters/chap03.ipynb | 347 +++++++++++++++++++++--------------------- 1 file changed, 172 insertions(+), 175 deletions(-) diff --git a/chapters/chap03.ipynb b/chapters/chap03.ipynb index 5f2cb1d..2320340 100644 --- a/chapters/chap03.ipynb +++ b/chapters/chap03.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать печатную и электронную версии *Think Python 3e* на сайте\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и на\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -41,15 +41,15 @@ "id": "6bd858a8", "metadata": {}, "source": [ - "# Functions\n", + "# Функции\n", "\n", - "In the previous chapter we used several functions provided by Python, like `int` and `float`, and a few provided by the `math` module, like `sqrt` and `pow`.\n", - "In this chapter, you will learn how to create your own functions and run them.\n", - "And we'll see how one function can call another.\n", - "As examples, we'll display lyrics from Monty Python songs.\n", - "These silly examples demonstrate an important feature -- the ability to write your own functions is the foundation of programming.\n", + "В предыдущей главе мы использовали несколько функций Python, таких как `int` и `float`, а также некоторые из модуля `math`, например `sqrt` и `pow`.\n", + "В этой главе вы узнаете, как создавать свои собственные функции и выполнять их.\n", + "Мы увидим, как одна функция может вызывать другую.\n", + "В качестве примеров мы будем выводить строки из песен Монти Пайтона.\n", + "Эти простые примеры демонстрируют важную особенность — возможность писать свои функции является основой программирования.\n", "\n", - "This chapter also introduces a new statement, the `for` loop, which is used to repeat a computation." + "Эта глава также вводит новый оператор — цикл `for`, который используется для повторения вычислений." ] }, { @@ -57,9 +57,9 @@ "id": "b4ea99c5", "metadata": {}, "source": [ - "## Defining new functions\n", + "## Определение новых функций\n", "\n", - "A **function definition** specifies the name of a new function and the sequence of statements that run when the function is called. Here's an example:" + "**Определение функции** задаёт имя новой функции и последовательность инструкций, которые выполняются при её вызове. Вот пример:" ] }, { @@ -79,17 +79,17 @@ "id": "0174fc41", "metadata": {}, "source": [ - "`def` is a keyword that indicates that this is a function definition.\n", - "The name of the function is `print_lyrics`.\n", - "Anything that's a legal variable name is also a legal function name.\n", + "`def` — это ключевое слово, которое указывает на определение функции.\n", + "Имя функции — `print_lyrics`.\n", + "Любое допустимое имя переменной также является допустимым именем функции.\n", "\n", - "The empty parentheses after the name indicate that this function doesn't take any arguments.\n", + "Пустые скобки после имени показывают, что функция не принимает аргументов.\n", "\n", - "The first line of the function definition is called the **header** -- the rest is called the **body**.\n", - "The header has to end with a colon and the body has to be indented. By convention, indentation is always four spaces. \n", - "The body of this function is two print statements; in general, the body of a function can contain any number of statements of any kind.\n", + "Первая строка определения функции называется **заголовком**, остальная часть — **телом**.\n", + "Заголовок должен заканчиваться двоеточием, а тело должно быть с отступом. По соглашению отступ составляет четыре пробела. \n", + "Тело этой функции состоит из двух инструкций `print`; в целом тело функции может содержать любое количество инструкций любого типа.\n", "\n", - "Defining a function creates a **function object**, which we can display like this." + "Определение функции создает **функциональный объект**, который можно вывести вот так." ] }, { @@ -107,10 +107,10 @@ "id": "12bd0879", "metadata": {}, "source": [ - "The output indicates that `print_lyrics` is a function that takes no arguments.\n", - "`__main__` is the name of the module that contains `print_lyrics`.\n", + "Результат показывает, что `print_lyrics` — функция без аргументов.\n", + "`__main__` — имя модуля, содержащего `print_lyrics`.\n", "\n", - "Now that we've defined a function, we can call it the same way we call built-in functions." + "Теперь, когда функция определена, мы можем вызывать её так же, как встроенные функции." ] }, { @@ -128,7 +128,7 @@ "id": "8f0fc45d", "metadata": {}, "source": [ - "When the function runs, it executes the statements in the body, which display the first two lines of \"The Lumberjack Song\"." + "Когда функция выполняется, она исполняет инструкции в теле, которые выводят первые две строки из «Песни дровосека»." ] }, { @@ -136,12 +136,12 @@ "id": "6d35193e", "metadata": {}, "source": [ - "## Parameters\n", + "## Параметры\n", "\n", - "Some of the functions we have seen require arguments; for example, when you call `abs` you pass a number as an argument.\n", - "Some functions take more than one argument; for example, `math.pow` takes two, the base and the exponent.\n", + "Некоторые из функций, которые мы уже видели, требуют аргументы; например, при вызове `abs` вы передаёте число.\n", + "Некоторые функции принимают больше одного аргумента; например, `math.pow` принимает два — основание и показатель степени.\n", "\n", - "Here is a definition for a function that takes an argument." + "Вот определение функции, которая принимает аргумент." ] }, { @@ -161,9 +161,9 @@ "id": "1716e3dc", "metadata": {}, "source": [ - "The variable name in parentheses is a **parameter**.\n", - "When the function is called, the value of the argument is assigned to the parameter.\n", - "For example, we can call `print_twice` like this." + "Имя переменной в скобках называется **параметром**.\n", + "Когда функция вызывается, значение аргумента присваивается параметру.\n", + "Например, мы можем вызвать `print_twice` так." ] }, { @@ -181,7 +181,7 @@ "id": "f02be6d2", "metadata": {}, "source": [ - "Running this function has the same effect as assigning the argument to the parameter and then executing the body of the function, like this." + "Выполнение этой функции имеет тот же эффект, что и присвоение аргумента параметру с последующим выполнением тела функции, как здесь." ] }, { @@ -201,7 +201,7 @@ "id": "ea8b8b6e", "metadata": {}, "source": [ - "You can also use a variable as an argument." + "В качестве аргумента можно использовать и переменную." ] }, { @@ -220,7 +220,7 @@ "id": "5c1884ad", "metadata": {}, "source": [ - "In this example, the value of `line` gets assigned to the parameter `string`." + "В этом примере значение `line` присваивается параметру `string`." ] }, { @@ -228,18 +228,18 @@ "id": "a3e5a790", "metadata": {}, "source": [ - "## Calling functions\n", + "## Вызов функций\n", "\n", - "Once you have defined a function, you can use it inside another function.\n", - "To demonstrate, we'll write functions that print the lyrics of \"The Spam Song\" ().\n", + "После того как вы определили функцию, её можно использовать внутри другой функции.\n", + "Чтобы показать это, напишем функции, которые выводят текст песни «The Spam Song» ().\n", "\n", - "> Spam, Spam, Spam, Spam, \n", - "> Spam, Spam, Spam, Spam, \n", - "> Spam, Spam, \n", - "> (Lovely Spam, Wonderful Spam!) \n", + "> Spam, Spam, Spam, Spam,\n", + "> Spam, Spam, Spam, Spam,\n", + "> Spam, Spam,\n", + "> (Lovely Spam, Wonderful Spam!)\n", "> Spam, Spam,\n", "\n", - "We'll start with the following function, which takes two parameters.\n" + "Начнём со следующей функции, которая принимает два параметра.\n" ] }, { @@ -258,7 +258,7 @@ "id": "bdd4daa4", "metadata": {}, "source": [ - "We can use this function to print the first line of the song, like this." + "Мы можем использовать эту функцию, чтобы вывести первую строку песни, вот так." ] }, { @@ -277,7 +277,7 @@ "id": "c6f81e09", "metadata": {}, "source": [ - "To display the first two lines, we can define a new function that uses `repeat`." + "Чтобы вывести первые две строки, мы можем определить новую функцию, использующую `repeat`." ] }, { @@ -297,7 +297,7 @@ "id": "8058ffe4", "metadata": {}, "source": [ - "And then call it like this." + "А затем вызвать её вот так." ] }, { @@ -315,7 +315,7 @@ "id": "07ca432a", "metadata": {}, "source": [ - "To display the last three lines, we can define another function, which also uses `repeat`." + "Чтобы вывести последние три строки, мы можем определить ещё одну функцию, которая также использует `repeat`." ] }, { @@ -346,7 +346,7 @@ "id": "d6456a19", "metadata": {}, "source": [ - "Finally, we can bring it all together with one function that prints the whole verse." + "Наконец, мы можем собрать всё вместе в одной функции, которая печатает весь куплет." ] }, { @@ -376,10 +376,10 @@ "id": "d088fe68", "metadata": {}, "source": [ - "When we run `print_verse`, it calls `first_two_lines`, which calls `repeat`, which calls `print`.\n", - "That's a lot of functions.\n", + "Когда мы вызываем `print_verse`, эта функция вызывает `first_two_lines`, которая вызывает `repeat`, а та вызывает `print`.\n", + "Это много функций.\n", "\n", - "Of course, we could have done the same thing with fewer functions, but the point of this example is to show how functions can work together." + "Конечно, то же самое можно было сделать и меньшим количеством функций, но цель примера — показать, как функции могут работать вместе." ] }, { @@ -387,10 +387,10 @@ "id": "c3b16e3f", "metadata": {}, "source": [ - "## Repetition\n", + "## Повторение\n", "\n", - "If we want to display more than one verse, we can use a `for` statement.\n", - "Here's a simple example." + "Если мы хотим вывести больше одного куплета, можно использовать оператор `for`.\n", + "Вот простой пример." ] }, { @@ -409,20 +409,20 @@ "id": "bf320549", "metadata": {}, "source": [ - "The first line is a header that ends with a colon.\n", - "The second line is the body, which has to be indented.\n", + "Первая строка — это заголовок, который заканчивается двоеточием.\n", + "Вторая строка — тело цикла, которое должно быть с отступом.\n", "\n", - "The header starts with the keyword `for`, a new variable named `i`, and another keyword, `in`. \n", - "It uses the `range` function to create a sequence of two values, which are `0` and `1`.\n", - "In Python, when we start counting, we usually start from `0`.\n", + "Заголовок начинается с ключевого слова `for`, новой переменной `i` и другого ключевого слова `in`. \n", + "Он использует функцию `range`, чтобы создать последовательность из двух значений — `0` и `1`.\n", + "В Python при счёте мы обычно начинаем с `0`.\n", "\n", - "When the `for` statement runs, it assigns the first value from `range` to `i` and then runs the `print` function in the body, which displays `0`.\n", + "Когда выполняется оператор `for`, он присваивает первое значение из `range` переменной `i`, а затем запускает функцию `print` в теле цикла, которая выводит `0`.\n", "\n", - "When it gets to the end of the body, it loops back around to the header, which is why this statement is called a **loop**.\n", - "The second time through the loop, it assigns the next value from `range` to `i`, and displays it.\n", - "Then, because that's the last value from `range`, the loop ends.\n", + "Дойдя до конца тела, он возвращается к заголовку, поэтому такой оператор называют **циклом**.\n", + "Во второй проход цикла переменной `i` присваивается следующее значение из `range`, и оно выводится.\n", + "Затем, так как это последнее значение из `range`, цикл завершается.\n", "\n", - "Here's how we can use a `for` loop to print two verses of the song." + "Вот как можно использовать цикл `for`, чтобы вывести два куплета песни." ] }, { @@ -443,8 +443,8 @@ "id": "88a46733", "metadata": {}, "source": [ - "You can put a `for` loop inside a function.\n", - "For example, `print_n_verses` takes a parameter named `n`, which has to be an integer, and displays the given number of verses. " + "Вы можете поместить цикл `for` внутрь функции.\n", + "Например, `print_n_verses` принимает параметр `n`, который должен быть целым числом, и выводит заданное количество куплетов. " ] }, { @@ -465,7 +465,7 @@ "id": "ad8060fe", "metadata": {}, "source": [ - "In this example, we don't use `i` in the body of the loop, but there has to be a variable name in the header anyway." + "В этом примере мы не используем `i` в теле цикла, но имя переменной в заголовке всё равно должно быть." ] }, { @@ -473,11 +473,11 @@ "id": "b320ec90", "metadata": {}, "source": [ - "## Variables and parameters are local\n", + "## Переменные и параметры являются локальными\n", "\n", - "When you create a variable inside a function, it is **local**, which\n", - "means that it only exists inside the function.\n", - "For example, the following function takes two arguments, concatenates them, and prints the result twice." + "Когда вы создаёте переменную внутри функции, она **локальная**,\n", + "то есть существует только внутри этой функции.\n", + "Например, следующая функция принимает два аргумента, объединяет их и печатает результат дважды." ] }, { @@ -497,7 +497,7 @@ "id": "3a35a6d0", "metadata": {}, "source": [ - "Here's an example that uses it:" + "Вот пример его использования:" ] }, { @@ -517,8 +517,8 @@ "id": "4ab4e008", "metadata": {}, "source": [ - "When `cat_twice` runs, it creates a local variable named `cat`, which is destroyed when the function ends.\n", - "If we try to display it, we get a `NameError`:" + "Когда выполняется `cat_twice`, создаётся локальная переменная `cat`, которая уничтожается после завершения функции.\n", + "Если попытаться вывести её, мы получим `NameError`:" ] }, { @@ -540,10 +540,10 @@ "id": "3ae36c29", "metadata": {}, "source": [ - "Outside of the function, `cat` is not defined. \n", + "Вне функции переменная `cat` не определена. \n", "\n", - "Parameters are also local.\n", - "For example, outside `cat_twice`, there is no such thing as `part1` or `part2`." + "Параметры тоже являются локальными.\n", + "Например, вне `cat_twice` не существует переменных `part1` и `part2`." ] }, { @@ -551,15 +551,15 @@ "id": "eabac8a6", "metadata": {}, "source": [ - "## Stack diagrams\n", + "## Диаграммы стека\n", "\n", - "To keep track of which variables can be used where, it is sometimes useful to draw a **stack diagram**. \n", - "Like state diagrams, stack diagrams show the value of each variable, but they also show the function each variable belongs to.\n", + "Чтобы отслеживать, какие переменные где можно использовать, иногда полезно рисовать **диаграмму стека**. \n", + "Как и диаграммы состояний, диаграммы стека показывают значение каждой переменной, а также функцию, которой она принадлежит.\n", "\n", - "Each function is represented by a **frame**.\n", - "A frame is a box with the name of a function on the outside and the parameters and local variables of the function on the inside.\n", + "Каждая функция представлена **фреймом**.\n", + "Фрейм — это прямоугольник с именем функции снаружи и параметрами и локальными переменными внутри.\n", "\n", - "Here's the stack diagram for the previous example." + "Вот диаграмма стека для предыдущего примера." ] }, { @@ -617,12 +617,12 @@ "id": "854fee12", "metadata": {}, "source": [ - "The frames are arranged in a stack that indicates which function called\n", - "which, and so on. Reading from the bottom, `print` was called by `print_twice`, which was called by `cat_twice`, which was called by `__main__` -- which is a special name for the topmost frame.\n", - "When you create a variable outside of any function, it belongs to `__main__`.\n", + "Фреймы располагаются в стеке, который показывает, какая функция вызвала\n", + "какую, и так далее. Снизу видно, что `print` был вызван `print_twice`, который вызвал `cat_twice`, который был вызван `__main__` — это специальное имя для верхнего фрейма.\n", + "Когда вы создаёте переменную вне какой-либо функции, она принадлежит `__main__`.\n", "\n", - "In the frame for `print`, the question mark indicates that we don't know the name of the parameter.\n", - "If you are curious, ask a virtual assistant, \"What are the parameters of the Python print function?\"" + "В фрейме для `print` вопросительный знак означает, что мы не знаем имя параметра.\n", + "Если вам интересно, спросите виртуального ассистента, \"Каковы параметры функции print в Python?\"" ] }, { @@ -630,10 +630,10 @@ "id": "5690cfc0", "metadata": {}, "source": [ - "## Tracebacks\n", + "## Обратные трассировки\n", "\n", - "When a runtime error occurs in a function, Python displays the name of the function that was running, the name of the function that called it, and so on, up the stack.\n", - "To see an example, I'll define a version of `print_twice` that contains an error -- it tries to print `cat`, which is a local variable in another function." + "Когда во время выполнения возникает ошибка, Python показывает имя функции, которая работала, имя функции, которая её вызвала, и так далее вверх по стеку.\n", + "Чтобы увидеть пример, я определю версию `print_twice`, содержащую ошибку — она пытается вывести `cat`, который является локальной переменной в другой функции." ] }, { @@ -653,7 +653,7 @@ "id": "d7c0713b", "metadata": {}, "source": [ - "Now here's what happens when we run `cat_twice`." + "Теперь посмотрим, что произойдёт при запуске `cat_twice`." ] }, { @@ -690,11 +690,11 @@ "id": "2f4defcf", "metadata": {}, "source": [ - "The error message includes a **traceback**, which shows the function that was running when the error occurred, the function that called it, and so on.\n", - "In this example, it shows that `cat_twice` called `print_twice`, and the error occurred in a `print_twice`.\n", + "Сообщение об ошибке содержит **traceback** — список функций, которые выполнялись в момент ошибки, и тех, что их вызывали.\n", + "В этом примере видно, что `cat_twice` вызвала `print_twice`, и ошибка возникла в `print_twice`.\n", "\n", - "The order of the functions in the traceback is the same as the order of the frames in the stack diagram.\n", - "The function that was running is at the bottom." + "Порядок функций в traceback совпадает с порядком фреймов на диаграмме стека.\n", + "Функция, выполнявшаяся во время ошибки, находится внизу." ] }, { @@ -702,23 +702,21 @@ "id": "374b4696", "metadata": {}, "source": [ - "## Why functions?\n", + "## Зачем нужны функции?\n", "\n", - "It may not be clear yet why it is worth the trouble to divide a program into\n", - "functions.\n", - "There are several reasons:\n", + "Пока может быть не очевидно, зачем делить программу на функции.\n", + "На это есть несколько причин:\n", "\n", - "- Creating a new function gives you an opportunity to name a group of\n", - " statements, which makes your program easier to read and debug.\n", + "- Создание новой функции даёт возможность дать имя группе инструкций,\n", + " что делает программу легче читаемой и отлаживаемой.\n", "\n", - "- Functions can make a program smaller by eliminating repetitive code.\n", - " Later, if you make a change, you only have to make it in one place.\n", + "- Функции позволяют сократить программу, устранив повторяющийся код.\n", + " Если позже что‑то изменится, исправление придётся сделать только в одном месте.\n", "\n", - "- Dividing a long program into functions allows you to debug the parts\n", - " one at a time and then assemble them into a working whole.\n", + "- Разделив длинную программу на функции, можно отлаживать части поодиночке,\n", + " а затем собрать их в рабочее целое.\n", "\n", - "- Well-designed functions are often useful for many programs. Once you\n", - " write and debug one, you can reuse it." + "- Хорошо спроектированные функции часто полезны во многих программах. Однажды написав и отладив такую функцию, её можно переиспользовать." ] }, { @@ -726,25 +724,24 @@ "id": "c6dd486e", "metadata": {}, "source": [ - "## Debugging\n", + "## Отладка\n", "\n", - "Debugging can be frustrating, but it is also challenging, interesting, and sometimes even fun.\n", - "And it is one of the most important skills you can learn.\n", + "Отладка может раздражать, но она также сложна, интересна и порой даже увлекательна.\n", + "Кроме того, это одно из самых важных умений, которое вы можете освоить.\n", "\n", - "In some ways debugging is like detective work.\n", - "You are given clues and you have to infer the events that led to the\n", - "results you see.\n", + "В некотором смысле отладка похожа на детективную работу.\n", + "У вас есть подсказки, и нужно восстановить события, которые привели к наблюдаемым результатам.\n", "\n", - "Debugging is also like experimental science.\n", - "Once you have an idea about what is going wrong, you modify your program and try again.\n", - "If your hypothesis was correct, you can predict the result of the modification, and you take a step closer to a working program.\n", - "If your hypothesis was wrong, you have to come up with a new one.\n", + "Отладка также похожа на экспериментальную науку.\n", + "Когда у вас появляется предположение о том, что идёт не так, вы меняете программу и пробуете снова.\n", + "Если гипотеза верна, можно предсказать результат изменения и на шаг приблизиться к работающей программе.\n", + "Если гипотеза оказалась неверной, нужно придумать новую.\n", "\n", - "For some people, programming and debugging are the same thing; that is, programming is the process of gradually debugging a program until it does what you want.\n", - "The idea is that you should start with a working program and make small modifications, debugging them as you go.\n", + "Для некоторых людей программирование и отладка — одно и то же; то есть программирование — это процесс постепенной отладки программы, пока она не начнёт делать то, что вам нужно.\n", + "Идея в том, что следует начать с работающей программы и вносить небольшие изменения, отлаживая их по ходу дела.\n", "\n", - "If you find yourself spending a lot of time debugging, that is often a sign that you are writing too much code before you start tests.\n", - "If you take smaller steps, you might find that you can move faster." + "Если вы проводите много времени за отладкой, часто это означает, что вы пишете слишком много кода перед тем, как начать тесты.\n", + "Делая более мелкие шаги, вы можете двигаться быстрее." ] }, { @@ -752,39 +749,39 @@ "id": "d4e95e63", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**function definition:**\n", - "A statement that creates a function.\n", + "**определение функции:**\n", + "Инструкция, создающая функцию.\n", "\n", - "**header:**\n", - " The first line of a function definition.\n", + "**заголовок:**\n", + " Первая строка определения функции.\n", "\n", - "**body:**\n", - " The sequence of statements inside a function definition.\n", + "**тело:**\n", + " Последовательность инструкций внутри определения функции.\n", "\n", - "**function object:**\n", - "A value created by a function definition.\n", - "The name of the function is a variable that refers to a function object.\n", + "**объект функции:**\n", + "Значение, создаваемое определением функции.\n", + "Имя функции — это переменная, которая ссылается на объект функции.\n", "\n", - "**parameter:**\n", - " A name used inside a function to refer to the value passed as an argument.\n", + "**параметр:**\n", + " Имя, используемое внутри функции для обращения к значению, переданному как аргумент.\n", "\n", - "**loop:**\n", - " A statement that runs one or more statements, often repeatedly.\n", + "**цикл:**\n", + " Инструкция, которая выполняет одну или несколько других инструкций, часто многократно.\n", "\n", - "**local variable:**\n", - "A variable defined inside a function, and which can only be accessed inside the function.\n", + "**локальная переменная:**\n", + "Переменная, определённая внутри функции и доступная только в ней.\n", "\n", - "**stack diagram:**\n", - "A graphical representation of a stack of functions, their variables, and the values they refer to.\n", + "**диаграмма стека:**\n", + "Графическое представление стека функций, их переменных и значений, на которые они ссылаются.\n", "\n", - "**frame:**\n", - " A box in a stack diagram that represents a function call.\n", - " It contains the local variables and parameters of the function.\n", + "**фрейм:**\n", + " Прямоугольник на диаграмме стека, представляющий вызов функции.\n", + " Он содержит локальные переменные и параметры функции.\n", "\n", - "**traceback:**\n", - " A list of the functions that are executing, printed when an exception occurs." + "**трассировка (traceback):**\n", + " Список выполняющихся функций, выводимый при возникновении исключения." ] }, { @@ -792,7 +789,7 @@ "id": "eca485f2", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -815,23 +812,23 @@ "id": "82951027", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "The statements in a function or a `for` loop are indented by four spaces, by convention.\n", - "But not everyone agrees with that convention.\n", - "If you are curious about the history of this great debate, ask a virtual assistant to \"tell me about spaces and tabs in Python\".\n", + "По соглашению инструкции в функции или цикле `for` имеют отступ в четыре пробела.\n", + "Но с этим согласны не все.\n", + "Если вам интересно, откуда взялся этот спор, попросите виртуального помощника «рассказать о пробелах и табуляции в Python».\n", "\n", - "Virtual assistant are pretty good at writing small functions.\n", + "Виртуальные помощники неплохо пишут небольшие функции.\n", "\n", - "1. Ask your favorite VA to \"Write a function called repeat that takes a string and an integer and prints the string the given number of times.\" \n", + "1. Попросите своего любимого помощника: «Напиши функцию `repeat`, которая принимает строку и целое число и печатает строку указанное количество раз.» \n", "\n", - "2. If the result uses a `for` loop, you could ask, \"Can you do it without a for loop?\"\n", + "2. Если результат использует цикл `for`, спросите: «Можно ли обойтись без цикла for?»\n", "\n", - "3. Pick any other function in this chapter and ask a VA to write it. The challenge is to describe the function precisely enough to get what you want. Use the vocabulary you have learned so far in this book.\n", + "3. Выберите любую другую функцию из этой главы и попросите помощника написать её. Задача в том, чтобы описать функцию достаточно точно. Используйте термины, которые вы изучили в этой книге.\n", "\n", - "Virtual assistants are also pretty good at debugging functions.\n", + "Виртуальные помощники также неплохо умеют искать ошибки в функциях.\n", "\n", - "1. Ask a VA what's wrong with this version of `print_twice`.\n", + "1. Спросите помощника, что не так в этой версии `print_twice`.\n", "\n", " ```\n", " def print_twice(string):\n", @@ -839,7 +836,7 @@ " print(cat)\n", " ```\n", " \n", - "And if you get stuck on any of the exercises below, consider asking a VA for help." + "И если вы застрянете в каком-нибудь из упражнений ниже, подумайте о том, чтобы попросить помощь у виртуального помощника." ] }, { @@ -847,9 +844,9 @@ "id": "b7157b09", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function named `print_right` that takes a string named `text` as a parameter and prints the string with enough leading spaces that the last letter of the string is in the 40th column of the display." + "Напишите функцию `print_right`, которая принимает строку `text` и выводит её с таким количеством пробелов слева, чтобы последняя буква строки оказалась в 40-й колонке экрана." ] }, { @@ -867,9 +864,9 @@ "id": "428fbee5", "metadata": {}, "source": [ - "Hint: Use the `len` function, the string concatenation operator (`+`) and the string repetition operator (`*`).\n", + "Подсказка: используйте функцию `len`, оператор конкатенации строк (`+`) и оператор повторения строк (`*`).\n", "\n", - "Here's an example that shows how it should work." + "Вот пример, показывающий как это должно работать." ] }, { @@ -891,9 +888,9 @@ "id": "b47467fa", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `triangle` that takes a string and an integer and draws a pyramid with the given height, made up using copies of the string. Here's an example of a pyramid with `5` levels, using the string `'L'`." + "Напишите функцию `triangle`, которая принимает строку и целое число и рисует пирамиду заданной высоты, составленную из копий этой строки. Ниже показан пример пирамиды из `5` уровней, построенной из строки `'L'`." ] }, { @@ -924,9 +921,9 @@ "id": "4a28f635", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `rectangle` that takes a string and two integers and draws a rectangle with the given width and height, made up using copies of the string. Here's an example of a rectangle with width `5` and height `4`, made up of the string `'H'`." + "Напишите функцию `rectangle`, которая принимает строку и два целых числа и рисует прямоугольник заданной ширины и высоты из копий этой строки. Ниже показан пример прямоугольника шириной `5` и высотой `4` из строки `'H'`." ] }, { @@ -957,20 +954,20 @@ "id": "44a5de6f", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "The song \"99 Bottles of Beer\" starts with this verse:\n", + "Песня «99 Bottles of Beer» начинается с такого куплета:\n", "\n", "> 99 bottles of beer on the wall \n", "> 99 bottles of beer \n", "> Take one down, pass it around \n", "> 98 bottles of beer on the wall \n", "\n", - "Then the second verse is the same, except that it starts with 98 bottles and ends with 97. The song continues -- for a very long time -- until there are 0 bottles of beer.\n", + "Затем идёт второй куплет, такой же, но начинается с 98 бутылок и заканчивается 97. Песня продолжается — очень долго — пока не останется 0 бутылок пива.\n", "\n", - "Write a function called `bottle_verse` that takes a number as a parameter and displays the verse that starts with the given number of bottles.\n", + "Напишите функцию `bottle_verse`, которая принимает число и выводит куплет, начинающийся с указанного количества бутылок.\n", "\n", - "Hint: Consider starting with a function that can print the first, second, or last line of the verse, and then use it to write `bottle_verse`." + "Подсказка: начните с функции, которая умеет печатать первую, вторую или последнюю строку куплета, а затем используйте её для написания `bottle_verse`." ] }, { @@ -1000,7 +997,7 @@ "tags": [] }, "source": [ - "Use this function call to display the first verse." + "Используйте этот вызов функции, чтобы вывести первый куплет." ] }, { @@ -1022,8 +1019,8 @@ "tags": [] }, "source": [ - "If you want to print the whole song, you can use this `for` loop, which counts down from `99` to `1`.\n", - "You don't have to completely understand this example---we'll learn more about `for` loops and the `range` function later." + "Если вы хотите распечатать всю песню, можно использовать этот цикл `for`, который считает от `99` до `1`.\n", + "Необязательно полностью понимать этот пример — позже мы подробнее поговорим о циклах `for` и функции `range`." ] }, { @@ -1055,13 +1052,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3-е издание](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -1087,4 +1084,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From f3e94d5da15ede750274e6b30d82be089c89da8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:46:09 +0300 Subject: [PATCH 34/44] Translate chap04 markdown to Russian --- chapters/chap04.ipynb | 317 +++++++++++++++--------------------------- 1 file changed, 113 insertions(+), 204 deletions(-) diff --git a/chapters/chap04.ipynb b/chapters/chap04.ipynb index 7117af6..50dd6dc 100644 --- a/chapters/chap04.ipynb +++ b/chapters/chap04.ipynb @@ -5,9 +5,7 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать печатные и электронные версии *Think Python 3e* на [Bookshop.org](https://bookshop.org/a/98697/9781098155438) и [Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, { @@ -55,10 +53,9 @@ "id": "fbb4d5a2", "metadata": {}, "source": [ - "# Functions and Interfaces\n", + "# Функции и интерфейсы\n", "\n", - "This chapter introduces a module called `jupyturtle`, which allows you to create simple drawings by giving instructions to an imaginary turtle.\n", - "We will use this module to write functions that draw squares, polygons, and circles -- and to demonstrate **interface design**, which is a way of designing functions that work together." + "В этой главе мы познакомимся с модулем `jupyturtle`, который позволяет создавать простые рисунки, отдавая команды воображаемой черепашке. Мы будем использовать этот модуль для написания функций, которые рисуют квадраты, многоугольники и окружности, — и чтобы продемонстрировать **проектирование интерфейсов**, то есть способ разработки функций, которые работают вместе." ] }, { @@ -68,9 +65,9 @@ "tags": [] }, "source": [ - "## The jupyturtle module\n", + "## Модуль jupyturtle\n", "\n", - "To use the `jupyturtle` module, we can import it like this." + "Чтобы использовать модуль `jupyturtle`, импортируем его так." ] }, { @@ -88,7 +85,7 @@ "id": "8c801121", "metadata": {}, "source": [ - "Now we can use the functions defined in the module, like `make_turtle` and `forward`." + "Теперь можно использовать функции из этого модуля, например `make_turtle` и `forward`." ] }, { @@ -107,14 +104,11 @@ "id": "77a61cbb", "metadata": {}, "source": [ - "`make_turtle` creates a **canvas**, which is a space on the screen where we can draw, and a turtle, which is represented by a circular shell and a triangular head.\n", - "The circle shows the location of the turtle and the triangle indicates the direction it is facing.\n", + "`make_turtle` создаёт **холст** — область на экране, где можно рисовать, и черепаху, которая изображается кругом‑панцирем и треугольной головой. Круг показывает положение черепахи, а треугольник указывает направление, куда она «смотрит».\n", "\n", - "`forward` moves the turtle a given distance in the direction it's facing, drawing a line segment along the way.\n", - "The distance is in arbitrary units -- the actual size depends on your computer's screen.\n", + "`forward` перемещает черепаху на указанное расстояние по направлению её движения, оставляя за собой отрезок линии. Расстояние измеряется в произвольных единицах — фактический размер зависит от вашего экрана.\n", "\n", - "We will use functions defined in the `jupyturtle` module many times, so it would be nice if we did not have to write the name of the module every time.\n", - "That's possible if we import the module like this." + "Функции из модуля `jupyturtle` мы будем использовать много раз, поэтому будет удобнее не писать имя модуля каждый раз. Это возможно, если импортировать модуль так." ] }, { @@ -132,7 +126,7 @@ "id": "c1322d31", "metadata": {}, "source": [ - "This version of the import statement imports `make_turtle` and `forward` from the `jupyturtle` module so we can call them like this." + "Такая версия инструкции импортирует `make_turtle` и `forward` из модуля `jupyturtle`, так что их можно вызывать вот так." ] }, { @@ -151,8 +145,7 @@ "id": "bd319754", "metadata": {}, "source": [ - "`jupyturtle` provides two other functions we'll use, called `left` and `right`.\n", - "We'll import them like this." + "Модуль `jupyturtle` предоставляет ещё две функции, которые нам пригодятся, — `left` и `right`. Импортируем их так." ] }, { @@ -170,8 +163,7 @@ "id": "0da2a311", "metadata": {}, "source": [ - "`left` causes the turtle to turn left. It takes one argument, which is the angle of the turn in degrees.\n", - "For example, we can make a 90 degree left turn like this." + "`left` заставляет черепаху повернуть налево. Функция принимает один аргумент — угол поворота в градусах. Например, так можно выполнить поворот на 90 градусов." ] }, { @@ -192,8 +184,7 @@ "id": "cea2940f", "metadata": {}, "source": [ - "This program moves the turtle east and then north, leaving two line segments behind.\n", - "Before you go on, see if you can modify the previous program to make a square." + "Эта программа перемещает черепаху сначала на восток, затем на север, оставляя позади две линии. Прежде чем продолжить, попробуйте изменить предыдущую программу так, чтобы она рисовала квадрат." ] }, { @@ -201,9 +192,9 @@ "id": "e20ea96c", "metadata": {}, "source": [ - "## Making a square\n", + "## Рисуем квадрат\n", "\n", - "Here's one way to make a square." + "Вот один из способов нарисовать квадрат." ] }, { @@ -233,7 +224,7 @@ "id": "a7500957", "metadata": {}, "source": [ - "Because this program repeats the same pair of lines four times, we can do the same thing more concisely with a `for` loop." + "Поскольку эта программа повторяет одну и ту же пару строк четыре раза, то же самое можно сделать короче с помощью цикла `for`." ] }, { @@ -256,9 +247,9 @@ "tags": [] }, "source": [ - "## Encapsulation and generalization\n", + "## Инкапсуляция и обобщение\n", "\n", - "Let's take the square-drawing code from the previous section and put it in a function called `square`." + "Возьмём код из предыдущей части, который рисует квадрат, и поместим его в функцию `square`." ] }, { @@ -279,7 +270,7 @@ "id": "0789b5d9", "metadata": {}, "source": [ - "Now we can call the function like this." + "Теперь её можно вызвать так." ] }, { @@ -298,11 +289,9 @@ "id": "da905fc6", "metadata": {}, "source": [ - "Wrapping a piece of code up in a function is called **encapsulation**.\n", - "One of the benefits of encapsulation is that it attaches a name to the code, which serves as a kind of documentation. Another advantage is that if you re-use the code, it is more concise to call a function twice than to copy and paste the body!\n", + "Упаковка участка кода в функцию называется **инкапсуляцией**. Одно из её преимуществ в том, что код получает имя, служащее своего рода документацией. Ещё один плюс: если нужно использовать код повторно, проще дважды вызвать функцию, чем копировать её содержимое!\n", "\n", - "In the current version, the size of the square is always `50`.\n", - "If we want to draw squares with different sizes, we can take the length of the sides as a parameter. " + "В текущей версии размер квадрата всегда равен `50`. Если мы хотим рисовать квадраты разных размеров, можно передавать длину стороны в качестве параметра." ] }, { @@ -323,7 +312,7 @@ "id": "397fda4b", "metadata": {}, "source": [ - "Now we can draw squares with different sizes." + "Теперь мы можем рисовать квадраты разного размера." ] }, { @@ -343,10 +332,9 @@ "id": "5a46bf64", "metadata": {}, "source": [ - "Adding a parameter to a function is called **generalization** because it makes the function more general: with the previous version, the square is always the same size; with this version it can be any size.\n", + "Добавление параметра к функции называется **обобщением**, потому что делает её более универсальной: в предыдущей версии квадрат был всегда одного размера, а в этой — любого.\n", "\n", - "If we add another parameter, we can make it even more general.\n", - "The following function draws regular polygons with a given number of sides." + "Если добавить ещё один параметр, функцию можно сделать ещё более общей. Следующая функция рисует правильные многоугольники с заданным числом сторон." ] }, { @@ -368,9 +356,9 @@ "id": "286d3c77", "metadata": {}, "source": [ - "In a regular polygon with `n` sides, the angle between adjacent sides is `360 / n` degrees. \n", + "В правильном многоугольнике с `n` сторонами угол между соседними сторонами равен `360 / n` градусов.\n", "\n", - "The following example draws a `7`-sided polygon with side length `30`." + "Следующий пример рисует 7‑угольник со стороной `30`." ] }, { @@ -389,8 +377,7 @@ "id": "dc0226db", "metadata": {}, "source": [ - "When a function has more than a few numeric arguments, it is easy to forget what they are, or what order they should be in. \n", - "It can be a good idea to include the names of the parameters in the argument list." + "Когда у функции несколько числовых аргументов, легко забыть, что они означают и в каком порядке их передавать. Поэтому полезно включать имена параметров в список аргументов." ] }, { @@ -411,10 +398,9 @@ "id": "6aa28eba", "metadata": {}, "source": [ - "These are sometimes called \"named arguments\" because they include the parameter names.\n", - "But in Python they are more often called **keyword arguments** (not to be confused with Python keywords like `for` and `def`).\n", + "Такой способ иногда называют «именованными аргументами», потому что в них присутствуют имена параметров. Но в Python их чаще называют **аргументами-ключевыми словами** (не путать с ключевыми словами языка `for` и `def`).\n", "\n", - "This use of the assignment operator, `=`, is a reminder about how arguments and parameters work -- when you call a function, the arguments are assigned to the parameters." + "Использование оператора присваивания `=` напоминает, как работают аргументы и параметры: при вызове функции аргументы присваиваются параметрам." ] }, { @@ -422,11 +408,9 @@ "id": "b10184b4", "metadata": {}, "source": [ - "## Approximating a circle\n", + "## Аппроксимация окружности\n", "\n", - "Now suppose we want to draw a circle.\n", - "We can do that, approximately, by drawing a polygon with a large number of sides, so each side is small enough that it's hard to see.\n", - "Here is a function that uses `polygon` to draw a `30`-sided polygon that approximates a circle." + "Предположим, мы хотим нарисовать окружность. Это можно сделать приближённо, нарисовав многоугольник с большим числом сторон, так что каждая из них будет достаточно маленькой, чтобы её было трудно увидеть. Вот функция, которая с помощью `polygon` рисует 30‑угольник, приближающий окружность." ] }, { @@ -450,13 +434,9 @@ "id": "39023314", "metadata": {}, "source": [ - "`circle` takes the radius of the the circle as a parameter.\n", - "It computes `circumference`, which is the circumference of a circle with the given radius.\n", - "`n` is the number of sides, so `circumference / n` is the length of each side.\n", + "`circle` принимает радиус окружности как параметр. Она вычисляет `circumference` — длину окружности с заданным радиусом. `n` — число сторон, поэтому `circumference / n` — длина каждой стороны.\n", "\n", - "This function might take a long time to run.\n", - "We can speed it up by calling `make_turtle` with a keyword argument called `delay` that sets the time, in seconds, the turtle waits after each step.\n", - "The default value is `0.2` seconds -- if we set it to `0.02` it runs about 10 times faster." + "Выполнение этой функции может занять много времени. Мы можем ускорить её, вызвав `make_turtle` с именованным аргументом `delay`, который задаёт паузу в секундах после каждого шага. Значение по умолчанию — 0.2 секунды; если установить 0.02, программа будет работать примерно в десять раз быстрее." ] }, { @@ -475,11 +455,7 @@ "id": "701f9cf8", "metadata": {}, "source": [ - "A limitation of this solution is that `n` is a constant, which means\n", - "that for very big circles, the sides are too long, and for small\n", - "circles, we waste time drawing very short sides.\n", - "One option is to generalize the function by taking `n` as a parameter.\n", - "But let's keep it simple for now." + "Недостаток этого решения в том, что `n` — константа: для очень больших окружностей стороны получаются слишком длинными, а для маленьких мы зря тратим время, рисуя очень короткие отрезки. Один из вариантов — обобщить функцию, добавив параметр `n`. Но пока оставим всё как есть." ] }, { @@ -487,15 +463,13 @@ "id": "c48f262c", "metadata": {}, "source": [ - "## Refactoring\n", + "## Рефакторинг\n", "\n", - "Now let's write a more general version of `circle`, called `arc`, that takes a second parameter, `angle`, and draws an arc of a circle that spans the given angle.\n", - "For example, if `angle` is `360` degrees, it draws a complete circle. If `angle` is `180` degrees, it draws a half circle.\n", + "Теперь напишем более общую версию `circle` под названием `arc`, которая принимает второй параметр `angle` и рисует дугу окружности на указанный угол. Например, если `angle` равен 360 градусов, получаем полную окружность; если 180 — полукруг.\n", "\n", - "To write `circle`, we were able to reuse `polygon`, because a many-sided polygon is a good approximation of a circle.\n", - "But we can't use `polygon` to write `arc`.\n", + "При написании `circle` мы смогли использовать `polygon`, потому что многоугольник с большим числом сторон хорошо приближает окружность. Но для `arc` `polygon` не подойдёт.\n", "\n", - "Instead, we'll create the more general version of `polygon`, called `polyline`." + "Вместо этого мы создадим более общую версию `polygon`, которую назовём `polyline`." ] }, { @@ -516,9 +490,9 @@ "id": "c2b2503e", "metadata": {}, "source": [ - "`polyline` takes as parameters the number of line segments to draw, `n`, the length of the segments, `length`, and the angle between them, `angle`.\n", + "`polyline` принимает в качестве параметров количество отрезков `n`, длину каждого отрезка `length` и угол между ними `angle`.\n", "\n", - "Now we can rewrite `polygon` to use `polyline`." + "Теперь мы можем переписать `polygon`, используя `polyline`." ] }, { @@ -538,7 +512,7 @@ "id": "2714a59e", "metadata": {}, "source": [ - "And we can use `polyline` to write `arc`." + "И с помощью `polyline` можно написать `arc`." ] }, { @@ -561,9 +535,7 @@ "id": "3c18773c", "metadata": {}, "source": [ - "`arc` is similar to `circle`, except that it computes `arc_length`, which is a fraction of the circumference of a circle.\n", - "\n", - "Finally, we can rewrite `circle` to use `arc`." + "`arc` похожа на `circle`, но вычисляет `arc_length`, то есть часть длины окружности. Наконец, мы можем переписать `circle`, чтобы она использовала `arc`." ] }, { @@ -582,8 +554,7 @@ "id": "313a357c", "metadata": {}, "source": [ - "To check that these functions work as expected, we'll use them to draw something like a snail.\n", - "With `delay=0`, the turtle runs as fast as possible." + "Чтобы убедиться, что функции работают как нужно, используем их для рисования чего-то вроде улитки. При `delay=0` черепаха движется максимально быстро." ] }, { @@ -604,12 +575,9 @@ "id": "a34da3d8", "metadata": {}, "source": [ - "In this example, we started with working code and reorganized it with different functions.\n", - "Changes like this, which improve the code without changing its behavior, are called **refactoring**.\n", + "В этом примере мы начали с рабочего кода и перестроили его, разбив на другие функции. Такие изменения, которые улучшают код, не меняя его поведение, называются **рефакторингом**.\n", "\n", - "If we had planned ahead, we might have written `polyline` first and avoided refactoring, but often you don't know enough at the beginning of a project to design all the functions.\n", - "Once you start coding, you understand the problem better.\n", - "Sometimes refactoring is a sign that you have learned something." + "Если бы мы планировали заранее, возможно, сначала написали бы `polyline` и избежали рефакторинга, но часто в начале проекта ещё не ясно, как лучше разделить программу на функции. Начав кодирование, вы лучше понимаете задачу. Иногда рефакторинг показывает, что вы чему‑то научились." ] }, { @@ -617,10 +585,9 @@ "id": "d18c9d16", "metadata": {}, "source": [ - "## Stack diagram\n", + "## Диаграмма стека\n", "\n", - "When we call `circle`, it calls `arc`, which calls `polyline`.\n", - "We can use a stack diagram to show this sequence of function calls and the parameters for each one." + "Когда вызывается `circle`, она вызывает `arc`, которая, в свою очередь, вызывает `polyline`. С помощью диаграммы стека можно показать эту последовательность вызовов функций и их параметры." ] }, { @@ -666,8 +633,7 @@ "id": "3160bba1", "metadata": {}, "source": [ - "Notice that the value of `angle` in `polyline` is different from the value of `angle` in `arc`.\n", - "Parameters are local, which means you can use the same parameter name in different functions; it's a different variable in each function, and it can refer to a different value. " + "Обратите внимание, что значение `angle` в `polyline` отличается от значения `angle` в `arc`. Параметры являются локальными, то есть можно использовать одно и то же имя параметра в разных функциях; в каждой функции это своя переменная, и она может иметь другое значение." ] }, { @@ -675,27 +641,21 @@ "id": "c23552d3", "metadata": {}, "source": [ - "## A development plan\n", + "## План разработки\n", "\n", - "A **development plan** is a process for writing programs.\n", - "The process we used in this chapter is \"encapsulation and generalization\".\n", - "The steps of this process are:\n", + "**План разработки** — это процесс написания программ. В этой главе мы использовали метод «инкапсуляция и обобщение». Его шаги таковы:\n", "\n", - "1. Start by writing a small program with no function definitions.\n", + "1. Начните с небольшой программы без определений функций.\n", "\n", - "2. Once you get the program working, identify a coherent piece of it,\n", - " encapsulate the piece in a function and give it a name.\n", + "2. Как только программа заработает, выделите в ней связную часть, инкапсулируйте её в функции и дайте имя.\n", "\n", - "3. Generalize the function by adding appropriate parameters.\n", + "3. Обобщите функцию, добавив подходящие параметры.\n", "\n", - "4. Repeat Steps 1 to 3 until you have a set of working functions.\n", + "4. Повторяйте шаги 1–3, пока не получите набор рабочих функций.\n", "\n", - "5. Look for opportunities to improve the program by refactoring. For\n", - " example, if you have similar code in several places, consider\n", - " factoring it into an appropriately general function.\n", + "5. Ищите возможности улучшить программу рефакторингом. Например, если в нескольких местах есть похожий код, вынесите его в достаточно общую функцию.\n", "\n", - "This process has some drawbacks -- we will see alternatives later -- but it can be useful if you don't know ahead of time how to divide the program into functions.\n", - "This approach lets you design as you go along." + "У этого подхода есть недостатки — позже мы увидим другие варианты — но он полезен, когда заранее непонятно, как разделить программу на функции. Такой подход позволяет проектировать по ходу дела." ] }, { @@ -703,13 +663,13 @@ "id": "a3b6b83d", "metadata": {}, "source": [ - "The design of a function has two parts:\n", + "Проектирование функции состоит из двух частей:\n", "\n", - "* The **interface** is how the function is used, including its name, the parameters it takes and what the function is supposed to do.\n", + "* **Интерфейс** определяет, как функция используется: её имя, параметры и что она должна делать.\n", "\n", - "* The **implementation** is how the function does what it's supposed to do.\n", + "* **Реализация** описывает, как функция выполняет свою работу.\n", "\n", - "For example, here's the first version of `circle` we wrote, which uses `polygon`." + "Например, ниже приведена первая версия `circle`, которая использует `polygon`." ] }, { @@ -731,7 +691,7 @@ "id": "5d3d2e79", "metadata": {}, "source": [ - "And here's the refactored version that uses `arc`." + "А вот переработанная версия, которая использует `arc`." ] }, { @@ -750,7 +710,7 @@ "id": "b726f72c", "metadata": {}, "source": [ - "These two functions have the same interface -- they take the same parameters and do the same thing -- but they have different implementations." + "Эти две функции имеют одинаковый интерфейс — принимают одни и те же параметры и делают одно и то же, — но реализация у них разная." ] }, { @@ -760,10 +720,9 @@ "tags": [] }, "source": [ - "## Docstrings\n", + "## Докстроки\n", "\n", - "A **docstring** is a string at the beginning of a function that explains the interface (\"doc\" is short for \"documentation\").\n", - "Here is an example:" + "**Докстрока** — это строка в начале функции, которая объясняет её интерфейс («doc» сокращение от «documentation»). Вот пример:" ] }, { @@ -790,18 +749,17 @@ "id": "55b60cbc", "metadata": {}, "source": [ - "By convention, docstrings are triple-quoted strings, also known as **multiline strings** because the triple quotes allow the string to span more than one line.\n", + "По соглашению, докстроки записываются в тройных кавычках, поэтому их ещё называют **многострочными строками**, так как они могут занимать несколько строк.\n", "\n", - "A docstring should:\n", + "Докстрока должна:\n", "\n", - "* Explain concisely what the function does, without getting into the details of how it works,\n", + "* Кратко объяснять, что делает функция, не вдаваясь в детали реализации,\n", "\n", - "* Explain what effect each parameter has on the behavior of the function, and\n", + "* описывать, как каждый параметр влияет на поведение функции,\n", "\n", - "* Indicate what type each parameter should be, if it is not obvious.\n", + "* указывать тип каждого параметра, если это не очевидно.\n", "\n", - "Writing this kind of documentation is an important part of interface design.\n", - "A well-designed interface should be simple to explain; if you have a hard time explaining one of your functions, maybe the interface could be improved." + "Написание такой документации — важная часть проектирования интерфейса. Хорошо спроектированный интерфейс легко объяснить; если вам тяжело объяснить, что делает функция, возможно, интерфейс стоит улучшить." ] }, { @@ -809,20 +767,17 @@ "id": "f1115940", "metadata": {}, "source": [ - "## Debugging\n", + "## Отладка\n", "\n", - "An interface is like a contract between a function and a caller. The\n", - "caller agrees to provide certain arguments and the function agrees to\n", - "do certain work.\n", + "Интерфейс похож на контракт между функцией и вызывающей стороной. Вызывающий обещает предоставить определённые аргументы, а функция — выполнить определённую работу.\n", "\n", - "For example, `polyline` requires three arguments: `n` has to be an integer; `length` should be a positive number; and `angle` has to be a number, which is understood to be in degrees.\n", + "Например, `polyline` требует три аргумента: `n` должно быть целым числом; `length` — положительным числом; `angle` — числом, подразумевается градусная мера.\n", "\n", - "These requirements are called **preconditions** because they are supposed to be true before the function starts executing. Conversely, conditions at the end of the function are **postconditions**.\n", - "Postconditions include the intended effect of the function (like drawing line segments) and any side effects (like moving the turtle or making other changes).\n", + "Эти требования называют **предусловиями**, потому что они должны выполняться до начала работы функции. Соответственно, условия на момент её окончания — **постусловия**. Постусловия описывают предполагаемый эффект функции (например, рисование отрезков) и возможные побочные эффекты (например, перемещение черепахи или другие изменения).\n", "\n", - "Preconditions are the responsibility of the caller. If the caller violates a precondition and the function doesn't work correctly, the bug is in the caller, not the function.\n", + "Предусловия лежат на ответственности вызывающей стороны. Если она их нарушает и функция работает неправильно, ошибка в вызывающем коде, а не в функции.\n", "\n", - "If the preconditions are satisfied and the postconditions are not, the bug is in the function. If your pre- and postconditions are clear, they can help with debugging." + "Если предусловия выполнены, а постусловия — нет, ошибка в функции. Чёткие предусловия и постусловия помогают при отладке." ] }, { @@ -830,40 +785,29 @@ "id": "a4d33a70", "metadata": {}, "source": [ - "## Glossary\n", + "## Словарь\n", "\n", - "**interface design:**\n", - "A process for designing the interface of a function, which includes the parameters it should take.\n", + "**interface design:** Процесс проектирования интерфейса функции, включающий определение параметров, которые она должна принимать.\n", "\n", - "**canvas:**\n", - "A window used to display graphical elements including lines, circles, rectangles, and other shapes.\n", + "**canvas:** Окно для отображения графических элементов, включая линии, окружности, прямоугольники и другие фигуры.\n", "\n", - "**encapsulation:**\n", - " The process of transforming a sequence of statements into a function definition.\n", + "**encapsulation:** Процесс превращения последовательности операторов в определение функции.\n", "\n", - "**generalization:**\n", - " The process of replacing something unnecessarily specific (like a number) with something appropriately general (like a variable or parameter).\n", + "**generalization:** Процесс замены чего-то излишне конкретного (например, числа) на что-то более общее (например, переменную или параметр).\n", "\n", - "**keyword argument:**\n", - "An argument that includes the name of the parameter.\n", + "**keyword argument:** Аргумент, в котором указано имя параметра.\n", "\n", - "**refactoring:**\n", - " The process of modifying a working program to improve function interfaces and other qualities of the code.\n", + "**refactoring:** Процесс модификации работающей программы для улучшения интерфейсов функций и других свойств кода.\n", "\n", - "**development plan:**\n", - "A process for writing programs.\n", + "**development plan:** Процесс написания программ.\n", "\n", - "**docstring:**\n", - " A string that appears at the top of a function definition to document the function's interface.\n", + "**docstring:** Строка, расположенная в начале определения функции и документирующая её интерфейс.\n", "\n", - "**multiline string:**\n", - "A string enclosed in triple quotes that can span more than one line of a program.\n", + "**multiline string:** Строка в тройных кавычках, способная занимать несколько строк программы.\n", "\n", - "**precondition:**\n", - " A requirement that should be satisfied by the caller before a function starts.\n", + "**precondition:** Требование, которое должно выполняться вызывающей стороной до начала работы функции.\n", "\n", - "**postcondition:**\n", - " A requirement that should be satisfied by the function before it ends." + "**postcondition:** Требование, которое должно выполняться функцией перед завершением." ] }, { @@ -871,7 +815,7 @@ "id": "0bfe2e19", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -894,13 +838,13 @@ "id": "50ed5c38", "metadata": {}, "source": [ - "For the exercises below, there are a few more turtle functions you might want to use.\n", + "В следующих упражнениях могут пригодиться ещё несколько функций черепахи.\n", "\n", - "* `penup` lifts the turtle's imaginary pen so it doesn't leave a trail when it moves.\n", + "* `penup` поднимает воображаемое перо, чтобы при перемещении черепаха не оставляла след.\n", "\n", - "* `pendown` puts the pen back down.\n", + "* `pendown` опускает перо обратно.\n", "\n", - "The following function uses `penup` and `pendown` to move the turtle without leaving a trail." + "Следующая функция использует `penup` и `pendown`, чтобы переместить черепаху без следа." ] }, { @@ -927,10 +871,9 @@ "id": "c78c1e17", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `rectangle` that draws a rectangle with given side lengths.\n", - "For example, here's a rectangle that's `80` units wide and `40` units tall." + "Напишите функцию `rectangle`, которая рисует прямоугольник с заданной длиной сторон. Например, вот прямоугольник шириной `80` и высотой `40`." ] }, { @@ -950,7 +893,7 @@ "tags": [] }, "source": [ - "You can use the following code to test your function." + "Можете использовать следующий код, чтобы проверить свою функцию." ] }, { @@ -971,9 +914,9 @@ "id": "8b8faaf6", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `rhombus` that draws a rhombus with a given side length and a given interior angle. For example, here's a rhombus with side length `50` and an interior angle of `60` degrees." + "Напишите функцию `rhombus`, которая рисует ромб с заданной длиной стороны и заданным внутренним углом. Например, вот ромб со стороной `50` и внутренним углом `60` градусов." ] }, { @@ -993,7 +936,7 @@ "tags": [] }, "source": [ - "You can use the following code to test your function." + "Вы можете использовать следующий код для проверки функции." ] }, { @@ -1014,9 +957,9 @@ "id": "a9175a90", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Now write a more general function called `parallelogram` that draws a quadrilateral with parallel sides. Then rewrite `rectangle` and `rhombus` to use `parallelogram`." + "Теперь напишите более общую функцию `parallelogram`, которая рисует четырёхугольник с параллельными сторонами. Затем перепишите `rectangle` и `rhombus`, используя `parallelogram`." ] }, { @@ -1056,7 +999,7 @@ "tags": [] }, "source": [ - "You can use the following code to test your functions." + "Для проверки функций можно использовать следующий код." ] }, { @@ -1083,13 +1026,13 @@ "id": "991ab59d", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write an appropriately general set of functions that can draw shapes like this.\n", + "Напишите достаточно общий набор функций, который сможет рисовать такие фигуры.\n", "\n", "![](https://github.com/AllenDowney/ThinkPython/raw/v3/jupyturtle_pie.png)\n", "\n", - "Hint: Write a function called `triangle` that draws one triangular segment, and then a function called `draw_pie` that uses `triangle`." + "Подсказка: создайте функцию `triangle`, которая рисует один треугольный сегмент, а затем функцию `draw_pie`, использующую `triangle`." ] }, { @@ -1119,7 +1062,7 @@ "tags": [] }, "source": [ - "You can use the following code to test your functions." + "Можете использовать следующий код, чтобы протестировать свои функции." ] }, { @@ -1159,13 +1102,13 @@ "id": "9c78b76f", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write an appropriately general set of functions that can draw flowers like this.\n", + "Напишите достаточно общий набор функций, который сможет рисовать такие цветы.\n", "\n", "![](https://github.com/AllenDowney/ThinkPython/raw/v3/jupyturtle_flower.png)\n", "\n", - "Hint: Use `arc` to write a function called `petal` that draws one flower petal." + "Подсказка: используйте `arc`, чтобы написать функцию `petal`, рисующую один лепесток." ] }, { @@ -1195,12 +1138,7 @@ "tags": [] }, "source": [ - "You can use the following code to test your functions.\n", - "\n", - "Because the solution draws a lot of small line segments, it tends to slow down as it runs.\n", - "To avoid that, you can add the keyword argument `auto_render=False` to avoid drawing after every step, and then call the `render` function at the end to show the result.\n", - "\n", - "While you are debugging, you might want to remove `auto_render=False`." + "Вы можете использовать следующий код для проверки функций. Поскольку решение рисует много маленьких отрезков, оно со временем замедляется. Чтобы этого избежать, можно добавить именованный аргумент `auto_render=False`, чтобы не прорисовывать изображение после каждого шага, а затем вызвать функцию `render`, чтобы показать результат. Пока вы отлаживаете программу, `auto_render=False` можно убрать." ] }, { @@ -1248,36 +1186,9 @@ "id": "9d9f35d1", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", - "\n", - "There are several modules like `jupyturtle` in Python, and the one we used in this chapter has been customized for this book.\n", - "So if you ask a virtual assistant for help, it won't know which module to use.\n", - "But if you give it a few examples to work with, it can probably figure it out.\n", - "For example, try this prompt and see if it can write a function that draws a spiral:\n", - "\n", - "```\n", - "The following program uses a turtle graphics module to draw a circle:\n", - "\n", - "from jupyturtle import make_turtle, forward, left\n", - "import math\n", - "\n", - "def polygon(n, length):\n", - " angle = 360 / n\n", - " for i in range(n):\n", - " forward(length)\n", - " left(angle)\n", - " \n", - "def circle(radius):\n", - " circumference = 2 * math.pi * radius\n", - " n = 30\n", - " length = circumference / n\n", - " polygon(n, length)\n", - " \n", - "make_turtle(delay=0)\n", - "circle(30)\n", + "### Спросите виртуального ассистента\n", "\n", - "Write a function that draws a spiral.\n", - "```" + "В Python есть несколько модулей, похожих на `jupyturtle`, и тот, что мы использовали в этой главе, был адаптирован для этой книги. Поэтому, если вы попросите виртуального помощника о помощи, он может не знать, какой модуль применять. Но если привести пару примеров, он, вероятно, разберётся. Например, попробуйте такой запрос и посмотрите, сможет ли ассистент написать функцию, которая рисует спираль:" ] }, { @@ -1285,9 +1196,7 @@ "id": "7beb2afe", "metadata": {}, "source": [ - "Keep in mind that the result might use features we have not seen yet, and it might have errors.\n", - "Copy the code from the VA and see if you can get it working.\n", - "If you didn't get what you wanted, try modifying the prompt.\n" + "Имейте в виду, что в результате могут использоваться возможности, которые мы ещё не изучали, и что там могут быть ошибки. Скопируйте код от ассистента и попробуйте заставить его работать. Если результат вас не устроил, попробуйте изменить запрос." ] }, { From 2a7e1de9048e1413e762623bba3f1b5612a39d0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:47:25 +0300 Subject: [PATCH 35/44] Translate Chapter 6 notebook to Russian --- chapters/chap06.ipynb | 2017 +---------------------------------------- 1 file changed, 1 insertion(+), 2016 deletions(-) diff --git a/chapters/chap06.ipynb b/chapters/chap06.ipynb index a8d03c3..d6a1fa3 100644 --- a/chapters/chap06.ipynb +++ b/chapters/chap06.ipynb @@ -1,2016 +1 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "1331faa1", - "metadata": {}, - "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "56b1c184", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "from os.path import basename, exists\n", - "\n", - "def download(url):\n", - " filename = basename(url)\n", - " if not exists(filename):\n", - " from urllib.request import urlretrieve\n", - "\n", - " local, _ = urlretrieve(url, filename)\n", - " print(\"Downloaded \" + str(local))\n", - " return filename\n", - "\n", - "download('https://github.com/AllenDowney/ThinkPython/raw/v3/thinkpython.py');\n", - "download('https://github.com/AllenDowney/ThinkPython/raw/v3/diagram.py');\n", - "\n", - "import thinkpython" - ] - }, - { - "cell_type": "markdown", - "id": "88ecc443", - "metadata": {}, - "source": [ - "# Return Values\n", - "\n", - "In previous chapters, we've used built-in functions -- like `abs` and `round` -- and functions in the math module -- like `sqrt` and `pow`.\n", - "When you call one of these functions, it returns a value you can assign to a variable or use as part of an expression.\n", - "\n", - "The functions we have written so far are different.\n", - "Some use the `print` function to display values, and some use turtle functions to draw figures.\n", - "But they don't return values we assign to variables or use in expressions.\n", - "\n", - "In this chapter, we'll see how to write functions that return values." - ] - }, - { - "cell_type": "markdown", - "id": "6cf2cf80", - "metadata": {}, - "source": [ - "## Some functions have return values\n", - "\n", - "When you call a function like `math.sqrt`, the result is called a **return value**.\n", - "If the function call appears at the end of a cell, Jupyter displays the return value immediately." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "e0e1dd91", - "metadata": {}, - "outputs": [], - "source": [ - "import math\n", - "\n", - "math.sqrt(42 / math.pi)" - ] - }, - { - "cell_type": "markdown", - "id": "4b4885c2", - "metadata": {}, - "source": [ - "If you assign the return value to a variable, it doesn't get displayed." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "5aaf62d2", - "metadata": {}, - "outputs": [], - "source": [ - "radius = math.sqrt(42 / math.pi)" - ] - }, - { - "cell_type": "markdown", - "id": "196c692b", - "metadata": {}, - "source": [ - "But you can display it later." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "741f7386", - "metadata": {}, - "outputs": [], - "source": [ - "radius" - ] - }, - { - "cell_type": "markdown", - "id": "257b28d5", - "metadata": {}, - "source": [ - "Or you can use the return value as part of an expression." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "e56d39c4", - "metadata": {}, - "outputs": [], - "source": [ - "radius + math.sqrt(42 / math.pi)" - ] - }, - { - "cell_type": "markdown", - "id": "23ed47ab", - "metadata": {}, - "source": [ - "Here's an example of a function that returns a value." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "50a9a9be", - "metadata": {}, - "outputs": [], - "source": [ - "def circle_area(radius):\n", - " area = math.pi * radius**2\n", - " return area" - ] - }, - { - "cell_type": "markdown", - "id": "273acabc", - "metadata": {}, - "source": [ - "`circle_area` takes `radius` as a parameter and computes the area of a circle with that radius.\n", - "\n", - "The last line is a `return` statement that returns the value of `area`.\n", - "\n", - "If we call the function like this, Jupyter displays the return value.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "d70fd9b5", - "metadata": {}, - "outputs": [], - "source": [ - "circle_area(radius)" - ] - }, - { - "cell_type": "markdown", - "id": "4f28bfd6", - "metadata": {}, - "source": [ - "We can assign the return value to a variable." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "ef20ba8c", - "metadata": {}, - "outputs": [], - "source": [ - "a = circle_area(radius)" - ] - }, - { - "cell_type": "markdown", - "id": "3f82fe70", - "metadata": {}, - "source": [ - "Or use it as part of an expression." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "0a4670f4", - "metadata": {}, - "outputs": [], - "source": [ - "circle_area(radius) + 2 * circle_area(radius / 2)" - ] - }, - { - "cell_type": "markdown", - "id": "15122fd2", - "metadata": {}, - "source": [ - "Later we can display the value of the variable we assigned the result to." - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "6e6460b9", - "metadata": {}, - "outputs": [], - "source": [ - "a" - ] - }, - { - "cell_type": "markdown", - "id": "a3f6dcae", - "metadata": {}, - "source": [ - "But we can't access `area`." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "77613df9", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "%%expect NameError\n", - "\n", - "area" - ] - }, - { - "cell_type": "markdown", - "id": "f8ace9ce", - "metadata": {}, - "source": [ - "`area` is a local variable in a function, so we can't access it from outside the function." - ] - }, - { - "cell_type": "markdown", - "id": "41a4f03f", - "metadata": {}, - "source": [ - "## And some have None\n", - "\n", - "If a function doesn't have a `return` statement, it returns `None`, which is a special value like `True` and `False`.\n", - "For example, here's the `repeat` function from Chapter 3." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "89c083f8", - "metadata": {}, - "outputs": [], - "source": [ - "def repeat(word, n):\n", - " print(word * n)" - ] - }, - { - "cell_type": "markdown", - "id": "6ada19cf", - "metadata": {}, - "source": [ - "If we call it like this, it displays the first line of the Monty Python song \"Finland\"." - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "737b67ca", - "metadata": {}, - "outputs": [], - "source": [ - "repeat('Finland, ', 3)" - ] - }, - { - "cell_type": "markdown", - "id": "fe49f5e5", - "metadata": {}, - "source": [ - "This function uses the `print` function to display a string, but it does not use a `return` statement to return a value.\n", - "If we assign the result to a variable, it displays the string anyway. " - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "9b4fa14f", - "metadata": {}, - "outputs": [], - "source": [ - "result = repeat('Finland, ', 3)" - ] - }, - { - "cell_type": "markdown", - "id": "4ecabbdb", - "metadata": {}, - "source": [ - "And if we display the value of the variable, we get nothing." - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "50f96bcb", - "metadata": {}, - "outputs": [], - "source": [ - "result" - ] - }, - { - "cell_type": "markdown", - "id": "07033959", - "metadata": {}, - "source": [ - "`result` actually has a value, but Jupyter doesn't show it.\n", - "However, we can display it like this." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "6712f2df", - "metadata": {}, - "outputs": [], - "source": [ - "print(result)" - ] - }, - { - "cell_type": "markdown", - "id": "379b98c5", - "metadata": {}, - "source": [ - "The return value from `repeat` is `None`.\n", - "\n", - "Now here's a function similar to `repeat` except that has a return value." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "0ec1afd3", - "metadata": {}, - "outputs": [], - "source": [ - "def repeat_string(word, n):\n", - " return word * n" - ] - }, - { - "cell_type": "markdown", - "id": "db6ad3d4", - "metadata": {}, - "source": [ - "Notice that we can use an expression in a `return` statement, not just a variable.\n", - "\n", - "With this version, we can assign the result to a variable.\n", - "When the function runs, it doesn't display anything." - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "c82334b6", - "metadata": {}, - "outputs": [], - "source": [ - "line = repeat_string('Spam, ', 4)" - ] - }, - { - "cell_type": "markdown", - "id": "1232cd8a", - "metadata": {}, - "source": [ - "But later we can display the value assigned to `line`." - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "595ec598", - "metadata": {}, - "outputs": [], - "source": [ - "line" - ] - }, - { - "cell_type": "markdown", - "id": "ae02c7d2", - "metadata": {}, - "source": [ - "A function like this is called a **pure function** because it doesn't display anything or have any other effect -- other than returning a value." - ] - }, - { - "cell_type": "markdown", - "id": "567ae734", - "metadata": {}, - "source": [ - "## Return values and conditionals\n", - "\n", - "If Python did not provide `abs`, we could write it like this." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "236c59e6", - "metadata": {}, - "outputs": [], - "source": [ - "def absolute_value(x):\n", - " if x < 0:\n", - " return -x\n", - " else:\n", - " return x" - ] - }, - { - "cell_type": "markdown", - "id": "ffd559b8", - "metadata": {}, - "source": [ - "If `x` is negative, the first `return` statement returns `-x` and the function ends immediately.\n", - "Otherwise, the second `return` statement returns `x` and the function ends.\n", - "So this function is correct.\n", - "\n", - "However, if you put `return` statements in a conditional, you have to make sure that every possible path through the program hits a `return` statement.\n", - "For example, here's an incorrect version of `absolute_value`." - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "2f60639c", - "metadata": {}, - "outputs": [], - "source": [ - "def absolute_value_wrong(x):\n", - " if x < 0:\n", - " return -x\n", - " if x > 0:\n", - " return x" - ] - }, - { - "cell_type": "markdown", - "id": "da3280ae", - "metadata": {}, - "source": [ - "Here's what happens if we call this function with `0` as an argument." - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "c9dae6c8", - "metadata": {}, - "outputs": [], - "source": [ - "absolute_value_wrong(0)" - ] - }, - { - "cell_type": "markdown", - "id": "5733f239", - "metadata": {}, - "source": [ - "We get nothing! Here's the problem: when `x` is `0`, neither condition is true, and the function ends without hitting a `return` statement, which means that the return value is `None`, so Jupyter displays nothing.\n", - "\n", - "As another example, here's a version of `absolute_value` with an extra `return` statement at the end." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "c8c4edee", - "metadata": {}, - "outputs": [], - "source": [ - "def absolute_value_extra_return(x):\n", - " if x < 0:\n", - " return -x\n", - " else:\n", - " return x\n", - " \n", - " return 'This is dead code'" - ] - }, - { - "cell_type": "markdown", - "id": "cf5486fd", - "metadata": {}, - "source": [ - "If `x` is negative, the first `return` statement runs and the function ends.\n", - "Otherwise the second `return` statement runs and the function ends.\n", - "Either way, we never get to the third `return` statement -- so it can never run.\n", - "\n", - "Code that can never run is called **dead code**.\n", - "In general, dead code doesn't do any harm, but it often indicates a misunderstanding, and it might be confusing to someone trying to understand the program." - ] - }, - { - "cell_type": "markdown", - "id": "68a6ae39", - "metadata": { - "tags": [] - }, - "source": [ - "## Incremental development\n", - "\n", - "As you write larger functions, you might find yourself spending more\n", - "time debugging.\n", - "To deal with increasingly complex programs, you might want to try **incremental development**, which is a way of adding and testing only a small amount of code at a time.\n", - "\n", - "As an example, suppose you want to find the distance between two points represented by the coordinates $(x_1, y_1)$ and $(x_2, y_2)$.\n", - "By the Pythagorean theorem, the distance is:\n", - "\n", - "$$\\mathrm{distance} = \\sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$$ \n", - "\n", - "The first step is to consider what a `distance` function should look like in Python -- that is, what are the inputs (parameters) and what is the output (return value)?\n", - "\n", - "For this function, the inputs are the coordinates of the points.\n", - "The return value is the distance.\n", - "Immediately you can write an outline of the function:" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "bbcab1ed", - "metadata": {}, - "outputs": [], - "source": [ - "def distance(x1, y1, x2, y2):\n", - " return 0.0" - ] - }, - { - "cell_type": "markdown", - "id": "7b384fcf", - "metadata": {}, - "source": [ - "This version doesn't compute distances yet -- it always returns zero.\n", - "But it is a complete function with a return value, which means that you can test it before you make it more complicated.\n", - "\n", - "To test the new function, we'll call it with sample arguments:" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "923d96db", - "metadata": {}, - "outputs": [], - "source": [ - "distance(1, 2, 4, 6)" - ] - }, - { - "cell_type": "markdown", - "id": "13a98096", - "metadata": {}, - "source": [ - "I chose these values so that the horizontal distance is `3` and the\n", - "vertical distance is `4`.\n", - "That way, the result is `5`, the hypotenuse of a `3-4-5` right triangle. When testing a function, it is useful to know the right answer.\n", - "\n", - "At this point we have confirmed that the function runs and returns a value, and we can start adding code to the body.\n", - "A good next step is to find the differences `x2 - x1` and `y2 - y1`. \n", - "Here's a version that stores those values in temporary variables and displays them." - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "9374cfe3", - "metadata": {}, - "outputs": [], - "source": [ - "def distance(x1, y1, x2, y2):\n", - " dx = x2 - x1\n", - " dy = y2 - y1\n", - " print('dx is', dx)\n", - " print('dy is', dy)\n", - " return 0.0" - ] - }, - { - "cell_type": "markdown", - "id": "c342a3bd", - "metadata": {}, - "source": [ - "If the function is working, it should display `dx is 3` and `dy is 4`.\n", - "If so, we know that the function is getting the right arguments and\n", - "performing the first computation correctly. If not, there are only a few\n", - "lines to check." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "405af839", - "metadata": {}, - "outputs": [], - "source": [ - "distance(1, 2, 4, 6)" - ] - }, - { - "cell_type": "markdown", - "id": "9424eca9", - "metadata": {}, - "source": [ - "Good so far. Next we compute the sum of squares of `dx` and `dy`:" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "e52b3b04", - "metadata": {}, - "outputs": [], - "source": [ - "def distance(x1, y1, x2, y2):\n", - " dx = x2 - x1\n", - " dy = y2 - y1\n", - " dsquared = dx**2 + dy**2\n", - " print('dsquared is: ', dsquared)\n", - " return 0.0" - ] - }, - { - "cell_type": "markdown", - "id": "e28262f9", - "metadata": {}, - "source": [ - "Again, we can run the function and check the output, which should be `25`. " - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "38eebbf3", - "metadata": {}, - "outputs": [], - "source": [ - "distance(1, 2, 4, 6)" - ] - }, - { - "cell_type": "markdown", - "id": "c09f0ddc", - "metadata": {}, - "source": [ - "Finally, we can use `math.sqrt` to compute the distance:" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "b4536ea0", - "metadata": {}, - "outputs": [], - "source": [ - "def distance(x1, y1, x2, y2):\n", - " dx = x2 - x1\n", - " dy = y2 - y1\n", - " dsquared = dx**2 + dy**2\n", - " result = math.sqrt(dsquared)\n", - " print(\"result is\", result)" - ] - }, - { - "cell_type": "markdown", - "id": "f27902ac", - "metadata": {}, - "source": [ - "And test it." - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "325efb93", - "metadata": {}, - "outputs": [], - "source": [ - "distance(1, 2, 4, 6)" - ] - }, - { - "cell_type": "markdown", - "id": "8ad2e626", - "metadata": {}, - "source": [ - "The result is correct, but this version of the function displays the result rather than returning it, so the return value is `None`.\n", - "\n", - "We can fix that by replacing the `print` function with a `return` statement." - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "3cd982ce", - "metadata": {}, - "outputs": [], - "source": [ - "def distance(x1, y1, x2, y2):\n", - " dx = x2 - x1\n", - " dy = y2 - y1\n", - " dsquared = dx**2 + dy**2\n", - " result = math.sqrt(dsquared)\n", - " return result" - ] - }, - { - "cell_type": "markdown", - "id": "f3a13a14", - "metadata": {}, - "source": [ - "This version of `distance` is a pure function.\n", - "If we call it like this, only the result is displayed." - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "c734f5b2", - "metadata": {}, - "outputs": [], - "source": [ - "distance(1, 2, 4, 6)" - ] - }, - { - "cell_type": "markdown", - "id": "7db8cf86", - "metadata": {}, - "source": [ - "And if we assign the result to a variable, nothing is displayed." - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "094a242f", - "metadata": {}, - "outputs": [], - "source": [ - "d = distance(1, 2, 4, 6)" - ] - }, - { - "cell_type": "markdown", - "id": "0c3b8829", - "metadata": {}, - "source": [ - "The `print` statements we wrote are useful for debugging, but once the function is working, we can remove them. \n", - "Code like that is called **scaffolding** because it is helpful for building the program but is not part of the final product.\n", - "\n", - "This example demonstrates incremental development.\n", - "The key aspects of this process are:\n", - "\n", - "1. Start with a working program, make small changes, and test after every change.\n", - "\n", - "2. Use variables to hold intermediate values so you can display and check them.\n", - "\n", - "3. Once the program is working, remove the scaffolding.\n", - "\n", - "At any point, if there is an error, you should have a good idea where it is.\n", - "Incremental development can save you a lot of debugging time." - ] - }, - { - "cell_type": "markdown", - "id": "3dd7514f", - "metadata": {}, - "source": [ - "## Boolean functions\n", - "\n", - "Functions can return the boolean values `True` and `False`, which is often convenient for encapsulating a complex test in a function.\n", - "For example, `is_divisible` checks whether `x` is divisible by `y` with no remainder." - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "64207948", - "metadata": {}, - "outputs": [], - "source": [ - "def is_divisible(x, y):\n", - " if x % y == 0:\n", - " return True\n", - " else:\n", - " return False" - ] - }, - { - "cell_type": "markdown", - "id": "f3a58afb", - "metadata": {}, - "source": [ - "Here's how we use it." - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "id": "c367cdae", - "metadata": {}, - "outputs": [], - "source": [ - "is_divisible(6, 4)" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "id": "837f4f95", - "metadata": {}, - "outputs": [], - "source": [ - "is_divisible(6, 3)" - ] - }, - { - "cell_type": "markdown", - "id": "e9103ece", - "metadata": {}, - "source": [ - "Inside the function, the result of the `==` operator is a boolean, so we can write the\n", - "function more concisely by returning it directly." - ] - }, - { - "cell_type": "code", - "execution_count": 42, - "id": "e411354f", - "metadata": {}, - "outputs": [], - "source": [ - "def is_divisible(x, y):\n", - " return x % y == 0" - ] - }, - { - "cell_type": "markdown", - "id": "4d82dae5", - "metadata": {}, - "source": [ - "Boolean functions are often used in conditional statements." - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "id": "925e7d4f", - "metadata": {}, - "outputs": [], - "source": [ - "if is_divisible(6, 2):\n", - " print('divisible')" - ] - }, - { - "cell_type": "markdown", - "id": "9e232afc", - "metadata": {}, - "source": [ - "It might be tempting to write something like this:" - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "id": "62178e75", - "metadata": {}, - "outputs": [], - "source": [ - "if is_divisible(6, 2) == True:\n", - " print('divisible')" - ] - }, - { - "cell_type": "markdown", - "id": "ff9e5160", - "metadata": {}, - "source": [ - "But the comparison is unnecessary." - ] - }, - { - "cell_type": "markdown", - "id": "a932a966", - "metadata": {}, - "source": [ - "## Recursion with return values\n", - "\n", - "Now that we can write functions with return values, we can write recursive functions with return values, and with that capability, we have passed an important threshold -- the subset of Python we have is now **Turing complete**, which means that we can perform any computation that can be described by an algorithm.\n", - "\n", - "To demonstrate recursion with return values, we'll evaluate a few recursively defined mathematical functions.\n", - "A recursive definition is similar to a circular definition, in the sense that the definition refers to the thing being defined. A truly circular definition is not very useful:\n", - "\n", - "> vorpal: An adjective used to describe something that is vorpal.\n", - "\n", - "If you saw that definition in the dictionary, you might be annoyed. \n", - "On the other hand, if you looked up the definition of the factorial function, denoted with the symbol $!$, you might get something like this: \n", - "\n", - "$$\\begin{aligned}\n", - "0! &= 1 \\\\\n", - "n! &= n~(n-1)!\n", - "\\end{aligned}$$ \n", - "\n", - "This definition says that the factorial of $0$ is $1$, and the factorial of any other value, $n$, is $n$ multiplied by the factorial of $n-1$.\n", - "\n", - "If you can write a recursive definition of something, you can write a Python program to evaluate it. \n", - "Following an incremental development process, we'll start with a function that take `n` as a parameter and always returns `0`." - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "id": "23e37c79", - "metadata": {}, - "outputs": [], - "source": [ - "def factorial(n):\n", - " return 0" - ] - }, - { - "cell_type": "markdown", - "id": "ee1f63b8", - "metadata": {}, - "source": [ - "Now let's add the first part of the definition -- if the argument happens to be `0`, all we have to do is return `1`:" - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "id": "5ea57d9f", - "metadata": {}, - "outputs": [], - "source": [ - "def factorial(n):\n", - " if n == 0:\n", - " return 1\n", - " else:\n", - " return 0" - ] - }, - { - "cell_type": "markdown", - "id": "4f2fd7c7", - "metadata": {}, - "source": [ - "Now let's fill in the second part -- if `n` is not `0`, we have to make a recursive\n", - "call to find the factorial of `n-1` and then multiply the result by `n`:" - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "id": "b66e670b", - "metadata": {}, - "outputs": [], - "source": [ - "def factorial(n):\n", - " if n == 0:\n", - " return 1\n", - " else:\n", - " recurse = factorial(n-1)\n", - " return n * recurse" - ] - }, - { - "cell_type": "markdown", - "id": "da3d1595", - "metadata": {}, - "source": [ - "The flow of execution for this program is similar to the flow of `countdown` in Chapter 5.\n", - "If we call `factorial` with the value `3`:\n", - "\n", - "Since `3` is not `0`, we take the second branch and calculate the factorial\n", - "of `n-1`\\...\n", - "\n", - "> Since `2` is not `0`, we take the second branch and calculate the\n", - "> factorial of `n-1`\\...\n", - ">\n", - "> > Since `1` is not `0`, we take the second branch and calculate the\n", - "> > factorial of `n-1`\\...\n", - "> >\n", - "> > > Since `0` equals `0`, we take the first branch and return `1` without\n", - "> > > making any more recursive calls.\n", - "> >\n", - "> > The return value, `1`, is multiplied by `n`, which is `1`, and the\n", - "> > result is returned.\n", - ">\n", - "> The return value, `1`, is multiplied by `n`, which is `2`, and the result\n", - "> is returned.\n", - "\n", - "The return value `2` is multiplied by `n`, which is `3`, and the result,\n", - "`6`, becomes the return value of the function call that started the whole\n", - "process.\n", - "\n", - "The following figure shows the stack diagram for this sequence of function calls." - ] - }, - { - "cell_type": "code", - "execution_count": 48, - "id": "455f0457", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "from diagram import Frame, Stack, make_binding\n", - "\n", - "main = Frame([], name='__main__', loc='left')\n", - "frames = [main]\n", - "\n", - "ns = 3, 2, 1\n", - "recurses = 2, 1, 1\n", - "results = 6, 2, 1\n", - "\n", - "for n, recurse, result in zip(ns, recurses, results):\n", - " binding1 = make_binding('n', n)\n", - " binding2 = make_binding('recurse', recurse)\n", - " frame = Frame([binding1, binding2], \n", - " name='factorial', value=result,\n", - " loc='left', dx=1.2)\n", - " frames.append(frame)\n", - " \n", - "binding1 = make_binding('n', 0)\n", - "frame = Frame([binding1], name='factorial', value=1, \n", - " shim=1.2, loc='left', dx=1.4)\n", - "frames.append(frame)\n", - "\n", - "stack = Stack(frames, dy=-0.45)" - ] - }, - { - "cell_type": "code", - "execution_count": 49, - "id": "a75ccd9b", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "from diagram import diagram, adjust\n", - "\n", - "width, height, x, y = [2.74, 2.26, 0.73, 2.05]\n", - "ax = diagram(width, height)\n", - "bbox = stack.draw(ax, x, y)\n", - "# adjust(x, y, bbox)" - ] - }, - { - "cell_type": "markdown", - "id": "f924c539", - "metadata": {}, - "source": [ - "The return values are shown being passed back up the stack.\n", - "In each frame, the return value is the product of `n` and `recurse`.\n", - "\n", - "In the last frame, the local variable `recurse` does not exist because the branch that creates it does not run." - ] - }, - { - "cell_type": "markdown", - "id": "acea9dc1", - "metadata": {}, - "source": [ - "## Leap of faith\n", - "\n", - "Following the flow of execution is one way to read programs, but it can quickly become overwhelming. An alternative is what I call the \"leap of faith\". When you come to a function call, instead of following the flow of execution, you *assume* that the function works correctly and returns the right result.\n", - "\n", - "In fact, you are already practicing this leap of faith when you use built-in functions.\n", - "When you call `abs` or `math.sqrt`, you don't examine the bodies of those functions -- you just assume that they work.\n", - "\n", - "The same is true when you call one of your own functions. For example, earlier we wrote a function called `is_divisible` that determines whether one number is divisible by another. Once we convince ourselves that this function is correct, we can use it without looking at the body again.\n", - "\n", - "The same is true of recursive programs.\n", - "When you get to the recursive call, instead of following the flow of execution, you should assume that the recursive call works and then ask yourself, \"Assuming that I can compute the factorial of $n-1$, can I compute the factorial of $n$?\"\n", - "The recursive definition of factorial implies that you can, by multiplying by $n$.\n", - "\n", - "Of course, it's a bit strange to assume that the function works correctly when you haven't finished writing it, but that's why it's called a leap of faith!" - ] - }, - { - "cell_type": "markdown", - "id": "ca2a2d76", - "metadata": { - "tags": [] - }, - "source": [ - "## Fibonacci\n", - "\n", - "After `factorial`, the most common example of a recursive function is `fibonacci`, which has the following definition: \n", - "\n", - "$$\\begin{aligned}\n", - "\\mathrm{fibonacci}(0) &= 0 \\\\\n", - "\\mathrm{fibonacci}(1) &= 1 \\\\\n", - "\\mathrm{fibonacci}(n) &= \\mathrm{fibonacci}(n-1) + \\mathrm{fibonacci}(n-2)\n", - "\\end{aligned}$$ \n", - "\n", - "Translated into Python, it looks like this:" - ] - }, - { - "cell_type": "code", - "execution_count": 50, - "id": "cad75752", - "metadata": {}, - "outputs": [], - "source": [ - "def fibonacci(n):\n", - " if n == 0:\n", - " return 0\n", - " elif n == 1:\n", - " return 1\n", - " else:\n", - " return fibonacci(n-1) + fibonacci(n-2)" - ] - }, - { - "cell_type": "markdown", - "id": "69d56a0b", - "metadata": {}, - "source": [ - "If you try to follow the flow of execution here, even for small values of $n$, your head explodes.\n", - "But according to the leap of faith, if you assume that the two recursive calls work correctly, you can be confident that the last `return` statement is correct.\n", - "\n", - "As an aside, this way of computing Fibonacci numbers is very inefficient.\n", - "In [Chapter 10](section_memos) I'll explain why and suggest a way to improve it." - ] - }, - { - "cell_type": "markdown", - "id": "26d9706b", - "metadata": {}, - "source": [ - "## Checking types\n", - "\n", - "What happens if we call `factorial` and give it `1.5` as an argument?" - ] - }, - { - "cell_type": "code", - "execution_count": 51, - "id": "5e4b5f1d", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "%%expect RecursionError\n", - "\n", - "factorial(1.5)" - ] - }, - { - "cell_type": "markdown", - "id": "0bec7ba4", - "metadata": {}, - "source": [ - "It looks like an infinite recursion. How can that be? The function has base cases when `n == 1` or `n == 0`.\n", - "But if `n` is not an integer, we can *miss* the base case and recurse forever.\n", - "\n", - "In this example, the initial value of `n` is `1.5`.\n", - "In the first recursive call, the value of `n` is `0.5`.\n", - "In the next, it is `-0.5`. \n", - "From there, it gets smaller (more negative), but it will never be `0`.\n", - "\n", - "To avoid infinite recursion we can use the built-in function `isinstance` to check the type of the argument.\n", - "Here's how we check whether a value is an integer." - ] - }, - { - "cell_type": "code", - "execution_count": 52, - "id": "3f607dff", - "metadata": {}, - "outputs": [], - "source": [ - "isinstance(3, int)" - ] - }, - { - "cell_type": "code", - "execution_count": 53, - "id": "ab638bfe", - "metadata": {}, - "outputs": [], - "source": [ - "isinstance(1.5, int)" - ] - }, - { - "cell_type": "markdown", - "id": "b0017b42", - "metadata": {}, - "source": [ - "Now here's a version of `factorial` with error-checking." - ] - }, - { - "cell_type": "code", - "execution_count": 54, - "id": "73aafac0", - "metadata": {}, - "outputs": [], - "source": [ - "def factorial(n):\n", - " if not isinstance(n, int):\n", - " print('factorial is only defined for integers.')\n", - " return None\n", - " elif n < 0:\n", - " print('factorial is not defined for negative numbers.')\n", - " return None\n", - " elif n == 0:\n", - " return 1\n", - " else:\n", - " return n * factorial(n-1)" - ] - }, - { - "cell_type": "markdown", - "id": "0561e3f5", - "metadata": {}, - "source": [ - "First it checks whether `n` is an integer.\n", - "If not, it displays an error message and returns `None`.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": 55, - "id": "be881cb7", - "metadata": {}, - "outputs": [], - "source": [ - "factorial('crunchy frog')" - ] - }, - { - "cell_type": "markdown", - "id": "10b00a39", - "metadata": {}, - "source": [ - "Then it checks whether `n` is negative.\n", - "If so, it displays an error message and returns `None.`" - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "id": "fa83014f", - "metadata": {}, - "outputs": [], - "source": [ - "factorial(-2)" - ] - }, - { - "cell_type": "markdown", - "id": "96aa1403", - "metadata": {}, - "source": [ - "If we get past both checks, we know that `n` is a non-negative integer, so we can be confident the recursion will terminate.\n", - "Checking the parameters of a function to make sure they have the correct types and values is called **input validation**." - ] - }, - { - "cell_type": "markdown", - "id": "eb8a85a7", - "metadata": { - "tags": [] - }, - "source": [ - "## Debugging\n", - "\n", - "Breaking a large program into smaller functions creates natural checkpoints for debugging.\n", - "If a function is not working, there are three possibilities to consider:\n", - "\n", - "- There is something wrong with the arguments the function is getting -- that is, a precondition is violated.\n", - "\n", - "- There is something wrong with the function -- that is, a postcondition is violated.\n", - "\n", - "- The caller is doing something wrong with the return value.\n", - "\n", - "To rule out the first possibility, you can add a `print` statement at the beginning of the function that displays the values of the parameters (and maybe their types).\n", - "Or you can write code that checks the preconditions explicitly.\n", - "\n", - "If the parameters look good, you can add a `print` statement before each `return` statement and display the return value.\n", - "If possible, call the function with arguments that make it easy check the result. \n", - "\n", - "If the function seems to be working, look at the function call to make sure the return value is being used correctly -- or used at all!\n", - "\n", - "Adding `print` statements at the beginning and end of a function can help make the flow of execution more visible.\n", - "For example, here is a version of `factorial` with print statements:" - ] - }, - { - "cell_type": "code", - "execution_count": 57, - "id": "1d50479e", - "metadata": {}, - "outputs": [], - "source": [ - "def factorial(n):\n", - " space = ' ' * (4 * n)\n", - " print(space, 'factorial', n)\n", - " if n == 0:\n", - " print(space, 'returning 1')\n", - " return 1\n", - " else:\n", - " recurse = factorial(n-1)\n", - " result = n * recurse\n", - " print(space, 'returning', result)\n", - " return result" - ] - }, - { - "cell_type": "markdown", - "id": "0c044111", - "metadata": {}, - "source": [ - "`space` is a string of space characters that controls the indentation of\n", - "the output. Here is the result of `factorial(3)` :" - ] - }, - { - "cell_type": "code", - "execution_count": 58, - "id": "798db5c4", - "metadata": {}, - "outputs": [], - "source": [ - "factorial(3)" - ] - }, - { - "cell_type": "markdown", - "id": "43b3e408", - "metadata": {}, - "source": [ - "If you are confused about the flow of execution, this kind of output can be helpful.\n", - "It takes some time to develop effective scaffolding, but a little bit of scaffolding can save a lot of debugging." - ] - }, - { - "cell_type": "markdown", - "id": "b7c3962f", - "metadata": {}, - "source": [ - "## Glossary\n", - "\n", - "**return value:**\n", - "The result of a function. If a function call is used as an expression, the return value is the value of the expression.\n", - "\n", - "**pure function:**\n", - "A function that does not display anything or have any other effect, other than returning a return value.\n", - "\n", - "\n", - "**dead code:**\n", - "Part of a program that can never run, often because it appears after a `return` statement.\n", - "\n", - "**incremental development:**\n", - "A program development plan intended to avoid debugging by adding and testing only a small amount of code at a time.\n", - "\n", - "**scaffolding:**\n", - " Code that is used during program development but is not part of the final version.\n", - "\n", - "**Turing complete:**\n", - "A language, or subset of a language, is Turing complete if it can perform any computation that can be described by an algorithm.\n", - "\n", - "**input validation:**\n", - "Checking the parameters of a function to make sure they have the correct types and values" - ] - }, - { - "cell_type": "markdown", - "id": "ff7b1edf", - "metadata": {}, - "source": [ - "## Exercises" - ] - }, - { - "cell_type": "code", - "execution_count": 59, - "id": "e0f15ca4", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "# This cell tells Jupyter to provide detailed debugging information\n", - "# when a runtime error occurs. Run it before working on the exercises.\n", - "\n", - "%xmode Verbose" - ] - }, - { - "cell_type": "markdown", - "id": "0da2daaf", - "metadata": {}, - "source": [ - "### Ask a virtual assistant\n", - "\n", - "In this chapter, we saw an incorrect function that can end without returning a value." - ] - }, - { - "cell_type": "code", - "execution_count": 60, - "id": "90b4979f", - "metadata": {}, - "outputs": [], - "source": [ - "def absolute_value_wrong(x):\n", - " if x < 0:\n", - " return -x\n", - " if x > 0:\n", - " return x" - ] - }, - { - "cell_type": "markdown", - "id": "69563d4b", - "metadata": {}, - "source": [ - "And a version of the same function that has dead code at the end." - ] - }, - { - "cell_type": "code", - "execution_count": 61, - "id": "9217f038", - "metadata": {}, - "outputs": [], - "source": [ - "def absolute_value_extra_return(x):\n", - " if x < 0:\n", - " return -x\n", - " else:\n", - " return x\n", - " \n", - " return 'This is dead code.'" - ] - }, - { - "cell_type": "markdown", - "id": "9fe8ae2e", - "metadata": {}, - "source": [ - "And we saw the following example, which is correct but not idiomatic." - ] - }, - { - "cell_type": "code", - "execution_count": 62, - "id": "3168489b", - "metadata": {}, - "outputs": [], - "source": [ - "def is_divisible(x, y):\n", - " if x % y == 0:\n", - " return True\n", - " else:\n", - " return False" - ] - }, - { - "cell_type": "markdown", - "id": "14f52688", - "metadata": {}, - "source": [ - "Ask a virtual assistant what's wrong with each of these functions and see if it can spot the errors or improve the style.\n", - "\n", - "Then ask \"Write a function that takes coordinates of two points and computes the distance between them.\" See if the result resembles the version of `distance` we wrote in this chapter." - ] - }, - { - "cell_type": "markdown", - "id": "fd23bb60", - "metadata": {}, - "source": [ - "### Exercise\n", - "\n", - "Use incremental development to write a function called `hypot` that returns the length of the hypotenuse of a right triangle given the lengths of the other two legs as arguments.\n", - "\n", - "Note: There's a function in the math module called `hypot` that does the same thing, but you should not use it for this exercise!\n", - "\n", - "Even if you can write the function correctly on the first try, start with a function that always returns `0` and practice making small changes, testing as you go.\n", - "When you are done, the function should only return a value -- it should not display anything." - ] - }, - { - "cell_type": "code", - "execution_count": 63, - "id": "62267fa3", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "code", - "execution_count": 64, - "id": "5f8fa829", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "code", - "execution_count": 65, - "id": "3d129b03", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "code", - "execution_count": 66, - "id": "030179b6", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "code", - "execution_count": 67, - "id": "d737b468", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "code", - "execution_count": 68, - "id": "77a74879", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "code", - "execution_count": 69, - "id": "0521d267", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "code", - "execution_count": 70, - "id": "468a31e9", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "code", - "execution_count": 71, - "id": "abbe3ebf", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "code", - "execution_count": 72, - "id": "651295e4", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "markdown", - "id": "0a66d82a", - "metadata": {}, - "source": [ - "### Exercise\n", - "\n", - "Write a boolean function, `is_between(x, y, z)`, that returns `True` if $x < y < z$ or if \n", - "$z < y < x$, and`False` otherwise." - ] - }, - { - "cell_type": "code", - "execution_count": 73, - "id": "0a4ee482", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "markdown", - "id": "c12f318d", - "metadata": { - "tags": [] - }, - "source": [ - "You can use these examples to test your function." - ] - }, - { - "cell_type": "code", - "execution_count": 74, - "id": "956ed6d7", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "is_between(1, 2, 3) # should be True" - ] - }, - { - "cell_type": "code", - "execution_count": 75, - "id": "a994eaa6", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "is_between(3, 2, 1) # should be True" - ] - }, - { - "cell_type": "code", - "execution_count": 76, - "id": "4318028d", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "is_between(1, 3, 2) # should be False" - ] - }, - { - "cell_type": "code", - "execution_count": 77, - "id": "05208c8b", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "is_between(2, 3, 1) # should be False" - ] - }, - { - "cell_type": "markdown", - "id": "57f06466", - "metadata": {}, - "source": [ - "### Exercise\n", - "\n", - "The Ackermann function, $A(m, n)$, is defined:\n", - "\n", - "$$\\begin{aligned}\n", - "A(m, n) = \\begin{cases} \n", - " n+1 & \\mbox{if } m = 0 \\\\ \n", - " A(m-1, 1) & \\mbox{if } m > 0 \\mbox{ and } n = 0 \\\\ \n", - "A(m-1, A(m, n-1)) & \\mbox{if } m > 0 \\mbox{ and } n > 0.\n", - "\\end{cases} \n", - "\\end{aligned}$$ \n", - "\n", - "Write a function named `ackermann` that evaluates the Ackermann function.\n", - "What happens if you call `ackermann(5, 5)`?" - ] - }, - { - "cell_type": "code", - "execution_count": 78, - "id": "7eb85c5c", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "markdown", - "id": "85f7f614", - "metadata": { - "tags": [] - }, - "source": [ - "You can use these examples to test your function." - ] - }, - { - "cell_type": "code", - "execution_count": 79, - "id": "687a3e5a", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "ackermann(3, 2) # should be 29" - ] - }, - { - "cell_type": "code", - "execution_count": 80, - "id": "c49e9749", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "ackermann(3, 3) # should be 61" - ] - }, - { - "cell_type": "code", - "execution_count": 81, - "id": "8497dec4", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "ackermann(3, 4) # should be 125" - ] - }, - { - "cell_type": "markdown", - "id": "4994ceae", - "metadata": { - "tags": [] - }, - "source": [ - "If you call this function with values bigger than 4, you get a `RecursionError`." - ] - }, - { - "cell_type": "code", - "execution_count": 82, - "id": "76be4d15", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "%%expect RecursionError\n", - "\n", - "ackermann(5, 5)" - ] - }, - { - "cell_type": "markdown", - "id": "b8af1586", - "metadata": { - "tags": [] - }, - "source": [ - "To see why, add a print statement to the beginning of the function to display the values of the parameters, and then run the examples again." - ] - }, - { - "cell_type": "markdown", - "id": "7c2ac0a4", - "metadata": { - "tags": [] - }, - "source": [ - "### Exercise\n", - "\n", - "A number, $a$, is a power of $b$ if it is divisible by $b$ and $a/b$ is\n", - "a power of $b$. Write a function called `is_power` that takes parameters\n", - "`a` and `b` and returns `True` if `a` is a power of `b`. Note: you will\n", - "have to think about the base case." - ] - }, - { - "cell_type": "code", - "execution_count": 83, - "id": "0bcba5fe", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "markdown", - "id": "e93a0715", - "metadata": { - "tags": [] - }, - "source": [ - "You can use these examples to test your function." - ] - }, - { - "cell_type": "code", - "execution_count": 84, - "id": "4b6656e6", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "is_power(65536, 2) # should be True" - ] - }, - { - "cell_type": "code", - "execution_count": 85, - "id": "36d9e92a", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "is_power(27, 3) # should be True" - ] - }, - { - "cell_type": "code", - "execution_count": 86, - "id": "1d944b42", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "is_power(24, 2) # should be False" - ] - }, - { - "cell_type": "code", - "execution_count": 87, - "id": "63ec57c9", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "is_power(1, 17) # should be True" - ] - }, - { - "cell_type": "markdown", - "id": "a33bbd07", - "metadata": {}, - "source": [ - "### Exercise\n", - "\n", - "The greatest common divisor (GCD) of $a$ and $b$ is the largest number\n", - "that divides both of them with no remainder.\n", - "\n", - "One way to find the GCD of two numbers is based on the observation that\n", - "if $r$ is the remainder when $a$ is divided by $b$, then $gcd(a,\n", - "b) = gcd(b, r)$. As a base case, we can use $gcd(a, 0) = a$.\n", - "\n", - "Write a function called `gcd` that takes parameters `a` and `b` and\n", - "returns their greatest common divisor." - ] - }, - { - "cell_type": "code", - "execution_count": 88, - "id": "4e067bfb", - "metadata": {}, - "outputs": [], - "source": [ - "# Solution goes here" - ] - }, - { - "cell_type": "markdown", - "id": "efbebde9", - "metadata": { - "tags": [] - }, - "source": [ - "You can use these examples to test your function." - ] - }, - { - "cell_type": "code", - "execution_count": 89, - "id": "2a7c1c21", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "gcd(12, 8) # should be 4" - ] - }, - { - "cell_type": "code", - "execution_count": 90, - "id": "5df00229", - "metadata": { - "tags": [] - }, - "outputs": [], - "source": [ - "gcd(13, 17) # should be 1" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8bec38b3", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "a7f4edf8", - "metadata": { - "tags": [] - }, - "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", - "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", - "\n", - "Code license: [MIT License](https://mit-license.org/)\n", - "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" - ] - } - ], - "metadata": { - "celltoolbar": "Tags", - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.11" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} +{"cells": [{"cell_type": "markdown", "id": "1331faa1", "metadata": {}, "source": ["Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)."]}, {"cell_type": "code", "execution_count": 5, "id": "56b1c184", "metadata": {"tags": []}, "outputs": [], "source": ["from os.path import basename, exists\n", "\n", "def download(url):\n", " filename = basename(url)\n", " if not exists(filename):\n", " from urllib.request import urlretrieve\n", "\n", " local, _ = urlretrieve(url, filename)\n", " print(\"Downloaded \" + str(local))\n", " return filename\n", "\n", "download('https://github.com/AllenDowney/ThinkPython/raw/v3/thinkpython.py');\n", "download('https://github.com/AllenDowney/ThinkPython/raw/v3/diagram.py');\n", "\n", "import thinkpython"]}, {"cell_type": "markdown", "id": "88ecc443", "metadata": {}, "source": ["# Вернуть значения\n", "\n", "В предыдущих главах мы использовали встроенные функции-например, `abs` и `round`-и функции в математическом модуле-например, `sqrt` и `pow`.\n", "Когда вы называете одну из этих функций, он возвращает значение, которое вы можете присвоить переменной или использовать как часть выражения.\n", "\n", "Функции, которые мы написали до сих пор, разные.\n", "Некоторые используют функцию `print` для отображения значений, а некоторые используют функции черепахи для рисования фигур.\n", "Но они не возвращают значения, которые мы назначаем переменным или используем в выражениях.\n", "\n", "В этой главе мы посмотрим, как писать функции, которые возвращают значения."]}, {"cell_type": "markdown", "id": "6cf2cf80", "metadata": {}, "source": ["## Некоторые функции имеют возвратные значения\n", "\n", "Когда вы называете функцию, такую как `math.sqrt`, результат называется ** возвращающим значением **.\n", "Если вызов функции появляется в конце ячейки, Юпитер немедленно отображает возвратное значение."]}, {"cell_type": "code", "execution_count": 6, "id": "e0e1dd91", "metadata": {}, "outputs": [], "source": ["import math\n", "\n", "math.sqrt(42 / math.pi)"]}, {"cell_type": "markdown", "id": "4b4885c2", "metadata": {}, "source": ["Если вы назначаете возвратное значение переменной, оно не отображается."]}, {"cell_type": "code", "execution_count": 7, "id": "5aaf62d2", "metadata": {}, "outputs": [], "source": ["radius = math.sqrt(42 / math.pi)"]}, {"cell_type": "markdown", "id": "196c692b", "metadata": {}, "source": ["Но вы можете отобразить его позже."]}, {"cell_type": "code", "execution_count": 8, "id": "741f7386", "metadata": {}, "outputs": [], "source": ["radius"]}, {"cell_type": "markdown", "id": "257b28d5", "metadata": {}, "source": ["Или вы можете использовать возвратное значение как часть выражения."]}, {"cell_type": "code", "execution_count": 9, "id": "e56d39c4", "metadata": {}, "outputs": [], "source": ["radius + math.sqrt(42 / math.pi)"]}, {"cell_type": "markdown", "id": "23ed47ab", "metadata": {}, "source": ["Вот пример функции, которая возвращает значение."]}, {"cell_type": "code", "execution_count": 10, "id": "50a9a9be", "metadata": {}, "outputs": [], "source": ["def circle_area(radius):\n", " area = math.pi * radius**2\n", " return area"]}, {"cell_type": "markdown", "id": "273acabc", "metadata": {}, "source": ["`circle_area` принимает `radius` как параметр и вычисляет область круга с этим радиусом.\n", "\n", "Последняя строка - это оператор `return`, который возвращает значение `area`.\n", "\n", "Если мы называем функцию такой, Jupyter отображает возвратное значение."]}, {"cell_type": "code", "execution_count": 11, "id": "d70fd9b5", "metadata": {}, "outputs": [], "source": ["circle_area(radius)"]}, {"cell_type": "markdown", "id": "4f28bfd6", "metadata": {}, "source": ["Мы можем назначить возвращаемое значение переменной."]}, {"cell_type": "code", "execution_count": 12, "id": "ef20ba8c", "metadata": {}, "outputs": [], "source": ["a = circle_area(radius)"]}, {"cell_type": "markdown", "id": "3f82fe70", "metadata": {}, "source": ["Или используйте его как часть выражения."]}, {"cell_type": "code", "execution_count": 13, "id": "0a4670f4", "metadata": {}, "outputs": [], "source": ["circle_area(radius) + 2 * circle_area(radius / 2)"]}, {"cell_type": "markdown", "id": "15122fd2", "metadata": {}, "source": ["Позже мы можем отобразить значение переменной, которой мы присвоили результат."]}, {"cell_type": "code", "execution_count": 14, "id": "6e6460b9", "metadata": {}, "outputs": [], "source": ["a"]}, {"cell_type": "markdown", "id": "a3f6dcae", "metadata": {}, "source": ["Но мы не можем получить доступ `area`."]}, {"cell_type": "code", "execution_count": 15, "id": "77613df9", "metadata": {"tags": []}, "outputs": [], "source": ["%%expect NameError\n", "\n", "area"]}, {"cell_type": "markdown", "id": "f8ace9ce", "metadata": {}, "source": ["`area` является локальной переменной в функции, поэтому мы не можем получить к ней доступ извне функции."]}, {"cell_type": "markdown", "id": "41a4f03f", "metadata": {}, "source": ["##, а некоторые нет\n", "\n", "Если функция не имеет оператора `return`], она возвращает `None`, что является специальным значением, подобным `True` и `False`.\n", "Например, вот функция `repeat` из главы 3."]}, {"cell_type": "code", "execution_count": 16, "id": "89c083f8", "metadata": {}, "outputs": [], "source": ["def repeat(word, n):\n", " print(word * n)"]}, {"cell_type": "markdown", "id": "6ada19cf", "metadata": {}, "source": ["Если мы называем это так, он отображает первую строку песни Monty Python \"Finland\"."]}, {"cell_type": "code", "execution_count": 17, "id": "737b67ca", "metadata": {}, "outputs": [], "source": ["repeat('Finland, ', 3)"]}, {"cell_type": "markdown", "id": "fe49f5e5", "metadata": {}, "source": ["Эта функция использует функцию `print` для отображения строки, но она не использует оператор `return` для возврата значения.\n", "Если мы назначаем результат переменной, она в любом случае отображает строку."]}, {"cell_type": "code", "execution_count": 18, "id": "9b4fa14f", "metadata": {}, "outputs": [], "source": ["result = repeat('Finland, ', 3)"]}, {"cell_type": "markdown", "id": "4ecabbdb", "metadata": {}, "source": ["И если мы отобразим значение переменной, мы ничего не получим."]}, {"cell_type": "code", "execution_count": 19, "id": "50f96bcb", "metadata": {}, "outputs": [], "source": ["result"]}, {"cell_type": "markdown", "id": "07033959", "metadata": {}, "source": ["`result` на самом деле имеет значение, но Юпитер не показывает этого.\n", "Тем не менее, мы можем отобразить это так."]}, {"cell_type": "code", "execution_count": 20, "id": "6712f2df", "metadata": {}, "outputs": [], "source": ["print(result)"]}, {"cell_type": "markdown", "id": "379b98c5", "metadata": {}, "source": ["Возвратное значение из `repeat` составляет `None`.\n", "\n", "Теперь вот функция, похожая на `repeat`, за исключением того, что имеет возвращаемое значение."]}, {"cell_type": "code", "execution_count": 21, "id": "0ec1afd3", "metadata": {}, "outputs": [], "source": ["def repeat_string(word, n):\n", " return word * n"]}, {"cell_type": "markdown", "id": "db6ad3d4", "metadata": {}, "source": ["Обратите внимание, что мы можем использовать выражение в операторе `return`, а не просто переменной.\n", "\n", "С этой версией мы можем назначить результат переменной.\n", "Когда функция работает, она ничего не отображает."]}, {"cell_type": "code", "execution_count": 22, "id": "c82334b6", "metadata": {}, "outputs": [], "source": ["line = repeat_string('Spam, ', 4)"]}, {"cell_type": "markdown", "id": "1232cd8a", "metadata": {}, "source": ["Но позже мы можем отобразить значение, назначенное `line`."]}, {"cell_type": "code", "execution_count": 23, "id": "595ec598", "metadata": {}, "outputs": [], "source": ["line"]}, {"cell_type": "markdown", "id": "ae02c7d2", "metadata": {}, "source": ["Такая функция называется ** чистой функцией **, потому что она ничего не отображает или не имеет какого -либо другого эффекта - кроме возврата значения."]}, {"cell_type": "markdown", "id": "567ae734", "metadata": {}, "source": ["## возвращаемые значения и условия\n", "\n", "Если Python не предоставил `abs`, мы могли бы написать это так."]}, {"cell_type": "code", "execution_count": 24, "id": "236c59e6", "metadata": {}, "outputs": [], "source": ["def absolute_value(x):\n", " if x < 0:\n", " return -x\n", " else:\n", " return x"]}, {"cell_type": "markdown", "id": "ffd559b8", "metadata": {}, "source": ["Если `x` отрицательный, первый оператор `return` возвращает `-x`, а функция заканчивается немедленно.\n", "В противном случае, второй оператор `return` возвращает `x`, а функция заканчивается.\n", "Так что эта функция верна.\n", "\n", "Однако, если вы поместите операторы `return` в условные, вы должны убедиться, что каждый возможный путь через программу достигает оператора `return`.\n", "Например, вот неправильная версия `absolute_value`."]}, {"cell_type": "code", "execution_count": 25, "id": "2f60639c", "metadata": {}, "outputs": [], "source": ["def absolute_value_wrong(x):\n", " if x < 0:\n", " return -x\n", " if x > 0:\n", " return x"]}, {"cell_type": "markdown", "id": "da3280ae", "metadata": {}, "source": ["Вот что произойдет, если мы назваем эту функцию `0` в качестве аргумента."]}, {"cell_type": "code", "execution_count": 26, "id": "c9dae6c8", "metadata": {}, "outputs": [], "source": ["absolute_value_wrong(0)"]}, {"cell_type": "markdown", "id": "5733f239", "metadata": {}, "source": ["Мы ничего не получаем!Вот проблема: когда `x`] является `0`, ни одно условие не является истинной, и функция заканчивается без удара `return`] оператора, что означает, что возвратное значение `None`, поэтому Юпитер ничего не отображает.\n", "\n", "В качестве другого примера, вот версия `absolute_value` с дополнительным `return`] в конце."]}, {"cell_type": "code", "execution_count": 27, "id": "c8c4edee", "metadata": {}, "outputs": [], "source": ["def absolute_value_extra_return(x):\n", " if x < 0:\n", " return -x\n", " else:\n", " return x\n", " \n", " return 'This is dead code'"]}, {"cell_type": "markdown", "id": "cf5486fd", "metadata": {}, "source": ["Если `x` отрицательный, первый оператор `return` выполняется, а функция заканчивается.\n", "В противном случае второй оператор `return` работает, и функция заканчивается.\n", "В любом случае, мы никогда не доберемся до третьего оператора `return` - так что он никогда не может работать.\n", "\n", "Код, который никогда не может запустить, называется ** Dead Code **.\n", "В целом, мертвый код не причиняет никакого вреда, но часто указывает на недоразумение, и это может сбивать с толку, что кто -то пытается понять программу."]}, {"cell_type": "markdown", "id": "68a6ae39", "metadata": {"tags": []}, "source": ["## постепенное развитие\n", "\n", "Когда вы пишете большие функции, вы можете потратить больше\n", "время отладки.\n", "Чтобы справиться со все более сложными программами, вы, возможно, захотите попробовать ** инкрементную разработку **, что является способом добавления и тестирования лишь небольшого количества кода за раз.\n", "\n", "В качестве примера, предположим, вы хотите найти расстояние между двумя точками, представленными координатами $ (x_1, Y_1) $ и $ (x_2, y_2) $.\n", "По питагорской теореме расстояние:\n", "\n", "$$ \\ mathrm {distance} = \\ sqrt {(x_2 - x_1)^2 + (y_2 - y_1)^2} $$\n", "\n", "Первый шаг - рассмотреть, как должна выглядеть функция `distance`] в Python, то есть каковы входные данные (параметры) и каков выход (возвращаемое значение)?\n", "\n", "Для этой функции входные данные являются координатами точек.\n", "Возвратное значение - это расстояние.\n", "Сразу же вы можете написать схему функции:"]}, {"cell_type": "code", "execution_count": 28, "id": "bbcab1ed", "metadata": {}, "outputs": [], "source": ["def distance(x1, y1, x2, y2):\n", " return 0.0"]}, {"cell_type": "markdown", "id": "7b384fcf", "metadata": {}, "source": ["Эта версия пока не вычисляет расстояния - она всегда возвращает ноль.\n", "Но это полная функция с возвратом значения, что означает, что вы можете проверить ее, прежде чем сделать ее более сложной.\n", "\n", "Чтобы проверить новую функцию, мы будем называть ее примером аргументов:"]}, {"cell_type": "code", "execution_count": 29, "id": "923d96db", "metadata": {}, "outputs": [], "source": ["distance(1, 2, 4, 6)"]}, {"cell_type": "markdown", "id": "13a98096", "metadata": {}, "source": ["Я выбрал эти значения так, чтобы горизонтальное расстояние было `3` и\n", "Вертикальное расстояние `4`.\n", "Таким образом, результатом является `5`, гипотенуза `3-4-5` правого треугольника.При тестировании функции полезно знать правильный ответ.\n", "\n", "На этом этапе мы подтвердили, что функция работает и возвращает значение, и мы можем начать добавлять код в тело.\n", "Хороший следующий шаг - найти различия `x2 - x1` и `y2 - y1`.\n", "Вот версия, которая хранит эти значения во временных переменных и отображает их."]}, {"cell_type": "code", "execution_count": 30, "id": "9374cfe3", "metadata": {}, "outputs": [], "source": ["def distance(x1, y1, x2, y2):\n", " dx = x2 - x1\n", " dy = y2 - y1\n", " print('dx is', dx)\n", " print('dy is', dy)\n", " return 0.0"]}, {"cell_type": "markdown", "id": "c342a3bd", "metadata": {}, "source": ["Если функция работает, она должна отображать `dx is 3` и `dy is 4`.\n", "Если так, мы знаем, что функция получает правильные аргументы и\n", "Выполнение первого вычисления правильно.Если нет, то есть только несколько\n", "строки для проверки."]}, {"cell_type": "code", "execution_count": 31, "id": "405af839", "metadata": {}, "outputs": [], "source": ["distance(1, 2, 4, 6)"]}, {"cell_type": "markdown", "id": "9424eca9", "metadata": {}, "source": ["До сих пор хорошо.Затем мы рассчитываем сумму квадратов `dx` и `dy`:"]}, {"cell_type": "code", "execution_count": 32, "id": "e52b3b04", "metadata": {}, "outputs": [], "source": ["def distance(x1, y1, x2, y2):\n", " dx = x2 - x1\n", " dy = y2 - y1\n", " dsquared = dx**2 + dy**2\n", " print('dsquared is: ', dsquared)\n", " return 0.0"]}, {"cell_type": "markdown", "id": "e28262f9", "metadata": {}, "source": ["Опять же, мы можем запустить функцию и проверить выход, который должен быть `25`."]}, {"cell_type": "code", "execution_count": 33, "id": "38eebbf3", "metadata": {}, "outputs": [], "source": ["distance(1, 2, 4, 6)"]}, {"cell_type": "markdown", "id": "c09f0ddc", "metadata": {}, "source": ["Наконец, мы можем использовать `math.sqrt` для вычисления расстояния:"]}, {"cell_type": "code", "execution_count": 34, "id": "b4536ea0", "metadata": {}, "outputs": [], "source": ["def distance(x1, y1, x2, y2):\n", " dx = x2 - x1\n", " dy = y2 - y1\n", " dsquared = dx**2 + dy**2\n", " result = math.sqrt(dsquared)\n", " print(\"result is\", result)"]}, {"cell_type": "markdown", "id": "f27902ac", "metadata": {}, "source": ["И проверить это."]}, {"cell_type": "code", "execution_count": 35, "id": "325efb93", "metadata": {}, "outputs": [], "source": ["distance(1, 2, 4, 6)"]}, {"cell_type": "markdown", "id": "8ad2e626", "metadata": {}, "source": ["Результат верен, но эта версия функции отображает результат, а не возвращает его, поэтому возвращаемое значение `None`.\n", "\n", "Мы можем исправить это, заменив функцию `print`] оператором `return`]."]}, {"cell_type": "code", "execution_count": 36, "id": "3cd982ce", "metadata": {}, "outputs": [], "source": ["def distance(x1, y1, x2, y2):\n", " dx = x2 - x1\n", " dy = y2 - y1\n", " dsquared = dx**2 + dy**2\n", " result = math.sqrt(dsquared)\n", " return result"]}, {"cell_type": "markdown", "id": "f3a13a14", "metadata": {}, "source": ["Эта версия `distance` является чистой функцией.\n", "Если мы называем это так, отображается только результат."]}, {"cell_type": "code", "execution_count": 37, "id": "c734f5b2", "metadata": {}, "outputs": [], "source": ["distance(1, 2, 4, 6)"]}, {"cell_type": "markdown", "id": "7db8cf86", "metadata": {}, "source": ["И если мы назначаем результат переменной, ничего не отображается."]}, {"cell_type": "code", "execution_count": 38, "id": "094a242f", "metadata": {}, "outputs": [], "source": ["d = distance(1, 2, 4, 6)"]}, {"cell_type": "markdown", "id": "0c3b8829", "metadata": {}, "source": ["Утверждения `print`, которые мы написали, полезны для отладки, но как только функция работает, мы можем их удалить.\n", "Подобный код называется ** леса **, потому что он полезен для создания программы, но не является частью конечного продукта.\n", "\n", "Этот пример демонстрирует постепенное развитие.\n", "Ключевыми аспектами этого процесса являются:\n", "\n", "1. Начните с рабочей программы, внесите небольшие изменения и проверяйте после каждого изменения.\n", "\n", "2. Используйте переменные для сохранения промежуточных значений, чтобы вы могли отобразить и проверить их.\n", "\n", "3. Как только программа работает, удалите леса.\n", "\n", "В любой момент, если есть ошибка, у вас должна быть хорошая идея, где она находится.\n", "Польшемная разработка может сэкономить вам много времени отладки."]}, {"cell_type": "markdown", "id": "3dd7514f", "metadata": {}, "source": ["## логические функции\n", "\n", "Функции могут возвращать логические значения `True` и `False`, что часто удобно для инкапсулирования сложного теста в функцию.\n", "Например, `is_divisible` проверяет, делится ли `x` на `y` без остатков."]}, {"cell_type": "code", "execution_count": 39, "id": "64207948", "metadata": {}, "outputs": [], "source": ["def is_divisible(x, y):\n", " if x % y == 0:\n", " return True\n", " else:\n", " return False"]}, {"cell_type": "markdown", "id": "f3a58afb", "metadata": {}, "source": ["Вот как мы его используем."]}, {"cell_type": "code", "execution_count": 40, "id": "c367cdae", "metadata": {}, "outputs": [], "source": ["is_divisible(6, 4)"]}, {"cell_type": "code", "execution_count": 41, "id": "837f4f95", "metadata": {}, "outputs": [], "source": ["is_divisible(6, 3)"]}, {"cell_type": "markdown", "id": "e9103ece", "metadata": {}, "source": ["Внутри функции, результатом оператора `==`] является логический, поэтому мы можем написать\n", "функционируйте более кратко, возвращая его напрямую."]}, {"cell_type": "code", "execution_count": 42, "id": "e411354f", "metadata": {}, "outputs": [], "source": ["def is_divisible(x, y):\n", " return x % y == 0"]}, {"cell_type": "markdown", "id": "4d82dae5", "metadata": {}, "source": ["Логические функции часто используются в условных утверждениях."]}, {"cell_type": "code", "execution_count": 43, "id": "925e7d4f", "metadata": {}, "outputs": [], "source": ["if is_divisible(6, 2):\n", " print('divisible')"]}, {"cell_type": "markdown", "id": "9e232afc", "metadata": {}, "source": ["Может быть заманчиво написать что -то вроде этого:"]}, {"cell_type": "code", "execution_count": 44, "id": "62178e75", "metadata": {}, "outputs": [], "source": ["if is_divisible(6, 2) == True:\n", " print('divisible')"]}, {"cell_type": "markdown", "id": "ff9e5160", "metadata": {}, "source": ["Но сравнение не нужно."]}, {"cell_type": "markdown", "id": "a932a966", "metadata": {}, "source": ["## Recursion с возвращающими значениями\n", "\n", "Теперь, когда мы можем писать функции с возвращающимися значениями, мы можем писать рекурсивные функции с возвращающими значениями, и с этой способностью мы прошли важный порог - подмножество Python, которое у нас есть, является ** Turing **, что означает, что мы можем выполнить любые вычисления, которое может быть описано алгоритмом.\n", "\n", "Чтобы продемонстрировать рекурсию с возвратными значениями, мы оценим несколько рекурсивно определенных математических функций.\n", "Рекурсивное определение похоже на круговое определение, в том смысле, что определение относится к определению.По -настоящему круговое определение не очень полезно:\n", "\n", "> ВОРПОЛ: прилагательное, используемое для описания чего -то, что является Ворпольным.\n", "\n", "Если вы видели это определение в словаре, вы можете быть раздражены.\n", "С другой стороны, если вы посмотрите на определение факториальной функции, обозначенное символом $! $, Вы можете получить что -то вроде этого:\n", "\n", "$$ \\ begin {выровнен}\n", "0!& = 1 \\\\\n", "n!& = n ~ (n-1)!\n", "\\ end {выровнен} $$\n", "\n", "В этом определении говорится, что фактор в размере $ 0 $ составляет 1 доллар США, а фактор любой другой стоимости, $ n $,-это $ n $, умноженная на фактор $ N-1 $.\n", "\n", "Если вы можете написать рекурсивное определение чего -либо, вы можете написать программу Python, чтобы оценить ее.\n", "После постепенного процесса разработки мы начнем с функции, которая принимает `n` в качестве параметра и всегда возвращается `0`."]}, {"cell_type": "code", "execution_count": 45, "id": "23e37c79", "metadata": {}, "outputs": [], "source": ["def factorial(n):\n", " return 0"]}, {"cell_type": "markdown", "id": "ee1f63b8", "metadata": {}, "source": ["Теперь давайте добавим первую часть определения - если аргумент оказался `0`, все, что нам нужно сделать, это вернуть `1`:"]}, {"cell_type": "code", "execution_count": 46, "id": "5ea57d9f", "metadata": {}, "outputs": [], "source": ["def factorial(n):\n", " if n == 0:\n", " return 1\n", " else:\n", " return 0"]}, {"cell_type": "markdown", "id": "4f2fd7c7", "metadata": {}, "source": ["Теперь давайте заполним вторую часть - если `n` не является `0`, мы должны сделать рекурсивный\n", "Призовите, чтобы найти фактор `n-1`, а затем умножить результат на `n`:"]}, {"cell_type": "code", "execution_count": 47, "id": "b66e670b", "metadata": {}, "outputs": [], "source": ["def factorial(n):\n", " if n == 0:\n", " return 1\n", " else:\n", " recurse = factorial(n-1)\n", " return n * recurse"]}, {"cell_type": "markdown", "id": "da3d1595", "metadata": {}, "source": ["Поток выполнения для этой программы аналогичен потоку `countdown` в главе 5.\n", "Если мы позвоним `factorial` со значением `3`:\n", "\n", "Поскольку `3` не является `0`, мы принимаем вторую ветвь и рассчитываем фактор\n", "из `n-1` \\ ...\n", "\n", "> Поскольку `2` не является `0`, мы принимаем вторую ветвь и рассчитываем\n", "> Фактор `n-1` \\ ...\n", ">\n", ">> Поскольку `1` не является `0`, мы принимаем вторую ветвь и рассчитываем\n", ">> Фактор `n-1` \\ ...\n", ">>\n", ">>> Поскольку `0`] равняется `0`, мы принимаем первую ветвь и возвращаем `1` без\n", ">>> Создание еще рекурсивных вызовов.\n", ">>\n", ">> возвращаемое значение, `1`], умножается на `n`, что является `1` и\n", ">> Результат возвращается.\n", ">\n", "> Возвращаемое значение, `1`, умножается на `n`, что `2`, и результат\n", "> возвращается.\n", "\n", "Возвращаемое значение `2`] умножается на `n`, что `3`, и результат,\n", "`6`, становится возвращаемым значением вызова функции, который начал целое\n", "процесс.\n", "\n", "На следующем рисунке показана диаграмма стека для этой последовательности функций вызовов."]}, {"cell_type": "code", "execution_count": 48, "id": "455f0457", "metadata": {"tags": []}, "outputs": [], "source": ["from diagram import Frame, Stack, make_binding\n", "\n", "main = Frame([], name='__main__', loc='left')\n", "frames = [main]\n", "\n", "ns = 3, 2, 1\n", "recurses = 2, 1, 1\n", "results = 6, 2, 1\n", "\n", "for n, recurse, result in zip(ns, recurses, results):\n", " binding1 = make_binding('n', n)\n", " binding2 = make_binding('recurse', recurse)\n", " frame = Frame([binding1, binding2], \n", " name='factorial', value=result,\n", " loc='left', dx=1.2)\n", " frames.append(frame)\n", " \n", "binding1 = make_binding('n', 0)\n", "frame = Frame([binding1], name='factorial', value=1, \n", " shim=1.2, loc='left', dx=1.4)\n", "frames.append(frame)\n", "\n", "stack = Stack(frames, dy=-0.45)"]}, {"cell_type": "code", "execution_count": 49, "id": "a75ccd9b", "metadata": {"tags": []}, "outputs": [], "source": ["from diagram import diagram, adjust\n", "\n", "width, height, x, y = [2.74, 2.26, 0.73, 2.05]\n", "ax = diagram(width, height)\n", "bbox = stack.draw(ax, x, y)\n", "# adjust(x, y, bbox)"]}, {"cell_type": "markdown", "id": "f924c539", "metadata": {}, "source": ["Показаны возвращаемые значения, передаваемые обратно в стек.\n", "В каждом кадре возвратное значение является продуктом `n` и `recurse`.\n", "\n", "В последнем кадре локальная переменная `recurse` не существует, потому что ветвь, которая создает ее, не работает."]}, {"cell_type": "markdown", "id": "acea9dc1", "metadata": {}, "source": ["## прыжок веры\n", "\n", "Следуя потоку исполнения является одним из способов чтения программ, но он может быстро стать ошеломляющим.Альтернатива - это то, что я называю «прыжком веры».Когда вы приходите к вызову функции, вместо того, чтобы следить за потоком выполнения, вы * предполагаете *, что функция работает правильно и возвращает правильный результат.\n", "\n", "На самом деле, вы уже практикуете этот прыжок веры, когда используете встроенные функции.\n", "Когда вы звоните `abs` или `math.sqrt`, вы не изучаете тела этих функций - вы просто предполагаете, что они работают.\n", "\n", "То же самое верно, когда вы называете одну из своих собственных функций.Например, ранее мы написали функцию, называемую `is_divisible`, которая определяет, делится ли одно число на другое.Как только мы убедимся в том, что эта функция верна, мы можем использовать ее, не глядя на тело снова.\n", "\n", "То же самое относится и к рекурсивным программам.\n", "Когда вы добираетесь до рекурсивного вызова, вместо того, чтобы следить за потоком исполнения, вы должны предположить, что рекурсивный вызов работает, а затем спросить себя: «Предполагая, что я могу вычислить фактор $ n-1 $, могу ли я вычислить фактор $ n $?»\n", "Рекурсивное определение факториального подразумевает, что вы можете, умножив на $ n $.\n", "\n", "Конечно, немного странно предположить, что функция работает правильно, когда вы не закончили писать ее, но именно поэтому она называется прыжком веры!"]}, {"cell_type": "markdown", "id": "ca2a2d76", "metadata": {"tags": []}, "source": ["## Фибонааччи\n", "\n", "После `factorial` наиболее распространенным примером рекурсивной функции является `fibonacci`, который имеет следующее определение:\n", "\n", "$$ \\ begin {выровнен}\n", "\\ mathrm {fibonaci} (0) & = 0 \\\\\n", "\\ mathrm {fibonaci} (1) & = 1 \\\\\n", "\\ mathrm {fibonaci} (n) & = \\ mathrm {fibonacci} (n-1) + \\ mathrm {fibonaci} (n-2)\n", "\\ ennd {выровнен} $$\n", "\n", "Переведено на Python, выглядит так:"]}, {"cell_type": "code", "execution_count": 50, "id": "cad75752", "metadata": {}, "outputs": [], "source": ["def fibonacci(n):\n", " if n == 0:\n", " return 0\n", " elif n == 1:\n", " return 1\n", " else:\n", " return fibonacci(n-1) + fibonacci(n-2)"]}, {"cell_type": "markdown", "id": "69d56a0b", "metadata": {}, "source": ["Если вы попытаетесь следовать потоку выполнения здесь, даже для небольших значений $ n $, ваша голова взрывается.\n", "Но в соответствии с прыжком веры, если вы предполагаете, что два рекурсивных звонка работают правильно, вы можете быть уверены, что последнее утверждение `return` является правильным.\n", "\n", "Кроме того, этот способ вычисления чисел Фибоначчи очень неэффективен.\n", "В [Chapter 10](section_memos) я объясню, почему и предложу способ улучшить его."]}, {"cell_type": "markdown", "id": "26d9706b", "metadata": {}, "source": ["## Проверка типов\n", "\n", "Что произойдет, если мы позвоним `factorial` и дадим его `1.5` в качестве аргумента?"]}, {"cell_type": "code", "execution_count": 51, "id": "5e4b5f1d", "metadata": {"tags": []}, "outputs": [], "source": ["%%expect RecursionError\n", "\n", "factorial(1.5)"]}, {"cell_type": "markdown", "id": "0bec7ba4", "metadata": {}, "source": ["Это похоже на бесконечную рекурсию.Как это может быть?Функция имеет базовые случаи, когда `n == 1` или `n == 0`.\n", "Но если `n` не является целым числом, мы можем * пропустить * базовый случай и повторяться навсегда.\n", "\n", "В этом примере начальное значение `n` составляет `1.5`.\n", "В первом рекурсивном вызове значение `n` составляет `0.5`.\n", "В следующем, это `-0.5`.\n", "Оттуда он становится меньше (более отрицательно), но никогда не будет `0`.\n", "\n", "Чтобы избежать бесконечной рекурсии, мы можем использовать встроенную функцию `isinstance`, чтобы проверить тип аргумента.\n", "Вот как мы проверяем, является ли значение целым числом."]}, {"cell_type": "code", "execution_count": 52, "id": "3f607dff", "metadata": {}, "outputs": [], "source": ["isinstance(3, int)"]}, {"cell_type": "code", "execution_count": 53, "id": "ab638bfe", "metadata": {}, "outputs": [], "source": ["isinstance(1.5, int)"]}, {"cell_type": "markdown", "id": "b0017b42", "metadata": {}, "source": ["Теперь вот версия `factorial` с проверкой ошибок."]}, {"cell_type": "code", "execution_count": 54, "id": "73aafac0", "metadata": {}, "outputs": [], "source": ["def factorial(n):\n", " if not isinstance(n, int):\n", " print('factorial is only defined for integers.')\n", " return None\n", " elif n < 0:\n", " print('factorial is not defined for negative numbers.')\n", " return None\n", " elif n == 0:\n", " return 1\n", " else:\n", " return n * factorial(n-1)"]}, {"cell_type": "markdown", "id": "0561e3f5", "metadata": {}, "source": ["Сначала он проверяет, является ли `n` целым числом.\n", "Если нет, он отображает сообщение об ошибке и возвращает `None`."]}, {"cell_type": "code", "execution_count": 55, "id": "be881cb7", "metadata": {}, "outputs": [], "source": ["factorial('crunchy frog')"]}, {"cell_type": "markdown", "id": "10b00a39", "metadata": {}, "source": ["Затем он проверяет, является ли отрицательным.\n", "Если так, он отображает сообщение об ошибке и возвращает `None.`"]}, {"cell_type": "code", "execution_count": 56, "id": "fa83014f", "metadata": {}, "outputs": [], "source": ["factorial(-2)"]}, {"cell_type": "markdown", "id": "96aa1403", "metadata": {}, "source": ["Если мы пройдем оба чека, мы знаем, что `n` является неотрицательным целым числом, поэтому мы можем быть уверены, что рекурсия прекратится.\n", "Проверка параметров функции, чтобы убедиться, что они имеют правильные типы и значения, называются ** Входная проверка **."]}, {"cell_type": "markdown", "id": "eb8a85a7", "metadata": {"tags": []}, "source": ["## отладка\n", "\n", "Разрыв большой программы на более мелкие функции создает естественные контрольные точки для отладки.\n", "Если функция не работает, есть три возможности для рассмотрения:\n", "\n", "- Что -то не так с аргументами, которые выполняет функция, то есть предварительное условие нарушается.\n", "\n", "- Что -то не так с этой функцией, то есть пост -кондиционирование нарушается.\n", "\n", "- Абонент делает что -то не так с возвратной стоимостью.\n", "\n", "Чтобы исключить первую возможность, вы можете добавить оператор `print` в начале функции, которая отображает значения параметров (и, возможно, их типы).\n", "Или вы можете написать код, который явно проверяет предпосылки.\n", "\n", "Если параметры выглядят хорошо, вы можете добавить оператор `print` перед каждым оператором `return` и отобразить возвращаемое значение.\n", "Если возможно, вызовите функцию с аргументами, которые позволяют легко проверить результат.\n", "\n", "Если функция, кажется, работает, посмотрите на вызов функции, чтобы убедиться, что возвращаемое значение используется правильно - или вообще используется!\n", "\n", "Добавление операторов `print` в начале и конце функции может помочь сделать поток выполнения более заметным.\n", "Например, вот версия `factorial` с печатными операторами:"]}, {"cell_type": "code", "execution_count": 57, "id": "1d50479e", "metadata": {}, "outputs": [], "source": ["def factorial(n):\n", " space = ' ' * (4 * n)\n", " print(space, 'factorial', n)\n", " if n == 0:\n", " print(space, 'returning 1')\n", " return 1\n", " else:\n", " recurse = factorial(n-1)\n", " result = n * recurse\n", " print(space, 'returning', result)\n", " return result"]}, {"cell_type": "markdown", "id": "0c044111", "metadata": {}, "source": ["`space` - это строка космических символов, которая управляет отступом\n", "вывод.Вот результат `factorial(3)`:"]}, {"cell_type": "code", "execution_count": 58, "id": "798db5c4", "metadata": {}, "outputs": [], "source": ["factorial(3)"]}, {"cell_type": "markdown", "id": "43b3e408", "metadata": {}, "source": ["Если вы смущены потоком выполнения, этот вид выводов может быть полезным.\n", "Требуется некоторое время, чтобы разработать эффективные леса, но немного лесов может сэкономить много отладки."]}, {"cell_type": "markdown", "id": "b7c3962f", "metadata": {}, "source": ["## Глоссарий\n", "\n", "** возвращаемое значение: **\n", "Результат функции.Если вызов функции используется в качестве выражения, возвращаемое значение - это значение выражения.\n", "\n", "** Чистая функция: **\n", "Функция, которая ничего не отображает или не имеет какого -либо другого эффекта, кроме возврата возвращаемого значения.\n", "\n", "\n", "** Мертвый код: **\n", "Часть программы, которая никогда не может работать, часто потому, что она появляется после оператора `return`.\n", "\n", "** Дополнительное развитие: **\n", "План разработки программы, предназначенный для того, чтобы избежать отладки путем добавления и тестирования лишь небольшого количества кода за раз.\n", "\n", "** Строительные леса: **\n", "Код, который используется во время разработки программы, но не является частью окончательной версии.\n", "\n", "** Turing Complete: **\n", "Язык, или подмножество языка, является полным, если он может выполнить любые вычисления, которые могут быть описаны алгоритмом.\n", "\n", "** Входная проверка: **\n", "Проверка параметров функции, чтобы убедиться, что они имеют правильные типы и значения"]}, {"cell_type": "markdown", "id": "ff7b1edf", "metadata": {}, "source": ["## Упражнения"]}, {"cell_type": "code", "execution_count": 59, "id": "e0f15ca4", "metadata": {"tags": []}, "outputs": [], "source": ["# This cell tells Jupyter to provide detailed debugging information\n", "# when a runtime error occurs. Run it before working on the exercises.\n", "\n", "%xmode Verbose"]}, {"cell_type": "markdown", "id": "0da2daaf", "metadata": {}, "source": ["### Спросите виртуального помощника\n", "\n", "В этой главе мы увидели неверную функцию, которая может закончиться без возврата значения."]}, {"cell_type": "code", "execution_count": 60, "id": "90b4979f", "metadata": {}, "outputs": [], "source": ["def absolute_value_wrong(x):\n", " if x < 0:\n", " return -x\n", " if x > 0:\n", " return x"]}, {"cell_type": "markdown", "id": "69563d4b", "metadata": {}, "source": ["И версия той же функции, которая имеет мертвый код в конце."]}, {"cell_type": "code", "execution_count": 61, "id": "9217f038", "metadata": {}, "outputs": [], "source": ["def absolute_value_extra_return(x):\n", " if x < 0:\n", " return -x\n", " else:\n", " return x\n", " \n", " return 'This is dead code.'"]}, {"cell_type": "markdown", "id": "9fe8ae2e", "metadata": {}, "source": ["И мы увидели следующий пример, который является правильным, но не идиоматическим."]}, {"cell_type": "code", "execution_count": 62, "id": "3168489b", "metadata": {}, "outputs": [], "source": ["def is_divisible(x, y):\n", " if x % y == 0:\n", " return True\n", " else:\n", " return False"]}, {"cell_type": "markdown", "id": "14f52688", "metadata": {}, "source": ["Спросите виртуального помощника, что не так с каждой из этих функций, и посмотрите, сможет ли он заметить ошибки или улучшить стиль.\n", "\n", "Затем спросите: «Напишите функцию, которая принимает координаты из двух точек и вычисляет расстояние между ними».Посмотрите, напоминает ли результат версию `distance` мы написали в этой главе."]}, {"cell_type": "markdown", "id": "fd23bb60", "metadata": {}, "source": ["### Упражнение\n", "\n", "Используйте инкрементное развитие, чтобы написать функцию, называемую `hypot`, которая возвращает длину гипотенузы правого треугольника, учитывая длину двух других ног в качестве аргументов.\n", "\n", "Примечание. В математическом модуле есть функция, которая называется `hypot`, которая делает то же самое, но вы не должны использовать ее для этого упражнения!\n", "\n", "Даже если вы можете правильно написать функцию с первой попытки, начните с функции, которая всегда возвращает `0` и практикуйте небольшие изменения, тестируя по мере продвижения.\n", "Когда вы закончите, функция должна только возвращать значение - она не должна отображать ничего."]}, {"cell_type": "code", "execution_count": 63, "id": "62267fa3", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "code", "execution_count": 64, "id": "5f8fa829", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "code", "execution_count": 65, "id": "3d129b03", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "code", "execution_count": 66, "id": "030179b6", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "code", "execution_count": 67, "id": "d737b468", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "code", "execution_count": 68, "id": "77a74879", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "code", "execution_count": 69, "id": "0521d267", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "code", "execution_count": 70, "id": "468a31e9", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "code", "execution_count": 71, "id": "abbe3ebf", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "code", "execution_count": 72, "id": "651295e4", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "markdown", "id": "0a66d82a", "metadata": {}, "source": ["### Упражнение\n", "\n", "Напишите логическую функцию, `is_between(x, y, z)`, которая возвращается `True`, если $ x 0 \\ mbox {и} n = 0 \\\\\n", "A (m-1, a (m, n-1)) & \\ mbox {if} m> 0 \\ mbox {и} n> 0.\n", "\\ end {случаи}\n", "\\ end {выровнен} $$\n", "\n", "Напишите функцию с именем `ackermann`, которая оценивает функцию Ackermann.\n", "Что произойдет, если вы позвоните `ackermann(5, 5)`?"]}, {"cell_type": "code", "execution_count": 78, "id": "7eb85c5c", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "markdown", "id": "85f7f614", "metadata": {"tags": []}, "source": ["Вы можете использовать эти примеры для проверки вашей функции."]}, {"cell_type": "code", "execution_count": 79, "id": "687a3e5a", "metadata": {"tags": []}, "outputs": [], "source": ["ackermann(3, 2) # should be 29"]}, {"cell_type": "code", "execution_count": 80, "id": "c49e9749", "metadata": {"tags": []}, "outputs": [], "source": ["ackermann(3, 3) # should be 61"]}, {"cell_type": "code", "execution_count": 81, "id": "8497dec4", "metadata": {"tags": []}, "outputs": [], "source": ["ackermann(3, 4) # should be 125"]}, {"cell_type": "markdown", "id": "4994ceae", "metadata": {"tags": []}, "source": ["Если вы называете эту функцию со значениями больше 4, вы получите `RecursionError`."]}, {"cell_type": "code", "execution_count": 82, "id": "76be4d15", "metadata": {"tags": []}, "outputs": [], "source": ["%%expect RecursionError\n", "\n", "ackermann(5, 5)"]}, {"cell_type": "markdown", "id": "b8af1586", "metadata": {"tags": []}, "source": ["Чтобы понять почему, добавьте оператор печати в начало функции, чтобы отобразить значения параметров, а затем снова запустите примеры."]}, {"cell_type": "markdown", "id": "7c2ac0a4", "metadata": {"tags": []}, "source": ["### Упражнение\n", "\n", "Число, $ a $, является силой $ b $, если он делится на $ b $, а $ a/b $\n", "Сила $ b $.Напишите функцию с названием `is_power`, которая принимает параметры\n", "`a` и `b` и возвращает `True`, если `a` является силой `b`].Примечание: вы будете\n", "нужно подумать о базовом случае."]}, {"cell_type": "code", "execution_count": 83, "id": "0bcba5fe", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "markdown", "id": "e93a0715", "metadata": {"tags": []}, "source": ["Вы можете использовать эти примеры для проверки вашей функции."]}, {"cell_type": "code", "execution_count": 84, "id": "4b6656e6", "metadata": {"tags": []}, "outputs": [], "source": ["is_power(65536, 2) # should be True"]}, {"cell_type": "code", "execution_count": 85, "id": "36d9e92a", "metadata": {"tags": []}, "outputs": [], "source": ["is_power(27, 3) # should be True"]}, {"cell_type": "code", "execution_count": 86, "id": "1d944b42", "metadata": {"tags": []}, "outputs": [], "source": ["is_power(24, 2) # should be False"]}, {"cell_type": "code", "execution_count": 87, "id": "63ec57c9", "metadata": {"tags": []}, "outputs": [], "source": ["is_power(1, 17) # should be True"]}, {"cell_type": "markdown", "id": "a33bbd07", "metadata": {}, "source": ["### Упражнение\n", "\n", "Наибольший распространенный делитель (GCD) в размере $ A $ и $ B $ является наибольшим числом\n", "Это разделяет их обоих без остатков.\n", "\n", "Один из способов найти GCD двух чисел основан на наблюдении, что\n", "Если $ r $ - остальная часть, когда $ a $ разделен на $ b $, то $ gcd (a,\n", "b) = GCD (B, R) $.В качестве базового случая мы можем использовать $ gcd (a, 0) = a $.\n", "\n", "Напишите функцию, называемую `gcd`, которая принимает параметры `a` и `b` и\n", "Возвращает своего самых распространенных делителей."]}, {"cell_type": "code", "execution_count": 88, "id": "4e067bfb", "metadata": {}, "outputs": [], "source": ["# Solution goes here"]}, {"cell_type": "markdown", "id": "efbebde9", "metadata": {"tags": []}, "source": ["Вы можете использовать эти примеры для проверки вашей функции."]}, {"cell_type": "code", "execution_count": 89, "id": "2a7c1c21", "metadata": {"tags": []}, "outputs": [], "source": ["gcd(12, 8) # should be 4"]}, {"cell_type": "code", "execution_count": 90, "id": "5df00229", "metadata": {"tags": []}, "outputs": [], "source": ["gcd(13, 17) # should be 1"]}, {"cell_type": "code", "execution_count": null, "id": "8bec38b3", "metadata": {}, "outputs": [], "source": []}, {"cell_type": "markdown", "id": "a7f4edf8", "metadata": {"tags": []}, "source": ["[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", "Лицензия кода: [MIT License](https://mit-license.org/)\n", "\n", "Текстовая лицензия: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)"]}], "metadata": {"celltoolbar": "Tags", "kernelspec": {"display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3"}, "language_info": {"codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11"}}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file From a8dfa27621e2e2f8e19bee585b30c0cd88fea9ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:48:46 +0300 Subject: [PATCH 36/44] Translate chapter 9 notebook to Russian --- chapters/chap09.ipynb | 429 +++++++++++++++++++++--------------------- 1 file changed, 214 insertions(+), 215 deletions(-) diff --git a/chapters/chap09.ipynb b/chapters/chap09.ipynb index 755c656..2bbb1b8 100644 --- a/chapters/chap09.ipynb +++ b/chapters/chap09.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432? ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325)." ] }, { @@ -41,12 +41,12 @@ "id": "3c25ca7e", "metadata": {}, "source": [ - "# Lists\n", + "# Списки\n", "\n", - "This chapter presents one of Python's most useful built-in types, lists.\n", - "You will also learn more about objects and what can happen when multiple variables refer to the same object.\n", + "В этой главе представлены один из самых полезных встроенных типов Python, списка.\n", + "Вы также узнаете больше об объектах и о том, что может произойти, когда несколько переменных относятся к одному и тому же объекту.\n", "\n", - "In the exercises at the end of the chapter, we'll make a word list and use it to search for special words like palindromes and anagrams." + "В упражнениях в конце главы мы составим список слов и будем использовать его для поиска особых слов, таких как палиндромы и анаграммы." ] }, { @@ -54,14 +54,14 @@ "id": "4d32b3e2", "metadata": {}, "source": [ - "## A list is a sequence\n", + "## Список - это последовательность\n", "\n", - "Like a string, a **list** is a sequence of values. In a string, the\n", - "values are characters; in a list, they can be any type.\n", - "The values in a list are called **elements**.\n", + "Как строка, список ** - это последовательность значений. В строке,\n", + "Значения - это символы; В списке они могут быть любым типом.\n", + "Значения в списке называются ** элементы **.\n", "\n", - "There are several ways to create a new list; the simplest is to enclose the elements in square brackets (`[` and `]`).\n", - "For example, here is a list of two integers. " + "Есть несколько способов создать новый список; Самым простым является заключение элементов в квадратные скобки (`[` и `]`).\n", + "Например, вот список из двух целых чисел." ] }, { @@ -79,7 +79,7 @@ "id": "b5d6112c", "metadata": {}, "source": [ - "And here's a list of three strings." + "А вот список из трех строк." ] }, { @@ -97,8 +97,8 @@ "id": "dda58c67", "metadata": {}, "source": [ - "The elements of a list don't have to be the same type.\n", - "The following list contains a string, a float, an integer, and even another list." + "Элементы списка не должны быть такого же типа.\n", + "Следующий список содержит строку, поплавок, целое число и даже еще один список." ] }, { @@ -116,10 +116,10 @@ "id": "147fa217", "metadata": {}, "source": [ - "A list within another list is **nested**.\n", + "Список в другом списке ** вложенного **.\n", "\n", - "A list that contains no elements is called an empty list; you can create\n", - "one with empty brackets, `[]`." + "Список, который не содержит элементов, называется пустым списком; Вы можете создать\n", + "один с пустыми кронштейнами, `[]`." ] }, { @@ -137,7 +137,7 @@ "id": "f95381bc", "metadata": {}, "source": [ - "The `len` function returns the length of a list." + "Функция `Len` возвращает длину списка." ] }, { @@ -155,7 +155,7 @@ "id": "371403a3", "metadata": {}, "source": [ - "The length of an empty list is `0`." + "Длина пустого списка - 0`." ] }, { @@ -175,7 +175,7 @@ "id": "d3589a5d", "metadata": {}, "source": [ - "The following figure shows the state diagram for `cheeses`, `numbers` and `empty`." + "На следующем рисунке показана диаграмма состояния для «сыров», `numbers` и` yelly '." ] }, { @@ -225,7 +225,7 @@ "id": "503f25d8", "metadata": {}, "source": [ - "Lists are represented by boxes with the word \"list\" outside and the numbered elements of the list inside." + "Списки представлены коробками со словом «Список» снаружи и пронумерованными элементами списка внутри." ] }, { @@ -233,10 +233,10 @@ "id": "e0b8ff01", "metadata": {}, "source": [ - "## Lists are mutable\n", + "## списки изменяются\n", "\n", - "To read an element of a list, we can use the bracket operator.\n", - "The index of the first element is `0`." + "Чтобы прочитать элемент списка, мы можем использовать оператор кронштейна.\n", + "Индекс первого элемента - `0`." ] }, { @@ -254,9 +254,9 @@ "id": "9747e951", "metadata": {}, "source": [ - "Unlike strings, lists are mutable. When the bracket operator appears on\n", - "the left side of an assignment, it identifies the element of the list\n", - "that will be assigned." + "В отличие от струн, списки являются изменчивыми. Когда оператор кронштейна появляется на\n", + "Левая сторона назначения, он идентифицирует элемент списка\n", + "это будет назначено." ] }, { @@ -275,19 +275,19 @@ "id": "5097a517", "metadata": {}, "source": [ - "The second element of `numbers`, which used to be `123`, is now `17`.\n", + "Второй элемент «чисел», который раньше был `123`, теперь` 17 '.\n", "\n", - "List indices work the same way as string indices:\n", + "Индексы списка работают так же, как строковые индексы:\n", "\n", - "- Any integer expression can be used as an index.\n", + "- Любое целочисленное выражение может использоваться в качестве индекса.\n", "\n", - "- If you try to read or write an element that does not exist, you get\n", - " an `IndexError`.\n", + "- Если вы попытаетесь прочитать или написать элемент, которого не существует, вы получите\n", + " `indexerror '.\n", "\n", - "- If an index has a negative value, it counts backward from the end of\n", - " the list.\n", + "- Если индекс имеет отрицательное значение, он считается отсталым от конца\n", + " Список.\n", "\n", - "The `in` operator works on lists -- it checks whether a given element appears anywhere in the list." + "Оператор `in` работает в списках - он проверяет, появляется ли данный элемент где -нибудь в списке." ] }, { @@ -315,7 +315,7 @@ "id": "89d01ebf", "metadata": {}, "source": [ - "Although a list can contain another list, the nested list still counts as a single element -- so in the following list, there are only four elements." + "Хотя список может содержать другой список, вложенный список по -прежнему считается одним элементом, поэтому в следующем списке есть только четыре элемента." ] }, { @@ -334,7 +334,7 @@ "id": "4e0ea41d", "metadata": {}, "source": [ - "And `10` is not considered to be an element of `t` because it is an element of a nested list, not `t`." + "И `10` не считается элементом` t`, потому что это элемент вложенного списка, а не `t`." ] }, { @@ -352,10 +352,10 @@ "id": "1ee7a4d9", "metadata": {}, "source": [ - "## List slices\n", + "## Списки ломтики\n", "\n", - "The slice operator works on lists the same way it works on strings.\n", - "The following example selects the second and third elements from a list of four letters." + "Оператор Slice работает на списках так же, как он работает на строках.\n", + "Следующий пример выбирает второй и третий элементы из списка из четырех букв." ] }, { @@ -374,7 +374,7 @@ "id": "bc59d952", "metadata": {}, "source": [ - "If you omit the first index, the slice starts at the beginning. " + "Если вы опустите первый индекс, среза начинается в начале." ] }, { @@ -392,7 +392,7 @@ "id": "1aaaae86", "metadata": {}, "source": [ - "If you omit the second, the slice goes to the end. " + "Если вы опустите второе, ломтик идет до конца." ] }, { @@ -410,7 +410,7 @@ "id": "67ad02e8", "metadata": {}, "source": [ - "So if you omit both, the slice is a copy of the whole list." + "Так что, если вы опустите оба, среза является копией всего списка." ] }, { @@ -428,7 +428,7 @@ "id": "9232c1ef", "metadata": {}, "source": [ - "Another way to copy a list is to use the `list` function." + "Другой способ скопировать список - использовать функцию `list`." ] }, { @@ -446,7 +446,7 @@ "id": "50e4b182", "metadata": {}, "source": [ - "Because `list` is the name of a built-in function, you should avoid using it as a variable name.\n" + "Поскольку `list`-это имя встроенной функции, вы должны избегать использования ее в качестве имени переменной." ] }, { @@ -454,9 +454,9 @@ "id": "1b057c0c", "metadata": {}, "source": [ - "## List operations\n", + "## Список операций\n", "\n", - "The `+` operator concatenates lists." + "Оператор `+` Списки." ] }, { @@ -476,7 +476,7 @@ "id": "474a5c40", "metadata": {}, "source": [ - "The `*` operator repeats a list a given number of times." + "Оператор `*` повторяет список заданного количества раз." ] }, { @@ -494,7 +494,7 @@ "id": "5b33bc51", "metadata": {}, "source": [ - "No other mathematical operators work with lists, but the built-in function `sum` adds up the elements." + "Никакие другие математические операторы не работают со списками, но встроенная функция `sum 'добавляет элементы." ] }, { @@ -512,7 +512,7 @@ "id": "f216a14d", "metadata": {}, "source": [ - "And `min` and `max` find the smallest and largest elements." + "И `min 'и` max` найдут самые маленькие и самые большие элементы." ] }, { @@ -540,10 +540,10 @@ "id": "533a2009", "metadata": {}, "source": [ - "## List methods\n", + "## Список методов\n", "\n", - "Python provides methods that operate on lists. For example, `append`\n", - "adds a new element to the end of a list:" + "Python предоставляет методы, которые работают в списках. Например, `adpend`\n", + "добавляет новый элемент в конце списка:" ] }, { @@ -562,7 +562,7 @@ "id": "ccc57f77", "metadata": {}, "source": [ - "`extend` takes a list as an argument and appends all of the elements:" + "`Extend` принимает список в качестве аргумента и добавляет все элементы:" ] }, { @@ -581,8 +581,8 @@ "id": "0f39d9f6", "metadata": {}, "source": [ - "There are two methods that remove elements from a list.\n", - "If you know the index of the element you want, you can use `pop`." + "Есть два метода, которые удаляют элементы из списка.\n", + "Если вы знаете индекс желаемого элемента, вы можете использовать `pop`." ] }, { @@ -601,8 +601,8 @@ "id": "6729415a", "metadata": {}, "source": [ - "The return value is the element that was removed.\n", - "And we can confirm that the list has been modified." + "Возвратное значение - это элемент, который был удален.\n", + "И мы можем подтвердить, что список был изменен." ] }, { @@ -620,7 +620,7 @@ "id": "1e97ee7d", "metadata": {}, "source": [ - "If you know the element you want to remove (but not the index), you can use `remove`:" + "Если вы знаете элемент, который хотите удалить (но не индекс), вы можете использовать `remove`:" ] }, { @@ -639,8 +639,8 @@ "id": "60e710fe", "metadata": {}, "source": [ - "The return value from `remove` is `None`.\n", - "But we can confirm that the list has been modified." + "Возвратное значение от `remove` -` none `.\n", + "Но мы можем подтвердить, что список был изменен." ] }, { @@ -658,7 +658,7 @@ "id": "2a9448a8", "metadata": {}, "source": [ - "If the element you ask for is not in the list, that's a ValueError." + "Если элемент, который вы просите, нет в списке, это ValueError." ] }, { @@ -680,11 +680,11 @@ "id": "18305f96", "metadata": {}, "source": [ - "## Lists and strings\n", + "## списки и строки\n", "\n", - "A string is a sequence of characters and a list is a sequence of values,\n", - "but a list of characters is not the same as a string. \n", - "To convert from a string to a list of characters, you can use the `list` function." + "Строка - это последовательность символов, а список - это последовательность значений,\n", + "Но список символов не то же самое, что строка. \n", + "Чтобы преобразовать из строки в список символов, вы можете использовать функцию `list`." ] }, { @@ -704,8 +704,8 @@ "id": "0291ef69", "metadata": {}, "source": [ - "The `list` function breaks a string into individual letters.\n", - "If you want to break a string into words, you can use the `split` method:" + "Функция `list` разбивает строку на отдельные буквы.\n", + "Если вы хотите сломать строку словами, вы можете использовать метод `split`:" ] }, { @@ -725,7 +725,7 @@ "id": "0e16909d", "metadata": {}, "source": [ - "An optional argument called a **delimiter** specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter." + "Необязательный аргумент, называемый ** разделитель **, указывает, какие символы использовать в качестве границ слов. В следующем примере используется дефис в качестве разделителя." ] }, { @@ -745,8 +745,8 @@ "id": "7c61f916", "metadata": {}, "source": [ - "If you have a list of strings, you can concatenate them into a single string using `join`.\n", - "`join` is a string method, so you have to invoke it on the delimiter and pass the list as an argument." + "Если у вас есть список строк, вы можете объединить их в одну строку, используя `join '.\n", + "`join ' - это струнный метод, поэтому вы должны вызвать его на разделителе и передать список в качестве аргумента." ] }, { @@ -767,9 +767,9 @@ "id": "bedd842b", "metadata": {}, "source": [ - "In this case the delimiter is a space character, so `join` puts a space\n", - "between words.\n", - "To join strings without spaces, you can use the empty string, `''`, as a delimiter." + "В этом случае разделитель является космическим персонажем, поэтому «Join» ставит пространство\n", + "между словами.\n", + "Чтобы присоединиться к струнам без пробелов, вы можете использовать пустую строку, `''`, в качестве разделителя." ] }, { @@ -777,9 +777,9 @@ "id": "181215ce", "metadata": {}, "source": [ - "## Looping through a list\n", + "## пройти через список\n", "\n", - "You can use a `for` statement to loop through the elements of a list." + "Вы можете использовать оператор «for», чтобы пройти через элементы списка." ] }, { @@ -798,7 +798,7 @@ "id": "c0e53a09", "metadata": {}, "source": [ - "For example, after using `split` to make a list of words, we can use `for` to loop through them." + "Например, после использования «Split» для составления списка слов мы можем использовать «for», чтобы пройти через них." ] }, { @@ -819,7 +819,7 @@ "id": "0857b55b", "metadata": {}, "source": [ - "A `for` loop over an empty list never runs the indented statements." + "Цикл `for` по пустому списку никогда не запускает отступы." ] }, { @@ -838,9 +838,9 @@ "id": "6e5f55c9", "metadata": {}, "source": [ - "## Sorting lists\n", + "## списки сортировки\n", "\n", - "Python provides a built-in function called `sorted` that sorts the elements of a list." + "Python предоставляет встроенную функцию под названием «отсортирован», которая сортирует элементы списка." ] }, { @@ -859,7 +859,7 @@ "id": "44e028cf", "metadata": {}, "source": [ - "The original list is unchanged." + "Оригинальный список неизменен." ] }, { @@ -877,7 +877,7 @@ "id": "530146af", "metadata": {}, "source": [ - "`sorted` works with any kind of sequence, not just lists. So we can sort the letters in a string like this." + "`Sorted` работает с любой последовательности, а не только списками. Таким образом, мы можем сортировать буквы в такой строке." ] }, { @@ -895,8 +895,8 @@ "id": "f90bd9ea", "metadata": {}, "source": [ - "The result is a list.\n", - "To convert the list to a string, we can use `join`." + "Результат - список.\n", + "Чтобы преобразовать список в строку, мы можем использовать `join '." ] }, { @@ -914,7 +914,7 @@ "id": "a57084e2", "metadata": {}, "source": [ - "With an empty string as the delimiter, the elements of the list are joined with nothing between them." + "С пустой строкой в качестве разделителя, элементы списка соединяются с чем -либо между ними." ] }, { @@ -922,9 +922,9 @@ "id": "ce98b3d5", "metadata": {}, "source": [ - "## Objects and values\n", + "## объекты и значения\n", "\n", - "If we run these assignment statements:" + "Если мы запустим эти заявления о назначении:" ] }, { @@ -943,8 +943,8 @@ "id": "33d020aa", "metadata": {}, "source": [ - "We know that `a` and `b` both refer to a string, but we don't know whether they refer to the *same* string. \n", - "There are two possible states, shown in the following figure." + "Мы знаем, что `a` и` b \n", + "Есть два возможных состояния, показанные на следующем рисунке." ] }, { @@ -989,9 +989,9 @@ "id": "2f0b0431", "metadata": {}, "source": [ - "In the diagram on the left, `a` and `b` refer to two different objects that have the\n", - "same value. In the diagram on the right, they refer to the same object.\n", - "To check whether two variables refer to the same object, you can use the `is` operator." + "На диаграмме слева `a` и` b` относятся к двум разным объектам, которые имеют\n", + "то же значение. На диаграмме справа они относятся к тому же объекту.\n", + "Чтобы проверить, относятся ли две переменные к одному и тому же объекту, вы можете использовать оператор `is '." ] }, { @@ -1011,9 +1011,9 @@ "id": "d1eb0e36", "metadata": {}, "source": [ - "In this example, Python only created one string object, and both `a`\n", - "and `b` refer to it.\n", - "But when you create two lists, you get two objects." + "В этом примере Python создал только один объект String, и оба `a`\n", + "и `b\n", + "Но когда вы создаете два списка, вы получаете два объекта." ] }, { @@ -1033,7 +1033,7 @@ "id": "a8d4c3d4", "metadata": {}, "source": [ - "So the state diagram looks like this." + "Так что диаграмма состояния выглядит так." ] }, { @@ -1071,8 +1071,8 @@ "id": "cc115a9f", "metadata": {}, "source": [ - "In this case we would say that the two lists are **equivalent**, because they have the same elements, but not **identical**, because they are not the same object. \n", - "If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical." + "В этом случае мы бы сказали, что два списка ** эквивалентны **, потому что они имеют одинаковые элементы, но не ** идентичные **, потому что они не один и тот же объект. \n", + "Если два объекта идентичны, они также эквивалентны, но если они эквивалентны, они не обязательно идентичны." ] }, { @@ -1080,9 +1080,9 @@ "id": "a58db021", "metadata": {}, "source": [ - "## Aliasing\n", + "## псевдоним\n", "\n", - "If `a` refers to an object and you assign `b = a`, then both variables refer to the same object." + "Если `a` относится к объекту, и вы назначаете` b = a`, то обе переменные относятся к одному и тому же объекту." ] }, { @@ -1102,7 +1102,7 @@ "id": "f6ab3262", "metadata": {}, "source": [ - "So the state diagram looks like this." + "Так что диаграмма состояния выглядит так." ] }, { @@ -1140,12 +1140,12 @@ "id": "c676fde9", "metadata": {}, "source": [ - "The association of a variable with an object is called a **reference**.\n", - "In this example, there are two references to the same object.\n", + "Ассоциация переменной с объектом называется ** ссылка **.\n", + "В этом примере есть две ссылки на один и тот же объект.\n", "\n", - "An object with more than one reference has more than one name, so we say the object is **aliased**.\n", - "If the aliased object is mutable, changes made with one name affect the other.\n", - "In this example, if we change the object `b` refers to, we are also changing the object `a` refers to." + "У объекта с более чем одной ссылкой есть более одного имени, поэтому мы говорим, что объект ** псевдоним **.\n", + "Если псевдоним, объект, изменен, изменения, внесенные с одним именем, влияют на другое.\n", + "В этом примере, если мы изменим объект `B` относится, мы также меняем объект` a` относится." ] }, { @@ -1164,12 +1164,12 @@ "id": "e3ef0537", "metadata": {}, "source": [ - "So we would say that `a` \"sees\" this change.\n", - "Although this behavior can be useful, it is error-prone.\n", - "In general, it is safer to avoid aliasing when you are working with mutable objects.\n", + "Итак, мы бы сказали, что «a» видит »это изменение.\n", + "Хотя это поведение может быть полезным, оно подвержено ошибкам.\n", + "В целом, безопаснее избегать псевдонима, когда вы работаете с изменчивыми объектами.\n", "\n", - "For immutable objects like strings, aliasing is not as much of a problem.\n", - "In this example:" + "Для неизменных объектов, таких как строки, псевдоним не такая проблема.\n", + "В этом примере:" ] }, { @@ -1188,8 +1188,8 @@ "id": "952bbf60", "metadata": {}, "source": [ - "It almost never makes a difference whether `a` and `b` refer to the same\n", - "string or not." + "Это почти никогда не имеет значения, ссылаются ли `a` и` b\n", + "строка или нет." ] }, { @@ -1197,11 +1197,11 @@ "id": "35045bef", "metadata": {}, "source": [ - "## List arguments\n", + "## Список аргументов\n", "\n", - "When you pass a list to a function, the function gets a reference to the\n", - "list. If the function modifies the list, the caller sees the change. For\n", - "example, `pop_first` uses the list method `pop` to remove the first element from a list." + "Когда вы передаете список функции, функция получает ссылку на\n", + "список. Если функция изменяет список, абонент видит изменение. Для\n", + "Пример, `pop_first` использует метод списка` pop`, чтобы удалить первый элемент из списка." ] }, { @@ -1220,7 +1220,7 @@ "id": "4953b0f9", "metadata": {}, "source": [ - "We can use it like this." + "Мы можем использовать это так." ] }, { @@ -1239,7 +1239,7 @@ "id": "ef5d3c1e", "metadata": {}, "source": [ - "The return value is the first element, which has been removed from the list -- as we can see by displaying the modified list." + "Возвратное значение - это первый элемент, который был удален из списка - как мы можем видеть, отображая измененный список." ] }, { @@ -1257,7 +1257,7 @@ "id": "e5288e08", "metadata": {}, "source": [ - "In this example, the parameter `lst` and the variable `letters` are aliases for the same object, so the state diagram looks like this:" + "В этом примере параметр `lst` и переменная« буквы »представляют собой псевдонимы для одного и того же объекта, поэтому диаграмма состояния выглядит так:" ] }, { @@ -1301,8 +1301,8 @@ "id": "c1a093d2", "metadata": {}, "source": [ - "Passing a reference to an object as an argument to a function creates a form of aliasing.\n", - "If the function modifies the object, those changes persist after the function is done." + "Передача ссылки на объект как аргумент на функцию создает форму псевдонима.\n", + "Если функция изменяет объект, эти изменения сохраняются после выполнения функции." ] }, { @@ -1312,12 +1312,12 @@ "tags": [] }, "source": [ - "## Making a word list\n", + "## Создание списка слов\n", "\n", - "In the previous chapter, we read the file `words.txt` and searched for words with certain properties, like using the letter `e`.\n", - "But we read the entire file many times, which is not efficient.\n", - "It is better to read the file once and put the words in a list.\n", - "The following loop shows how." + "В предыдущей главе мы читаем файл `words.txt` и искали слова с определенными свойствами, например, используя букву` e`.\n", + "Но мы читаем весь файл много раз, что не эффективно.\n", + "Лучше прочитать файл один раз и поместить слова в список.\n", + "Следующий цикл показывает, как." ] }, { @@ -1353,11 +1353,11 @@ "id": "44450ffa", "metadata": {}, "source": [ - "Before the loop, `word_list` is initialized with an empty list.\n", - "Each time through the loop, the `append` method adds a word to the end.\n", - "When the loop is done, there are more than 113,000 words in the list.\n", + "Перед циклом `word_list` инициализируется с пустым списком.\n", + "Каждый раз через цикл метод «Приложение» добавляет слово к концу.\n", + "Когда петля будет сделана, в списке более 113 000 слов.\n", "\n", - "Another way to do the same thing is to use `read` to read the entire file into a string." + "Еще один способ сделать то же самое - использовать `read`, чтобы прочитать весь файл в строку." ] }, { @@ -1376,8 +1376,8 @@ "id": "65718c7f", "metadata": {}, "source": [ - "The result is a single string with more than a million characters.\n", - "We can use the `split` method to split it into a list of words." + "Результатом является единственная строка с более чем миллионами символов.\n", + "Мы можем использовать метод «разделения», чтобы разделить его на список слов." ] }, { @@ -1396,8 +1396,8 @@ "id": "1b5b25a3", "metadata": {}, "source": [ - "Now, to check whether a string appears in the list, we can use the `in` operator.\n", - "For example, `'demotic'` is in the list." + "Теперь, чтобы проверить, появляется ли в списке строку, мы можем использовать оператор `in`.\n", + "Например, «демотический» находится в списке." ] }, { @@ -1415,7 +1415,7 @@ "id": "9df6674d", "metadata": {}, "source": [ - "But `'contrafibularities'` is not." + "Но «противоположность» не." ] }, { @@ -1433,7 +1433,7 @@ "id": "243c25b6", "metadata": {}, "source": [ - "And I have to say, I'm anaspeptic about it." + "И я должен сказать, что я анаспептик об этом." ] }, { @@ -1441,12 +1441,12 @@ "id": "ce9ffd79", "metadata": {}, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "Note that most list methods modify the argument and return `None`.\n", - "This is the opposite of the string methods, which return a new string and leave the original alone.\n", + "Обратите внимание, что большинство методов списка изменяют аргумент и возвращают «нет».\n", + "Это противоположность методам струн, которые возвращают новую строку и оставляют оригинал в покое.\n", "\n", - "If you are used to writing string code like this:" + "Если вы привыкли к написанию строкового кода, как это:" ] }, { @@ -1466,7 +1466,7 @@ "id": "d2117582", "metadata": {}, "source": [ - "It is tempting to write list code like this:" + "Заманчиво написать код списка, как это:" ] }, { @@ -1485,7 +1485,7 @@ "id": "991c439d", "metadata": {}, "source": [ - "`remove` modifies the list and returns `None`, so next operation you perform with `t` is likely to fail." + "`Удалить 'изменяет список и возвращает« нет », поэтому следующая операция, которую вы выполняете с помощью` t`, скорее всего, потерпит неудачу." ] }, { @@ -1507,11 +1507,11 @@ "id": "c500e2d8", "metadata": {}, "source": [ - "This error message takes some explaining.\n", - "An **attribute** of an object is a variable or method associated with it.\n", - "In this case, the value of `t` is `None`, which is a `NoneType` object, which does not have a attribute named `remove`, so the result is an `AttributeError`.\n", + "Это сообщение об ошибке требует некоторого объяснения.\n", + "** атрибут ** объекта - это переменная или метод, связанный с ним.\n", + "В этом случае значение `t` равно` none`, которое представляет собой объект `nonetype`, который не имеет атрибута с именем` remove`, поэтому результатом является `attributeerror.\n", "\n", - "If you see an error message like this, you should look backward through the program and see if you might have called a list method incorrectly." + "Если вы видите подобное сообщение об ошибке, вы должны оглянуться назад через программу и посмотреть, не неправильно ли вы вызвали метод списка." ] }, { @@ -1519,34 +1519,34 @@ "id": "f90db780", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**list:**\n", - " An object that contains a sequence of values.\n", + "**список:**\n", + " Объект, который содержит последовательность значений.\n", "\n", - "**element:**\n", - " One of the values in a list or other sequence.\n", + "**элемент:**\n", + " Одно из значений в списке или другой последовательности.\n", "\n", - "**nested list:**\n", - "A list that is an element of another list.\n", + "** Вложенный список: **\n", + "Список, который является элементом другого списка.\n", "\n", - "**delimiter:**\n", - " A character or string used to indicate where a string should be split.\n", + "** разделитель: **\n", + " Символ или строка, используемая для указания, где следует разделить строку.\n", "\n", - "**equivalent:**\n", - " Having the same value.\n", + "** эквивалент: **\n", + " Имея такое же значение.\n", "\n", - "**identical:**\n", - " Being the same object (which implies equivalence).\n", + "** идентично: **\n", + " Быть одним и тем же объектом (что подразумевает эквивалентность).\n", "\n", - "**reference:**\n", - " The association between a variable and its value.\n", + "**ссылка:**\n", + " Связь между переменной и ее значением.\n", "\n", - "**aliased:**\n", - "If there is more than one variable that refers to an object, the object is aliased.\n", + "** псевдоним: **\n", + "Если существует более одной переменной, которая относится к объекту, объект подселян.\n", "\n", - "**attribute:**\n", - " One of the named values associated with an object." + "**атрибут:**\n", + " Одно из названных значений, связанных с объектом." ] }, { @@ -1554,8 +1554,7 @@ "id": "e67864e5", "metadata": {}, "source": [ - "## Exercises\n", - "\n" + "## Упражнения" ] }, { @@ -1578,24 +1577,24 @@ "id": "ae9c42da", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "In this chapter, I used the words \"contrafibularities\" and \"anaspeptic\", but they are not actually English words.\n", - "They were used in the British television show *Black Adder*, Season 3, Episode 2, \"Ink and Incapability\".\n", + "В этой главе я использовал слова «противоположность» и «анаспептические», но на самом деле они не английские слова.\n", + "Они использовались в британском телевизионном шоу *Black Adder *, сезон 3, эпизод 2, «Чернила и неспособность».\n", "\n", - "However, when I asked ChatGPT 3.5 (August 3, 2023 version) where those words came from, it initially claimed they are from Monty Python, and later claimed they are from the Tom Stoppard play *Rosencrantz and Guildenstern Are Dead*.\n", + "Однако, когда я спросил CHATGPT 3.5 (версия 3 августа 2023 года), откуда поступили эти слова, он первоначально утверждал, что они из Монти Пайтона, а затем утверждали, что они из пьесы Тома Стоппард *Розенкранц и Гильдженстерн мертвы *.\n", "\n", - "If you ask now, you might get different results.\n", - "But this example is a reminder that virtual assistants are not always accurate, so you should check whether the results are correct.\n", - "As you gain experience, you will get a sense of which questions virtual assistants can answer reliably.\n", - "In this example, a conventional web search can identify the source of these words quickly.\n", + "Если вы спросите сейчас, вы можете получить разные результаты.\n", + "Но этот пример является напоминанием о том, что виртуальные помощники не всегда точны, поэтому вы должны проверить, являются ли результаты правильными.\n", + "Получив опыт, вы получите представление о том, какие вопросы виртуальные помощники могут ответить надежно.\n", + "В этом примере обычный веб -поиск может быстро определить источник этих слов.\n", "\n", - "If you get stuck on any of the exercises in this chapter, consider asking a virtual assistant for help.\n", - "If you get a result that uses features we haven't learned yet, you can assign the VA a \"role\".\n", + "Если вы застряли в каком -либо из упражнений в этой главе, подумайте о том, чтобы попросить виртуального помощника за помощью.\n", + "Если вы получите результат, который использует функции, которые мы еще не выучили, вы можете назначить VA «роль».\n", "\n", - "For example, before you ask a question try typing \"Role: Basic Python Programming Instructor\".\n", - "After that, the responses you get should use only basic features.\n", - "If you still see features we you haven't learned, you can follow up with \"Can you write that using only basic Python features?\"" + "Например, прежде чем задать вопрос, попробуйте вводить «Роль: базовый инструктор по программированию Python».\n", + "После этого ответы, которые вы получаете, должны использовать только основные функции.\n", + "Если вы все еще видите функции, которые мы не изучили, вы можете следить за \"Можете ли вы написать это, используя только основные функции Python?\"" ] }, { @@ -1603,15 +1602,15 @@ "id": "31d5b304", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Two words are anagrams if you can rearrange the letters from one to spell the other.\n", - "For example, `tops` is an anagram of `stop`.\n", + "Два слова - это анаграммы, если вы можете изменить буквы от одного, чтобы записать другое.\n", + "Например, «Tops» - это анаграмма «остановки».\n", "\n", - "One way to check whether two words are anagrams is to sort the letters in both words.\n", - "If the lists of sorted letters are the same, the words are anagrams.\n", + "Один из способов проверить, являются ли два слова анаграммы - сортировать буквы в обоих словах.\n", + "Если списки отсортированных букв одинаковы, слова являются анаграммами.\n", "\n", - "Write a function called `is_anagram` that takes two strings and returns `True` if they are anagrams." + "Напишите функцию под названием `is_anagram`, которая принимает две строки и возвращает` true`, если они являются анаграммами." ] }, { @@ -1621,7 +1620,7 @@ "tags": [] }, "source": [ - "To get you started, here's an outline of the function with doctests." + "Чтобы начать, вот схема функции с Doctests." ] }, { @@ -1665,7 +1664,7 @@ "tags": [] }, "source": [ - "You can use `doctest` to test your function." + "Вы можете использовать `doctest`, чтобы проверить вашу функцию." ] }, { @@ -1690,7 +1689,7 @@ "id": "8501f3ba", "metadata": {}, "source": [ - "Using your function and the word list, find all the anagrams of `takes`." + "Используя вашу функцию и список слов, найдите все анаграммы `takes '." ] }, { @@ -1708,9 +1707,9 @@ "id": "7f279f2f", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Python provides a built-in function called `reversed` that takes as an argument a sequence of elements -- like a list or string -- and returns a `reversed` object that contains the elements in reverse order." + "Python предоставляет встроенную функцию, называемую «reversed», которая принимает в качестве аргумента последовательность элементов-например, список или строка-и возвращает объект «обратный», который содержит элементы в обратном порядке." ] }, { @@ -1728,7 +1727,7 @@ "id": "0f95c76f", "metadata": {}, "source": [ - "If you want the reversed elements in a list, you can use the `list` function." + "Если вам нужны обращенные элементы в списке, вы можете использовать функцию `list`." ] }, { @@ -1746,7 +1745,7 @@ "id": "8fc79a2f", "metadata": {}, "source": [ - "Or if you want them in a string, you can use the `join` method." + "Или, если вы хотите их в строке, вы можете использовать метод `join '." ] }, { @@ -1764,7 +1763,7 @@ "id": "ec4ce196", "metadata": {}, "source": [ - "So we can write a function that reverses a word like this." + "Таким образом, мы можем написать функцию, которая меняет слово, подобное этому." ] }, { @@ -1783,8 +1782,8 @@ "id": "21550b5f", "metadata": {}, "source": [ - "A palindrome is a word that is spelled the same backward and forward, like \"noon\" and \"rotator\".\n", - "Write a function called `is_palindrome` that takes a string argument and returns `True` if it is a palindrome and `False` otherwise." + "Палиндром - это слово, которое написано одинаково назад и вперед, как «Полдень» и «Ротатор».\n", + "Напишите функцию, называемую `is_palindrome`, которая принимает аргумент строки и возвращает` true`, если это палиндром и `false 'иначе." ] }, { @@ -1794,7 +1793,7 @@ "tags": [] }, "source": [ - "Here's an outline of the function with doctests you can use to check your function." + "Вот краткий план функции с Doctests, которые вы можете использовать для проверки вашей функции." ] }, { @@ -1848,7 +1847,7 @@ "id": "ad857abf", "metadata": {}, "source": [ - "You can use the following loop to find all of the palindromes in the word list with at least 7 letters." + "Вы можете использовать следующий цикл, чтобы найти все палиндромы в списке слов как минимум с 7 буквами." ] }, { @@ -1870,13 +1869,13 @@ "id": "11386f70", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `reverse_sentence` that takes as an argument a string that contains any number of words separated by spaces.\n", - "It should return a new string that contains the same words in reverse order.\n", - "For example, if the argument is \"Reverse this sentence\", the result should be \"Sentence this reverse\".\n", + "Напишите функцию, называемую `reverse_sentence`, которая принимает в качестве аргумента строка, которая содержит любое количество слов, разделенных пространствами.\n", + "Он должен вернуть новую строку, которая содержит одинаковые слова в обратном порядке.\n", + "Например, если аргумент является «обратным предложением», результатом должен быть «предложение на этот обратный».\n", "\n", - "Hint: You can use the `capitalize` methods to capitalize the first word and convert the other words to lowercase. " + "Подсказка: вы можете использовать методы `wallize`, чтобы заработать первое слово и преобразовать другие слова в строчный." ] }, { @@ -1886,7 +1885,7 @@ "tags": [] }, "source": [ - "To get you started, here's an outline of the function with doctests." + "Чтобы начать, вот схема функции с Doctests." ] }, { @@ -1943,10 +1942,10 @@ "id": "fb5f24b1", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `total_length` that takes a list of strings and returns the total length of the strings.\n", - "The total length of the words in `word_list` should be $902{,}728$." + "Напишите функцию с именем `total_length`, которая принимает список строк и возвращает общую длину строк.\n", + "Общая длина слов в `word_list` должна составлять $ 902 {,} 728 $." ] }, { @@ -1984,13 +1983,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT] (https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik" ] } ], @@ -2016,4 +2015,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 948dfaf2b8bc5b5b41d81dec981164a4be16badf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:49:47 +0300 Subject: [PATCH 37/44] Translate chap11 notebook to Russian --- chapters/chap11.ipynb | 548 +++++++++++++++++++++--------------------- 1 file changed, 274 insertions(+), 274 deletions(-) diff --git a/chapters/chap11.ipynb b/chapters/chap11.ipynb index e10980c..53e0c93 100644 --- a/chapters/chap11.ipynb +++ b/chapters/chap11.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432? ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325)." ] }, { @@ -43,16 +43,16 @@ "tags": [] }, "source": [ - "# Tuples\n", + "# КУТУ\n", "\n", - "This chapter introduces one more built-in type, the tuple, and then shows how lists, dictionaries, and tuples work together.\n", - "It also presents tuple assignment and a useful feature for functions with variable-length argument lists: the packing and unpacking operators.\n", + "В этой главе представлены еще один встроенный тип, кортеж, а затем показывает, как списки, словари и кортежи работают вместе.\n", + "Он также представляет назначение кортежей и полезную функцию для функций с списками аргументов переменной длины: операторов упаковки и распаковки.\n", "\n", - "In the exercises, we'll use tuples, along with lists and dictionaries, to solve more word puzzles and implement efficient algorithms.\n", + "В упражнениях мы будем использовать кортежи, наряду с списками и словарями, чтобы решить больше головоломок и реализации эффективных алгоритмов.\n", "\n", - "One note: There are two ways to pronounce \"tuple\".\n", - "Some people say \"tuh-ple\", which rhymes with \"supple\".\n", - "But in the context of programming, most people say \"too-ple\", which rhymes with \"quadruple\"." + "Одно примечание: есть два способа произнесения «корзина».\n", + "Некоторые люди говорят «Tuh-Ple», который рифмуется с «пушкой».\n", + "Но в контексте программирования большинство людей говорят «Too-Ple», который рифмуется с «четырехкратным»." ] }, { @@ -60,12 +60,12 @@ "id": "19474596", "metadata": {}, "source": [ - "## Tuples are like lists\n", + "## КУТУ - это как списки\n", "\n", - "A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so tuples are a lot like lists.\n", - "The important difference is that tuples are immutable.\n", + "Крупель - это последовательность значений. Значения могут быть любым типом, и они индексируются целыми числами, поэтому кортежи очень похожи на списки.\n", + "Важным отличием является то, что кортежи неизменны.\n", "\n", - "To create a tuple, you can write a comma-separated list of values." + "Чтобы создать кортеж, вы можете написать список значений, разделяемый запятыми." ] }, { @@ -84,7 +84,7 @@ "id": "a2ec15d8", "metadata": {}, "source": [ - "Although it is not necessary, it is common to enclose tuples in parentheses." + "Хотя в этом нет необходимости, это обычно прикладывает в скобки в скобках." ] }, { @@ -103,7 +103,7 @@ "id": "9194a159", "metadata": {}, "source": [ - "To create a tuple with a single element, you have to include a final comma." + "Чтобы создать кортеж с одним элементом, вы должны включить окончательную запятую." ] }, { @@ -122,7 +122,7 @@ "id": "e39b95a5", "metadata": {}, "source": [ - "A single value in parentheses is not a tuple." + "Единственное значение в скобках - это не кортеж." ] }, { @@ -141,8 +141,8 @@ "id": "a64bfb64", "metadata": {}, "source": [ - "Another way to create a tuple is the built-in function `tuple`. With no\n", - "argument, it creates an empty tuple." + "Другим способом создания кортежа является встроенная функция `tuple '. Без\n", + "Аргумент, это создает пустой кортеж." ] }, { @@ -161,8 +161,8 @@ "id": "f3447831", "metadata": {}, "source": [ - "If the argument is a sequence (string, list or tuple), the result is a\n", - "tuple with the elements of the sequence." + "Если аргумент представляет собой последовательность (строка, список или кортеж), результатом является\n", + "Круп с элементами последовательности." ] }, { @@ -181,10 +181,10 @@ "id": "2e48b980", "metadata": {}, "source": [ - "Because `tuple` is the name of a built-in function, you should avoid using it as a variable name.\n", + "Поскольку `tuple`-это имя встроенной функции, вы должны избегать использования ее в качестве имени переменной.\n", "\n", - "Most list operators also work with tuples.\n", - "For example, the bracket operator indexes an element." + "Большинство операторов списка также работают с кортежами.\n", + "Например, оператор кронштейна индексирует элемент." ] }, { @@ -202,7 +202,7 @@ "id": "2f702785", "metadata": {}, "source": [ - "And the slice operator selects a range of elements." + "И оператор среза выбирает ряд элементов." ] }, { @@ -220,7 +220,7 @@ "id": "c9ed9af2", "metadata": {}, "source": [ - "The `+` operator concatenates tuples." + "Оператор `+` объединяет платы." ] }, { @@ -238,7 +238,7 @@ "id": "1d7dcd6d", "metadata": {}, "source": [ - "And the `*` operator duplicates a tuple a given number of times." + "И оператор `*` дублирует кортеж на определенное количество раз." ] }, { @@ -256,7 +256,7 @@ "id": "a53ce8bd", "metadata": {}, "source": [ - "The `sorted` function works with tuples -- but the result is a list, not a tuple." + "Функция «отсортированная» работает с кортежами, но результатом является список, а не кортеж." ] }, { @@ -274,7 +274,7 @@ "id": "50e5cadc", "metadata": {}, "source": [ - "The `reversed` function also works with tuples." + "Функция `reversed` также работает с кортежами." ] }, { @@ -292,7 +292,7 @@ "id": "f6d973c5", "metadata": {}, "source": [ - "The result is a `reversed` object, which we can convert to a list or tuple." + "Результатом является объект «обратный», который мы можем преобразовать в список или кортеж." ] }, { @@ -310,7 +310,7 @@ "id": "a7cb9ee6", "metadata": {}, "source": [ - "Based on the examples so far, it might seem like tuples are the same as lists." + "Основываясь на примерах до сих пор, может показаться, что кортежи такие же, как и списки." ] }, { @@ -318,9 +318,9 @@ "id": "8c3f381e", "metadata": {}, "source": [ - "## But tuples are immutable\n", + "## но кортежи неизменны\n", "\n", - "If you try to modify a tuple with the bracket operator, you get a `TypeError`." + "Если вы попытаетесь изменить кортеж с оператором кронштейна, вы получите `typeerror." ] }, { @@ -341,7 +341,7 @@ "id": "592ce99c", "metadata": {}, "source": [ - "And tuples don't have any of the methods that modify lists, like `append` and `remove`." + "И у кортежей нет ни одного из методов, которые изменяют списки, такие как `adpend` и` remove '." ] }, { @@ -363,10 +363,10 @@ "id": "70772ba2", "metadata": {}, "source": [ - "Recall that an \"attribute\" is a variable or method associated with an object -- this error message means that tuples don't have a method named `remove`.\n", + "Напомним, что «атрибут» - это переменная или метод, связанный с объектом - это сообщение об ошибке означает, что у кортежей нет метода с именем `remove '.\n", "\n", - "Because tuples are immutable, they are hashable, which means they can be used as keys in a dictionary.\n", - "For example, the following dictionary contains two tuples as keys that map to integers." + "Поскольку кортежи неизменны, они являются хэшабельными, что означает, что их можно использовать в качестве ключей в словаре.\n", + "Например, следующий словарь содержит две кортежи в качестве ключей, которые отображают целые числа." ] }, { @@ -386,7 +386,7 @@ "id": "47ba17ab", "metadata": {}, "source": [ - "We can look up a tuple in a dictionary like this:" + "Мы можем посмотреть кортеж в таком словаре, как это:" ] }, { @@ -404,7 +404,7 @@ "id": "f2c0a354", "metadata": {}, "source": [ - "Or if we have a variable that refers to a tuple, we can use it as a key." + "Или, если у нас есть переменная, которая относится к кортежу, мы можем использовать ее в качестве ключа." ] }, { @@ -423,7 +423,7 @@ "id": "2ea8fc3c", "metadata": {}, "source": [ - "Tuples can also appear as values in a dictionary." + "ПУЛЯ также могут появляться в виде значений в словаре." ] }, { @@ -443,9 +443,9 @@ "id": "25655ab3", "metadata": {}, "source": [ - "## Tuple assignment\n", + "## назначение кортежей\n", "\n", - "You can put a tuple of variables on the left side of an assignment, and a tuple of values on the right." + "Вы можете поставить кортеж с переменными на левую сторону назначения и кортеж значений справа." ] }, { @@ -463,8 +463,8 @@ "id": "92c00ceb", "metadata": {}, "source": [ - "The values are assigned to the variables from left to right -- in this example, `a` gets the value `1` and `b` gets the value `2`.\n", - "We can display the results like this:" + "Значения присваиваются переменным слева направо - в этом примере `a` получает значение` 1`, а `B` получает значение` 2`.\n", + "Мы можем отобразить результаты подобными:" ] }, { @@ -482,8 +482,8 @@ "id": "6362b36e", "metadata": {}, "source": [ - "More generally, if the left side of an assignment is a tuple, the right side can be any kind of sequence -- string, list or tuple. \n", - "For example, to split an email address into a user name and a domain, you could write:" + "В более общем плане, если левая сторона назначения является кортежом, правая сторона может быть какой -либо последовательности - строка, список или кортеж. \n", + "Например, чтобы разделить адрес электронной почты на имя пользователя и домен, вы можете написать:" ] }, { @@ -502,7 +502,7 @@ "id": "d134a94c", "metadata": {}, "source": [ - "The return value from `split` is a list with two elements -- the first element is assigned to `username`, the second to `domain`." + "Возвращаемое значение из `split` - это список с двумя элементами - первый элемент назначается« имя пользователя », второе - домен '." ] }, { @@ -520,8 +520,8 @@ "id": "5a7e3c62", "metadata": {}, "source": [ - "The number of variables on the left and the number of values on the\n", - "right have to be the same -- otherwise you get a `ValueError`." + "Количество переменных слева и количество значений на\n", + "Правильно должно быть одинаковым - иначе вы получаете `valueError '." ] }, { @@ -542,8 +542,8 @@ "id": "808c2928", "metadata": {}, "source": [ - "Tuple assignment is useful if you want to swap the values of two variables.\n", - "With conventional assignments, you have to use a temporary variable, like this:" + "Назначение кортежей полезно, если вы хотите поменять значения двух переменных.\n", + "С обычными заданиями вы должны использовать временную переменную, например:" ] }, { @@ -563,7 +563,7 @@ "id": "98496d02", "metadata": {}, "source": [ - "That works, but with tuple assignment we can do the same thing without a temporary variable." + "Это работает, но с назначением кортежей мы можем сделать то же самое без временной переменной." ] }, { @@ -581,10 +581,10 @@ "id": "a66a87bc", "metadata": {}, "source": [ - "This works because all of the expressions on the right side are evaluated before any of the assignments.\n", + "Это работает, потому что все выражения на правой стороне оцениваются перед какими -либо заданиями.\n", "\n", - "We can also use tuple assignment in a `for` statement.\n", - "For example, to loop through the items in a dictionary, we can use the `items` method." + "Мы также можем использовать назначение кортежа в операторе `for`.\n", + "Например, чтобы пройти через элементы в словаре, мы можем использовать метод «элементов»." ] }, { @@ -606,9 +606,9 @@ "id": "dd0d4feb", "metadata": {}, "source": [ - "Each time through the loop, `item` is assigned a tuple that contains a key and the corresponding value.\n", + "Каждый раз через цикл «Item» назначается кортеж, который содержит ключ и соответствующее значение.\n", "\n", - "We can write this loop more concisely, like this:" + "Мы можем написать эту петлю более кратко, как это:" ] }, { @@ -627,7 +627,7 @@ "id": "f0513578", "metadata": {}, "source": [ - "Each time through the loop, a key and the corresponding value are assigned directly to `key` and `value`." + "Каждый раз через цикл, ключ и соответствующее значение назначаются непосредственно на `key` и` value`." ] }, { @@ -635,16 +635,16 @@ "id": "efedeb37", "metadata": {}, "source": [ - "## Tuples as return values\n", + "## КУТУ В качестве возвращаемых значений\n", "\n", - "Strictly speaking, a function can only return one value, but if the\n", - "value is a tuple, the effect is the same as returning multiple values.\n", - "For example, if you want to divide two integers and compute the quotient\n", - "and remainder, it is inefficient to compute `x//y` and then `x%y`. It is\n", - "better to compute them both at the same time.\n", + "Строго говоря, функция может вернуть только одно значение, но если\n", + "Значение - это кортеж, эффект такой же, как и возврат нескольких значений.\n", + "Например, если вы хотите разделить два целых числа и вычислить коэффициент\n", + "а остаток неэффективен вычислять `x // y`, а затем` x%y`. Это\n", + "Лучше вычислить их обоих одновременно.\n", "\n", - "The built-in function `divmod` takes two arguments and returns a tuple\n", - "of two values, the quotient and remainder." + "Встроенная функция `divmod` принимает два аргумента и возвращает кортеж\n", + "двух значений, коэффициента и остатка." ] }, { @@ -662,7 +662,7 @@ "id": "33f3c57d", "metadata": {}, "source": [ - "We can use tuple assignment to store the elements of the tuple in two variables. " + "Мы можем использовать назначение кортежа для хранения элементов кортежа в двух переменных." ] }, { @@ -691,7 +691,7 @@ "id": "15079805", "metadata": {}, "source": [ - "Here is an example of a function that returns a tuple." + "Вот пример функции, которая возвращает кортеж." ] }, { @@ -710,8 +710,8 @@ "id": "43c4e1e0", "metadata": {}, "source": [ - "`max` and `min` are built-in functions that find the largest and smallest elements of a sequence. \n", - "`min_max` computes both and returns a tuple of two values." + "`max` и` min '-это встроенные функции, которые находят самые большие и наименьшие элементы последовательности. \n", + "`min_max` вычисляет оба и возвращает кортеж из двух значений." ] }, { @@ -729,7 +729,7 @@ "id": "86b60e71", "metadata": {}, "source": [ - "We can assign the results to variables like this:" + "Мы можем назначить результаты с такими переменными:" ] }, { @@ -750,11 +750,11 @@ "tags": [] }, "source": [ - "## Argument packing\n", + "## Аргумент упаковка\n", "\n", - "Functions can take a variable number of arguments. \n", - "A parameter name that begins with the `*` operator **packs** arguments into a tuple.\n", - "For example, the following function takes any number of arguments and computes their arithmetic mean -- that is, their sum divided by the number of arguments. " + "Функции могут принимать переменное количество аргументов. \n", + "Имя параметра, которое начинается с оператора `*` упаковывает ** аргументы в кортеж.\n", + "Например, следующая функция принимает любое количество аргументов и вычисляет их среднее арифметику, то есть их сумму, разделенную на количество аргументов." ] }, { @@ -773,8 +773,8 @@ "id": "6044fc1b", "metadata": {}, "source": [ - "The parameter can have any name you like, but `args` is conventional.\n", - "We can call the function like this:" + "Параметр может иметь любое имя, которое вам нравится, но `args 'является обычным.\n", + "Мы можем назвать функцию так:" ] }, { @@ -792,8 +792,8 @@ "id": "a5e8b158", "metadata": {}, "source": [ - "If you have a sequence of values and you want to pass them to a function as multiple arguments, you can use the `*` operator to **unpack** the tuple.\n", - "For example, `divmod` takes exactly two arguments -- if you pass a tuple as a parameter, you get an error." + "Если у вас есть последовательность значений, и вы хотите передать их в функцию в качестве нескольких аргументов, вы можете использовать оператор `*` для ** распаковывать ** кортеж.\n", + "Например, «Divmod» принимает ровно два аргумента - если вы передаете кортеж в качестве параметра, вы получаете ошибку." ] }, { @@ -815,8 +815,8 @@ "id": "5a9110db", "metadata": {}, "source": [ - "Even though the tuple contains two elements, it counts as a single argument.\n", - "But if you unpack the tuple, it is treated as two arguments." + "Несмотря на то, что кортеж содержит два элемента, он считается единственным аргументом.\n", + "Но если вы распаковываете кортеж, его рассматривают как два аргумента." ] }, { @@ -834,8 +834,8 @@ "id": "da554863", "metadata": {}, "source": [ - "Packing and unpacking can be useful if you want to adapt the behavior of an existing function.\n", - "For example, this function takes any number of arguments, removes the lowest and highest, and computes the mean of the rest." + "Упаковка и распаковка могут быть полезны, если вы хотите адаптировать поведение существующей функции.\n", + "Например, эта функция принимает любое количество аргументов, удаляет самое низкое и самое высокое и вычисляет среднее значение для остальных." ] }, { @@ -858,11 +858,11 @@ "id": "d1e05e49", "metadata": {}, "source": [ - "First it uses `min_max` to find the lowest and highest elements.\n", - "Then it converts `args` to a list so it can use the `remove` method.\n", - "Finally it unpacks the list so the elements are passed to `mean` as separate arguments, rather than as a single list.\n", + "Сначала он использует `min_max`, чтобы найти самые низкие и самые высокие элементы.\n", + "Затем он преобразует «args» в список, чтобы использовать метод `remove`.\n", + "Наконец, он распаковывает список, поэтому элементы передаются в «среднее» в виде отдельных аргументов, а не как один список.\n", "\n", - "Here's an example that shows the effect." + "Вот пример, который показывает эффект." ] }, { @@ -890,7 +890,7 @@ "id": "35e04996", "metadata": {}, "source": [ - "This kind of \"trimmed\" mean is used in some sports with subjective judging -- like diving and gymnastics -- to reduce the effect of a judge whose score deviates from the others. " + "Этот вид «подстриженного» среднего значения используется в некоторых видах спорта с субъективным судейством - например, дайвинг и гимнастика - чтобы уменьшить эффект судьи, чей счет отклоняется от других." ] }, { @@ -900,8 +900,8 @@ "source": [ "## Zip\n", "\n", - "Tuples are useful for looping through the elements of two sequences and performing operations on corresponding elements.\n", - "For example, suppose two teams play a series of seven games, and we record their scores in two lists, one for each team." + "Клетки полезны для зацикливания через элементы двух последовательностей и выполнения операций на соответствующих элементах.\n", + "Например, предположим, что две команды играют в серию из семи игр, и мы записываем их результаты в двух списках, по одной для каждой команды." ] }, { @@ -920,8 +920,8 @@ "id": "b44f228b", "metadata": {}, "source": [ - "Let's see how many games each team won.\n", - "We'll use `zip`, which is a built-in function that takes two or more sequences and returns a **zip object**, so-called because it pairs up the elements of the sequences like the teeth of a zipper." + "Давайте посмотрим, сколько игр выиграла каждая команда.\n", + "Мы используем `Zip`, который представляет собой встроенную функцию, которая принимает две или более последовательности и возвращает ** Zip-объект **, так называемый, потому что он соединяет элементы последовательностей, таких как зубы молнии." ] }, { @@ -939,7 +939,7 @@ "id": "9adcf8f9", "metadata": {}, "source": [ - "We can use the zip object to loop through the values in the sequences pairwise." + "Мы можем использовать объект ZIP, чтобы пройти через значения в последовательностях пары." ] }, { @@ -958,8 +958,8 @@ "id": "51d1dabb", "metadata": {}, "source": [ - "Each time through the loop, `pair` gets assigned a tuple of scores.\n", - "So we can assign the scores to variables, and count the victories for the first team, like this:" + "Каждый раз через петлю, «Пару» назначают кортеж с результатами.\n", + "Таким образом, мы можем назначить оценки переменным и подсчитать победы для первой команды, например, это:" ] }, { @@ -982,9 +982,9 @@ "id": "ad740fcd", "metadata": {}, "source": [ - "Sadly, the first team won only three games and lost the series.\n", + "К сожалению, первая команда выиграла только три игры и проиграла сериал.\n", "\n", - "If you have two lists and you want a list of pairs, you can use `zip` and `list`." + "Если у вас есть два списка и вам нужен список пар, вы можете использовать `Zip` и` list`." ] }, { @@ -1003,7 +1003,7 @@ "id": "ec4249fa", "metadata": {}, "source": [ - "The result is a list of tuples, so we can get the result of the last game like this:" + "Результатом является список кортежей, поэтому мы можем получить результат последней игры, как это:" ] }, { @@ -1021,8 +1021,8 @@ "id": "436486b9", "metadata": {}, "source": [ - "If you have a list of keys and a list of values, you can use `zip` and `dict` to make a dictionary.\n", - "For example, here's how we can make a dictionary that maps from each letter to its position in the alphabet." + "Если у вас есть список ключей и список значений, вы можете использовать `Zip` и` dict ', чтобы сделать словарь.\n", + "Например, вот как мы можем сделать словарь, который отображает из каждой буквы в ее положение в алфавите." ] }, { @@ -1042,7 +1042,7 @@ "id": "b4de6974", "metadata": {}, "source": [ - "Now we can look up a letter and get its index in the alphabet." + "Теперь мы можем посмотреть букву и получить его индекс в алфавите." ] }, { @@ -1060,9 +1060,9 @@ "id": "cc632542", "metadata": {}, "source": [ - "In this mapping, the index of `'a'` is `0` and the index of `'z'` is `25`.\n", + "В этом отображении индекс «a» - «0`», а индекс «Z'» - `25`.\n", "\n", - "If you need to loop through the elements of a sequence and their indices, you can use the built-in function `enumerate`." + "Если вам нужно пройти через элементы последовательности и их индексов, вы можете использовать встроенную функцию `перечислить '." ] }, { @@ -1080,7 +1080,7 @@ "id": "92ad45bb", "metadata": {}, "source": [ - "The result is an **enumerate object** that loops through a sequence of pairs, where each pair contains an index (starting from 0) and an element from the given sequence." + "Результатом является ** перечисливший объект **, который проходит через последовательность пар, где каждая пара содержит индекс (начиная с 0) и элемент из данной последовательности." ] }, { @@ -1099,11 +1099,11 @@ "id": "cf0b55d7", "metadata": {}, "source": [ - "## Comparing and Sorting\n", + "## Сравнение и сортировка\n", "\n", - "The relational operators work with tuples and other sequences.\n", - "For example, if you use the `<` operator with tuples, it starts by comparing the first element from each sequence.\n", - "If they are equal, it goes on to the next pair of elements, and so on, until it finds a pair that differ. " + "Реляционные операторы работают с кортежами и другими последовательностями.\n", + "Например, если вы используете оператор «<` `с кортежами, он начинается с сравнения первого элемента из каждой последовательности».\n", + "Если они равны, это переходит к следующей паре элементов, и так далее, пока не найдет пару, которая отличается." ] }, { @@ -1121,7 +1121,7 @@ "id": "65ceea86", "metadata": {}, "source": [ - "Subsequent elements are not considered -- even if they are really big." + "Последующие элементы не рассматриваются - даже если они действительно большие." ] }, { @@ -1139,9 +1139,9 @@ "id": "55e4a35e", "metadata": {}, "source": [ - "This way of comparing tuples is useful for sorting a list of tuples, or finding the minimum or maximum.\n", - "As an example, let's find the most common letter in a word.\n", - "In the previous chapter, we wrote `value_counts`, which takes a string and returns a dictionary that maps from each letter to the number of times it appears." + "Этот способ сравнения кортежей полезен для сортировки списка кортежей или поиска минимального или максимума.\n", + "В качестве примера, давайте найдем наиболее распространенное письмо одним словом.\n", + "В предыдущей главе мы написали `value_counts`, который берет строку и возвращает словарь, который отображает из каждой буквы в количество раз." ] }, { @@ -1166,7 +1166,7 @@ "id": "a80012c1", "metadata": {}, "source": [ - "Here is the result for the string `'banana'`." + "Вот результат для строки `'banana''." ] }, { @@ -1185,10 +1185,10 @@ "id": "cc1ea4a7", "metadata": {}, "source": [ - "With only three items, we can easily see that the most frequent letter is `'a'`, which appears three times.\n", - "But if there were more items, it would be useful to sort them automatically.\n", + "Только с тремя элементами мы можем легко увидеть, что самая частая буква - «A», которая появляется три раза.\n", + "Но если бы было больше предметов, было бы полезно разортировать их автоматически.\n", "\n", - "We can get the items from `counter` like this." + "Мы можем получить элементы от «стойки», как это." ] }, { @@ -1207,7 +1207,7 @@ "id": "ac8dea7a", "metadata": {}, "source": [ - "The result is a `dict_items` object that behaves like a list of tuples, so we can sort it like this." + "Результатом является объект `dict_items`, который ведет себя как список кортежей, поэтому мы можем сортировать его так." ] }, { @@ -1225,10 +1225,10 @@ "id": "b690d17a", "metadata": {}, "source": [ - "The default behavior is to use the first element from each tuple to sort the list, and use the second element to break ties.\n", + "Поведение по умолчанию состоит в том, чтобы использовать первый элемент из каждого корзина для сортировки списка и использовать второй элемент для разрыва связей.\n", "\n", - "However, to find the items with the highest counts, we want to use the second element to sort the list.\n", - "We can do that by writing a function that takes a tuple and returns the second element." + "Однако, чтобы найти элементы с наибольшим количеством количества, мы хотим использовать второй элемент для сортировки списка.\n", + "Мы можем сделать это, написав функцию, которая берет кортеж и возвращает второй элемент." ] }, { @@ -1247,7 +1247,7 @@ "id": "b964aa14", "metadata": {}, "source": [ - "Then we can pass that function to `sorted` as an optional argument called `key`, which indicates that this function should be used to compute the **sort key** for each item." + "Затем мы можем передать эту функцию в «сортированное» в качестве необязательного аргумента, называемого «Key», который указывает на то, что эта функция должна использоваться для вычисления клавиши ** Sort ** для каждого элемента." ] }, { @@ -1266,9 +1266,9 @@ "id": "4dc96848", "metadata": {}, "source": [ - "The sort key determines the order of the items in the list.\n", - "The letter with the lowest count appears first, and the letter with the highest count appears last.\n", - "So we can find the most common letter like this." + "Ключ сорта определяет порядок элементов в списке.\n", + "Сначала появляется письмо с самым низким подсчетом, и буква с наивысшим количеством подсчета появляется последней.\n", + "Таким образом, мы можем найти самое распространенное письмо, как это." ] }, { @@ -1286,8 +1286,8 @@ "id": "d0d8b999", "metadata": {}, "source": [ - "If we only want the maximum, we don't have to sort the list.\n", - "We can use `max`, which also takes `key` as an optional argument." + "Если мы хотим только максимум, нам не нужно сортировать список.\n", + "Мы можем использовать `max`, который также принимает` key 'в качестве необязательного аргумента." ] }, { @@ -1305,7 +1305,7 @@ "id": "8a8327df", "metadata": {}, "source": [ - "To find the letter with the lowest count, we could use `min` the same way." + "Чтобы найти букву с самым низким подсчетом, мы могли бы использовать «min» таким же образом." ] }, { @@ -1313,15 +1313,15 @@ "id": "a62394a5", "metadata": {}, "source": [ - "## Inverting a dictionary\n", + "## инвертирование словаря\n", "\n", - "Suppose you want to invert a dictionary so you can look up a value and get the corresponding key.\n", - "For example, if you have a word counter that maps from each word to the number of times it appears, you could make a dictionary that maps from integers to the words that appear that number of times.\n", + "Предположим, вы хотите инвертировать словарь, чтобы вы могли найти значение и получить соответствующий ключ.\n", + "Например, если у вас есть счетчик слов, который отображает от каждого слова до того, как оно появляется, вы можете сделать словарь, который отображает из целых чисел в слова, которые появляются в течение этого количества раз.\n", "\n", - "But there's a problem -- the keys in a dictionary have to be unique, but the values don't. For example, in a word counter, there could be many words with the same count.\n", + "Но есть проблема - ключи в словаре должны быть уникальными, но значения нет. Например, в счетчике слова может быть много слов с тем же количеством.\n", "\n", - "So one way to invert a dictionary is to create a new dictionary where the values are lists of keys from the original.\n", - "As an example, let's count the letters in `parrot`." + "Таким образом, одним из способов инвертировать словарь является создание нового словаря, в котором значения являются списками клавиш из оригинала.\n", + "В качестве примера, давайте подсчитаем буквы в «попугаи»." ] }, { @@ -1340,9 +1340,9 @@ "id": "f4570eae", "metadata": {}, "source": [ - "If we invert this dictionary, the result should be `{1: ['p', 'a', 'o', 't'], 2: ['r']}`, which indicates that the letters that appear once are `'p'`, `'a'`, `'o'`, and `'t'`, and the letter than appears twice is `'r'`.\n", + "Если мы инвертируем этот словарь, результат должен быть `{1: ['p', 'a', 'o', 't'], 2: ['r']}`, что указывает на то, что буквы, которые когда -то появляются, - «p'`», `a'``,` 'O'' и `'t', и буква, чем появляется, - это два раза - это` r '.\n", "\n", - "The following function takes a dictionary and returns its inverse as a new dictionary." + "Следующая функция принимает словарь и возвращает его обратный в качестве нового словаря." ] }, { @@ -1367,11 +1367,11 @@ "id": "ca5fa025", "metadata": {}, "source": [ - "The `for` statement loops through the keys and values in `d`.\n", - "If the value is not already in the new dictionary, it is added and associated with a list that contains a single element.\n", - "Otherwise it is appended to the existing list.\n", + "Оператор «для» проходит через ключи и значения в `d`.\n", + "Если значение еще не в новом словаре, оно добавлено и связано с списком, который содержит один элемент.\n", + "В противном случае он добавляется в существующий список.\n", "\n", - "We can test it like this:" + "Мы можем проверить это так:" ] }, { @@ -1389,10 +1389,10 @@ "id": "4cfb1693", "metadata": {}, "source": [ - "And we get the result we expected.\n", + "И мы получаем результат, который мы ожидали.\n", "\n", - "This is the first example we've seen where the values in the dictionary are lists.\n", - "We will see more!" + "Это первый пример, где мы видели, где значения в словаре являются списками.\n", + "Посмотрим больше!" ] }, { @@ -1402,17 +1402,17 @@ "tags": [] }, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "Lists, dictionaries and tuples are **data structures**.\n", - "In this chapter we are starting to see compound data structures, like lists of tuples, or dictionaries that contain tuples as keys and lists as values.\n", - "Compound data structures are useful, but they are prone to errors caused when a data structure has the wrong type, size, or structure.\n", - "For example, if a function expects a list of integers and you give it a plain old integer\n", - "(not in a list), it probably won't work.\n", + "Списки, словари и кортежи - это ** структуры данных **.\n", + "В этой главе мы начинаем видеть составные структуры данных, такие как списки кортежей, или словари, которые содержат кортежи в качестве ключей и списков в качестве значений.\n", + "Составные структуры данных полезны, но они подвержены ошибкам, вызванным, когда структура данных имеет неправильный тип, размер или структуру.\n", + "Например, если функция ожидает список целых чисел, и вы даете ей простое старое целое число\n", + "(Не в списке), это, вероятно, не сработает.\n", "\n", - "To help debug these kinds of errors, I wrote a module called `structshape` that provides a function, also called `structshape`, that takes any kind of data structure as an argument and returns a string that summarizes its structure.\n", - "You can download it from\n", - "." + "Чтобы помочь отладить такие ошибки, я написал модуль под названием «Structshape», который обеспечивает функцию, также называемую «Structshape», который принимает какую -либо структуру данных в качестве аргумента и возвращает строку, которая суммирует его структуру.\n", + "Вы можете скачать его с\n", + "." ] }, { @@ -1432,7 +1432,7 @@ "id": "646f4d55", "metadata": {}, "source": [ - "We can import it like this." + "Мы можем импортировать его так." ] }, { @@ -1450,7 +1450,7 @@ "id": "86cc6ccc", "metadata": {}, "source": [ - "Here's an example with a simple list." + "Вот пример с простым списком." ] }, { @@ -1469,7 +1469,7 @@ "id": "9de4f6ec", "metadata": {}, "source": [ - "Here's a list of lists." + "Вот список списков." ] }, { @@ -1488,8 +1488,8 @@ "id": "aced9984", "metadata": {}, "source": [ - "If the elements of the list are not the same type, `structshape` groups\n", - "them by type." + "Если элементы списка не являются такими же типами, `structshape\n", + "их по типу." ] }, { @@ -1508,7 +1508,7 @@ "id": "f63ff690", "metadata": {}, "source": [ - "Here's a list of tuples." + "Вот список кортежей." ] }, { @@ -1528,7 +1528,7 @@ "id": "c9ec67eb", "metadata": {}, "source": [ - "And here's a dictionary with three items that map integers to strings." + "А вот словарь с тремя элементами, которые отображают целые числа на струны." ] }, { @@ -1547,8 +1547,8 @@ "id": "f29bb82b", "metadata": {}, "source": [ - "If you are having trouble keeping track of your data structures,\n", - "`structshape` can help." + "Если у вас проблемы с отслеживанием ваших структур данных,\n", + "`Structshape 'может помочь." ] }, { @@ -1556,25 +1556,25 @@ "id": "79d93082", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**pack:**\n", - "Collect multiple arguments into a tuple.\n", + "**пакет:**\n", + "Соберите несколько аргументов в кортеж.\n", "\n", - "**unpack:**\n", - "Treat a tuple (or other sequence) as multiple arguments.\n", + "** распаковывать: **\n", + "Обратитесь в кортеж (или другую последовательность) как множественные аргументы.\n", "\n", - "**zip object:**\n", - "The result of calling the built-in function `zip`, can be used to loop through a sequence of tuples.\n", + "** Объект Zip: **\n", + "Результат вызова встроенной функции `Zip` может быть использован для перехода через последовательность кортежей.\n", "\n", - "**enumerate object:**\n", - "The result of calling the built-in function `enumerate`, can be used to loop through a sequence of tuples.\n", + "** перечислять объект: **\n", + "Результат вызова встроенной функции `enumerate` может быть использован для перехода через последовательность кортежей.\n", "\n", - "**sort key:**\n", - "A value, or function that computes a value, used to sort the elements of a collection.\n", + "** Ключ сортировки: **\n", + "Значение или функция, которая вычисляет значение, используемое для сортировки элементов коллекции.\n", "\n", - "**data structure:**\n", - "A collection of values, organized to perform certain operations efficiently." + "** Структура данных: **\n", + "Коллекция значений, организованных для эффективного выполнения определенных операций." ] }, { @@ -1582,7 +1582,7 @@ "id": "1471b3c0", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -1605,17 +1605,17 @@ "id": "97a0352d", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "The exercises in this chapter might be more difficult than exercises in previous chapters, so I encourage you to get help from a virtual assistant.\n", - "When you pose more difficult questions, you might find that the answers are not correct on the first attempt, so this is a chance to practice crafting good prompts and following up with good refinements.\n", + "Упражнения в этой главе могут быть сложнее, чем упражнения в предыдущих главах, поэтому я призываю вас получить помощь от виртуального помощника.\n", + "Когда вы задаете более сложные вопросы, вы можете обнаружить, что ответы не верны с первой попытки, так что это шанс попрактиковаться в создании хороших подсказок и следовать хорошим усовершенствованиям.\n", "\n", - "One strategy you might consider is to break a big problems into pieces that can be solved with simple functions.\n", - "Ask the virtual assistant to write the functions and test them.\n", - "Then, once they are working, ask for a solution to the original problem.\n", + "Одна стратегия, которую вы можете рассмотреть, - это разбить большие проблемы на части, которые можно решить с помощью простых функций.\n", + "Попросите виртуального помощника написать функции и проверить их.\n", + "Затем, как только они работают, попросите решение исходной проблемы.\n", "\n", - "For some of the exercises below, I make suggestions about which data structures and algorithms to use.\n", - "You might find these suggestions useful when you work on the problems, but they are also good prompts to pass along to a virtual assistant." + "Для некоторых упражнений ниже я делаю предложения о том, какие структуры данных и алгоритмы использовать.\n", + "Вы можете найти эти предложения полезными, когда вы работаете над проблемами, но они также являются хорошими подсказками, чтобы передать виртуальному помощнику." ] }, { @@ -1623,12 +1623,12 @@ "id": "f90e011f", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In this chapter I said that tuples can be used as keys in dictionaries because they are hashable, and they are hashable because they are immutable.\n", - "But that is not always true.\n", + "В этой главе я сказал, что кортежи могут использоваться в качестве ключей в словарях, потому что они хэшабель, и они хэшаруются, потому что они неизменны.\n", + "Но это не всегда правда.\n", "\n", - "If a tuple contains a mutable value, like a list or a dictionary, the tuple is no longer hashable because it contains elements that are not hashable. As an example, here's a tuple that contains two lists of integers." + "Если кортеж содержит изменяемое значение, например, список или словарь, кортеж больше не является хэшабельным, потому что он содержит элементы, которые не являются хэшабельными. В качестве примера, вот кортеж, который содержит два списка целых чисел." ] }, { @@ -1650,7 +1650,7 @@ "id": "02799077", "metadata": {}, "source": [ - "Write a line of code that appends the value `6` to the end of the second list in `t`. If you display `t`, the result should be `([1, 2, 3], [4, 5, 6])`." + "Напишите строку кода, которая добавляет значение `6` к концу второго списка в` t`. Если вы отображаете `t`, результат должен быть` ([1, 2, 3], [4, 5, 6]) `." ] }, { @@ -1670,7 +1670,7 @@ "id": "644b1dfb", "metadata": {}, "source": [ - "Try to create a dictionary that maps from `t` to a string, and confirm that you get a `TypeError`." + "Попробуйте создать словарь, который отображает от `t` на строку, и подтвердите, что вы получаете` typeerror '." ] }, { @@ -1690,7 +1690,7 @@ "id": "fb77a352", "metadata": {}, "source": [ - "For more on this topic, ask a virtual assistant, \"Are Python tuples always hashable?\"" + "Для получения дополнительной информации по этой теме, спросите виртуального помощника: «Всегда ли кортежи для Python всегда хелают?»" ] }, { @@ -1700,9 +1700,9 @@ "tags": [] }, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In this chapter we made a dictionary that maps from each letter to its index in the alphabet." + "В этой главе мы сделали словарь, который отображает из каждой буквы в его индекс в алфавите." ] }, { @@ -1722,7 +1722,7 @@ "id": "a8cd720b", "metadata": {}, "source": [ - "For example, the index of `'a'` is `0`." + "Например, индекс `'a'`` 0`." ] }, { @@ -1740,8 +1740,8 @@ "id": "a04c25db", "metadata": {}, "source": [ - "To go in the other direction, we can use list indexing.\n", - "For example, the letter at index `1` is `'b'`." + "Чтобы идти в другом направлении, мы можем использовать индексацию списка.\n", + "Например, буква в индексе `1` -` 'b'." ] }, { @@ -1759,18 +1759,18 @@ "id": "165ab770", "metadata": {}, "source": [ - "We can use `letter_map` and `letters` to encode and decode words using a Caesar cipher.\n", + "Мы можем использовать `lect_map` и` буквы 'для кодирования и декодирования слов с помощью шифра Цезаря.\n", "\n", - "A Caesar cipher is a weak form of encryption that involves shifting each letter\n", - "by a fixed number of places in the alphabet, wrapping around to the beginning if necessary. For example, `'a'` shifted by 2 is `'c'` and `'z'` shifted by 1 is `'a'`.\n", + "Цезарь -шифр - это слабая форма шифрования, которая включает в себя изменение каждой буквы\n", + "По фиксированному количеству мест в алфавите, при необходимости, обернувшись до начала. Например, «a», сдвинутый на 2, - это `'c'' ', а`' Z''сдвинулся на 1 IS `' a '.\n", "\n", - "Write a function called `shift_word` that takes as parameters a string and an integer, and returns a new string that contains the letters from the string shifted by the given number of places.\n", + "Напишите функцию с именем `shift_word`, которая принимает в качестве параметров строку и целое число, и возвращает новую строку, которая содержит буквы из строки, сдвинутой на заданное количество мест.\n", "\n", - "To test your function, confirm that \"cheer\" shifted by 7 is \"jolly\" and \"melon\" shifted by 16 is \"cubed\".\n", + "Чтобы проверить вашу функцию, подтвердите, что «Cheer», сдвинутое на 7, \"Jolly\" и \"melon\", сдвинутая на 16, \"кубики\".\n", "\n", - "Hints: Use the modulus operator to wrap around from `'z'` back to `'a'`. \n", - "Loop through the letters of the word, shift each one, and append the result to a list of letters.\n", - "Then use `join` to concatenate the letters into a string." + "Подсказки: используйте оператор модуля, чтобы обернуться от `Z'` 'Back to`' a '. \n", + "Проверьте буквы слова, сдвиньте каждый из них и добавьте результат в список букв.\n", + "Затем используйте `join ', чтобы объединить буквы в строку." ] }, { @@ -1780,7 +1780,7 @@ "tags": [] }, "source": [ - "You can use this outline to get started." + "Вы можете использовать этот контур, чтобы начать." ] }, { @@ -1844,7 +1844,7 @@ "tags": [] }, "source": [ - "You can use `doctest` to test your function." + "Вы можете использовать `doctest`, чтобы проверить вашу функцию." ] }, { @@ -1869,11 +1869,11 @@ "id": "779f13af", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `most_frequent_letters` that takes a string and prints the letters in decreasing order of frequency.\n", + "Напишите функцию, называемую `most_frequent_letters`, которая принимает строку и печатает буквы в порядке уменьшения частоты.\n", "\n", - "To get the items in decreasing order, you can use `reversed` along with `sorted` or you can pass `reverse=True` as a keyword parameter to `sorted`." + "Чтобы получить элементы в порядке уменьшения, вы можете использовать `reversed` вместе с« сортированным »или вы можете передать` reverse = true` в качестве параметра ключевого слова для `sorted`." ] }, { @@ -1883,7 +1883,7 @@ "tags": [] }, "source": [ - "You can use this outline of the function to get started." + "Вы можете использовать этот план функции, чтобы начать работу." ] }, { @@ -1916,7 +1916,7 @@ "tags": [] }, "source": [ - "And this example to test your function." + "И этот пример для проверки вашей функции." ] }, { @@ -1938,7 +1938,7 @@ "tags": [] }, "source": [ - "Once your function is working, you can use the following code to print the most common letters in *Dracula*, which we can download from Project Gutenberg." + "Как только ваша функция работает, вы можете использовать следующий код для печати наиболее распространенных букв в *Dracula *, которые мы можем загрузить из Project Gutenberg." ] }, { @@ -1973,8 +1973,8 @@ "tags": [] }, "source": [ - "According to Zim's \"Codes and Secret Writing\", the sequence of letters in decreasing order of frequency in English starts with \"ETAONRISH\".\n", - "How does this sequence compare with the results from *Dracula*?" + "Согласно «кодам и секретному письму Зима», последовательность букв в уменьшении порядка частоты на английском языке начинается с «Etaonrish».\n", + "Как эта последовательность сравнивается с результатами *Dracula *?" ] }, { @@ -1982,20 +1982,20 @@ "id": "cbe9933e", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In a previous exercise, we tested whether two strings are anagrams by sorting the letters in both words and checking whether the sorted letters are the same.\n", - "Now let's make the problem a little more challenging.\n", + "В предыдущем упражнении мы проверили, являются ли две строки анаграммы, сортируя буквы в обоих словах и проверяя, являются ли сортированные буквы одинаковыми.\n", + "Теперь давайте сделаем проблему немного более сложной.\n", "\n", - "We'll write a program that takes a list of words and prints all the sets of words that are anagrams.\n", - "Here is an example of what the output might look like:\n", + "Мы напишем программу, которая принимает список слов и печатает все наборы слов, которые являются анаграммами.\n", + "Вот пример того, как может выглядеть выход:\n", "\n", - " ['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled']\n", - " ['retainers', 'ternaries']\n", - " ['generating', 'greatening']\n", - " ['resmelts', 'smelters', 'termless']\n", + " ['deltas', 'desalt', 'Laft', «Salted», «Planted», «Staled»]\n", + " ['Сборники', 'ТЕРНАРИ']\n", + " ['Generation', 'Greating']\n", + " ['resmelts', 'Mellters', 'termers']\n", "\n", - "Hint: For each word in the word list, sort the letters and join them back into a string. Make a dictionary that maps from this sorted string to a list of words that are anagrams of it." + "Подсказка: для каждого слова в списке слова сортируйте буквы и присоединяйтесь к ним обратно в строку. Сделайте словарь, который отображает из этой отсортированной строки в список слов, которые являются его анаграммами." ] }, { @@ -2005,7 +2005,7 @@ "tags": [] }, "source": [ - "The following cells download `words.txt` and read the words into a list." + "Следующие ячейки загружают `words.txt` и читают слова в список." ] }, { @@ -2039,7 +2039,7 @@ "tags": [] }, "source": [ - "Here's the `sort_word` function we've used before." + "Вот функция `sort_word`, которую мы использовали ранее." ] }, { @@ -2072,8 +2072,8 @@ "tags": [] }, "source": [ - "To find the longest list of anagrams, you can use the following function, which takes a key-value pair where the key is a string and the value is a list of words.\n", - "It returns the length of the list." + "Чтобы найти самый длинный список анаграмм, вы можете использовать следующую функцию, которая принимает пару клавиш, где ключ-это строка, а значение-это список слов.\n", + "Он возвращает длину списка." ] }, { @@ -2097,7 +2097,7 @@ "tags": [] }, "source": [ - "We can use this function as a sort key to find the longest lists of anagrams." + "Мы можем использовать эту функцию в качестве ключа сортировки, чтобы найти самые длинные списки анаграмм." ] }, { @@ -2121,7 +2121,7 @@ "tags": [] }, "source": [ - "If you want to know the longest words that have anagrams, you can use the following loop to print some of them." + "Если вы хотите узнать самые длинные слова, которые имеют анаграммы, вы можете использовать следующий цикл, чтобы распечатать некоторые из них." ] }, { @@ -2148,11 +2148,11 @@ "id": "4fbe939e", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `word_distance` that takes two words with the same length and returns the number of places where the two words differ.\n", + "Напишите функцию, называемую `word_distance`, которая занимает два слова с одинаковой длиной и возвращает количество мест, где различаются два слова.\n", "\n", - "Hint: Use `zip` to loop through the corresponding letters of the words." + "Подсказка: используйте `Zip`, чтобы пройти через соответствующие буквы слов." ] }, { @@ -2162,7 +2162,7 @@ "tags": [] }, "source": [ - "Here's an outline of the function with doctests you can use to check your function." + "Вот краткий план функции с Doctests, которые вы можете использовать для проверки вашей функции." ] }, { @@ -2219,15 +2219,15 @@ "id": "066eec59", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "\"Metathesis\" is the transposition of letters in a word.\n", - "Two words form a \"metathesis pair\" if you can transform one into the other by swapping two letters, like `converse` and `conserve`.\n", - "Write a program that finds all of the metathesis pairs in the word list. \n", + "«Метатезис» - это транспозиция букв в слове.\n", + "Два слова образуют «пару метатезисов», если вы можете преобразовать одно в другое, заменив две буквы, например, «Converse» и «Sonvere».\n", + "Напишите программу, которая находит все пара метатезисов в списке слов. \n", "\n", - "Hint: The words in a metathesis pair must be anagrams of each other.\n", + "Подсказка: слова в паре метатезиса должны быть анаграммами друг друга.\n", "\n", - "Credit: This exercise is inspired by an example at ." + "Кредит: Это упражнение вдохновлено примером по адресу ." ] }, { @@ -2247,49 +2247,49 @@ "tags": [] }, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "This is a bonus exercise that is not in the book.\n", - "It is more challenging than the other exercises in this chapter, so you might want to ask a virtual assistant for help, or come back to it after you've read a few more chapters.\n", + "Это бонусное упражнение, которого нет в книге.\n", + "Это сложнее, чем другие упражнения в этой главе, поэтому вы можете попросить виртуального помощника за помощью или вернуться к нему после того, как прочитали еще несколько глав.\n", "\n", - "Here's another Car Talk Puzzler\n", + "Вот еще одна головоломка.\n", "():\n", "\n", - "> What is the longest English word, that remains a valid English word,\n", - "> as you remove its letters one at a time?\n", + "> Какое самое длинное английское слово, которое остается действительным английским словом,\n", + "> Когда вы удаляете его буквы по одному?\n", ">\n", - "> Now, letters can be removed from either end, or the middle, but you\n", - "> can't rearrange any of the letters. Every time you drop a letter, you\n", - "> wind up with another English word. If you do that, you're eventually\n", - "> going to wind up with one letter and that too is going to be an\n", - "> English word---one that's found in the dictionary. I want to know\n", - "> what's the longest word and how many letters does it have?\n", + "> Теперь буквы могут быть удалены с конца или в середине, но вы\n", + "> Не могу изменить ни одной буквы. Каждый раз, когда вы бросаете письмо, вы\n", + "> Получить еще одно английское слово. Если вы сделаете это, вы в конце концов\n", + "> Собираюсь выйти с одной буквой, и это тоже будет\n", + "> Английское слово --- то, что найдено в словаре. Я хочу знать\n", + "> Какое самое длинное слово и сколько букв у него?\n", ">\n", - "> I'm going to give you a little modest example: Sprite. Ok? You start\n", - "> off with sprite, you take a letter off, one from the interior of the\n", - "> word, take the r away, and we're left with the word spite, then we\n", - "> take the e off the end, we're left with spit, we take the s off, we're\n", - "> left with pit, it, and I.\n", + "> Я собираюсь привести вам небольшой скромный пример: Sprite. Хорошо? Вы начинаете\n", + "> уйти с Sprite, вы снимаете письмо, один из внутренних\n", + "> Слово, заберите R, и у нас остается слово злобное, тогда мы\n", + "> Снимите E с конца, мы остаемся с Spit, мы снимаем S, мы\n", + "> остался с ямой, это и я.\n", "\n", - "Write a program to find all words that can be reduced in this way, and\n", - "then find the longest one.\n", + "Напишите программу, чтобы найти все слова, которые могут быть уменьшены таким образом, и\n", + "Затем найдите самый длинный.\n", "\n", - "This exercise is a little more challenging than most, so here are some\n", - "suggestions:\n", + "Это упражнение немного сложнее, чем большинство, так что вот некоторые\n", + "предложения:\n", "\n", - "1. You might want to write a function that takes a word and computes a\n", - " list of all the words that can be formed by removing one letter.\n", - " These are the \"children\" of the word.\n", + "1. Вы можете написать функцию, которая принимает слово и вычисляет\n", + " Список всех слов, которые могут быть сформированы путем удаления одной буквы.\n", + " Это «дети» слова.\n", "\n", - "2. Recursively, a word is reducible if any of its children are\n", - " reducible. As a base case, you can consider the empty string\n", - " reducible.\n", + "2. рекурсивно, слово уменьшается, если кто -либо из его детей\n", + " уменьшается. В качестве базового корпуса вы можете рассмотреть пустую строку\n", + " уменьшается.\n", "\n", - "3. The word list we've been using doesn't contain single letter\n", - " words. So you might have to add \"I\" and \"a\".\n", + "3. Список слов, которые мы использовали\n", + " слова Таким образом, вам, возможно, придется добавить «я» и «а».\n", "\n", - "4. To improve the performance of your program, you might want to\n", - " memoize the words that are known to be reducible." + "4. Чтобы улучшить производительность вашей программы, вы можете захотеть\n", + " Запомните слова, которые, как известно, являются уменьшенными." ] }, { @@ -2349,13 +2349,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT] (https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik" ] } ], @@ -2381,4 +2381,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 75547f92f2cfa110576c7b9c8024614bf52b1945 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:50:22 +0300 Subject: [PATCH 38/44] Fix license link in translated notebook --- chapters/chap12.ipynb | 540 +++++++++++++++++++++--------------------- 1 file changed, 270 insertions(+), 270 deletions(-) diff --git a/chapters/chap12.ipynb b/chapters/chap12.ipynb index 49c55ce..b136bb5 100644 --- a/chapters/chap12.ipynb +++ b/chapters/chap12.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -41,20 +41,20 @@ "id": "59a8621b", "metadata": {}, "source": [ - "# Text Analysis and Generation\n", + "# Анализ текста и поколение\n", "\n", - "At this point we have covered Python's core data structures -- lists, dictionaries, and tuples -- and some algorithms that use them.\n", - "In this chapter, we'll use them to explore text analysis and Markov generation:\n", + "На этом этапе мы рассмотрели основные структуры данных Python - списки, словари и кортежи - и некоторые алгоритмы, которые их используют.\n", + "В этой главе мы будем использовать их для изучения текстового анализа и генерации Маркова:\n", "\n", - "* Text analysis is a way to describe the statistical relationships between the words in a document, like the probability that one word is followed by another, and\n", + "* Анализ текста - это способ описать статистические отношения между словами в документе, например, вероятность того, что одно слово следует другому, и\n", "\n", - "* Markov generation is a way to generate new text with words and phrases similar to the original text.\n", + "* Генерация Маркова - это способ генерировать новый текст со словами и фразами, похожими на исходный текст.\n", "\n", - "These algorithms are similar to parts of a Large Language Model (LLM), which is the key component of a chatbot.\n", + "Эти алгоритмы аналогичны частям большой языковой модели (LLM), которая является ключевым компонентом чат -бота.\n", "\n", - "We'll start by counting the number of times each word appears in a book.\n", - "Then we'll look at pairs of words, and make a list of the words that can follow each word.\n", - "We'll make a simple version of a Markov generator, and as an exercise, you'll have a chance to make a more general version." + "Мы начнем с подсчета количества раз, когда каждое слово появляется в книге.\n", + "Затем мы посмотрим на пары слов и составим список слов, которые могут следовать каждому слову.\n", + "Мы сделаем простую версию генератора Маркова, и в качестве упражнения у вас будет возможность сделать более общую версию." ] }, { @@ -62,10 +62,10 @@ "id": "0e3811b8", "metadata": {}, "source": [ - "## Unique words\n", + "## уникальные слова\n", "\n", - "As a first step toward text analysis, let's read a book -- *The Strange Case Of Dr. Jekyll And Mr. Hyde* by Robert Louis Stevenson -- and count the number of unique words.\n", - "Instructions for downloading the book are in the notebook for this chapter." + "В качестве первого шага к анализу текста, давайте прочитаем книгу - * Странный случай доктора Джекилла и мистера Хайда * Роберта Луи Стивенсона - и подсчитывать количество уникальных слов.\n", + "Инструкции по загрузке книги находятся в записной книжке для этой главы." ] }, { @@ -75,7 +75,7 @@ "tags": [] }, "source": [ - "The following cell downloads the book from Project Gutenberg." + "Следующая ячейка загружает книгу из Project Gutenberg." ] }, { @@ -97,8 +97,8 @@ "tags": [] }, "source": [ - "The version available from Project Gutenberg includes information about the book at the beginning and license information at the end.\n", - "We'll use `clean_file` from Chapter 8 to remove this material and write a \"clean\" file that contains only the text of the book." + "Версия, доступная в Project Gutenberg, включает информацию о книге в начале и информацию о лицензии в конце.\n", + "Мы используем `clean_file` из главы 8, чтобы удалить этот материал и написать« чистый »файл, который содержит только текст книги." ] }, { @@ -167,8 +167,8 @@ "id": "bc66d7e2", "metadata": {}, "source": [ - "We'll use a `for` loop to read lines from the file and `split` to divide the lines into words.\n", - "Then, to keep track of unique words, we'll store each word as a key in a dictionary." + "Мы используем цикл «for» для чтения строк из файла и «разделить», чтобы разделить строки на слова.\n", + "Затем, чтобы отслеживать уникальные слова, мы сохраним каждое слово в качестве ключа в словаре." ] }, { @@ -192,11 +192,11 @@ "id": "85171a3a", "metadata": {}, "source": [ - "The length of the dictionary is the number of unique words -- about `6000` by this way of counting.\n", - "But if we inspect them, we'll see that some are not valid words.\n", + "Длина словаря - это количество уникальных слов - около `6000` по этому способу подсчета.\n", + "Но если мы осмотрим их, мы увидим, что некоторые не являются действительными словами.\n", "\n", - "For example, let's look at the longest words in `unique_words`.\n", - "We can use `sorted` to sort the words, passing the `len` function as a keyword argument so the words are sorted by length." + "Например, давайте посмотрим на самые длинные слова в `in unique_words`.\n", + "Мы можем использовать «отсортированный» для сортировки слов, передавая функцию `len` в качестве аргумента ключевого слова, чтобы слова отсортированы по длине." ] }, { @@ -214,13 +214,13 @@ "id": "795f5327", "metadata": {}, "source": [ - "The slice index, `[-5:]`, selects the last `5` elements of the sorted list, which are the longest words. \n", + "Индекс среза, `[-5:]`, выбирает последние элементы сортированного списка, которые являются самыми длинными словами. \n", "\n", - "The list includes some legitimately long words, like \"circumscription\", and some hyphenated words, like \"chocolate-coloured\".\n", - "But some of the longest \"words\" are actually two words separated by a dash.\n", - "And other words include punctuation like periods, exclamation points, and quotation marks.\n", + "Список включает в себя некоторые законно длинные слова, такие как «Ограничение», и некоторые дефис-слова, такие как «шоколадный цвет».\n", + "Но некоторые из самых длинных «слов» на самом деле являются двумя словами, разделенными чертой.\n", + "И другие слова включают пунктуацию, как периоды, восклицательные знаки и кавычки.\n", "\n", - "So, before we move on, let's deal with dashes and other punctuation." + "Итак, прежде чем мы пойдем дальше, давайте разберемся с Dashes и другими пунктуациями." ] }, { @@ -228,15 +228,15 @@ "id": "bf89fafa", "metadata": {}, "source": [ - "## Punctuation\n", + "## пунктуация\n", "\n", - "To identify the words in the text, we need to deal with two issues:\n", + "Чтобы определить слова в тексте, нам нужно решить два вопроса:\n", "\n", - "* When a dash appears in a line, we should replace it with a space -- then when we use `split`, the words will be separated.\n", + "* Когда в линии появляется черта, мы должны заменить ее пространством - затем, когда мы используем `split`, слова будут разделены.\n", "\n", - "* After splitting the words, we can use `strip` to remove punctuation.\n", + "* После разделения слов мы можем использовать `strip 'для удаления пунктуации.\n", "\n", - "To handle the first issue, we can use the following function, which takes a string, replaces dashes with spaces, splits the string, and returns the resulting list." + "Чтобы решить первую проблему, мы можем использовать следующую функцию, которая принимает строку, заменяет тире на пробелы, разбивает строку и возвращает полученный список." ] }, { @@ -255,8 +255,8 @@ "id": "d5decdec", "metadata": {}, "source": [ - "Notice that `split_line` only replaces dashes, not hyphens.\n", - "Here's an example." + "Обратите внимание, что `split_line 'только заменяет панели, а не дефисы.\n", + "Вот пример." ] }, { @@ -274,11 +274,11 @@ "id": "0d9eb318", "metadata": {}, "source": [ - "Now, to remove punctuation from the beginning and end of each word, we can use `strip`, but we need a list of characters that are considered punctuation.\n", + "Теперь, чтобы удалить пунктуацию с самого начала и конца каждого слова, мы можем использовать «полосу», но нам нужен список символов, которые считаются пунктуацией.\n", "\n", - "Characters in Python strings are in Unicode, which is an international standard used to represent letters in nearly every alphabet, numbers, symbols, punctuation marks, and more.\n", - "The `unicodedata` module provides a `category` function we can use to tell which characters are punctuation.\n", - "Given a letter, it returns a string with information about what category the letter is in." + "Персонажи в струнах Python находятся в Unicode, который является международным стандартом, используемым для представления букв почти в каждом алфавите, числах, символах, знаках пунктуации и многом другом.\n", + "Модуль `UnicodeData` обеспечивает функцию« категория », которую мы можем использовать, чтобы сказать, какие символы являются пунктуацией.\n", + "Учитывая письмо, он возвращает строку с информацией о категории, в которой находится письмо." ] }, { @@ -298,9 +298,9 @@ "id": "994835ea", "metadata": {}, "source": [ - "The category string of `'A'` is `'Lu'` -- the `'L'` means it is a letter and the `'u'` means it is uppercase.\n", + "Строка категории `'a'`` `lu'' -` 'l'`означает, что это буква, а« u »означает, что это - верх.\n", "\n", - "The category string of `'.'` is `'Po'` -- the `'P'` means it is punctuation and the `'o'` means its subcategory is \"other\"." + "Строка категории `'.'` '' Po'` - «p'» означает, что это пунктуация, а «O'» означает, что его подкатегория - «Другое»." ] }, { @@ -318,8 +318,8 @@ "id": "03773b9b", "metadata": {}, "source": [ - "We can find the punctuation marks in the book by checking for characters with categories that begin with `'P'`.\n", - "The following loop stores the unique punctuation marks in a dictionary." + "Мы можем найти знаки препинания в книге, проверив персонажей с категориями, которые начинаются с «p'».\n", + "Следующая петля хранит уникальные знаки препинания в словаре." ] }, { @@ -342,7 +342,7 @@ "id": "e6741dfa", "metadata": {}, "source": [ - "To make a list of punctuation marks, we can join the keys of the dictionary into a string." + "Чтобы составить список знаков препинания, мы можем присоединиться к ключам словаря в строку." ] }, { @@ -361,7 +361,7 @@ "id": "6af8d5a2", "metadata": {}, "source": [ - "Now that we know which characters in the book are punctuation, we can write a function that takes a word, strips punctuation from the beginning and end, and converts it to lower case." + "Теперь, когда мы знаем, какие персонажи в книге являются пунктуацией, мы можем написать функцию, которая берет слово, линит пунктуацию с самого начала и конец и преобразует ее в нижний регистр." ] }, { @@ -380,7 +380,7 @@ "id": "58a78cb1", "metadata": {}, "source": [ - "Here's an example." + "Вот пример." ] }, { @@ -398,7 +398,7 @@ "id": "314e4fbd", "metadata": {}, "source": [ - "Because `strip` removes characters from the beginning and end, it leaves hyphenated words alone." + "Поскольку `strip 'удаляет символы с самого начала и конец, он оставляет дефисацию в покое." ] }, { @@ -416,7 +416,7 @@ "id": "99050f8a", "metadata": {}, "source": [ - "Now here's a loop that uses `split_line` and `clean_word` to identify the unique words in the book." + "Теперь вот цикл, который использует `split_line` и` clean_word`, чтобы определить уникальные слова в книге." ] }, { @@ -440,8 +440,8 @@ "id": "992e5466", "metadata": {}, "source": [ - "With this stricter definition of what a word is, there are about 4000 unique words.\n", - "And we can confirm that the list of longest words has been cleaned up." + "С этим более строгим определением того, что такое слово, существует около 4000 уникальных слов.\n", + "И мы можем подтвердить, что список самых длинных слов был очищен." ] }, { @@ -459,7 +459,7 @@ "id": "8014c330", "metadata": {}, "source": [ - "Now let's see how many times each word is used." + "Теперь давайте посмотрим, сколько раз используется каждое слово." ] }, { @@ -467,9 +467,9 @@ "id": "7ef40180", "metadata": {}, "source": [ - "## Word frequencies\n", + "## частоты слов\n", "\n", - "The following loop computes the frequency of each unique word." + "Следующий цикл вычисляет частоту каждого уникального слова." ] }, { @@ -494,10 +494,10 @@ "id": "bd680b81", "metadata": {}, "source": [ - "The first time we see a word, we initialize its frequency to `1`. If we see the same word again later, we increment its frequency.\n", + "В первый раз, когда мы видим слово, мы инициализируем его частоту до `1`. Если мы снова увидим то же слово, мы увеличиваем его частоту.\n", "\n", - "To see which words appear most often, we can use `items` to get the key-value pairs from `word_counter`, and sort them by the second element of the pair, which is the frequency.\n", - "First we'll define a function that selects the second element." + "Чтобы увидеть, какие слова появляются чаще всего, мы можем использовать «элементы», чтобы получить пары клавиш значений от `word_counter` и отсортировать их по вторым элементам пары, которая является частотой.\n", + "Сначала мы определим функцию, которая выбирает второй элемент." ] }, { @@ -516,11 +516,11 @@ "id": "b15a5bd6", "metadata": {}, "source": [ - "Now we can use `sorted` with two keyword arguments:\n", + "Теперь мы можем использовать `sorted` с двумя аргументами ключевого слова:\n", "\n", - "* `key=second_element` means the items will be sorted according to the frequencies of the words.\n", + "* `key = second_element` означает, что элементы будут отсортированы в соответствии с частотами слов.\n", "\n", - "* `reverse=True` means the items will be sorted in reverse order, with the most frequent words first." + "* `reverse = true` означает, что элементы будут отсортированы в обратном порядке, сначала с наиболее частыми словами." ] }, { @@ -538,7 +538,7 @@ "id": "db6812e2", "metadata": {}, "source": [ - "Here are the five most frequent words." + "Вот пять наиболее частых слов." ] }, { @@ -557,8 +557,8 @@ "id": "551e81bb", "metadata": {}, "source": [ - "In the next section, we'll encapsulate this loop in a function.\n", - "And we'll use it to demonstrate a new feature -- optional parameters." + "В следующем разделе мы инкапсулируем этот цикл в функцию.\n", + "И мы будем использовать его, чтобы продемонстрировать новую функцию - дополнительные параметры." ] }, { @@ -566,10 +566,10 @@ "id": "45243ccc", "metadata": {}, "source": [ - "## Optional parameters\n", + "## необязательные параметры\n", "\n", - "We've used built-in functions that take optional parameters.\n", - "For example, `round` takes an optional parameters called `ndigits` that indicates how many decimal places to keep." + "Мы использовали встроенные функции, которые принимают дополнительные параметры.\n", + "Например, «Round» принимает дополнительные параметры, называемые «ndigits», которые указывают на то, сколько десятичных мест сохранить." ] }, { @@ -587,8 +587,8 @@ "id": "6ae60945", "metadata": {}, "source": [ - "But it's not just built-in functions -- we can write functions with optional parameters, too.\n", - "For example, the following function takes two parameters, `word_counter` and `num`." + "Но это не просто встроенные функции-мы также можем написать функции с дополнительными параметрами.\n", + "Например, следующая функция принимает два параметра: `word_counter` и` num`." ] }, { @@ -610,9 +610,9 @@ "id": "78cb1531", "metadata": {}, "source": [ - "The second parameter looks like an assignment statement, but it's not -- it's an optional parameter.\n", + "Второй параметр выглядит как оператор назначения, но это не так - это необязательный параметр.\n", "\n", - "If you call this function with one argument, `num` gets the **default value**, which is `5`." + "Если вы называете эту функцию одним аргументом, `num` получает значение ** по умолчанию **, которое равно` 5`." ] }, { @@ -630,7 +630,7 @@ "id": "29753ad6", "metadata": {}, "source": [ - "If you call this function with two arguments, the second argument gets assigned to `num` instead of the default value." + "Если вы называете эту функцию с двумя аргументами, второй аргумент назначается «num» вместо значения по умолчанию." ] }, { @@ -648,9 +648,9 @@ "id": "e9bf907b", "metadata": {}, "source": [ - "In that case, we would say the optional argument **overrides** the default value.\n", + "В этом случае мы бы сказали, что необязательный аргумент ** переопределяет ** значение по умолчанию.\n", "\n", - "If a function has both required and optional parameters, all of the required parameters have to come first, followed by the optional ones." + "Если функция имеет как требуемые, так и дополнительные параметры, все необходимые параметры должны быть первыми, а затем дополнительные." ] }, { @@ -675,14 +675,14 @@ "tags": [] }, "source": [ - "## Dictionary subtraction\n", + "## Словарь вычитание\n", "\n", - "Suppose we want to spell-check a book -- that is, find a list of words that might be misspelled.\n", - "One way to do that is to find words in the book that don't appear in a list of valid words.\n", - "In previous chapters, we've used a list of words that are considered valid in word games like Scrabble.\n", - "Now we'll use this list to spell-check Robert Louis Stevenson.\n", + "Предположим, мы хотим проверить книгу, то есть найти список слов, которые могут быть написаны с ошибкой.\n", + "Один из способов сделать это - найти слова в книге, которые не появляются в списке действительных слов.\n", + "В предыдущих главах мы использовали список слов, которые считаются действительными в таких словах, как Scrabble.\n", + "Теперь мы будем использовать этот список для проверки орфографии Роберта Луи Стивенсона.\n", "\n", - "We can think of this problem as set subtraction -- that is, we want to find all the words from one set (the words in the book) that are not in the other (the words in the list)." + "Мы можем думать об этой проблеме как о вычитании установки, то есть мы хотим найти все слова из одного набора (слова в книге), которые не находятся в другом (слова в списке)." ] }, { @@ -692,7 +692,7 @@ "tags": [] }, "source": [ - "The following cell downloads the word list." + "Следующая ячейка загружает список слов." ] }, { @@ -712,7 +712,7 @@ "id": "2a46556c", "metadata": {}, "source": [ - "As we've done before, we can read the contents of `words.txt` and split it into a list of strings." + "Как мы делали раньше, мы можем прочитать содержимое `words.txt` и разделить его на список строк." ] }, { @@ -730,7 +730,7 @@ "id": "22becbab", "metadata": {}, "source": [ - "Then we'll store the words as keys in a dictionary so we can use the `in` operator to check quickly whether a word is valid." + "Затем мы сохраним слова в качестве ключей в словаре, чтобы мы могли использовать оператора «в», чтобы быстро проверить, является ли слово достоверным." ] }, { @@ -750,7 +750,7 @@ "id": "94cc7c61", "metadata": {}, "source": [ - "Now, to identify words that appear in the book but not in the word list, we'll use `subtract`, which takes two dictionaries as parameters and returns a new dictionary that contains all the keys from one that are not in the other." + "Теперь, чтобы идентифицировать слова, которые появляются в книге, но не в списке слов, мы будем использовать «вычтенный», который принимает два словаря в качестве параметров и возвращает новый словарь, который содержит все ключи от одного, которых нет в другом." ] }, { @@ -773,7 +773,7 @@ "id": "e70c63b4", "metadata": {}, "source": [ - "Here's how we use it." + "Вот как мы его используем." ] }, { @@ -791,7 +791,7 @@ "id": "f8ada7bd", "metadata": {}, "source": [ - "To get a sample of words that might be misspelled, we can print the most common words in `diff`." + "Чтобы получить образец слов, которые могут быть сформулированы, мы можем распечатать наиболее распространенные слова в «diff»." ] }, { @@ -809,10 +809,10 @@ "id": "deeec418", "metadata": {}, "source": [ - "The most common \"misspelled\" words are mostly names and a few single-letter words (Mr. Utterson is Dr. Jekyll's friend and lawyer).\n", + "Наиболее распространенными словами «неправильно» являются в основном имена и несколько однобуквенных слов (мистер Уттерсон-друг и адвокат доктора Джекилла).\n", "\n", - "If we select words that only appear once, they are more likely to be actual misspellings.\n", - "We can do that by looping through the items and making a list of words with frequency `1`." + "Если мы выбираем слова, которые появляются только один раз, они с большей вероятностью будут фактическими ошибками.\n", + "Мы можем сделать это, пробежая элементы и составив список слов с частотой `1`." ] }, { @@ -833,7 +833,7 @@ "id": "98ae9281", "metadata": {}, "source": [ - "Here are the last few elements of the list." + "Вот последние несколько элементов списка." ] }, { @@ -851,8 +851,8 @@ "id": "c5040834", "metadata": {}, "source": [ - "Most of them are valid words that are not in the word list.\n", - "But `'reindue'` appears to be a misspelling of `'reinduce'`, so at least we found one legitimate error." + "Большинство из них являются действительными словами, которых нет в списке слов.\n", + "Но «охрана», по -видимому, является неправильным написанием «повторного положения», поэтому, по крайней мере, мы нашли одну законную ошибку." ] }, { @@ -860,22 +860,22 @@ "id": "afcbbe19", "metadata": {}, "source": [ - "## Random numbers\n", + "## случайные числа\n", "\n", - "As a step toward Markov text generation, next we'll choose a random sequence of words from `word_counter`.\n", - "But first let's talk about randomness.\n", + "В качестве шага к генерации текста Маркова, затем мы выберем случайную последовательность слов из `word_counter`.\n", + "Но сначала давайте поговорим о случайности.\n", "\n", - "Given the same inputs, most computer programs are **deterministic**, which means they generate the same outputs every time.\n", - "Determinism is usually a good thing, since we expect the same calculation to yield the same result.\n", - "For some applications, though, we want the computer to be unpredictable.\n", - "Games are one example, but there are more.\n", + "Учитывая те же входные данные, большинство компьютерных программ ** детерминированные **, что означает, что они генерируют одни и те же выходы каждый раз.\n", + "Обычно детерминизм - это хорошая вещь, поскольку мы ожидаем, что тот же расчет будет даст тот же результат.\n", + "Однако для некоторых приложений мы хотим, чтобы компьютер был непредсказуемым.\n", + "Игры - один из примеров, но есть еще больше.\n", "\n", - "Making a program truly nondeterministic turns out to be difficult, but there are ways to fake it.\n", - "One is to use algorithms that generate **pseudorandom** numbers.\n", - "Pseudorandom numbers are not truly random because they are generated by a deterministic computation, but just by looking at the numbers it is all but impossible to distinguish them from random.\n", + "Сделать программу по -настоящему нетерминированной оказывается трудной, но есть способы ее подделать.\n", + "Одним из них является использование алгоритмов, которые генерируют ** псевдорандома ** числа.\n", + "Числа псевдордомов не являются по -настоящему случайными, потому что они генерируются детерминированными вычислениями, но, просто глядя на числа, почти невозможно отличить их от случайных.\n", "\n", - "The `random` module provides functions that generate pseudorandom numbers -- which I will simply call \"random\" from here on.\n", - "We can import it like this." + "Модуль «случайный» предоставляет функции, которые генерируют числа псевдордомов, которые я просто назову «случайным» с этого момента.\n", + "Мы можем импортировать его так." ] }, { @@ -908,7 +908,7 @@ "id": "8cbbd7f8", "metadata": {}, "source": [ - "The `random` module provides a function called `choice` that chooses an element from a list at random, with every element having the same probability of being chosen." + "Модуль «случайный» предоставляет функцию, называемую «выбор», которая выбирает элемент из списка случайным образом, причем каждый элемент имеет одинаковую вероятность выбора." ] }, { @@ -927,7 +927,7 @@ "id": "57c15af2", "metadata": {}, "source": [ - "If you call the function again, you might get the same element again, or a different one." + "Если вы снова вызовите функцию, вы можете снова получить один и тот же элемент или другой." ] }, { @@ -945,9 +945,9 @@ "id": "6f0c2572", "metadata": {}, "source": [ - "In the long run, we expect to get every element about the same number of times.\n", + "В долгосрочной перспективе мы ожидаем получить каждый элемент примерно одинаково раз.\n", "\n", - "If you use `choice` with a dictionary, you get a `KeyError`." + "Если вы используете «выбор» с словарем, вы получите `keeError '." ] }, { @@ -969,7 +969,7 @@ "id": "592722f3", "metadata": {}, "source": [ - "To choose a random key, you have to put the keys in a list and then call `choice`." + "Чтобы выбрать случайный ключ, вы должны поместить клавиши в список, а затем позвонить «выбор»." ] }, { @@ -988,7 +988,7 @@ "id": "172d72f6", "metadata": {}, "source": [ - "If we generate a random sequence of words, it doesn't make much sense." + "Если мы генерируем случайную последовательность слов, это не имеет большого смысла." ] }, { @@ -1008,10 +1008,10 @@ "id": "e0e2fbc4", "metadata": {}, "source": [ - "Part of the problem is that we are not taking into account that some words are more common than others.\n", - "The results will be better if we choose words with different \"weights\", so that some are chosen more often than others.\n", + "Часть проблемы в том, что мы не учитываем, что некоторые слова чаще, чем другие.\n", + "Результаты будут лучше, если мы выберем слова с различными «весами», чтобы некоторые из них выбирались чаще, чем другие.\n", "\n", - "If we use the values from `word_counter` as weights, each word is chosen with a probability that depends on its frequency." + "Если мы используем значения из `word_counter` в качестве веса, каждое слово выбирается с вероятностью, которая зависит от его частоты." ] }, { @@ -1029,7 +1029,7 @@ "id": "5098bf93", "metadata": {}, "source": [ - "The `random` module provides another function called `choices` that takes weights as an optional argument." + "Модуль `случайный 'предоставляет другую функцию под названием« Выбор », которая принимает веса в качестве необязательного аргумента." ] }, { @@ -1047,7 +1047,7 @@ "id": "a3341e84", "metadata": {}, "source": [ - "And it takes another optional argument, `k`, that specifies the number of words to select." + "И требуется еще один необязательный аргумент, `k`, который указывает количество слов для выбора." ] }, { @@ -1066,7 +1066,7 @@ "id": "e57e6f3d", "metadata": {}, "source": [ - "The result is a list of strings that we can join into something that's looks more like a sentence." + "Результатом является список строк, которые мы можем присоединиться к чем -то, что больше похоже на предложение." ] }, { @@ -1084,9 +1084,9 @@ "id": "c7a35dff", "metadata": {}, "source": [ - "If you choose words from the book at random, you get a sense of the vocabulary, but a series of random words seldom makes sense because there is no relationship between successive words.\n", - "For example, in a real sentence you expect an article like \"the\" to be followed by an adjective or a noun, and probably not a verb or adverb.\n", - "So the next step is to look at these relationships between words." + "Если вы выбираете слова из книги случайным образом, вы понимаете словарный запас, но серия случайных слов редко имеет смысл, потому что нет никакой связи между последовательными словами.\n", + "Например, в реальном предложении вы ожидаете, что статья, такая как «The», за которой следует прилагательное или существительное, и, вероятно, не глагол или наречие.\n", + "Таким образом, следующий шаг - взглянуть на эти отношения между словами." ] }, { @@ -1096,17 +1096,17 @@ "source": [ "## Bigrams\n", "\n", - "Instead of looking at one word at a time, now we'll look at sequences of two words, which are called **bigrams**.\n", - "A sequence of three words is called a **trigram**, and a sequence with some unspecified number of words is called an **n-gram**.\n", + "Вместо того, чтобы смотреть на одно слово за раз, теперь мы рассмотрим последовательности из двух слов, которые называются ** Bigrams **.\n", + "Последовательность из трех слов называется ** триграмма **, а последовательность с некоторым неустановленным количеством слов называется ** n-грамм **.\n", "\n", - "Let's write a program that finds all of the bigrams in the book and the number of times each one appears.\n", - "To store the results, we'll use a dictionary where\n", + "Давайте напишем программу, которая находит все биграмы в книге, и количество раз каждый раз.\n", + "Чтобы сохранить результаты, мы будем использовать словарь, где\n", "\n", - "* The keys are tuples of strings that represent bigrams, and \n", + "* Ключи - это корты струн, которые представляют биграмс, и \n", "\n", - "* The values are integers that represent frequencies.\n", + "* Значения - это целые числа, которые представляют частоты.\n", "\n", - "Let's call it `bigram_counter`." + "Назовем это `bigram_counter`." ] }, { @@ -1124,9 +1124,9 @@ "id": "33f97a2a", "metadata": {}, "source": [ - "The following function takes a list of two strings as a parameter.\n", - "First it makes a tuple of the two strings, which can be used as a key in a dictionary.\n", - "Then it adds the key to `bigram_counter`, if it doesn't exist, or increments the frequency if it does." + "Следующая функция принимает список из двух строк в качестве параметра.\n", + "Сначала он делает кортеж из двух струн, которые можно использовать в качестве ключа в словаре.\n", + "Затем он добавляет ключ к `bigram_counter`, если он не существует, или увеличивает частоту, если она это делает." ] }, { @@ -1149,11 +1149,11 @@ "id": "5c30f429", "metadata": {}, "source": [ - "As we go through the book, we have to keep track of each pair of consecutive words.\n", - "So if we see the sequence \"man is not truly one\", we would add the bigrams \"man is\", \"is not\", \"not truly\", and so on.\n", + "Когда мы проходим через книгу, мы должны отслеживать каждую пару последовательных слов.\n", + "Поэтому, если мы увидим последовательность «Человек не один», мы бы добавили биграмс «человек», «не», «не по -настоящему» и так далее.\n", "\n", - "To keep track of these bigrams, we'll use a list called `window`, because it is like a window that slides over the pages of the book, showing only two words at a time.\n", - "Initially, `window` is empty." + "Чтобы отслеживать эти Bigrams, мы будем использовать список под названием «Window», потому что это похоже на окно, которое скользит по страницам книги, показывая только два слова за раз.\n", + "Первоначально `window 'пусто." ] }, { @@ -1171,7 +1171,7 @@ "id": "9376558c", "metadata": {}, "source": [ - "We'll use the following function to process the words one at a time." + "Мы будем использовать следующую функцию для обработки слов по одному." ] }, { @@ -1194,14 +1194,14 @@ "id": "56895591", "metadata": {}, "source": [ - "The first time this function is called, it appends the given word to `window`.\n", - "Since there is only one word in the window, we don't have a bigram yet, so the function ends.\n", + "В первый раз, когда эта функция называется, она добавляет данное слово в `window '.\n", + "Поскольку в окне есть только одно слово, у нас еще нет биграма, поэтому функция заканчивается.\n", "\n", - "The second time it's called -- and every time thereafter -- it appends a second word to `window`.\n", - "Since there are two words in the window, it calls `count_bigram` to keep track of how many times each bigram appears.\n", - "Then it uses `pop` to remove the first word from the window.\n", + "Во второй раз это называется - и каждый раз после этого - он добавляет второе слово в «окно».\n", + "Поскольку в окне есть два слова, он называет `count_bigram`, чтобы отслеживать, сколько раз появляется каждый биграм.\n", + "Затем он использует `pop`, чтобы удалить первое слово из окна.\n", "\n", - "The following program loops through the words in the book and processes them one at a time." + "Следующая программа проходит через слова в книге и обрабатывает их по одному." ] }, { @@ -1222,8 +1222,8 @@ "id": "20c4627a", "metadata": {}, "source": [ - "The result is a dictionary that maps from each bigram to the number of times it appears.\n", - "We can use `print_most_common` to see the most common bigrams." + "Результатом является словарь, который отображает от каждого биграма до количества раз, когда он появляется.\n", + "Мы можем использовать `print_sty_common`, чтобы увидеть наиболее распространенные биграмы." ] }, { @@ -1241,8 +1241,8 @@ "id": "757bd309", "metadata": {}, "source": [ - "Looking at these results, we can get a sense of which pairs of words are most likely to appear together.\n", - "We can also use the results to generate random text, like this." + "Глядя на эти результаты, мы можем понять, какие пары слов, скорее всего, появятся вместе.\n", + "Мы также можем использовать результаты для генерации случайного текста, как это." ] }, { @@ -1274,10 +1274,10 @@ "id": "eda80407", "metadata": {}, "source": [ - "`bigrams` is a list of the bigrams that appear in the books.\n", - "`weights` is a list of their frequencies, so `random_bigrams` is a sample where the probability a bigram is selected is proportional to its frequency. \n", + "`Bigrams ' - это список биграмсов, которые появляются в книгах.\n", + "`Weews` - это список их частот, поэтому` random_bigrams` - это выборка, в которой вероятность выбранности биграм пропорциональна его частоте. \n", "\n", - "Here are the results." + "Вот результаты." ] }, { @@ -1296,7 +1296,7 @@ "id": "5f24c3b6", "metadata": {}, "source": [ - "This way of generating text is better than choosing random words, but still doesn't make a lot of sense." + "Этот способ создания текста лучше, чем выбирать случайные слова, но все еще не имеет большого смысла." ] }, { @@ -1304,10 +1304,10 @@ "id": "a13d93b5", "metadata": {}, "source": [ - "## Markov analysis\n", + "## Анализ Маркова\n", "\n", - "We can do better with Markov chain text analysis, which computes, for each word in a text, the list of words that come next.\n", - "As an example, we'll analyze these lyrics from the Monty Python song *Eric, the Half a Bee*:" + "Мы можем добиться большего успеха с анализом текста цепи Маркова, который вычисляет для каждого слова в тексте, список слов, которые следуют дальше.\n", + "Например, мы проанализируем эти тексты из песни Monty Python *Eric, половина пчелы *:" ] }, { @@ -1330,7 +1330,7 @@ "id": "583ab9f0", "metadata": {}, "source": [ - "To store the results, we'll use a dictionary that maps from each word to the list of words that follow it." + "Чтобы сохранить результаты, мы будем использовать словарь, который отображает из каждого слова в список слов, которые следуют за ним." ] }, { @@ -1348,7 +1348,7 @@ "id": "d5d85b09", "metadata": {}, "source": [ - "As an example, let's start with the first two words of the song." + "В качестве примера, давайте начнем с первых двух слов песни." ] }, { @@ -1367,7 +1367,7 @@ "id": "0349fe78", "metadata": {}, "source": [ - "If the first word is not in `successor_map`, we have to add a new item that maps from the first word to a list containing the second word." + "Если первое слово не в `customor_map`, мы должны добавить новый элемент, который отображает из первого слова в список, содержащий второе слово." ] }, { @@ -1386,7 +1386,7 @@ "id": "55bb8df9", "metadata": {}, "source": [ - "If the first word is already in the dictionary, we can look it up to get the list of successors we've seen so far, and append the new one." + "Если первое слово уже в словаре, мы можем посмотреть его, чтобы получить список преемников, которых мы видели до сих пор, и добавить новый." ] }, { @@ -1408,7 +1408,7 @@ "id": "6289cc32", "metadata": {}, "source": [ - "The following function encapsulates these steps." + "Следующая функция инкапсулирует эти шаги." ] }, { @@ -1432,11 +1432,11 @@ "id": "74a51700", "metadata": {}, "source": [ - "If the same bigram appears more that once, the second word is added to the list more than once.\n", - "In this way, `successor_map` keeps track of how many times each successor appears.\n", + "Если тот же биграм появляется больше, чем один раз, второе слово добавляется в список более одного раза.\n", + "Таким образом, `custeror_map` отслеживает, сколько раз появляется каждый преемник.\n", "\n", - "As we did in the previous section, we'll use a list called `window` to store pairs of consecutive words.\n", - "And we'll use the following function to process the words one at a time." + "Как и в предыдущем разделе, мы будем использовать список под названием «Window» для хранения пар последовательных слов.\n", + "И мы будем использовать следующую функцию для обработки слов по одному." ] }, { @@ -1459,7 +1459,7 @@ "id": "861a60d9", "metadata": {}, "source": [ - "Here's how we use it to process the words in the song." + "Вот как мы используем его для обработки слов в песне." ] }, { @@ -1482,7 +1482,7 @@ "id": "bf490d67", "metadata": {}, "source": [ - "And here are the results." + "И вот результаты." ] }, { @@ -1500,11 +1500,11 @@ "id": "ff7bad74", "metadata": {}, "source": [ - "The word `'half'` can be followed by `'a'`, `'not'`, or `'the'`.\n", - "The word `'a'` can be followed by `'bee'` or `'vis'`.\n", - "Most of the other words appear only once, so they are followed by only a single word.\n", + "Слово «полу» может сопровождаться `'a' ',`' not '' или `''.\n", + "Слово «a» может сопровождаться `'bee'' 'или`' vis '.\n", + "Большинство других слов появляются только один раз, поэтому за ними следует только одно слово.\n", "\n", - "Now let's analyze the book." + "Теперь давайте проанализируем книгу." ] }, { @@ -1528,7 +1528,7 @@ "id": "2676e2fb", "metadata": {}, "source": [ - "We can look up any word and find the words that can follow it." + "Мы можем искать любое слово и найти слова, которые могут следовать ему." ] }, { @@ -1566,7 +1566,7 @@ "id": "7b777a9c", "metadata": {}, "source": [ - "In this list of successors, notice that the word `'to'` appears three times -- the other successors only appear once." + "В этом списке преемников обратите внимание, что слово «до» появляется три раза - другие преемники появляются только один раз." ] }, { @@ -1574,18 +1574,18 @@ "id": "e8bf85fc", "metadata": {}, "source": [ - "## Generating text\n", + "## генерирование текста\n", "\n", - "We can use the results from the previous section to generate new text with the same relationships between consecutive words as in the original.\n", - "Here's how it works:\n", + "Мы можем использовать результаты из предыдущего раздела для создания нового текста с теми же отношениями между последовательными словами, что и в оригинале.\n", + "Вот как это работает:\n", "\n", - "* Starting with any word that appears in the text, we look up its possible successors and choose one at random.\n", + "* Начиная с любого слова, которое появляется в тексте, мы смотрим на его возможных преемников и выбираем его случайным образом.\n", "\n", - "* Then, using the chosen word, we look up its possible successors, and choose one at random.\n", + "* Затем, используя выбранное слово, мы смотрим его возможных преемников и выбираем его случайным образом.\n", "\n", - "We can repeat this process to generate as many words as we want.\n", - "As an example, let's start with the word `'although'`.\n", - "Here are the words that can follow it." + "Мы можем повторить этот процесс, чтобы генерировать столько слов, сколько хотим.\n", + "В качестве примера, давайте начнем со слова «хотя».\n", + "Вот слова, которые могут следовать за ним." ] }, { @@ -1621,7 +1621,7 @@ "id": "b26a2ead", "metadata": {}, "source": [ - "We can use `choice` to choose from the list with equal probability." + "Мы можем использовать «выбор», чтобы выбрать из списка с одинаковой вероятностью." ] }, { @@ -1640,9 +1640,9 @@ "id": "9741beca", "metadata": {}, "source": [ - "If the same word appears more than once in the list, it is more likely to be selected.\n", + "Если одно и то же слово появляется более одного раза в списке, оно будет выбран.\n", "\n", - "Repeating these steps, we can use the following loop to generate a longer series." + "Повторяя эти шаги, мы можем использовать следующий цикл для создания более длинной серии." ] }, { @@ -1663,11 +1663,11 @@ "id": "38a2d79a", "metadata": {}, "source": [ - "The result sounds more like a real sentence, but it still doesn't make much sense.\n", + "Результат звучит больше как реальное предложение, но это все еще не имеет большого смысла.\n", "\n", - "We can do better using more than one word as a key in `successor_map`.\n", - "For example, we can make a dictionary that maps from each bigram -- or trigram -- to the list of words that come next.\n", - "As an exercise, you'll have a chance to implement this analysis and see what the results look like." + "Мы можем лучше использовать более одного слова в качестве ключа в `curstor_map`.\n", + "Например, мы можем сделать словарь, который карты из каждой биграм - или триграммы - в список слов, которые приходят дальше.\n", + "В качестве упражнения у вас будет возможность реализовать этот анализ и посмотреть, как выглядят результаты." ] }, { @@ -1677,32 +1677,32 @@ "tags": [] }, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "At this point we are writing more substantial programs, and you might find that you are spending more time debugging.\n", - "If you are stuck on a difficult bug, here are a few things to try:\n", + "На данный момент мы пишем более существенные программы, и вы можете обнаружить, что вы тратите больше времени на отладку.\n", + "Если вы застряли на сложной ошибке, вот несколько вещей, которые нужно попробовать:\n", "\n", - "* Reading: Examine your code, read it back to yourself, and check that it says what you meant to say.\n", + "* Чтение: проверьте свой код, прочитайте его обратно и проверьте, что он говорит то, что вы хотели сказать.\n", "\n", - "* Running: Experiment by making changes and running different versions. Often if you display the right thing at the right place in the program, the problem becomes obvious, but sometimes you have to build scaffolding.\n", + "* Запуск: Экспериментируйте, внося изменения и запустив разные версии. Часто, если вы отображаете правильные вещи в нужном месте в программе, проблема становится очевидной, но иногда вам приходится строить леса.\n", "\n", - "* Ruminating: Take some time to think! What kind of error is it: syntax, runtime,\n", - " or semantic? What information can you get from the error messages,\n", - " or from the output of the program? What kind of error could cause\n", - " the problem you're seeing? What did you change last, before the\n", - " problem appeared?\n", + "* Размышления: понадобится время, чтобы подумать! Что это за ошибка: синтаксис, время выполнения,\n", + " или семантический? Какая информация вы можете получить от сообщений об ошибках,\n", + " Или из вывода программы? Какая ошибка может вызвать\n", + " Проблема, которую вы видите? Что вы изменили в последний раз, до\n", + " Появилась проблема?\n", "\n", - "* Rubberducking: If you explain the problem to someone else, you sometimes find the\n", - " answer before you finish asking the question. Often you don't need\n", - " the other person; you could just talk to a rubber duck. And that's\n", - " the origin of the well-known strategy called **rubber duck\n", - " debugging**. I am not making this up -- see\n", - " .\n", + "* RubberDucking: Если вы объясните проблему кому -то другому, вы иногда найдете\n", + " Ответьте, прежде чем закончить задание вопроса. Часто вам не нужно\n", + " другой человек; Вы могли бы просто поговорить с резиновой уткой. И это\n", + " Происхождение известной стратегии под названием ** резиновая утка\n", + " отладка **. Я не придумываю это - вижу\n", + " .\n", "\n", - "* Retreating: At some point, the best thing to do is back up -- undoing recent\n", - " changes -- until you get to a program that works. Then you can start rebuilding.\n", + "* Отступление: в какой -то момент лучше\n", + " Изменения - пока вы не доберетесь до программы, которая работает. Тогда вы можете начать восстановление.\n", " \n", - "* Resting: If you give your brain a break, sometime it will find the problem for you." + "* Отдых: если вы дадите своему мозгу разрыв, иногда это найдет проблему для вас." ] }, { @@ -1710,15 +1710,15 @@ "id": "12c2cd32", "metadata": {}, "source": [ - "Beginning programmers sometimes get stuck on one of these activities and forget the others. Each activity comes with its own failure mode.\n", + "Начальные программисты иногда застряли на одном из этих действий и забывают других. Каждое действие поставляется с собственным режимом отказа.\n", "\n", - "For example, reading your code works if the problem is a typographical error, but not if the problem is a conceptual misunderstanding.\n", - "If you don't understand what your program does, you can read it 100 times and never see the error, because the error is in your head.\n", + "Например, чтение вашего кода работает, если проблема является типографской ошибкой, но не в том случае, если проблема является концептуальным недопониманием.\n", + "Если вы не понимаете, что делает ваша программа, вы можете прочитать ее 100 раз и никогда не увидеть ошибку, потому что ошибка у вас в голове.\n", "\n", - "Running experiments can work, especially if you run small, simple tests.\n", - "But if you run experiments without thinking or reading your code, it can take a long time to figure out what's happening.\n", + "Запуск экспериментов может работать, особенно если вы запускаете маленькие, простые тесты.\n", + "Но если вы запускаете эксперименты, не задумываясь и не читая свой код, может потребоваться много времени, чтобы выяснить, что происходит.\n", "\n", - "You have to take time to think. Debugging is like an experimental science. You should have at least one hypothesis about what the problem is. If there are two or more possibilities, try to think of a test that would eliminate one of them." + "Вы должны понадобиться, чтобы подумать. Отладка похожа на экспериментальную науку. У вас должна быть хотя бы одна гипотеза о том, в чем проблема. Если есть две или более возможностей, попробуйте придумать тест, который устранит один из них." ] }, { @@ -1726,18 +1726,18 @@ "id": "a55036e1", "metadata": {}, "source": [ - "But even the best debugging techniques will fail if there are too many\n", - "errors, or if the code you are trying to fix is too big and complicated.\n", - "Sometimes the best option is to retreat, simplifying the program until\n", - "you get back to something that works.\n", + "Но даже лучшие методы отладки потерпят неудачу, если их слишком много\n", + "Ошибки, или если код, который вы пытаетесь исправить, слишком большой и сложный.\n", + "Иногда лучший вариант - отступить, упрощая программу до тех пор, пока\n", + "Вы возвращаетесь к чему -то, что работает.\n", "\n", - "Beginning programmers are often reluctant to retreat because they can't\n", - "stand to delete a line of code (even if it's wrong). If it makes you\n", - "feel better, copy your program into another file before you start\n", - "stripping it down. Then you can copy the pieces back one at a time.\n", + "Начальные программисты часто неохотно отступают, потому что они не могут\n", + "Встаньте, чтобы удалить строку кода (даже если это не так). Если это заставит вас\n", + "Почувствуйте себя лучше, скопируйте свою программу в другой файл, прежде чем начать\n", + "Разбрасывая это. Тогда вы можете скопировать части обратно по одному.\n", "\n", - "Finding a hard bug requires reading, running, ruminating, retreating, and sometimes resting.\n", - "If you get stuck on one of these activities, try the others." + "Поиск жесткой ошибки требует чтения, бега, размышлений, отступления и иногда отдыха.\n", + "Если вы застряли на одном из этих действий, попробуйте другие." ] }, { @@ -1745,31 +1745,31 @@ "id": "25d091af", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**default value:**\n", - "The value assigned to a parameter if no argument is provided.\n", + "** Значение по умолчанию: **\n", + "Значение, присвоенное параметру, если аргумент не предоставлен.\n", "\n", - "**override:**\n", - " To replace a default value with an argument.\n", + "** Переопределение: **\n", + " Чтобы заменить значение по умолчанию на аргумент.\n", "\n", - "**deterministic:**\n", - " A deterministic program does the same thing each time it runs, given the same inputs.\n", + "** Детерминированный: **\n", + " Детерминистская программа делает одно и то же каждый раз, когда она работает, учитывая одинаковые входы.\n", "\n", - "**pseudorandom:**\n", - " A pseudorandom sequence of numbers appears to be random, but is generated by a deterministic program.\n", + "** псевдорандома: **\n", + " Последовательность псевдорендомов чисел, по -видимому, является случайной, но генерируется детерминистской программой.\n", "\n", - "**bigram:**\n", - "A sequence of two elements, often words.\n", + "** Bigram: **\n", + "Последовательность двух элементов, часто слова.\n", "\n", - "**trigram:**\n", - "A sequence of three elements.\n", + "** Триграмма: **\n", + "Последовательность из трех элементов.\n", "\n", - "**n-gram:**\n", - "A sequence of an unspecified number of elements.\n", + "** n-gram: **\n", + "Последовательность неустановленного числа элементов.\n", "\n", - "**rubber duck debugging:**\n", - "A way of debugging by explaining a problem aloud to an inanimate object." + "** Отладка резиновой утки: **\n", + "Способ отладки, объяснив проблему вслух неодушевленным объектам." ] }, { @@ -1777,7 +1777,7 @@ "id": "cde18229", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -1800,9 +1800,9 @@ "id": "9b0efab8", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального помощника\n", "\n", - "In `add_bigram`, the `if` statement creates a new list or appends an element to an existing list, depending on whether the key is already in the dictionary." + "В `add_bigram` оператор« if »создает новый список или добавляет элемент к существующему списку, в зависимости от того, находится ли ключ в словаре." ] }, { @@ -1826,13 +1826,13 @@ "id": "30d9e549", "metadata": {}, "source": [ - "Dictionaries provide a method called `setdefault` that we can use to do the same thing more concisely.\n", - "Ask a virtual assistant how it works, or copy `add_bigram` into a virtual assistant and ask \"Can you rewrite this using `setdefault`?\"\n", + "Словары предоставляют метод под названием «SetDefault», который мы можем использовать, чтобы сделать то же самое более кратко.\n", + "Спросите виртуального помощника, как это работает, или скопируйте `add_bigram` в виртуального помощника и спросите:« Можете ли вы переписать это, используя `setdefault`?»\n", "\n", - "In this chapter we implemented Markov chain text analysis and generation.\n", - "If you are curious, you can ask a virtual assistant for more information on the topic.\n", - "One of the things you might learn is that virtual assistants use algorithms that are similar in many ways -- but also different in important ways.\n", - "Ask a VA, \"What are the differences between large language models like GPT and Markov chain text analysis?\"" + "В этой главе мы реализовали анализ текста и генерации цепи Маркова.\n", + "Если вам любопытно, вы можете попросить виртуального помощника для получения дополнительной информации по теме.\n", + "Одна из вещей, которые вы можете узнать, заключается в том, что виртуальные помощники используют алгоритмы, которые во многих отношениях похожи, но также различны важными способами.\n", + "Спросите VA: «Каковы различия между большими языковыми моделями, такими как анализ текста GPT и марковского текста?»" ] }, { @@ -1840,12 +1840,12 @@ "id": "060c9ef6", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function that counts the number of times each trigram (sequence of three words) appears. \n", - "If you test your function with the text of _Dr. Jekyll and Mr. Hyde_, you should find that the most common trigram is \"said the lawyer\".\n", + "Напишите функцию, которая подсчитывает количество раз, когда появляется каждая триграмма (последовательность трех слов). \n", + "Если вы проверяете свою функцию с помощью текста _dr. Jekyll и Mr. Hyde_, вы должны обнаружить, что наиболее распространенной триграммой является «сказал адвокат».\n", "\n", - "Hint: Write a function called `count_trigram` that is similar to `count_bigram`. Then write a function called `process_word_trigram` that is similar to `process_word_bigram`." + "Подсказка: напишите функцию с именем `count_trigram`, которая похожа на` count_bigram`. Затем напишите функцию с именем `process_word_trigram`, которая похожа на` process_word_bigram`." ] }, { @@ -1875,7 +1875,7 @@ "tags": [] }, "source": [ - "You can use the following loop to read the book and process the words." + "Вы можете использовать следующий цикл, чтобы прочитать книгу и обработать слова." ] }, { @@ -1903,7 +1903,7 @@ "tags": [] }, "source": [ - "Then use `print_most_common` to find the most common trigrams in the book." + "Затем используйте `print_sty_common`, чтобы найти наиболее распространенные триграммы в книге." ] }, { @@ -1923,11 +1923,11 @@ "id": "4bd07bb7", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Now let's implement Markov chain text analysis with a mapping from each bigram to a list of possible successors.\n", + "Теперь давайте внедрим анализ текста цепи Маркова с отображением от каждого биграма в список возможных преемников.\n", "\n", - "Starting with `add_bigram`, write a function called `add_trigram` that takes a list of three words and either adds or updates an item in `successor_map`, using the first two words as the key and the third word as a possible successor." + "Начиная с `add_bigram`, напишите функцию под названием` add_trigram`, которая принимает список из трех слов и добавляет или обновляет элемент в `custcortor_map`, используя первые два слова в качестве ключа и третье слово в качестве возможного преемника." ] }, { @@ -1945,7 +1945,7 @@ "id": "94d683fe", "metadata": {}, "source": [ - "Here's a version of `process_word_trigram` that calls `add_trigram`." + "Вот версия `process_word_trigram`, которая вызывает` add_trigram`." ] }, { @@ -1970,7 +1970,7 @@ "tags": [] }, "source": [ - "You can use the following loop to test your function with the lyrics of \"Eric, the Half a Bee\"." + "Вы можете использовать следующий цикл, чтобы проверить свою функцию с помощью текста «Эрик, половина пчелы»." ] }, { @@ -1997,8 +1997,8 @@ "tags": [] }, "source": [ - "If your function works as intended, the predecessor `('half', 'a')` should map to a list with the single element `'bee'`.\n", - "In fact, as it happens, each bigram in this song appear only once, so all of the values in `successor_map` have a single element." + "Если ваша функция работает так, как предназначена, предшественник `(« половина », 'a')` должен составить карту в список с одним элементом `'bee''.\n", + "На самом деле, как это происходит, каждый биграм в этой песне появляется только один раз, поэтому все значения в `custcoror_map` имеют единый элемент." ] }, { @@ -2018,7 +2018,7 @@ "id": "886212b5", "metadata": {}, "source": [ - "You can use the following loop to test your function with the words from the book." + "Вы можете использовать следующий цикл, чтобы проверить свою функцию со словами из книги." ] }, { @@ -2042,7 +2042,7 @@ "id": "3e1d073e", "metadata": {}, "source": [ - "In the next exercise, you'll use the results to generate new random text." + "В следующем упражнении вы используете результаты для генерации нового случайного текста." ] }, { @@ -2050,9 +2050,9 @@ "id": "04d7a6ee", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "For this exercise, we'll assume that `successor_map` is a dictionary that maps from each bigram to the list of words that follow it." + "Для этого упражнения мы предположим, что `custoror_map` - это словарь, который отображает из каждого биграма в список слов, которые следуют за ним." ] }, { @@ -2076,7 +2076,7 @@ "id": "fb0f8f7d", "metadata": {}, "source": [ - "To generate random text, we'll start by choosing a random key from `successor_map`." + "Чтобы сгенерировать случайный текст, мы начнем с выбора случайного ключа из `customor_map`." ] }, { @@ -2096,15 +2096,15 @@ "id": "83ed6c7e", "metadata": {}, "source": [ - "Now write a loop that generates 50 more words following these steps:\n", + "Теперь напишите цикл, который генерирует еще 50 слов после этих шагов:\n", "\n", - "1. In `successor_map`, look up the list of words that can follow `bigram`.\n", + "1. В `custeror_map` найдите список слов, которые могут следовать за` bigram '.\n", "\n", - "2. Choose one of them at random and print it.\n", + "2. Выберите один из них случайным образом и распечатайте его.\n", "\n", - "3. For the next iteration, make a new bigram that contains the second word from `bigram` and the chosen successor.\n", + "3. Для следующей итерации сделайте новый биграм, который содержит второе слово от `Bigram` и выбранного преемника.\n", "\n", - "For example, if we start with the bigram `('doubted', 'if')` and choose `'from'` as its successor, the next bigram is `('if', 'from')`." + "Например, если мы начнем с Bigram `('сомневались', 'if')` и выберем `'from' 'в качестве преемника, следующий биграм - (' if ',' from ')`." ] }, { @@ -2122,9 +2122,9 @@ "id": "c71d8a89", "metadata": {}, "source": [ - "If everything is working, you should find that the generated text is recognizably similar in style to the original, and some phrases make sense, but the text might wander from one topic to another.\n", + "Если все работает, вы должны обнаружить, что сгенерированный текст узнаваемо по -настоящему похож на оригинал, а некоторые фразы имеют смысл, но текст может бродить от одной темы к другой.\n", "\n", - "As a bonus exercise, modify your solution to the last two exercises to use trigrams as keys in `successor_map`, and see what effect it has on the results." + "В качестве бонусного упражнения измените свое решение до двух последних упражнений, чтобы использовать триграммы в качестве ключей в `custormor_map`, и посмотрите, какое влияние он оказывает на результаты." ] }, { @@ -2146,9 +2146,9 @@ "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -2174,4 +2174,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From afe43afdff92c82bfda4d7e58c8b67c35a95ccdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:54:37 +0300 Subject: [PATCH 39/44] Translate chap14 markdown to Russian --- chapters/chap14.ipynb | 407 +++++++++++++++++++----------------------- 1 file changed, 186 insertions(+), 221 deletions(-) diff --git a/chapters/chap14.ipynb b/chapters/chap14.ipynb index f0f9998..97772ab 100644 --- a/chapters/chap14.ipynb +++ b/chapters/chap14.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг *Think Python 3e* из\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon](https://www.amazon.com/_/dp/1098155432? ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325).\n" ] }, { @@ -41,14 +41,14 @@ "id": "e826e661", "metadata": {}, "source": [ - "# Classes and Functions\n", + "# Классы и функции\n", "\n", - "At this point you know how to use functions to organize code and how to use built-in types to organize data.\n", - "The next step is **object-oriented programming**, which uses programmer-defined types to organize both code and data.\n", + "На этом этапе вы знаете, как использовать функции для организации кода и как использовать встроенные типы для организации данных.\n", + "Следующим шагом является **объектно-ориентированное программирование**, в котором используются типы, определяемые программистом для организации как кода, так и данных.\n", "\n", - "Object-oriented programming is a big topic, so we will proceed gradually.\n", - "In this chapter, we'll start with code that is not idiomatic -- that is, it is not the kind of code experienced programmers write -- but it is a good place to start.\n", - "In the next two chapters, we will use additional features to write more idiomatic code." + "Объектно-ориентированное программирование-большая тема, поэтому мы будем продолжаться постепенно.\n", + "В этой главе мы начнем с кода, который не является идиоматическим, то есть не тот код, которые пишут опытные программисты, но это хорошее место для начала.\n", + "В следующих двух главах мы будем использовать дополнительные функции для написания более идиоматического кода.\n" ] }, { @@ -56,12 +56,12 @@ "id": "6b414d4a", "metadata": {}, "source": [ - "## Programmer-defined types\n", + "## Defermore Programmed Tipes\n", "\n", - "We have used many of Python's built-in types -- now we will define a new type.\n", - "As a first example, we'll create a type called `Time` that represents a time of day.\n", - "A programmer-defined type is also called a **class**.\n", - "A class definition looks like this:" + "Мы использовали многие из встроенных типов Python-теперь мы определим новый тип.\n", + "В качестве первого примера мы создадим тип под названием «Time», который представляет время дня.\n", + "Тип, определенный программистом, также называется **класс**.\n", + "Определение класса выглядит следующим образом:\n" ] }, { @@ -80,12 +80,12 @@ "id": "e2414cd2", "metadata": {}, "source": [ - "The header indicates that the new class is called `Time`.\n", - "The body is a docstring that explains what the class is for.\n", - "Defining a class creates a **class object**.\n", + "Заголовок указывает, что новый класс называется «Время».\n", + "Тело - это Docstring, который объясняет, для чего для класса.\n", + "Определение класса создает объект класса ****.\n", "\n", - "The class object is like a factory for creating objects.\n", - "To create a `Time` object, you call `Time` as if it were a function." + "Объект класса похож на фабрику для создания объектов.\n", + "Чтобы создать объект «Time», вы называете «время», как будто это была функция.\n" ] }, { @@ -103,7 +103,7 @@ "id": "f63247d4", "metadata": {}, "source": [ - "The result is a new object whose type is `__main__.Time`, where `__main__` is the name of the module where `Time` is defined." + "Результатом является новый объект, чей тип `__main __. Time`, где` __main__` - это имя модуля, где определяется `time`.\n" ] }, { @@ -121,7 +121,7 @@ "id": "14d0c96a", "metadata": {}, "source": [ - "When you print an object, Python tells you what type it is and where it is stored in memory (the prefix `0x` means that the following number is in hexadecimal)." + "Когда вы печатаете объект, Python говорит вам, какой он тип и где он хранится в памяти (префикс `0x` означает, что следующее число находится в шестнадцатеричном).\n" ] }, { @@ -139,7 +139,7 @@ "id": "b6445414", "metadata": {}, "source": [ - "Creating a new object is called **instantiation**, and the object is an **instance** of the class." + "Создание нового объекта называется **Commentiation**, а объект - это**экземпляр** класса.\n" ] }, { @@ -147,10 +147,10 @@ "id": "4c3768ec", "metadata": {}, "source": [ - "## Attributes\n", + "## атрибуты\n", "\n", - "An object can contain variables, which are called **attributes** and pronounced with the emphasis on the first syllable, like \"AT-trib-ute\", rather than the second syllable, like \"a-TRIB-ute\".\n", - "We can create attributes using dot notation." + "Объект может содержать переменные, которые называются **атрибутами** и произносятся с акцентом на первый слог, как «At-Trib-ute», а не второй слог, такой как «A-Trib-ute».\n", + "Мы можем создавать атрибуты с использованием точечной нотации.\n" ] }, { @@ -170,9 +170,9 @@ "id": "b3fd8858", "metadata": {}, "source": [ - "This example creates attributes called `hour`, `minute`, and `second`, which contain the hours, minutes, and seconds of the time `11:59:01`, which is lunch time as far as I am concerned.\n", + "Этот пример создает атрибуты, называемые «час», «минута» и «второй», которые содержат часы, минуты и секунды времени `11: 59: 01`, которое, насколько я обеспокоен.\n", "\n", - "The following diagram shows the state of `lunch` and its attributes after these assignments. " + "На следующей диаграмме показано состояние «ланча» и его атрибуты после этих заданий.\n" ] }, { @@ -213,11 +213,11 @@ "id": "d9df5b48", "metadata": {}, "source": [ - "The variable `lunch` refers to a `Time` object, which contains three attributes. \n", - "Each attribute refers to an integer.\n", - "A state diagram like this -- which shows an object and its attributes -- is called an **object diagram**.\n", + "Переменная «обед» относится к объекту «время», который содержит три атрибута. \n", + "Каждый атрибут относится к целому числу.\n", + "Такая диаграмма состояния, которая показывает объект и его атрибуты - называется **объектной диаграммой**.\n", "\n", - "You can read the value of an attribute using the dot operator." + "Вы можете прочитать значение атрибута с помощью оператора DOT.\n" ] }, { @@ -235,7 +235,7 @@ "id": "5ccfaea0", "metadata": {}, "source": [ - "You can use an attribute as part of any expression." + "Вы можете использовать атрибут как часть любого выражения.\n" ] }, { @@ -254,7 +254,7 @@ "id": "c5e6725b", "metadata": {}, "source": [ - "And you can use the dot operator in an expression in an f-string." + "И вы можете использовать оператор DOT в выражении в F-String.\n" ] }, { @@ -272,10 +272,10 @@ "id": "e70671d2", "metadata": {}, "source": [ - "But notice that the previous example is not in the standard format.\n", - "To fix it, we have to print the `minute` and `second` attributes with a leading zero.\n", - "We can do that by extending the expressions in curly braces with a **format specifier**.\n", - "In the following example, the format specifiers indicate that `minute` and `second` should be displayed with at least two digits and a leading zero if needed." + "Но обратите внимание, что предыдущий пример не находится в стандартном формате.\n", + "Чтобы исправить это, мы должны распечатать атрибуты «минута» и «второй» с ведущим нолью.\n", + "Мы можем сделать это, расширяя выражения в кудрявых скобках со спецификатором формата ****.\n", + "В следующем примере спецификаторы формата указывают, что «минута» и «второй» должны отображаться как минимум с двумя цифрами и при необходимости ведущего нуля.\n" ] }, { @@ -293,9 +293,9 @@ "id": "bcbea13a", "metadata": {}, "source": [ - "We'll use this f-string to write a function that displays the value of a `Time`object.\n", - "You can pass an object as an argument in the usual way.\n", - "For example, the following function takes a `Time` object as an argument. " + "Мы будем использовать эту F-String, чтобы написать функцию, которая отображает значение `time`Object.\n", + "Вы можете передать объект как аргумент обычным способом.\n", + "Например, следующая функция принимает объект «Time» в качестве аргумента.\n" ] }, { @@ -315,7 +315,7 @@ "id": "3b8ccbed", "metadata": {}, "source": [ - "When we call it, we can pass `lunch` as an argument." + "Когда мы называем это, мы можем передать «обед» в качестве спора.\n" ] }, { @@ -333,9 +333,9 @@ "id": "18826e53", "metadata": {}, "source": [ - "## Objects as return values\n", + "## объекты как возвращаемые значения\n", "\n", - "Functions can return objects. For example, `make_time` takes parameters called `hour`, `minute`, and `second`, stores them as attributes in a `Time` object, and returns the new object." + "Функции могут возвращать объекты. Например, `make_time` принимает параметры, называемые` hour`, `minute` и` second`, хранит их как атрибуты в объекте «время» и возвращает новый объект.\n" ] }, { @@ -358,8 +358,8 @@ "id": "d8a6acca", "metadata": {}, "source": [ - "It might be surprising that the parameters have the same names as the attributes, but that's a common way to write a function like this.\n", - "Here's how we use `make_time` to create a `Time` object." + "Может быть, удивительно, что параметры имеют те же имена, что и атрибуты, но это общий способ написать такую функцию.\n", + "Вот как мы используем `make_time`, чтобы создать объект« время ».\n" ] }, { @@ -378,12 +378,12 @@ "id": "05720bcb", "metadata": {}, "source": [ - "## Objects are mutable\n", + "## объекты изменяются\n", "\n", - "Suppose you are going to a screening of a movie, like *Monty Python and the Holy Grail*, which starts at `9:20 PM` and runs for `92` minutes, which is one hour `32` minutes.\n", - "What time will the movie end?\n", + "Предположим, что вы собираетесь показывать фильм, например, *Монти Пайтон и Святой Грааль*, который начинается в 9:20 вечера и работает в течение 92 `минут, что составляет один час` 32 `минут.\n", + "В какое время фильм закончится?\n", "\n", - "First, we'll create a `Time` object that represents the start time." + "Во -первых, мы создадим объект «Time», который представляет время начала.\n" ] }, { @@ -402,7 +402,7 @@ "id": "001bcda9", "metadata": {}, "source": [ - "To find the end time, we can modify the attributes of the `Time` object, adding the duration of the movie." + "Чтобы найти время окончания, мы можем изменить атрибуты объекта «время», добавив продолжительность фильма.\n" ] }, { @@ -422,9 +422,9 @@ "id": "7007ab61", "metadata": {}, "source": [ - "The movie will be over at 10:52 PM.\n", + "Фильм будет закончен в 10:52 вечера.\n", "\n", - "Let's encapsulate this computation in a function and generalize it to take the duration of the movie in three parameters: `hours`, `minutes`, and `seconds`." + "Давайте инкапсулируем это вычисление в функцию и обобщаем его, чтобы взять продолжительность фильма в трех параметрах: «Часы», «Минут» и «Секунды».\n" ] }, { @@ -445,7 +445,7 @@ "id": "a51913e2", "metadata": {}, "source": [ - "Here is an example that demonstrates the effect." + "Вот пример, который демонстрирует эффект.\n" ] }, { @@ -465,7 +465,7 @@ "id": "42d7de02", "metadata": {}, "source": [ - "The following stack diagram shows the state of the program just before `increment_time` modifies the object." + "Следующая диаграмма стека показывает состояние программы незадолго до `increment_time` -изменение объекта.\n" ] }, { @@ -519,11 +519,11 @@ "id": "d1e27667", "metadata": {}, "source": [ - "Inside the function, `time` is an alias for `start`, so when `time` is modified, `start` changes.\n", + "Внутри функции «Time» является псевдонимом для `start ', поэтому, когда` time' изменяется, `start 'изменяется.\n", "\n", - "This function works, but after it runs, we're left with a variable named `start` that refers to an object that represents the *end* time, and we no longer have an object that represents the start time.\n", - "It would be better to leave `start` unchanged and make a new object to represent the end time.\n", - "We can do that by copying `start` and modifying the copy." + "Эта функция работает, но после того, как она работает, у нас осталась переменная с именем «Start», которая относится к объекту, который представляет время *end*, и у нас больше нет объекта, который представляет время начала.\n", + "Было бы лучше оставить `start 'без изменений и сделать новый объект, чтобы представлять время окончания.\n", + "Мы можем сделать это, копировав `start 'и изменив копию.\n" ] }, { @@ -531,10 +531,10 @@ "id": "0128f850", "metadata": {}, "source": [ - "## Copying\n", + "## копирование\n", "\n", - "The `copy` module provides a function called `copy` that can duplicate any object.\n", - "We can import it like this." + "Модуль `copy` предоставляет функцию с именем` copy`, которая может дублировать любой объект.\n", + "Мы можем импортировать его так.\n" ] }, { @@ -552,7 +552,7 @@ "id": "940adbeb", "metadata": {}, "source": [ - "To see how it works, let's start with a new `Time` object that represents the start time of the movie." + "Чтобы увидеть, как это работает, давайте начнем с нового объекта «Time», который представляет время начала фильма.\n" ] }, { @@ -570,7 +570,7 @@ "id": "514f05b9", "metadata": {}, "source": [ - "And make a copy." + "И сделать копию.\n" ] }, { @@ -588,7 +588,7 @@ "id": "87d8956b", "metadata": {}, "source": [ - "Now `start` and `end` contain the same data." + "Теперь `start` и` end 'содержат те же данные.\n" ] }, { @@ -607,7 +607,7 @@ "id": "e75c1e09", "metadata": {}, "source": [ - "But the `is` operator confirms that they are not the same object." + "Но оператор IS 'подтверждает, что они не один и тот же объект.\n" ] }, { @@ -625,7 +625,7 @@ "id": "22b68a3f", "metadata": {}, "source": [ - "Let's see what the `==` operator does." + "Посмотрим, что делает оператор `==`.\n" ] }, { @@ -643,8 +643,8 @@ "id": "78ebf931", "metadata": {}, "source": [ - "You might expect `==` to yield `True` because the objects contain the same data.\n", - "But for programmer-defined classes, the default behavior of the `==` operator is the same as the `is` operator -- it checks identity, not equivalence." + "Вы можете ожидать, что `==` позволит `true`, потому что объекты содержат одни и те же данные.\n", + "Но для определенных программиста классов поведение оператора `==` совпадает с оператором `is`-он проверяет идентичность, а не эквивалентность.\n" ] }, { @@ -652,11 +652,11 @@ "id": "a3934fdd-d4cd-41e0-86e6-5bb78d0886a7", "metadata": {}, "source": [ - "## Pure functions\n", + "## чистые функции\n", "\n", - "We can use `copy` to write pure functions that don't modify their parameters.\n", - "For example, here's a function that takes a `Time` object and a duration in hours, minutes and seconds.\n", - "It makes a copy of the original object, uses `increment_time` to modify the copy, and returns it." + "Мы можем использовать `copy` для написания чистых функций, которые не изменяют их параметры.\n", + "Например, вот функция, которая занимает объект «время» и продолжительность часа, минуты и секунды.\n", + "Он делает копию исходного объекта, использует `urment_time` для изменения копии и возвращает ее.\n" ] }, { @@ -677,7 +677,7 @@ "id": "c181af12", "metadata": {}, "source": [ - "Here's how we use it." + "Вот как мы его используем.\n" ] }, { @@ -696,8 +696,8 @@ "id": "54b1ca4a", "metadata": {}, "source": [ - "The return value is a new object representing the end time of the movie.\n", - "And we can confirm that `start` is unchanged." + "Возвращаемое значение - это новый объект, представляющий время окончания фильма.\n", + "И мы можем подтвердить, что `start 'не изменился.\n" ] }, { @@ -715,14 +715,14 @@ "id": "1233b2db", "metadata": {}, "source": [ - "`add_time` is a **pure function** because it does not modify any of the objects passed to it as arguments and its only effect is to return a value.\n", + "`add_time` - это **чистая функция**, потому что она не изменяет ни один из объектов, передаваемых ему в качестве аргументов, и его единственный эффект - вернуть значение.\n", "\n", - "Anything that can be done with impure functions can also be done with pure functions.\n", - "In fact, some programming languages only allow pure functions.\n", - "Programs that use pure functions might be less error-prone, but impure functions are sometimes convenient and can be more efficient.\n", + "Все, что можно сделать с нечистыми функциями, также может быть сделано с помощью чистых функций.\n", + "На самом деле, некоторые языки программирования позволяют только чистые функции.\n", + "Программы, которые используют чистые функции, могут быть менее подверженными ошибкам, но нечистые функции иногда удобны и могут быть более эффективными.\n", "\n", - "In general, I suggest you write pure functions whenever it is reasonable and resort to impure functions only if there is a compelling advantage.\n", - "This approach might be called a **functional programming style**." + "В целом, я предлагаю вам написать чистые функции всякий раз, когда это разумно, и прибегать к нечистым функциям, только если есть убедительное преимущество.\n", + "Этот подход можно назвать**функциональным стилем программирования**.\n" ] }, { @@ -730,12 +730,12 @@ "id": "9d9fabbc", "metadata": {}, "source": [ - "## Prototype and patch\n", + "## Прототип и патч\n", "\n", - "In the previous example, `increment_time` and `add_time` seem to work, but if we try another example, we'll see that they are not quite correct.\n", + "В предыдущем примере `increment_time` и` add_time`, кажется, работают, но если мы попробуем другой пример, мы увидим, что они не совсем правы.\n", "\n", - "Suppose you arrive at the theater and discover that the movie starts at `9:40`, not `9:20`.\n", - "Here's what happens when we compute the updated end time." + "Предположим, вы приходите в театр и обнаружите, что фильм начинается в 9: 40 `, а не« 9: 20 `.\n", + "Вот что происходит, когда мы вычисляем обновленное время окончания.\n" ] }, { @@ -755,10 +755,10 @@ "id": "c712ebf7-7e52-490e-91d7-5f1c83334de0", "metadata": {}, "source": [ - "The result is not a valid time.\n", - "The problem is that `increment_time` does not deal with cases where the number of seconds or minutes adds up to more than `60`.\n", + "Результат не является достоверным временем.\n", + "Проблема заключается в том, что `increment_time` не касается случаев, когда количество секунд или минут наносит более чем« 60 ».\n", "\n", - "Here's an improved version that checks whether `second` exceeds or equals `60` -- if so, it increments `minute` -- then checks whether `minute` exceeds or equals `60` -- if so, it increments `hour`." + "Вот улучшенная версия, которая проверяет, превышает ли «второе» или равняется `60` - если да, то увеличивает` minute` - затем проверяет, превышает ли `minute` или равно` 60` - если это так, это увеличивает `час\n" ] }, { @@ -787,8 +787,8 @@ "id": "c133c5d8", "metadata": {}, "source": [ - "Fixing `increment_time` also fixes `add_time`, which uses it.\n", - "So now the previous example works correctly." + "Исправление `increment_time` также исправляет` add_time`, который использует его.\n", + "Так что теперь предыдущий пример работает правильно.\n" ] }, { @@ -807,9 +807,9 @@ "id": "a2f644a6-ca43-494e-af14-6e845b3d7973", "metadata": {}, "source": [ - "But this function is still not correct, because the arguments might be bigger than `60`.\n", - "For example, suppose we are given the run time as `92` minutes, rather than `1` hours and `32` minutes.\n", - "We might call `add_time` like this." + "Но эта функция все еще не верна, потому что аргументы могут быть больше, чем `60 '.\n", + "Например, предположим, что нам дают время выполнения как «92» минуты, а не «1» и «32» минуты.\n", + "Мы могли бы назвать «add_time».\n" ] }, { @@ -828,9 +828,9 @@ "id": "72e0a08b", "metadata": {}, "source": [ - "The result is not a valid time.\n", - "So let's try a different approach, using the `divmod` function.\n", - "We'll make a copy of `start` and modify it by incrementing the `minute` attribute." + "Результат не является достоверным временем.\n", + "Итак, давайте попробуем другой подход, используя функцию «divmod».\n", + "Мы сделаем копию «Start» и изменим ее, увеличив атрибут `Minute '.\n" ] }, { @@ -850,8 +850,8 @@ "id": "c56355bc", "metadata": {}, "source": [ - "Now `minute` is `132`, which is `2` hours and `12` minutes.\n", - "We can use `divmod` to divide by `60` and return the number of whole hours and the number of minutes left over." + "Теперь `minute` -` 132`, что составляет `2` часы и `12 'минут.\n", + "Мы можем использовать «divmod», чтобы разделить на `60 'и вернуть количество целых часов и количество оставшихся минут.\n" ] }, { @@ -870,7 +870,7 @@ "id": "43204703", "metadata": {}, "source": [ - "Now `minute` is correct, and we can add the hours to `hour`." + "Теперь «минута» верна, и мы можем добавить часы к «часу».\n" ] }, { @@ -889,8 +889,8 @@ "id": "a68ae1cd", "metadata": {}, "source": [ - "The result is a valid time.\n", - "We can do the same thing with `hour` and `second`, and encapsulate the whole process in a function." + "Результат - достоверное время.\n", + "Мы можем сделать то же самое с «Часом» и «вторым» и инкапсулировать весь процесс в функцию.\n" ] }, { @@ -915,7 +915,7 @@ "id": "7437113a", "metadata": {}, "source": [ - "With this version of `increment_time`, `add_time` works correctly, even if the arguments exceed `60`." + "С этой версией `urment_time`` add_time` работает правильно, даже если аргументы превышают `60 '.\n" ] }, { @@ -934,13 +934,13 @@ "id": "7c6329b2", "metadata": {}, "source": [ - "This section demonstrates a program development plan I call **prototype and patch**.\n", - "We started with a simple prototype that worked correctly for the first example.\n", - "Then we tested it with more difficult examples -- when we found an error, we modified the program to fix it, like putting a patch on tire with a puncture.\n", + "Этот раздел демонстрирует план разработки программы, который я называю **прототипом и патч**.\n", + "Мы начали с простого прототипа, который работал правильно для первого примера.\n", + "Затем мы проверили его с более сложными примерами - когда мы нашли ошибку, мы изменили программу, чтобы исправить ее, например, нанести патч на шину с прокол.\n", "\n", - "This approach can be effective, especially if you don't yet have a deep understanding of the problem.\n", - "But incremental corrections can generate code that is unnecessarily complicated -- since it deals with many special cases -- and unreliable -- since it is hard to know if you have\n", - "found all the errors." + "Этот подход может быть эффективным, особенно если у вас еще нет глубокого понимания проблемы.\n", + "Но постепенные исправления могут генерировать код, который излишне сложный - поскольку он имеет дело со многими особыми случаями - и ненадежным - поскольку трудно понять, есть ли у вас\n", + "Нашел все ошибки.\n" ] }, { @@ -948,18 +948,18 @@ "id": "39031461-49a9-4eba-a075-ef49a6f5552b", "metadata": {}, "source": [ - "## Design-first development\n", + "## Design-Pirst Development\n", "\n", - "An alternative plan is **design-first development**, which involves more planning before prototyping. In a design-first process, sometimes a high-level insight into the problem makes the programming much easier.\n", + "Альтернативным планом является **проектирование-первое развитие**, которое включает в себя больше планирования перед прототипированием. В процессе первого дизайна иногда высокое понимание проблемы облегчает программирование.\n", "\n", - "In this case, the insight is that we can think of a `Time` object as a three-digit number in base 60 -- also known as sexagesimal.\n", - "The `second` attribute is the \"ones column\", the `minute` attribute is the \"sixties column\",\n", - "and the `hour` attribute is the \"thirty-six hundreds column\".\n", - "When we wrote `increment_time`, we were effectively doing addition in base 60, which is why we had to carry from one column to the next.\n", + "В этом случае понимание состоит в том, что мы можем думать о объекте «Время» как о трехзначном числе в базе 60, также известном как сексмальный.\n", + "Атрибут «второй» - это «столбец», атрибут `Minute` -« столбец шестидесятых »,\n", + "А атрибут «часа»-это «тридцать шесть сотни сотни столбцов».\n", + "Когда мы написали `urment_time`, мы эффективно делали дополнение в базе 60, поэтому мы должны были перенести из одного столбца в другой.\n", "\n", - "This observation suggests another approach to the whole problem -- we can convert `Time` objects to integers and take advantage of the fact that Python knows how to do integer arithmetic.\n", + "Это наблюдение предлагает другой подход ко всей проблеме - мы можем преобразовать объекты «время» в целые числа и воспользоваться тем фактом, что Python знает, как выполнять целочисленную арифметику.\n", "\n", - "Here is a function that converts from a `Time` to an integer." + "Вот функция, которая преобразуется из «времени» в целое число.\n" ] }, { @@ -980,8 +980,8 @@ "id": "c7e7789e", "metadata": {}, "source": [ - "The result is the number of seconds since the beginning of the day.\n", - "For example, `01:01:01` is `1` hour, `1` minute and `1` second from the beginning of the day, which is the sum of `3600` seconds, `60` seconds, and `1` second." + "Результатом является количество секунд с начала дня.\n", + "Например, `01: 01: 01` - 1` час, `1` минута и` 1` секунды с начала дня, которая является суммой `3600` секунды, `60` 1 секунды и `1` второй.\n" ] }, { @@ -1001,7 +1001,7 @@ "id": "6ea525c8-4547-4bde-91c3-17f45add1bf8", "metadata": {}, "source": [ - "And here's a function that goes in the other direction -- converting an integer to a `Time` object -- using the `divmod` function." + "А вот функция, которая идет в другом направлении - преобразование целого числа в объект «время» - с использованием функции «divmod».\n" ] }, { @@ -1022,7 +1022,7 @@ "id": "4706b5df", "metadata": {}, "source": [ - "We can test it by converting the previous example back to a `Time`." + "Мы можем проверить его, преобразив предыдущий пример обратно в «время».\n" ] }, { @@ -1041,7 +1041,7 @@ "id": "0c2b8469-d4a7-46f9-a0a1-f2a6c1595183", "metadata": {}, "source": [ - "Using these functions, we can write a more concise version of `add_time`." + "Используя эти функции, мы можем написать более краткую версию `add_time`.\n" ] }, { @@ -1062,11 +1062,11 @@ "id": "cb560257", "metadata": {}, "source": [ - "The first line converts the arguments to a `Time` object called `duration`.\n", - "The second line converts `time` and `duration` to seconds and adds them.\n", - "The third line converts the sum to a `Time` object and returns it.\n", + "Первая строка преобразует аргументы в объект «время», называемый «продолжительность».\n", + "Вторая строка преобразует «время» и «продолжительность» в секунды и добавляет их.\n", + "Третья строка преобразует сумму в объект «время» и возвращает ее.\n", "\n", - "Here's how it works." + "Вот как это работает.\n" ] }, { @@ -1086,17 +1086,17 @@ "id": "db762aa8-4aab-4c17-a88d-72c5048f18c0", "metadata": {}, "source": [ - "In some ways, converting from base 60 to base 10 and back is harder than\n", - "just dealing with times. Base conversion is more abstract; our intuition\n", - "for dealing with time values is better.\n", + "В некотором смысле преобразование из базы 60 в основание 10 и назад сложнее, чем\n", + "Просто дело со временем. Базовое преобразование более абстрактно; наша интуиция\n", + "Для работы с временными значениями лучше.\n", "\n", - "But if we have the insight to treat times as base 60 numbers -- and invest the effort to write the conversion functions `time_to_int` and `int_to_time` -- we get a program that is shorter, easier to read and debug, and more reliable.\n", + "Но если у нас есть понимание, чтобы рассматривать время как базовые 60 чисел - и инвестировать усилия, чтобы написать функции преобразования `time_to_int` и` int_to_time` - мы получаем программу, которая легче, проще для чтения и отладка и более надежных.\n", "\n", - "It is also easier to add features later. For example, imagine subtracting two `Time` objects to find the duration between them.\n", - "The naive approach is to implement subtraction with borrowing.\n", - "Using the conversion functions is easier and more likely to be correct.\n", + "Также легче добавить функции позже. Например, представьте, что вы вычитаете два объекта «время», чтобы найти продолжительность между ними.\n", + "Наивный подход заключается в реализации вычитания с заимствованием.\n", + "Использование функций преобразования проще и с большей вероятностью будет правильным.\n", "\n", - "Ironically, sometimes making a problem harder -- or more general -- makes it easier, because there are fewer special cases and fewer opportunities for error." + "По иронии судьбы, иногда усложняет проблему - или более общий - облегчает, потому что существует меньше особых случаев и меньше возможностей для ошибок.\n" ] }, { @@ -1106,10 +1106,10 @@ "tags": [] }, "source": [ - "## Debugging\n", + "## отладка\n", "\n", - "Python provides several built-in functions that are useful for testing and debugging programs that work with objects.\n", - "For example, if you are not sure what type an object is, you can ask." + "Python предоставляет несколько встроенных функций, которые полезны для тестирования и программ отладки, которые работают с объектами.\n", + "Например, если вы не уверены, какой тип объект, вы можете спросить.\n" ] }, { @@ -1127,7 +1127,7 @@ "id": "7ec0eabf", "metadata": {}, "source": [ - "You can also use `isinstance` to check whether an object is an instance of a particular class." + "Вы также можете использовать `isInstance`, чтобы проверить, является ли объект экземпляром определенного класса.\n" ] }, { @@ -1145,8 +1145,8 @@ "id": "4f453fe9", "metadata": {}, "source": [ - "If you are not sure whether an object has a particular attribute, you\n", - "can use the built-in function `hasattr`." + "Если вы не уверены, есть ли у объекта определенный атрибут, вы\n", + "может использовать встроенную функцию `hasattr`.\n" ] }, { @@ -1164,7 +1164,7 @@ "id": "a0131d84", "metadata": {}, "source": [ - "To get all of the attributes, and their values, in a dictionary, you can use `vars`." + "Чтобы получить все атрибуты и их значения в словаре, вы можете использовать «vars».\n" ] }, { @@ -1182,7 +1182,7 @@ "id": "f1a443c8", "metadata": {}, "source": [ - "The `structshape` module, which we saw in [Chapter 11](section_debugging_11), also works with programmer-defined types." + "Модуль Structshape`, который мы видели в [Глава 11](section_debugging_11), также работает с типами, определенными программистом.\n" ] }, { @@ -1215,43 +1215,10 @@ "id": "501436c0-6634-415f-be84-2d130232b2b8", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**object-oriented programming:**\n", - "A style of programming that uses objects to organize code and data.\n", - "\n", - "**class:**\n", - " A programmer-defined type. A class definition creates a new class object.\n", - "\n", - "**class object:**\n", - "An object that represents a class -- it is the result of a class definition.\n", - "\n", - "**instantiation:**\n", - "The process of creating an object that belongs to a class.\n", - "\n", - "**instance:**\n", - " An object that belongs to a class.\n", - "\n", - "**attribute:**\n", - " A variable associated with an object, also called an instance variable.\n", - "\n", - "**object diagram:**\n", - "A graphical representation of an object, its attributes, and their values.\n", - "\n", - "**format specifier:**\n", - "In an f-string, a format specifier determines how a value is converted to a string.\n", - "\n", - "**pure function:**\n", - "A function that does not modify its parameters or have any effect other than returning a value.\n", - "\n", - "**functional programming style:**\n", - "A way of programming that uses pure functions whenever possible.\n", - "\n", - "**prototype and patch:**\n", - "A way of developing programs by starting with a rough draft and gradually adding features and fixing bugs.\n", - "\n", - "**design-first development:**\n", - "A way of developing programs with more careful planning that prototype and patch." + "**Объектно-ориентированное программирование:**Стиль программирования, который использует объекты для организации кода и данных.**сорт:**Определяемый программистом тип. Определение класса создает новый объект класса.**Объект класса:**Объект, который представляет класс - это результат определения класса.**экземпляр:**Процесс создания объекта, который принадлежит классу.**пример:**Объект, который принадлежит классу.**атрибут:**Переменная, связанная с объектом, также называемой переменной экземпляра.**Диаграмма объектов:**Графическое представление объекта, его атрибутов и его значений.**Спецификатор формата:**В F-String спецификатор формата определяет, как значение преобразуется в строку.**Чистая функция:**Функция, которая не изменяет свои параметры или не имеет какого -либо эффекта, кроме возврата значения.**Стиль функционального программирования:**Способ программирования, который использует чистые функции, когда это возможно.**Прототип и патч:**Способ разработки программ, начиная с черновой черновики и постепенно добавляя функции и исправляя ошибки.**Проектирование-первая разработка:**\n", + "Способ разработки программ с более тщательным планированием этого прототипа и патча.\n" ] }, { @@ -1259,7 +1226,7 @@ "id": "09dd41c1", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения\n" ] }, { @@ -1282,29 +1249,25 @@ "id": "da0aea86", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", - "\n", - "There is a lot of new vocabulary in this chapter.\n", - "A conversation with a virtual assistant can help solidify your understanding.\n", - "Consider asking:\n", + "### Спросите виртуального помощника\n", "\n", - "* \"What is the difference between a class and a type?\"\n", + "В этой главе много нового словаря.\n", + "Разговор с виртуальным помощником может помочь укрепить ваше понимание.\n", + "Подумайте о том, чтобы спросить:\n", "\n", - "* \"What is the difference between an object and an instance?\"\n", + "*«В чем разница между классом и типом?»* «В чем разница между объектом и экземпляром?»\n", "\n", - "* \"What is the difference between a variable and an attribute?\"\n", + "*«В чем разница между переменной и атрибутом?»* «Каковы плюсы и минусы чистых функций по сравнению с нечистыми функциями?»\n", "\n", - "* \"What are the pros and cons of pure functions compared to impure functions?\"\n", + "Поскольку мы только начинаем с объектно -ориентированным программированием, код в этой главе не является идиоматическим - это не тот код, которые пишут опытные программисты.\n", + "Если вы попросите виртуального помощника о помощи с упражнениями, вы, вероятно, увидите функции, которые мы еще не покрыли.\n", + "В частности, вы, вероятно, увидите метод, называемый `__init__`, используемый для инициализации атрибутов экземпляра.\n", "\n", - "Because we are just getting started with object oriented programming, the code in this chapter is not idiomatic -- it is not the kind of code experienced programmers write.\n", - "If you ask a virtual assistant for help with the exercises, you will probably see features we have not covered yet.\n", - "In particular, you are likely to see a method called `__init__` used to initialize the attributes of an instance.\n", + "Если эти функции имеют смысл для вас, продолжайте и используйте их.\n", + "Но если нет, будьте терпеливы - мы скоро доберемся.\n", + "В то же время, посмотрите, сможете ли вы решить следующие упражнения, используя только те функции, которые мы рассмотрели до сих пор.\n", "\n", - "If these features make sense to you, go ahead and use them.\n", - "But if not, be patient -- we will get there soon.\n", - "In the meantime, see if you can solve the following exercises using only the features we have covered so far.\n", - "\n", - "Also, in this chapter we saw one example of a format specifier. For more information, ask \"What format specifiers can be used in a Python f-string?\"" + "Кроме того, в этой главе мы увидели один пример спецификатора формата. Для получения дополнительной информации спросите: «Какие спецификаторы формата можно использовать в Fython F-String?»\n" ] }, { @@ -1312,9 +1275,9 @@ "id": "bcdab7d6", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `subtract_time` that takes two `Time` objects and returns the interval between them in seconds -- assuming that they are two times during the same day." + "Напишите функцию, называемую `suptract_time`, которая занимает два объекта« Time »и возвращает интервал между ними за считанные секунды - при условии, что они два раза в тот же день.\n" ] }, { @@ -1324,7 +1287,7 @@ "tags": [] }, "source": [ - "Here's an outline of the function to get you started." + "Вот набросок функции, чтобы вы начали.\n" ] }, { @@ -1366,7 +1329,7 @@ "tags": [] }, "source": [ - "You can use `doctest` to test your function." + "Вы можете использовать `doctest`, чтобы проверить вашу функцию.\n" ] }, { @@ -1391,9 +1354,9 @@ "id": "c3189549", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a function called `is_after` that takes two `Time` objects and returns `True` if the first time is later in the day than the second, and `False` otherwise." + "Напишите функцию, называемую `is_after`, которая занимает два объекта« Time »и возвращает` true`, если в первый раз в первый раз, как второй, и `false 'в противном случае.\n" ] }, { @@ -1403,7 +1366,7 @@ "tags": [] }, "source": [ - "Here's an outline of the function to get you started." + "Вот набросок функции, чтобы вы начали.\n" ] }, { @@ -1443,7 +1406,7 @@ "tags": [] }, "source": [ - "You can use `doctest` to test your function." + "Вы можете использовать `doctest`, чтобы проверить вашу функцию.\n" ] }, { @@ -1463,9 +1426,9 @@ "id": "16dff862", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Here's a definition for a `Date` class that represents a date -- that is, a year, month, and day of the month." + "Вот определение для класса «Дата», которое представляет собой дату, то есть год, месяц и день месяца.\n" ] }, { @@ -1484,13 +1447,13 @@ "id": "3311fa97", "metadata": {}, "source": [ - "1. Write a function called `make_date` that takes `year`, `month`, and `day` as parameters, makes a `Date` object, assigns the parameters to attributes, and returns the result the new object. Create an object that represents June 22, 1933.\n", + "1. Напишите функцию, называемую «make_date», которая занимает `year`,` month` и `day 'как параметры, делает объект` date', назначает параметры атрибутам и возвращает результат новый объект. Создайте объект, который представляет 22 июня 1933 года.\n", "\n", - "2. Write a function called `print_date` that takes a `Date` object, uses an f-string to format the attributes, and prints the result. If you test it with the `Date` you created, the result should be `1933-06-22`.\n", + "2. Напишите функцию с именем `print_date`, которая принимает объект` date`, использует F-String для форматирования атрибутов, и печатает результат. Если вы тестируете его с созданной вами датой, результатом должен быть `1933-06-22 '.\n", "\n", - "3. Write a function called `is_after` that takes two `Date` objects as parameters and returns `True` if the first comes after the second. Create a second object that represents September 17, 1933, and check whether it comes after the first object.\n", + "3. Напишите функцию с именем `is_after`, которая принимает два объекта` date` в виде параметров и возвращает `true`, если первый появится после второго. Создайте второй объект, который представляет 17 сентября 1933 года, и проверьте, наступает ли он после первого объекта.\n", "\n", - "Hint: You might find it useful to write a function called `date_to_tuple` that takes a `Date` object and returns a tuple that contains its attributes in year, month, day order." + "Подсказка: вы можете найти полезное написание функции с именем `date_to_tuple`, которая принимает объект` date` и возвращает кортеж, который содержит свои атрибуты в год, месяц, дневной заказ.\n" ] }, { @@ -1500,7 +1463,7 @@ "tags": [] }, "source": [ - "You can use this function outline to get started." + "Вы можете использовать этот контур функции, чтобы начать.\n" ] }, { @@ -1533,7 +1496,7 @@ "tags": [] }, "source": [ - "You can use these examples to test `make_date`." + "Вы можете использовать эти примеры для проверки `make_date`.\n" ] }, { @@ -1567,7 +1530,7 @@ "tags": [] }, "source": [ - "You can use this function outline to get started." + "Вы можете использовать этот контур функции, чтобы начать.\n" ] }, { @@ -1600,7 +1563,7 @@ "tags": [] }, "source": [ - "You can use this example to test `print_date`." + "Вы можете использовать этот пример для проверки `print_date`.\n" ] }, { @@ -1622,7 +1585,7 @@ "tags": [] }, "source": [ - "You can use this function outline to get started." + "Вы можете использовать этот контур функции, чтобы начать.\n" ] }, { @@ -1665,7 +1628,7 @@ "tags": [] }, "source": [ - "You can use these examples to test `is_after`." + "Вы можете использовать эти примеры для проверки `is_after`.\n" ] }, { @@ -1696,7 +1659,9 @@ "cell_type": "markdown", "id": "d6f1cc2f", "metadata": {}, - "source": [] + "source": [ + "\n" + ] }, { "cell_type": "markdown", @@ -1705,13 +1670,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание](https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik\n" ] } ], @@ -1737,4 +1702,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 023d9a316345fc1fe35cf46626a13127b41aff33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:56:45 +0300 Subject: [PATCH 40/44] Translate chap15 Markdown to Russian --- chapters/chap15.ipynb | 268 ++++++++++++++++++++---------------------- 1 file changed, 125 insertions(+), 143 deletions(-) diff --git a/chapters/chap15.ipynb b/chapters/chap15.ipynb index 52fb9c8..d597563 100644 --- a/chapters/chap15.ipynb +++ b/chapters/chap15.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Вы можете заказать печатную и электронную версии *Think Python 3e* на", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -41,19 +41,19 @@ "id": "fa22117f", "metadata": {}, "source": [ - "# Classes and Methods\n", + "# Классы и методы\n", "\n", - "Python is an **object-oriented language** -- that is, it provides features that support object-oriented programming, which has these defining characteristics:\n", + "Python — это **объектно-ориентированный язык**, то есть он предоставляет возможности, поддерживающие объектно-ориентированное программирование, которое характеризуется следующим:\n", "\n", - "- Most of the computation is expressed in terms of operations on objects.\n", + "- Большая часть вычислений выражается через операции над объектами.\n", "\n", - "- Objects often represent things in the real world, and methods often correspond to the ways things in the real world interact.\n", + "- Объекты часто представляют вещи из реального мира, а методы обычно соответствуют тому, как эти вещи взаимодействуют.\n", "\n", - "- Programs include class and method definitions.\n", + "- В программах присутствуют определения классов и методов.\n", "\n", - "For example, in the previous chapter we defined a `Time` class that corresponds to the way people record the time of day, and we defined functions that correspond to the kinds of things people do with times.\n", - "But there was no explicit connection between the definition of the `Time` class and the function definitions that follow.\n", - "We can make the connection explicit by rewriting a function as a **method**, which is defined inside a class definition." + "Например, в предыдущей главе мы определили класс `Time`, соответствующий тому, как люди записывают время суток, и написали функции, соответствующие действиям, которые люди выполняют со временем.\n", + "Но между определением класса `Time` и последующими функциями не было явной связи.\n", + "Мы можем сделать эту связь явной, переписав функцию в виде **метода**, определённого внутри класса." ] }, { @@ -61,9 +61,9 @@ "id": "9857823a", "metadata": {}, "source": [ - "## Defining methods\n", + "## Определение методов\n", "\n", - "In the previous chapter we defined a class named `Time` and wrote a function named `print_time` that displays a time of day." + "В предыдущей главе мы определили класс `Time` и написали функцию `print_time`, которая выводит время суток." ] }, { @@ -86,12 +86,9 @@ "id": "a89ddf58", "metadata": {}, "source": [ - "To make `print_time` a method, all we have to do is move the function\n", - "definition inside the class definition. Notice the change in\n", - "indentation.\n", + "Чтобы превратить `print_time` в метод, достаточно перенести определение функции внутрь определения класса. Обратите внимание на изменение отступов.\n", "\n", - "At the same time, we'll change the name of the parameter from `time` to `self`.\n", - "This change is not necessary, but it is conventional for the first parameter of a method to be named `self`." + "Одновременно мы изменим имя параметра с `time` на `self`. Это изменение не обязательно, но принято называть первым параметром метода `self`." ] }, { @@ -114,8 +111,8 @@ "id": "8da4079c", "metadata": {}, "source": [ - "To call this method, you have to pass a `Time` object as an argument.\n", - "Here's the function we'll use to make a `Time` object." + "Чтобы вызвать этот метод, нужно передать объект `Time` в качестве аргумента.\n", + "Вот функция, с помощью которой мы будем создавать объект `Time`." ] }, { @@ -138,7 +135,7 @@ "id": "c6ad4e12", "metadata": {}, "source": [ - "And here's a `Time` instance." + "А вот и экземпляр `Time`." ] }, { @@ -156,8 +153,7 @@ "id": "bbbcd333", "metadata": {}, "source": [ - "Now there are two ways to call `print_time`. The first (and less common)\n", - "way is to use function syntax." + "Теперь `print_time` можно вызвать двумя способами. Первый (менее распространённый) — использовать синтаксис функции." ] }, { @@ -175,8 +171,8 @@ "id": "2eb0847e", "metadata": {}, "source": [ - "In this version, `Time` is the name of the class, `print_time` is the name of the method, and `start` is passed as a parameter.\n", - "The second (and more idiomatic) way is to use method syntax:" + "В этой версии `Time` — имя класса, `print_time` — имя метода, а `start` передаётся в качестве параметра.\n", + "Второй (более идиоматичный) способ — использовать синтаксис метода:" ] }, { @@ -194,10 +190,9 @@ "id": "c80c40f0", "metadata": {}, "source": [ - "In this version, `start` is the object the method is invoked on, which is called the **receiver**, based on the analogy that invoking a method is like sending a message to an object.\n", + "В этой версии `start` — объект, на котором вызывается метод; его называют **приёмником**, по аналогии с тем, что вызов метода подобен отправке сообщения объекту.\n", "\n", - "Regardless of the syntax, the behavior of the method is the same.\n", - "The receiver is assigned to the first parameter, so inside the method, `self` refers to the same object as `start`." + "Независимо от синтаксиса поведение метода одинаково. Приёмник присваивается первому параметру, поэтому внутри метода `self` ссылается на тот же объект, что и `start`." ] }, { @@ -205,9 +200,9 @@ "id": "8deb6c34", "metadata": {}, "source": [ - "## Another method\n", + "## Ещё один метод\n", "\n", - "Here's the `time_to_int` function from the previous chapter." + "Вот функция `time_to_int` из предыдущей главы." ] }, { @@ -228,7 +223,7 @@ "id": "144e043f", "metadata": {}, "source": [ - "And here's a version rewritten as a method.\n" + "А вот вариант, переписанный в виде метода." ] }, { @@ -251,14 +246,14 @@ "id": "e3a721ab", "metadata": {}, "source": [ - "The first line uses the special command `add_method_to`, which adds a method to a previously-defined class.\n", - "This command works in a Jupyter notebook, but it is not part of Python, so it won't work in other environments.\n", - "Normally, all methods of a class are inside the class definition, so they get defined at the same time as the class.\n", - "But for this book, it is helpful to define one method at a time.\n", + "Первая строка использует специальную команду `add_method_to`, которая добавляет метод к уже определённому классу.\n", + "Эта команда работает в Jupyter Notebook, но не является частью Python и потому не будет работать в других средах.\n", + "Обычно все методы класса находятся внутри определения класса и определяются одновременно с ним.\n", + "Но для этой книги полезно определять по одному методу за раз.\n", "\n", - "As in the previous example, the method definition is indented and the name of the parameter is `self`.\n", - "Other than that, the method is identical to the function.\n", - "Here's how we invoke it." + "Как и в предыдущем примере, определение метода имеет отступ, а имя параметра — `self`.\n", + "В остальном метод идентичен функции.\n", + "Вот как его вызвать." ] }, { @@ -276,7 +271,7 @@ "id": "14565505", "metadata": {}, "source": [ - "It is common to say that we \"call\" a function and \"invoke\" a method, but they mean the same thing." + "Часто говорят, что функцию мы \"вызываем\", а метод \"инициируем\", но по сути это одно и то же." ] }, { @@ -284,10 +279,9 @@ "id": "7bc24683", "metadata": {}, "source": [ - "## Static methods\n", + "## Статические методы\n", "\n", - "As another example, let's consider the `int_to_time` function.\n", - "Here's the version from the previous chapter." + "Рассмотрим ещё функцию `int_to_time`. Вот её вариант из предыдущей главы." ] }, { @@ -308,12 +302,12 @@ "id": "2b77c2a0", "metadata": {}, "source": [ - "This function takes `seconds` as a parameter and returns a new `Time` object.\n", - "If we transform it into a method of the `Time` class, we have to invoke it on a `Time` object.\n", - "But if we're trying to create a new `Time` object, what are we supposed to invoke it on?\n", + "Эта функция принимает параметр `seconds` и возвращает новый объект `Time`.\n", + "Если преобразовать её в метод класса `Time`, его придётся вызывать на объекте `Time`.\n", + "Но если мы хотим создать новый объект `Time`, на чём мы должны его вызывать?\n", "\n", - "We can solve this chicken-and-egg problem using a **static method**, which is a method that does not require an instance of the class to be invoked.\n", - "Here's how we rewrite this function as a static method." + "Эту проблему курицы и яйца можно решить с помощью **статического метода**, который не требует экземпляра класса для вызова.\n", + "Вот как переписать эту функцию как статический метод." ] }, { @@ -336,8 +330,8 @@ "id": "a7e2e788", "metadata": {}, "source": [ - "Because it is a static method, it does not have `self` as a parameter.\n", - "To invoke it, we use `Time`, which is the class object." + "Поскольку это статический метод, у него нет параметра `self`.\n", + "Вызываем его с помощью `Time`, то есть объекта класса." ] }, { @@ -355,7 +349,7 @@ "id": "d2f4fd5a", "metadata": {}, "source": [ - "The result is a new object that represents 9:40." + "Результатом будет новый объект, представляющий 9:40." ] }, { @@ -373,8 +367,8 @@ "id": "e6a18c76", "metadata": {}, "source": [ - "Now that we have `Time.from_seconds`, we can use it to write `add_time` as a method.\n", - "Here's the function from the previous chapter." + "Теперь, имея `Time.from_seconds`, мы можем написать `add_time` как метод.\n", + "Вот функция из предыдущей главы." ] }, { @@ -395,7 +389,7 @@ "id": "8e56da48", "metadata": {}, "source": [ - "And here's a version rewritten as a method." + "А вот версия, переписанная в виде метода." ] }, { @@ -418,9 +412,8 @@ "id": "b784a4ea", "metadata": {}, "source": [ - "`add_time` has `self` as a parameter because it is not a static method.\n", - "It is an ordinary method -- also called an **instance method**.\n", - "To invoke it, we need a `Time` instance." + "У метода `add_time` есть параметр `self`, потому что это не статический, а обычный **экземплярный метод**.\n", + "Чтобы вызвать его, нам нужен экземпляр `Time`." ] }, { @@ -439,10 +432,10 @@ "id": "f1c806a9", "metadata": {}, "source": [ - "## Comparing Time objects\n", + "## Сравнение объектов Time\n", "\n", - "As one more example, let's write `is_after` as a method.\n", - "Here's the `is_after` function, which is a solution to an exercise in the previous chapter." + "В качестве ещё одного примера напишем `is_after` как метод.\n", + "Вот функция `is_after`, которая была решением упражнения в предыдущей главе." ] }, { @@ -461,7 +454,7 @@ "id": "8e7153e8", "metadata": {}, "source": [ - "And here it is as a method." + "А вот она же в виде метода." ] }, { @@ -482,9 +475,8 @@ "id": "50815aec", "metadata": {}, "source": [ - "Because we're comparing two objects, and the first parameter is `self`, we'll call the second parameter `other`.\n", - "To use this method, we have to invoke it on one object and pass the\n", - "other as an argument." + "Поскольку мы сравниваем два объекта, а первым параметром является `self`, второй параметр назовём `other`.\n", + "Чтобы использовать этот метод, нужно вызвать его на одном объекте и передать\nдругой в качестве аргумента." ] }, { @@ -502,8 +494,7 @@ "id": "cf97e358", "metadata": {}, "source": [ - "One nice thing about this syntax is that it almost reads like a question,\n", - "\"`end` is after `start`?\"" + "Хорошо ещё то, что этот синтаксис почти читается как вопрос: \"`end` позже `start`?\"" ] }, { @@ -511,12 +502,11 @@ "id": "15a17fce", "metadata": {}, "source": [ - "## The `__str__` method\n", + "## Метод `__str__`\n", "\n", - "When you write a method, you can choose almost any name you want.\n", - "However, some names have special meanings.\n", - "For example, if an object has a method named `__str__`, Python uses that method to convert the object to a string.\n", - "For example, here is a `__str__` method for a time object." + "Создавая метод, можно выбрать почти любое имя. Однако некоторые имена имеют особое значение.\n", + "Например, если у объекта есть метод `__str__`, Python использует его для преобразования объекта в строку.\n", + "Вот пример метода `__str__` для объекта времени." ] }, { @@ -538,9 +528,9 @@ "id": "b056b729", "metadata": {}, "source": [ - "This method is similar to `print_time`, from the previous chapter, except that it returns the string rather than printing it.\n", + "Этот метод похож на `print_time` из предыдущей главы, но возвращает строку вместо вывода её на экран.\n", "\n", - "You can invoke this method in the usual way." + "Вызвать его можно обычным способом." ] }, { @@ -558,8 +548,8 @@ "id": "76092a0c", "metadata": {}, "source": [ - "But Python can also invoke it for you.\n", - "If you use the built-in function `str` to convert a `Time` object to a string, Python uses the `__str__` method in the `Time` class." + "Но Python может вызвать его и сам.\n", + "Если использовать встроенную функцию `str` для преобразования объекта `Time` в строку, Python применит метод `__str__` класса `Time`." ] }, { @@ -577,7 +567,7 @@ "id": "8a26caa8", "metadata": {}, "source": [ - "And it does the same if you print a `Time` object." + "То же самое произойдёт, если напечатать объект `Time`." ] }, { @@ -595,8 +585,7 @@ "id": "97eb30c2", "metadata": {}, "source": [ - "Methods like `__str__` are called **special methods**.\n", - "You can identify them because their names begin and end with two underscores." + "Методы вроде `__str__` называются **специальными**. Узнать их можно по тому, что они начинаются и заканчиваются двумя символами подчёркивания." ] }, { @@ -604,10 +593,10 @@ "id": "e01e9673", "metadata": {}, "source": [ - "## The init method\n", + "## Метод `__init__`\n", "\n", - "The most special of the special methods is `__init__`, so-called because it initializes the attributes of a new object.\n", - "An `__init__` method for the `Time` class might look like this:" + "Самым особенным из специальных методов является `__init__`, потому что он инициализирует атрибуты нового объекта.\n", + "Метод `__init__` для класса `Time` может выглядеть так:" ] }, { @@ -630,8 +619,8 @@ "id": "8ba624c3", "metadata": {}, "source": [ - "Now when we instantiate a `Time` object, Python invokes `__init__`, and passes along the arguments.\n", - "So we can create an object and initialize the attributes at the same time." + "Теперь при создании объекта `Time` Python вызывает `__init__` и передаёт ему аргументы.\n", + "Так мы можем создать объект и сразу инициализировать его атрибуты." ] }, { @@ -650,8 +639,7 @@ "id": "55e0e296", "metadata": {}, "source": [ - "In this example, the parameters are optional, so if you call `Time` with no arguments,\n", - "you get the default values." + "В этом примере параметры необязательны, поэтому если вызвать `Time` без аргументов,\nполучатся значения по умолчанию." ] }, { @@ -670,7 +658,7 @@ "id": "bacb036d", "metadata": {}, "source": [ - "If you provide one argument, it overrides `hour`:" + "Если передать один аргумент, он заменит значение `hour`:" ] }, { @@ -689,7 +677,7 @@ "id": "37edb221", "metadata": {}, "source": [ - "If you provide two arguments, they override `hour` and `minute`." + "Если передать два аргумента, они заменят `hour` и `minute`." ] }, { @@ -708,10 +696,9 @@ "id": "277de217", "metadata": {}, "source": [ - "And if you provide three arguments, they override all three default\n", - "values.\n", + "А если передать три аргумента, они заменят все три значения по умолчанию.\n", "\n", - "When I write a new class, I almost always start by writing `__init__`, which makes it easier to create objects, and `__str__`, which is useful for debugging." + "Когда я пишу новый класс, почти всегда начинаю с `__init__`, который упрощает создание объектов, и `__str__`, который помогает при отладке." ] }, { @@ -719,14 +706,11 @@ "id": "94bbbd7d", "metadata": {}, "source": [ - "## Operator overloading\n", + "## Перегрузка операторов\n", "\n", - "By defining other special methods, you can specify the behavior of\n", - "operators on programmer-defined types. For example, if you define a\n", - "method named `__add__` for the `Time` class, you can use the `+`\n", - "operator on Time objects.\n", + "Определив другие специальные методы, можно задать поведение операторов для пользовательских типов. Например, если определить метод `__add__` для класса `Time`, можно использовать оператор `+` с объектами `Time`.\n", "\n", - "Here is an `__add__` method." + "Вот метод `__add__`." ] }, { @@ -748,7 +732,7 @@ "id": "0221c9ad", "metadata": {}, "source": [ - "We can use it like this." + "Использовать его можно так." ] }, { @@ -768,16 +752,16 @@ "id": "7cc7866e", "metadata": {}, "source": [ - "There is a lot happening when we run these three lines of code:\n", + "При выполнении этих трёх строк кода происходит много всего:\n", "\n", - "* When we instantiate a `Time` object, the `__init__` method is invoked.\n", + "* При создании объекта `Time` вызывается метод `__init__`.\n", "\n", - "* When we use the `+` operator with a `Time` object, its `__add__` method is invoked.\n", + "* При использовании оператора `+` с объектом `Time` вызывается его метод `__add__`.\n", "\n", - "* And when we print a `Time` object, its `__str__` method is invoked.\n", + "* А при печати объекта `Time` вызывается метод `__str__`.\n", "\n", - "Changing the behavior of an operator so that it works with programmer-defined types is called **operator overloading**.\n", - "For every operator, like `+`, there is a corresponding special method, like `__add__`. " + "Изменение поведения оператора так, чтобы он работал с пользовательскими типами, называется **перегрузкой операторов**.\n", + "Для каждого оператора, например `+`, существует соответствующий специальный метод, например `__add__`." ] }, { @@ -785,15 +769,13 @@ "id": "b7299e62", "metadata": {}, "source": [ - "## Debugging\n", + "## Отладка\n", "\n", - "A `Time` object is valid if the values of `minute` and `second` are between `0` and `60` -- including `0` but not `60` -- and if `hour` is positive.\n", - "Also, `hour` and `minute` should be integer values, but we might allow `second` to have a fraction part.\n", - "Requirements like these are called **invariants** because they should always be true.\n", - "To put it a different way, if they are not true, something has gone wrong.\n", + "Объект `Time` считается корректным, если значения `minute` и `second` находятся в диапазоне от `0` до `60` — включая `0`, но не `60` — и если `hour` положительно.\n", + "Кроме того, `hour` и `minute` должны быть целыми числами, хотя `second` может иметь дробную часть.\n", + "Такие требования называются **инвариантами**, потому что они должны быть истинны всегда. Если это не так, значит что-то пошло не так.\n", "\n", - "Writing code to check invariants can help detect errors and find their causes.\n", - "For example, you might have a method like `is_valid` that takes a Time object and returns `False` if it violates an invariant." + "Проверка инвариантов помогает обнаруживать ошибки и находить их причины. Например, можно написать метод `is_valid`, который принимает объект Time и возвращает `False`, если тот нарушает инвариант." ] }, { @@ -822,7 +804,7 @@ "id": "a10ad3db", "metadata": {}, "source": [ - "Then, at the beginning of each method you can check the arguments to make sure they are valid." + "Затем в начале каждого метода можно проверять аргументы на корректность." ] }, { @@ -845,8 +827,8 @@ "id": "e7c78e9a", "metadata": {}, "source": [ - "The `assert` statement evaluates the expression that follows. If the result is `True`, it does nothing; if the result is `False`, it causes an `AssertionError`.\n", - "Here's an example." + "Оператор `assert` вычисляет следующее за ним выражение. Если результат `True`, ничего не происходит; если `False`, возбуждается `AssertionError`.\n", + "Вот пример." ] }, { @@ -879,7 +861,7 @@ "id": "18bd34ad", "metadata": {}, "source": [ - "`assert` statements are useful because they distinguish code that deals with normal conditions from code that checks for errors." + "Выражения `assert` полезны тем, что отделяют код, работающий с нормальными условиями, от кода, проверяющего наличие ошибок." ] }, { @@ -887,31 +869,31 @@ "id": "58b86fbe", "metadata": {}, "source": [ - "## Glossary\n", + "## Словарь терминов\n", "\n", "**object-oriented language:**\n", - "A language that provides features to support object-oriented programming, notably user-defined types.\n", + "Язык, предоставляющий средства для объектно-ориентированного программирования, прежде всего пользовательские типы.\n", "\n", "**method:**\n", - "A function that is defined inside a class definition and is invoked on instances of that class.\n", + "Функция, определённая внутри класса и вызываемая для экземпляров этого класса.\n", "\n", "**receiver:**\n", - "The object a method is invoked on.\n", + "Объект, на котором вызывается метод.\n", "\n", "**static method:**\n", - "A method that can be invoked without an object as receiver.\n", + "Метод, который можно вызвать без объекта-приёмника.\n", "\n", "**instance method:**\n", - "A method that must be invoked with an object as receiver.\n", + "Метод, который должен вызываться с объектом-приёмником.\n", "\n", "**special method:**\n", - "A method that changes the way operators and some functions work with an object.\n", + "Метод, изменяющий работу операторов и некоторых функций с объектом.\n", "\n", "**operator overloading:**\n", - "The process of using special methods to change the way operators with with user-defined types.\n", + "Процесс изменения работы операторов с пользовательскими типами с помощью специальных методов.\n", "\n", "**invariant:**\n", - " A condition that should always be true during the execution of a program." + "Условие, которое должно оставаться истинным во время выполнения программы." ] }, { @@ -919,7 +901,7 @@ "id": "796adf5c", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -942,20 +924,20 @@ "id": "25cd6888", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Спросите виртуального ассистента\n", "\n", - "For more information about static methods, ask a virtual assistant:\n", + "Чтобы узнать больше о статических методах, спросите виртуального ассистента:\n", "\n", - "* \"What's the difference between an instance method and a static method?\"\n", + "* \"В чём разница между методом экземпляра и статическим методом?\"\n", "\n", - "* \"Why are static methods called static?\"\n", + "* \"Почему статические методы называются статическими?\"\n", "\n", - "If you ask a virtual assistant to generate a static method, the result will probably begin with `@staticmethod`, which is a \"decorator\" that indicates that it is a static method.\n", - "Decorators are not covered in this book, but if you are curious, you can ask a VA for more information.\n", + "Если попросить виртуального ассистента сгенерировать статический метод, он, скорее всего, начнётся с `@staticmethod` — это \"декоратор\", указывающий, что метод статический.\n", + "Декораторы не рассматриваются в этой книге, но при желании можно спросить VA подробности.\n", "\n", - "In this chapter we rewrote several functions as methods.\n", - "Virtual assistants are generally good at this kind of code transformation.\n", - "As an example, paste the following function into a VA and ask it, \"Rewrite this function as a method of the `Time` class.\"" + "В этой главе мы переписали несколько функций в виде методов.\n", + "Виртуальные ассистенты обычно хорошо справляются с такими преобразованиями.\n", + "Например, вставьте следующую функцию в VA и попросите: \"Перепиши эту функцию как метод класса `Time`.\"" ] }, { @@ -974,20 +956,20 @@ "id": "fc9f135b-e242-4ef6-83eb-8e028235c07b", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In the previous chapter, a series of exercises asked you to write a `Date` class and several functions that work with `Date` objects.\n", - "Now let's practice rewriting those functions as methods.\n", + "В предыдущей главе серия упражнений предлагала написать класс `Date` и несколько функций, работающих с объектами `Date`.\n", + "Теперь потренируемся переписывать эти функции как методы.\n", "\n", - "1. Write a definition for a `Date` class that represents a date -- that is, a year, month, and day of the month.\n", + "1. Напишите определение класса `Date`, представляющего дату — то есть год, месяц и день месяца.\n", "\n", - "2. Write an `__init__` method that takes `year`, `month`, and `day` as parameters and assigns the parameters to attributes. Create an object that represents June 22, 1933.\n", + "2. Напишите метод `__init__`, который принимает `year`, `month` и `day` и присваивает их атрибутам. Создайте объект, представляющий 22 июня 1933 года.\n", "\n", - "3. Write `__str__` method that uses an f-string to format the attributes and returns the result. If you test it with the `Date` you created, the result should be `1933-06-22`.\n", + "3. Напишите метод `__str__`, который формирует строку с помощью f-строки и возвращает её. Если проверить его на созданном объекте `Date`, результат должен быть `1933-06-22`.\n", "\n", - "4. Write a method called `is_after` that takes two `Date` objects and returns `True` if the first comes after the second. Create a second object that represents September 17, 1933, and check whether it comes after the first object.\n", + "4. Напишите метод `is_after`, который принимает два объекта `Date` и возвращает `True`, если первый идёт после второго. Создайте второй объект, представляющий 17 сентября 1933 года, и проверьте, идёт ли он после первого.\n", "\n", - "Hint: You might find it useful write a method called `to_tuple` that returns a tuple that contains the attributes of a `Date` object in year-month-day order." + "Подсказка: может оказаться полезным метод `to_tuple`, который возвращает кортеж с атрибутами объекта `Date` в порядке год-месяц-день." ] }, { @@ -1007,7 +989,7 @@ "tags": [] }, "source": [ - "You can use these examples to test your solution." + "Вы можете использовать эти примеры, чтобы проверить своё решение." ] }, { @@ -1079,9 +1061,9 @@ "\n", "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -1107,4 +1089,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From d0e3b2ce0bb4caa564d63383f4f096d9c1ef2689 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:57:49 +0300 Subject: [PATCH 41/44] translate chapter 16 notebook to Russian --- chapters/chap16.ipynb | 354 +++++++++++++++++++++--------------------- 1 file changed, 177 insertions(+), 177 deletions(-) diff --git a/chapters/chap16.ipynb b/chapters/chap16.ipynb index 57f3d41..e2e749f 100644 --- a/chapters/chap16.ipynb +++ b/chapters/chap16.ipynb @@ -5,8 +5,8 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "Печатную и электронную версии *Think Python 3e* можно заказать на\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) и\n", "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." ] }, @@ -42,15 +42,15 @@ "id": "e826e661", "metadata": {}, "source": [ - "# Classes and Objects\n", + "# Классы и объекты\n", "\n", - "At this point we have defined classes and created objects that represent the time of day and the day of the year.\n", - "And we've defined methods that create, modify, and perform computations with these objects.\n", + "К этому моменту мы уже определили классы и создали объекты, которые представляют время суток и день в году.\n", + "Мы написали методы, которые создают, изменяют и выполняют вычисления с этими объектами.\n", "\n", - "In this chapter we'll continue our tour of object-oriented programming (OOP) by defining classes that represent geometric objects, including points, lines, rectangles, and circles.\n", - "We'll write methods that create and modify these objects, and we'll use the `jupyturtle` module to draw them.\n", + "В этой главе мы продолжим знакомство с объектно-ориентированным программированием (ООП), определив классы, представляющие геометрические объекты: точки, линии, прямоугольники и окружности.\n", + "Мы напишем методы для создания и изменения этих объектов и будем использовать модуль `jupyturtle` для их рисования.\n", "\n", - "I'll use these classes to demonstrate OOP topics including object identity and equivalence, shallow and deep copying, and polymorphism." + "Эти классы я буду использовать, чтобы продемонстрировать темы ООП, включая идентичность и эквивалентность объектов, поверхностное и глубинное копирование и полиморфизм." ] }, { @@ -60,22 +60,22 @@ "tags": [] }, "source": [ - "## Creating a Point\n", + "## Создание точки\n", "\n", - "In computer graphics a location on the screen is often represented using a pair of coordinates in an `x`-`y` plane.\n", - "By convention, the point `(0, 0)` usually represents the upper-left corner of the screen, and `(x, y)` represents the point `x` units to the right and `y` units down from the origin.\n", - "Compared to the Cartesian coordinate system you might have seen in a math class, the `y` axis is upside-down.\n", + "В компьютерной графике положение на экране часто представляется парой координат в плоскости `x`–`y`.\n", + "По договорённости точка `(0, 0)` обычно соответствует левому верхнему углу экрана, а `(x, y)` обозначает точку на `x` единиц правее и `y` единиц ниже начала координат.\n", + "По сравнению с привычной из математики декартовой системой координат ось `y` здесь направлена вниз.\n", "\n", - "There are several ways we might represent a point in Python:\n", + "В Python точку можно представить несколькими способами:\n", "\n", - "- We can store the coordinates separately in two variables, `x` and `y`.\n", + "- хранить координаты отдельно в двух переменных `x` и `y`;\n", "\n", - "- We can store the coordinates as elements in a list or tuple.\n", + "- хранить координаты элементами списка или кортежа;\n", "\n", - "- We can create a new type to represent points as objects.\n", + "- создать новый тип, представляющий точки как объекты.\n", "\n", - "In object-oriented programming, it would be most idiomatic to create a new type.\n", - "To do that, we'll start with a class definition for `Point`." + "В духе объектно-ориентированного программирования лучше всего создать новый тип.\n", + "Начнём с определения класса `Point`." ] }, { @@ -101,10 +101,10 @@ "id": "3d35a095", "metadata": {}, "source": [ - "The `__init__` method takes the coordinates as parameters and assigns them to attributes `x` and `y`.\n", - "The `__str__` method returns a string representation of the `Point`.\n", + "Метод `__init__` принимает координаты в качестве параметров и сохраняет их в атрибутах `x` и `y`.\n", + "Метод `__str__` возвращает строковое представление `Point`.\n", "\n", - "Now we can instantiate and display a `Point` object like this." + "Теперь мы можем создать и вывести объект `Point` так." ] }, { @@ -123,7 +123,7 @@ "id": "b3fd8858", "metadata": {}, "source": [ - "The following diagram shows the state of the new object. " + "Следующая диаграмма показывает состояние нового объекта." ] }, { @@ -164,9 +164,9 @@ "id": "713b7410", "metadata": {}, "source": [ - "As usual, a programmer-defined type is represented by a box with the name of the type outside and the attributes inside.\n", + "Как обычно, тип, определённый программистом, изображается прямоугольником: снаружи — имя типа, внутри — его атрибуты.\n", "\n", - "In general, programmer-defined types are mutable, so we can write a method like `translate` that takes two numbers, `dx` and `dy`, and adds them to the attributes `x` and `y`." + "В целом пользовательские типы изменяемы, поэтому мы можем написать метод `translate`, который принимает два числа `dx` и `dy` и прибавляет их к атрибутам `x` и `y`." ] }, { @@ -188,8 +188,8 @@ "id": "4d183292", "metadata": {}, "source": [ - "This function translates the `Point` from one location in the plane to another.\n", - "If we don't want to modify an existing `Point`, we can use `copy` to copy the original object and then modify the copy." + "Эта функция переносит `Point` из одной точки плоскости в другую.\n", + "Если мы не хотим изменять существующий `Point`, можно воспользоваться `copy`, чтобы скопировать исходный объект и затем изменить копию." ] }, { @@ -211,7 +211,7 @@ "id": "562567c2", "metadata": {}, "source": [ - "We can encapsulate those steps in another method called `translated`." + "Эти действия можно собрать в другом методе — `translated`." ] }, { @@ -234,9 +234,9 @@ "id": "a7a635ee", "metadata": {}, "source": [ - "In the same way that the built in function `sort` modifies a list, and the `sorted` function creates a new list, now we have a `translate` method that modifies a `Point` and a `translated` method that creates a new one.\n", + "Подобно тому как встроенная функция `sort` изменяет список на месте, а `sorted` создаёт новый список, у нас есть метод `translate`, который изменяет `Point`, и `translated`, который создаёт новый.\n", "\n", - "Here's an example:" + "Вот пример:" ] }, { @@ -255,7 +255,7 @@ "id": "923362d2", "metadata": {}, "source": [ - "In the next section, we'll use these points to define and draw a line." + "В следующем разделе мы воспользуемся этими точками, чтобы определить и нарисовать линию." ] }, { @@ -263,10 +263,10 @@ "id": "837f98fd", "metadata": {}, "source": [ - "## Creating a Line\n", + "## Создание линии\n", "\n", - "Now let's define a class that represents the line segment between two points.\n", - "As usual, we'll start with an `__init__` method and a `__str__` method." + "Теперь определим класс, представляющий отрезок между двумя точками.\n", + "Как обычно, начнём с методов `__init__` и `__str__`." ] }, { @@ -290,7 +290,7 @@ "id": "d7dad30e", "metadata": {}, "source": [ - "With those two methods, we can instantiate and display a `Line` object we'll use to represent the `x` axis." + "С этими двумя методами мы можем создать и вывести объект `Line`, который будет представлять ось `x`." ] }, { @@ -309,16 +309,16 @@ "id": "e7b5fd9a", "metadata": {}, "source": [ - "When we call `print` and pass `line` as a parameter, `print` invokes `__str__` on `line`.\n", - "The `__str__` method uses an f-string to create a string representation of the `line`. \n", + "Когда мы вызываем `print` и передаём ему `line`, функция вызывает у него `__str__`.\n", + "Метод `__str__` использует f-строку, чтобы создать строковое представление линии.\n", "\n", - "The f-string contains two expressions in curly braces, `self.p1` and `self.p2`.\n", - "When those expressions are evaluated, the results are `Point` objects.\n", - "Then, when they are converted to strings, the `__str__` method from the `Point` class gets invoked.\n", + "В f-строке две выражения в фигурных скобках: `self.p1` и `self.p2`.\n", + "При их вычислении получаются объекты `Point`.\n", + "Затем при преобразовании их в строку вызывается метод `__str__` из класса `Point`.\n", "\n", - "That's why, when we display a `Line`, the result contains the string representations of the `Point` objects.\n", + "Поэтому, выводя `Line`, мы видим строковые представления объектов `Point`.\n", "\n", - "The following object diagram shows the state of this `Line` object." + "Следующая диаграмма показывает состояние этого объекта `Line`." ] }, { @@ -365,17 +365,17 @@ "id": "079859b5", "metadata": {}, "source": [ - "String representations and object diagrams are useful for debugging, but the point of this example is to generate graphics, not text!\n", - "So we'll use the `jupyturtle` module to draw lines on the screen.\n", + "Строковые представления и объектные диаграммы полезны для отладки, но цель этого примера — вывести графику, а не текст!\n", + "Поэтому мы воспользуемся модулем `jupyturtle`, чтобы рисовать линии на экране.\n", "\n", - "As we did in [Chapter 4](section_turtle_module), we'll use `make_turtle` to create a `Turtle` object and a small canvas where it can draw.\n", - "To draw lines, we'll use two new functions from the `jupyturtle` module:\n", + "Как и в [главе 4](section_turtle_module), мы вызовем `make_turtle`, чтобы создать объект `Turtle` и небольшое окно для рисования.\n", + "Для рисования линий используем две новые функции из модуля `jupyturtle`:\n", "\n", - "* `jumpto`, which takes two coordinates and moves the `Turtle` to the given location without drawing a line, and \n", + "* `jumpto` — принимает две координаты и перемещает `Turtle` в указанное место без рисования линии, и\n", "\n", - "* `moveto`, which moves the `Turtle` from its current location to the given location, and draws a line segment between them.\n", + "* `moveto` — перемещает `Turtle` из текущего положения в указанное место, рисуя линию между ними.\n", "\n", - "Here's how we import them." + "Вот как их импортировать." ] }, { @@ -393,7 +393,7 @@ "id": "9d2dd88f", "metadata": {}, "source": [ - "And here's a method that draws a `Line`." + "А вот метод, который рисует `Line`." ] }, { @@ -415,7 +415,7 @@ "id": "2341f0e0", "metadata": {}, "source": [ - "To show how it's used, I'll create a second line that represents the `y` axis." + "Чтобы показать, как это работает, я создам вторую линию, представляющую ось `y`." ] }, { @@ -434,7 +434,7 @@ "id": "d7450736", "metadata": {}, "source": [ - "And then draw the axes." + "А потом нарисую оси." ] }, { @@ -454,8 +454,8 @@ "id": "473c156f", "metadata": {}, "source": [ - "As we define and draw more objects, we'll use these lines again.\n", - "But first let's talk about object equivalence and identity." + "По мере того как мы будем определять и рисовать новые объекты, эти линии нам ещё пригодятся.\n", + "Но прежде поговорим об эквивалентности и идентичности объектов." ] }, { @@ -463,9 +463,9 @@ "id": "950da673", "metadata": {}, "source": [ - "## Equivalence and identity\n", + "## Эквивалентность и идентичность\n", "\n", - "Suppose we create two points with the same coordinates." + "Предположим, мы создадим две точки с одинаковыми координатами." ] }, { @@ -484,7 +484,7 @@ "id": "82b14526", "metadata": {}, "source": [ - "If we use the `==` operator to compare them, we get the default behavior for programmer-defined types -- the result is `True` only if they are the same object, which they are not." + "Если применить к ним оператор `==`, получим поведение по умолчанию для пользовательских типов — результат `True` только если это один и тот же объект, что здесь не так." ] }, { @@ -502,7 +502,7 @@ "id": "96be0ff8", "metadata": {}, "source": [ - "If we want to change that behavior, we can provide a special method called `__eq__` that defines what it means for two `Point` objects to be equal." + "Чтобы изменить это поведение, можно определить специальный метод `__eq__`, задающий, что значит равенство двух объектов `Point`." ] }, { @@ -523,8 +523,8 @@ "id": "7f4409de", "metadata": {}, "source": [ - "This definition considers two `Points` to be equal if their attributes are equal.\n", - "Now when we use the `==` operator, it invokes the `__eq__` method, which indicates that `p1` and `p2` are considered equal." + "В этом определении две точки считаются равными, если равны их атрибуты.\n", + "Теперь при использовании оператора `==` вызывается метод `__eq__`, который показывает, что `p1` и `p2` считаются равными." ] }, { @@ -542,7 +542,7 @@ "id": "52662e6a", "metadata": {}, "source": [ - "But the `is` operator still indicates that they are different objects." + "Но оператор `is` по-прежнему показывает, что это разные объекты." ] }, { @@ -560,9 +560,9 @@ "id": "c008d3dd", "metadata": {}, "source": [ - "It's not possible to override the `is` operator -- it always checks whether the objects are identical.\n", - "But for programmer-defined types, you can override the `==` operator so it checks whether the objects are equivalent.\n", - "And you can define what equivalent means." + "Переопределить оператор `is` невозможно — он всегда проверяет идентичность объектов.\n", + "А вот оператор `==` в пользовательских типах можно переопределить, чтобы он проверял эквивалентность.\n", + "Причём вы сами решаете, что считать эквивалентным." ] }, { @@ -570,20 +570,20 @@ "id": "893a8cab", "metadata": {}, "source": [ - "## Creating a Rectangle\n", + "## Создание прямоугольника\n", "\n", - "Now let's define a class that represents and draws rectangles.\n", - "To keep things simple, we'll assume that the rectangles are either vertical or horizontal, not at an angle.\n", - "What attributes do you think we should use to specify the location and size of a rectangle?\n", + "Теперь определим класс, который представляет и рисует прямоугольники.\n", + "Чтобы не усложнять, будем считать, что прямоугольники расположены вертикально или горизонтально, без наклона.\n", + "Какие атрибуты нам нужны, чтобы задать положение и размер прямоугольника?\n", "\n", - "There are at least two possibilities:\n", + "Возможны по крайней мере два варианта:\n", "\n", - "- You could specify the width and height of the rectangle and the location of one corner.\n", + "- указать ширину и высоту прямоугольника и координаты одного из углов.\n", "\n", - "- You could specify two opposing corners.\n", + "- указать координаты двух противоположных углов.\n", "\n", - "At this point it's hard to say whether either is better than the other, so let's implement the first one.\n", - "Here is the class definition." + "Пока трудно сказать, какой вариант лучше, поэтому реализуем первый.\n", + "Вот определение класса." ] }, { @@ -612,8 +612,8 @@ "id": "df2852f3", "metadata": {}, "source": [ - "As usual, the `__init__` method assigns the parameters to attributes and the `__str__` returns a string representation of the object.\n", - "Now we can instantiate a `Rectangle` object, using a `Point` as the location of the upper-left corner." + "Как обычно, `__init__` сохраняет параметры в атрибутах, а `__str__` возвращает строковое представление объекта.\n", + "Теперь мы можем создать объект `Rectangle`, используя `Point` в качестве координат верхнего левого угла." ] }, { @@ -633,7 +633,7 @@ "id": "a9e0b5ec", "metadata": {}, "source": [ - "The following diagram shows the state of this object." + "Следующая диаграмма показывает состояние этого объекта." ] }, { @@ -686,7 +686,7 @@ "id": "bb54e6b5", "metadata": {}, "source": [ - "To draw a rectangle, we'll use the following method to make four `Point` objects to represent the corners." + "Чтобы нарисовать прямоугольник, используем следующий метод: он создаёт четыре объекта `Point`, представляющие углы." ] }, { @@ -711,7 +711,7 @@ "id": "20dbe0cb", "metadata": {}, "source": [ - "Then we'll make four `Line` objects to represent the sides." + "Затем создадим четыре объекта `Line`, соответствующие сторонам." ] }, { @@ -733,7 +733,7 @@ "id": "30fe41cc", "metadata": {}, "source": [ - "Then we'll draw the sides." + "После этого нарисуем стороны." ] }, { @@ -756,7 +756,7 @@ "id": "390ba3e7", "metadata": {}, "source": [ - "Here's an example." + "Вот пример." ] }, { @@ -777,7 +777,7 @@ "id": "532a4f69", "metadata": {}, "source": [ - "The figure includes two lines to represent the axes." + "На рисунке есть две линии, обозначающие оси." ] }, { @@ -785,13 +785,13 @@ "id": "0e713a90", "metadata": {}, "source": [ - "## Changing rectangles\n", + "## Изменение прямоугольников\n", "\n", - "Now let's consider two methods that modify rectangles, `grow` and `translate`.\n", - "We'll see that `grow` works as expected, but `translate` has a subtle bug.\n", - "See if you can figure it out before I explain.\n", + "Рассмотрим два метода, изменяющих прямоугольники: `grow` и `translate`.\n", + "Мы увидим, что `grow` работает как ожидалось, а в `translate` скрыта тонкая ошибка.\n", + "Попробуйте обнаружить её до того, как я объясню.\n", "\n", - "`grow` takes two numbers, `dwidth` and `dheight`, and adds them to the `width` and `height` attributes of the rectangle." + "Метод `grow` принимает два числа `dwidth` и `dheight` и прибавляет их к атрибутам `width` и `height` прямоугольника." ] }, { @@ -813,7 +813,7 @@ "id": "a51913e2", "metadata": {}, "source": [ - "Here's an example that demonstrates the effect by making a copy of `box1` and invoking `grow` on the copy." + "Этот пример демонстрирует результат: мы сделаем копию `box1` и вызовем `grow` для копии." ] }, { @@ -833,7 +833,7 @@ "id": "6d74da62", "metadata": {}, "source": [ - "If we draw `box1` and `box2`, we can confirm that `grow` works as expected." + "Если нарисовать `box1` и `box2`, можно убедиться, что `grow` сработал правильно." ] }, { @@ -855,8 +855,8 @@ "id": "0c940008", "metadata": {}, "source": [ - "Now let's see about `translate`.\n", - "It takes two numbers, `dx` and `dy`, and moves the rectangle the given distances in the `x` and `y` directions. " + "Теперь посмотрим на `translate`.\n", + "Этот метод принимает два числа `dx` и `dy` и перемещает прямоугольник на указанные расстояния по осям `x` и `y`." ] }, { @@ -877,7 +877,7 @@ "id": "c27fe91d", "metadata": {}, "source": [ - "To demonstrate the effect, we'll translate `box2` to the right and down." + "Чтобы показать результат, переместим `box2` вправо и вниз." ] }, { @@ -896,7 +896,7 @@ "id": "e01badbc", "metadata": {}, "source": [ - "Now let's see what happens if we draw `box1` and `box2` again." + "Теперь посмотрим, что произойдёт, если снова нарисовать `box1` и `box2`." ] }, { @@ -918,8 +918,8 @@ "id": "5310bdd7", "metadata": {}, "source": [ - "It looks like both rectangles moved, which is not what we intended!\n", - "The next section explains what went wrong." + "Похоже, переместились оба прямоугольника, чего мы не хотели!\n", + "В следующем разделе объясняется, что пошло не так." ] }, { @@ -927,10 +927,10 @@ "id": "940adbeb", "metadata": {}, "source": [ - "## Deep copy\n", + "## Глубокое копирование\n", "\n", - "When we use `copy` to duplicate `box1`, it copies the `Rectangle` object but not the `Point` object it contains.\n", - "So `box1` and `box2` are different objects, as intended." + "Когда мы используем `copy` для дублирования `box1`, копируется объект `Rectangle`, но не объект `Point`, содержащийся в нём.\n", + "Поэтому `box1` и `box2` — разные объекты, как и задумывалось." ] }, { @@ -948,7 +948,7 @@ "id": "eac5309b", "metadata": {}, "source": [ - "But their `corner` attributes refer to the same object." + "Но их атрибуты `corner` указывают на один и тот же объект." ] }, { @@ -966,7 +966,7 @@ "id": "f0cc51b5", "metadata": {}, "source": [ - "The following diagram shows the state of these objects." + "На следующей диаграмме показано состояние этих объектов." ] }, { @@ -1012,14 +1012,14 @@ "id": "35f3e7e1", "metadata": {}, "source": [ - "What `copy` does is called a **shallow copy** because it copies the object but not the objects it contains.\n", - "As a result, changing the `width` or `height` of one `Rectangle` does not affect the other, but changing the attributes of the shared `Point` affects both!\n", - "This behavior is confusing and error-prone.\n", + "То, что делает `copy`, называется **поверхностным копированием**, потому что копируется сам объект, но не объекты внутри него.\n", + "Поэтому изменение `width` или `height` одного прямоугольника не затрагивает другой, а изменение атрибутов общего объекта `Point` отражается на обоих!\n", + "Такое поведение сбивает с толку и приводит к ошибкам.\n", "\n", - "Fortunately, the `copy` module provides another function, called `deepcopy`, that copies not only the object but also the objects it refers to, and the objects *they* refer to, and so on. \n", - "This operation is called a **deep copy**.\n", + "К счастью, модуль `copy` предоставляет функцию `deepcopy`, которая копирует не только сам объект, но и объекты, на которые он ссылается, и те, на которые ссылаются они, и так далее.\n", + "Эта операция называется **глубоким копированием**.\n", "\n", - "To demonstrate, let's start with a new `Rectangle` that contains a new `Point`." + "Для демонстрации создадим новый `Rectangle`, содержащий новый `Point`." ] }, { @@ -1039,7 +1039,7 @@ "id": "ff9ee872", "metadata": {}, "source": [ - "And we'll make a deep copy." + "И сделаем его глубокую копию." ] }, { @@ -1059,7 +1059,7 @@ "id": "7efd0e6a", "metadata": {}, "source": [ - "We can confirm that the two `Rectangle` objects refer to different `Point` objects." + "Мы можем убедиться, что два объекта `Rectangle` содержат разные объекты `Point`." ] }, { @@ -1077,8 +1077,8 @@ "id": "ca925206", "metadata": {}, "source": [ - "Because `box3` and `box4` are completely separate objects, we can modify one without affecting the other.\n", - "To demonstrate, we'll move `box3` and grow `box4`." + "Поскольку `box3` и `box4` полностью независимы, мы можем изменять один, не затрагивая другой.\n", + "Для примера переместим `box3` и увеличим `box4`." ] }, { @@ -1097,7 +1097,7 @@ "id": "3ff31c7c", "metadata": {}, "source": [ - "And we can confirm that the effect is as expected." + "И мы можем убедиться, что всё работает как нужно." ] }, { @@ -1119,10 +1119,10 @@ "id": "67051d62", "metadata": {}, "source": [ - "## Polymorphism\n", + "## Полиморфизм\n", "\n", - "In the previous example, we invoked the `draw` method on two `Line` objects and two `Rectangle` objects.\n", - "We can do the same thing more concisely by making a list of objects." + "В предыдущем примере мы вызывали метод `draw` у двух объектов `Line` и двух объектов `Rectangle`.\n", + "То же самое можно сделать короче, составив список объектов." ] }, { @@ -1140,7 +1140,7 @@ "id": "773955dd", "metadata": {}, "source": [ - "The elements of this list are different types, but they all provide a `draw` method, so we can loop through the list and invoke `draw` on each one." + "Элементы этого списка разных типов, но у всех есть метод `draw`, поэтому можно пройти по списку циклом и вызвать `draw` для каждого." ] }, { @@ -1161,17 +1161,17 @@ "id": "a1ae190c", "metadata": {}, "source": [ - "The first and second time through the loop, `shape` refers to a `Line` object, so when `draw` is invoked, the method that runs is the one defined in the `Line` class.\n", + "Первый и второй раз в цикле переменная `shape` ссылается на объект `Line`, поэтому вызывается метод, определённый в классе `Line`.\n", "\n", - "The third and fourth time through the loop, `shape` refers to a `Rectangle` object, so when `draw` is invoked, the method that runs is the one defined in the `Rectangle` class.\n", + "Третий и четвёртый раз `shape` ссылается на объект `Rectangle`, и вызывается метод из класса `Rectangle`.\n", "\n", - "In a sense, each object knows how to draw itself.\n", - "This feature is called **polymorphism**.\n", - "The word comes from Greek roots that mean \"many shaped\".\n", - "In object-oriented programming, polymorphism is the ability of different types to provide the same methods, which makes it possible to perform many computations -- like drawing shapes -- by invoking the same method on different types of objects.\n", + "В некотором смысле каждый объект знает, как нарисовать себя.\n", + "Эта возможность называется **полиморфизмом**.\n", + "Слово происходит от греческих корней, означающих «многообразие форм».\n", + "В ООП полиморфизм — это способность разных типов предоставлять одни и те же методы, что позволяет выполнять множество операций — например, рисование фигур — вызывая один и тот же метод у объектов разных типов.\n", "\n", - "As an exercise at the end of this chapter, you'll define a new class that represents a circle and provides a `draw` method.\n", - "Then you can use polymorphism to draw lines, rectangles, and circles." + "В упражнении в конце главы вы определите новый класс, представляющий окружность и предоставляющий метод `draw`.\n", + "Тогда вы сможете использовать полиморфизм, чтобы рисовать линии, прямоугольники и окружности." ] }, { @@ -1179,15 +1179,15 @@ "id": "74d1b48f", "metadata": {}, "source": [ - "## Debugging\n", + "## Отладка\n", "\n", - "In this chapter, we ran into a subtle bug that happened because we created a `Point` that was shared by two `Rectangle` objects, and then we modified the `Point`.\n", - "In general, there are two ways to avoid problems like this: you can avoid sharing objects or you can avoid modifying them.\n", + "В этой главе мы столкнулись с тонкой ошибкой: мы создали `Point`, который использовали два объекта `Rectangle`, а затем изменили этот `Point`.\n", + "В общем случае есть два способа избежать подобных проблем: не делиться объектами и не изменять их.\n", "\n", - "To avoid sharing objects, you can use deep copy, as we did in this chapter.\n", + "Чтобы не делиться объектами, можно использовать глубокое копирование, как мы сделали в этой главе.\n", "\n", - "To avoid modifying objects, consider replacing impure functions like `translate` with pure functions like `translated`.\n", - "For example, here's a version of `translated` that creates a new `Point` and never modifies its attributes." + "Чтобы не изменять объекты, рассмотрите возможность заменить нечистые функции типа `translate` чистыми функциями, например `translated`.\n", + "Вот вариант `translated`, который создаёт новый `Point` и никогда не меняет его атрибуты." ] }, { @@ -1208,11 +1208,11 @@ "id": "76972167", "metadata": {}, "source": [ - "Python provides features that make it easier to avoid modifying objects.\n", - "They are beyond the scope of this book, but if you are curious, ask a virtual assistant, \"How do I make a Python object immutable?\"\n", + "В Python есть возможности, позволяющие легче избегать изменения объектов.\n", + "Они выходят за рамки этой книги, но если вам интересно, спросите у виртуального помощника: «Как сделать объект Python неизменяемым?»\n", "\n", - "Creating a new object takes more time than modifying an existing one, but the difference seldom matters in practice.\n", - "Programs that avoid shared objects and impure functions are often easier to develop, test, and debug -- and the best kind of debugging is the kind you don't have to do." + "Создание нового объекта требует больше времени, чем изменение существующего, но на практике эта разница редко имеет значение.\n", + "Программы, избегающие общих объектов и нечистых функций, обычно легче разрабатывать, тестировать и отлаживать — а лучшая отладка та, которую не приходится делать." ] }, { @@ -1220,16 +1220,16 @@ "id": "02106995", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**shallow copy:**\n", - "A copy operation that does not copy nested objects.\n", + "**shallow copy:** \n", + "операция копирования, которая не копирует вложенные объекты.\n", "\n", - "**deep copy:**\n", - "A copy operation that also copies nested objects.\n", + "**deep copy:** \n", + "операция копирования, которая также копирует вложенные объекты.\n", "\n", - "**polymorphism:**\n", - "The ability of a method or operator to work with multiple types of objects." + "**polymorphism:** \n", + "способность метода или оператора работать с объектами разных типов." ] }, { @@ -1237,7 +1237,7 @@ "id": "09dd41c1", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -1260,10 +1260,10 @@ "id": "da0aea86", "metadata": {}, "source": [ - "### Ask a virtual assistant\n", + "### Вопрос виртуальному помощнику\n", "\n", - "For all of the following exercises, consider asking a virtual assistant for help.\n", - "If you do, you'll want include as part of the prompt the class definitions for `Point`, `Line`, and `Rectangle` -- otherwise the VA will make a guess about their attributes and functions, and the code it generates won't work." + "Во всех последующих упражнениях подумайте о том, чтобы обратиться за помощью к виртуальному ассистенту.\n", + "Если решите это сделать, включите в запрос определения классов `Point`, `Line` и `Rectangle` — иначе помощник лишь предположит их атрибуты и методы, и сгенерированный код не заработает." ] }, { @@ -1271,9 +1271,9 @@ "id": "7721e47b", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write an `__eq__` method for the `Line` class that returns `True` if the `Line` objects refer to `Point` objects that are equivalent, in either order." + "Напишите метод `__eq__` для класса `Line`, который возвращает `True`, если объекты `Line` ссылаются на эквивалентные объекты `Point`, независимо от порядка." ] }, { @@ -1281,7 +1281,7 @@ "id": "2e488e0f", "metadata": {}, "source": [ - "You can use the following outline to get started." + "Для начала можно использовать следующую заготовку." ] }, { @@ -1314,7 +1314,7 @@ "id": "3a44e45a", "metadata": {}, "source": [ - "You can use these examples to test your code." + "Вы можете использовать эти примеры для проверки кода." ] }, { @@ -1334,7 +1334,7 @@ "id": "e825f049", "metadata": {}, "source": [ - "This example should be `True` because the `Line` objects refer to `Point` objects that are equivalent, in the same order." + "Здесь результат должен быть `True`, потому что объекты `Line` ссылаются на эквивалентные объекты `Point` в том же порядке." ] }, { @@ -1356,7 +1356,7 @@ "tags": [] }, "source": [ - "This example should be `True` because the `Line` objects refer to `Point` objects that are equivalent, in reverse order." + "Этот пример тоже должен быть `True`, потому что объекты `Line` ссылаются на эквивалентные объекты `Point` в обратном порядке." ] }, { @@ -1375,7 +1375,7 @@ "id": "8c9c787b", "metadata": {}, "source": [ - "Equivalence should always be transitive -- that is, if `line_a` and `line_b` are equivalent, and `line_a` and `line_c` are equivalent, then `line_b` and `line_c` should also be equivalent." + "Эквивалентность должна быть транзитивной: если `line_a` эквивалентна `line_b`, а `line_a` эквивалентна `line_c`, то `line_b` и `line_c` тоже должны быть эквивалентны." ] }, { @@ -1393,7 +1393,7 @@ "id": "d4f385fa", "metadata": {}, "source": [ - "This example should be `False` because the `Line` objects refer to `Point` objects that are not equivalent." + "Здесь результат должен быть `False`, потому что объекты `Line` ссылаются на разные точки." ] }, { @@ -1412,9 +1412,9 @@ "id": "0e629491", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a `Line` method called `midpoint` that computes the midpoint of a line segment and returns the result as a `Point` object." + "Напишите метод `midpoint` класса `Line`, который вычисляет середину отрезка и возвращает результат в виде объекта `Point`." ] }, { @@ -1422,7 +1422,7 @@ "id": "b8c52d19", "metadata": {}, "source": [ - "You can use the following outline to get started." + "Для начала можно использовать следующую заготовку." ] }, { @@ -1455,7 +1455,7 @@ "id": "4df69a9f", "metadata": {}, "source": [ - "You can use the following examples to test your code and draw the result." + "Этими примерами можно воспользоваться для проверки кода и рисования результата." ] }, { @@ -1522,9 +1522,9 @@ "id": "0518c200", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a `Rectangle` method called `midpoint` that find the point in the center of a rectangle and returns the result as a `Point` object." + "Напишите метод `midpoint` класса `Rectangle`, который находит точку в центре прямоугольника и возвращает её как объект `Point`." ] }, { @@ -1532,7 +1532,7 @@ "id": "c586a3ed", "metadata": {}, "source": [ - "You can use the following outline to get started." + "Для начала можно использовать следующую заготовку." ] }, { @@ -1565,7 +1565,7 @@ "id": "d186c84b", "metadata": {}, "source": [ - "You can use the following example to test your code." + "Вы можете использовать следующий пример для проверки кода." ] }, { @@ -1618,15 +1618,15 @@ "id": "00cbc4d9", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a `Rectangle` method called `make_cross` that:\n", + "Напишите метод `make_cross` класса `Rectangle`, который:\n", "\n", - "1. Uses `make_lines` to get a list of `Line` objects that represent the four sides of the rectangle.\n", + "1. с помощью `make_lines` получает список объектов `Line`, представляющих четыре стороны прямоугольника;\n", "\n", - "2. Computes the midpoints of the four lines.\n", + "2. вычисляет середины этих четырёх линий;\n", "\n", - "3. Makes and returns a list of two `Line` objects that represent lines connecting opposite midpoints, forming a cross through the middle of the rectangle." + "3. создаёт и возвращает список из двух объектов `Line`, которые соединяют противоположные середины, образуя крест через центр прямоугольника." ] }, { @@ -1634,7 +1634,7 @@ "id": "29e994c6", "metadata": {}, "source": [ - "You can use this outline to get started." + "Для начала можете использовать эту заготовку." ] }, { @@ -1667,7 +1667,7 @@ "id": "970fcbca", "metadata": {}, "source": [ - "You can use the following example to test your code." + "Следующий пример можно использовать для проверки кода." ] }, { @@ -1710,10 +1710,10 @@ "id": "0f707fe3", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a definition for a class named `Circle` with attributes `center` and `radius`, where `center` is a Point object and `radius` is a number.\n", - "Include special methods `__init__` and a `__str__`, and a method called `draw` that uses `jupyturtle` functions to draw the circle." + "Определите класс `Circle` с атрибутами `center` и `radius`, где `center` — объект `Point`, а `radius` — число.\n", + "Добавьте специальные методы `__init__` и `__str__`, а также метод `draw`, который использует функции `jupyturtle` для рисования окружности." ] }, { @@ -1721,7 +1721,7 @@ "id": "cb1b24a3", "metadata": {}, "source": [ - "You can use the following function, which is a version of the `circle` function we wrote in Chapter 4." + "Вы можете использовать следующую функцию — это вариант функции `circle`, которую мы писали в Главе 4." ] }, { @@ -1760,8 +1760,8 @@ "id": "b4325143", "metadata": {}, "source": [ - "You can use the following example to test your code.\n", - "We'll start with a square `Rectangle` with width and height `100`." + "Для проверки кода можно воспользоваться следующим примером.\n", + "Начнём с квадратного прямоугольника шириной и высотой `100`." ] }, { @@ -1780,7 +1780,7 @@ "id": "2cdecfa9", "metadata": {}, "source": [ - "The following code should create a `Circle` that fits inside the square." + "Следующий код должен создать `Circle`, вписанный в квадрат." ] }, { @@ -1802,7 +1802,7 @@ "id": "37e94d98", "metadata": {}, "source": [ - "If everything worked correctly, the following code should draw the circle inside the square (touching on all four sides)." + "Если всё сработало правильно, следующий код нарисует окружность внутри квадрата (касаясь всех четырёх сторон)." ] }, { @@ -1827,11 +1827,11 @@ "source": [ "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "© 2024 [Allen B. Downey](https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -1857,4 +1857,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 3ac403ad0999982a15f7005ad8d4e3286b881fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:58:34 +0300 Subject: [PATCH 42/44] Translate chap17 markdown cells to Russian --- chapters/chap17.ipynb | 540 ++++++++++++++++++++---------------------- 1 file changed, 260 insertions(+), 280 deletions(-) diff --git a/chapters/chap17.ipynb b/chapters/chap17.ipynb index c26b8b7..5268057 100644 --- a/chapters/chap17.ipynb +++ b/chapters/chap17.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432? ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325)." ] }, { @@ -43,12 +43,12 @@ "tags": [] }, "source": [ - "# Inheritance\n", + "# Наследование\n", "\n", - "The language feature most often associated with object-oriented programming is **inheritance**.\n", - "Inheritance is the ability to define a new class that is a modified version of an existing class.\n", - "In this chapter I demonstrate inheritance using classes that represent playing cards, decks of cards, and poker hands.\n", - "If you don't play poker, don't worry -- I'll tell you what you need to know." + "Языковая особенность чаще всего связана с объектно-ориентированным программированием,-это ** наследование **.\n", + "Наследование - это способность определить новый класс, который является модифицированной версией существующего класса.\n", + "В этой главе я демонстрирую наследование, используя классы, которые представляют воспроизводимые карты, колоды карт и покерные руки.\n", + "Если вы не играете в покер, не волнуйтесь - я скажу вам, что вам нужно знать." ] }, { @@ -56,21 +56,8 @@ "id": "b19c4dae", "metadata": {}, "source": [ - "## Representing cards\n", - "\n", - "There are 52 playing cards in a standard deck -- each of them belongs to one of four suits and one of thirteen ranks. \n", - "The suits are Spades, Hearts, Diamonds, and Clubs.\n", - "The ranks are Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King.\n", - "Depending on which game you are playing, an Ace can be higher than King or lower than 2.\n", - "\n", - "If we want to define a new object to represent a playing card, it is obvious what the attributes should be: `rank` and `suit`.\n", - "It is less obvious what type the attributes should be.\n", - "One possibility is to use strings like `'Spade'` for suits and `'Queen'` for ranks.\n", - "A problem with this implementation is that it would not be easy to compare cards to see which had a higher rank or suit.\n", - "\n", - "An alternative is to use integers to **encode** the ranks and suits.\n", - "In this context, \"encode\" means that we are going to define a mapping between numbers and suits, or between numbers and ranks.\n", - "This kind of encoding is not meant to be a secret (that would be \"encryption\")." + "## Представление карт В стандартной колоде есть 52 игры для игры - каждая из них принадлежит одному из четырех костюмов и одной из тринадцати рангов. Костюмы - пики, сердца, бриллианты и клубы. Ранги - туз, 2, 3, 4, 5, 6, 7, 8, 9, 10, Джек, королева и король. В зависимости от того, в какой игре вы играете, туз может быть выше, чем король или ниже 2. Если мы хотим определить новый объект для представления игровой карты, очевидно, какими должны быть атрибуты: `rank` и` костюм. Менее очевидно, какой тип должен быть атрибуты. Одна возможность состоит в том, чтобы использовать струны, такие как «Spade» для костюмов и «Queen» для рядов. Проблема с этой реализацией заключается в том, что было бы нелегко сравнить карты, чтобы увидеть, что имело более высокий ранг или костюм. Альтернативой является использование целых чисел для ** кодировать ** ранги и костюмы. В этом контексте «кодирование» означает, что мы собираемся определить отображение между числами и костюмами или между числами и рангами. Этот вид кодировки не предназначен для секрета (это будет\n", + "быть \"шифрование\")." ] }, { @@ -78,17 +65,17 @@ "id": "a9bafecf", "metadata": {}, "source": [ - "For example, this table shows the suits and the corresponding integer codes:\n", + "Например, в этой таблице показаны подходящие и соответствующие целочисленные коды:\n", "\n", "\n", - "| Suit | Code |\n", + "| Костюм | Код |\n", "| --- | --- |\n", - "| Spades | 3 |\n", - "| Hearts | 2 |\n", - "| Diamonds | 1 |\n", - "| Clubs | 0 |\n", + "| Spades | 3 |\n", + "| Сердца | 2 |\n", + "| Бриллианты | 1 |\n", + "| Клубы | 0 |\n", "\n", - "With this encoding, we can compare suits by comparing their codes." + "С помощью этого кодирования мы можем сравнить костюмы, сравнивая их коды." ] }, { @@ -96,21 +83,23 @@ "id": "a1b46b1a", "metadata": {}, "source": [ - "To encode the ranks, we'll use the integer `2` to represent the rank `2`, `3` to represent `3`, and so on up to `10`.\n", - "The following table shows the codes for the face cards.\n", + "Чтобы кодировать ранги, мы будем использовать целое число `2`, чтобы представить ранг` 2`, `3`, чтобы представлять` 3` и т. Д. до `10`.\n", + "В следующей таблице показаны коды для карт лица.\n", "\n", " \n", - "| Rank | Code |\n", + "| Ранг | Код |\n", "| --- | --- |\n", - "| Jack | 11 |\n", - "| Queen | 12 |\n", - "| King | 13 |\n", + "| Джек | 11 |\n", + "| Королева | 12 |\n", + "| Король | 13 |\n", "\n", - "And we can use either `1` or `14` to represent an Ace, depending on whether we want it to be considered lower or higher than the other ranks.\n", + "И мы можем использовать либо `1`, либо« 14 », чтобы представлять ACE, в зависимости от того, хотим ли мы считаться ниже или выше, чем другие ранги.\n", "\n", - "To represent these encodings, we will use two lists of strings, one with the names of the suits and the other with the names of the ranks.\n", + "Чтобы представить эти кодировки, мы будем использовать два списка строк, один с именами костюмов, а другой с именами рангов.\n", "\n", - "Here's a definition for a class that represents a playing card, with these lists of strings as **class variables**, which are variables defined inside a class definition, but not inside a method." + "Вот определение для класса, который представляет собой игровую карту, с этими списками строк как ** переменные класса **, которые являются переменными, определенными \n", + "1dea\n", + "внутри определения класса, но не внутри метода." ] }, { @@ -133,9 +122,9 @@ "id": "d63f798a", "metadata": {}, "source": [ - "The first element of `rank_names` is `None` because there is no card with rank zero. By including `None` as a place-keeper, we get a list with the nice property that the index `2` maps to the string `'2'`, and so on.\n", + "Первым элементом `rank_names` является« нет », потому что нет карты с ноль. Включив «нет» в качестве хранителя, мы получаем список со свойством хорошего, что индекс `2` отображает на строку` '2'' и так далее.\n", "\n", - "Class variables are associated with the class, rather than an instance of the class, so we can access them like this." + "Переменные класса связаны с классом, а не с экземпляром класса, поэтому мы можем получить к ним доступ к ним." ] }, { @@ -153,7 +142,7 @@ "id": "c837fff6", "metadata": {}, "source": [ - "We can use `suit_names` to look up a suit and get the corresponding string." + "Мы можем использовать `suit_names`, чтобы найти костюм и получить соответствующую строку." ] }, { @@ -171,7 +160,7 @@ "id": "a59d905e", "metadata": {}, "source": [ - "And `rank_names` to look up a rank." + "И `rank_names`, чтобы посмотреть ранг." ] }, { @@ -189,9 +178,9 @@ "id": "50dda19b", "metadata": {}, "source": [ - "## Card attributes\n", + "## Карточные атрибуты\n", "\n", - "Here's an `__init__` method for the `Card` class -- it takes `suit` and `rank` as parameters and assigns them to attributes with the same names." + "Вот метод `__init__` для класса` card` - он принимает `костюм 'и` rank' в качестве параметров и назначает их атрибутам с одинаковыми именами." ] }, { @@ -213,7 +202,7 @@ "id": "31a2782d", "metadata": {}, "source": [ - "Now we can create a `Card` object like this." + "Теперь мы можем создать такой объект «карты»." ] }, { @@ -231,7 +220,7 @@ "id": "85e5cf5d", "metadata": {}, "source": [ - "We can use the new instance to access the attributes." + "Мы можем использовать новый экземпляр для доступа к атрибутам." ] }, { @@ -249,7 +238,7 @@ "id": "449225d3", "metadata": {}, "source": [ - "It is also legal to use the instance to access the class variables." + "Также законно использовать экземпляр для доступа к переменным класса." ] }, { @@ -267,7 +256,7 @@ "id": "97232ffa", "metadata": {}, "source": [ - "But if you use the class, it is clearer that they are class variables, not attributes." + "Но если вы используете класс, ясно, что они являются переменными класса, а не атрибутами." ] }, { @@ -275,9 +264,9 @@ "id": "7a0a79ae", "metadata": {}, "source": [ - "## Printing cards\n", + "## печатные карты\n", "\n", - "Here's a `__str__` method for `Card` objects." + "Вот метод `__str__` для объектов` card`." ] }, { @@ -300,7 +289,7 @@ "id": "d6c51352", "metadata": {}, "source": [ - "When we print a `Card`, Python calls the `__str__` method to get a human-readable representation of the card." + "Когда мы печатаем «карту», Python называет метод `__str__`, чтобы получить читаемое на человеку представление карты." ] }, { @@ -318,10 +307,10 @@ "id": "76044b9e", "metadata": {}, "source": [ - "The following is a diagram of the `Card` class object and the Card instance.\n", - "`Card` is a class object, so its type is `type`.\n", - "`queen` is an instance of `Card`, so its type is `Card`.\n", - "To save space, I didn't draw the contents of `suit_names` and `rank_names`." + "Ниже приведена диаграмма объекта класса `card` и экземпляра карты.\n", + "`Card` - это объект класса, поэтому его тип` type`.\n", + "`Queen` - это экземпляр` card ', поэтому ее тип `card'.\n", + "Чтобы сохранить пространство, я не нарисовал содержимое `suit_names` и` rank_names`." ] }, { @@ -380,7 +369,7 @@ "id": "ccb8e41d", "metadata": {}, "source": [ - "Every `Card` instance has its own `suit` and `rank` attributes, but there is only one `Card` class object, and only one copy of the class variables `suit_names` and `rank_names`." + "Каждый экземпляр `card` имеет свои собственные атрибуты` костюма и `ранга, но есть только один объект класса` card`, и только одна копия переменных класса `suit_names` и` rank_names`." ] }, { @@ -388,9 +377,9 @@ "id": "98c6508d", "metadata": {}, "source": [ - "## Comparing cards\n", + "## Сравнение карт\n", "\n", - "Suppose we create a second `Card` object with the same suit and rank." + "Предположим, мы создаем второй объект `card` с тем же костюмом и рангом." ] }, { @@ -409,7 +398,7 @@ "id": "3c92779c", "metadata": {}, "source": [ - "If we use the `==` operator to compare them, it checks whether `queen` and `queen2` refer to the same object." + "Если мы используем оператор `==` для их сравнения, он проверяет, относятся ли «Queen» и `Queen2` к одному и тому же объекту." ] }, { @@ -427,8 +416,8 @@ "id": "278d8abe", "metadata": {}, "source": [ - "They don't, so it returns `False`.\n", - "We can change this behavior by defining the special method `__eq__`." + "Они этого не делают, поэтому он возвращает `false '.\n", + "Мы можем изменить это поведение, определив специальный метод `__eq__`." ] }, { @@ -449,10 +438,10 @@ "id": "bd66a9d3", "metadata": {}, "source": [ - "`__eq__` takes two `Card` objects as parameters and returns `True` if they have the same suit and rank, even if they are not the same object.\n", - "In other words, it checks whether they are equivalent, even if they are not identical.\n", + "`__eq__` принимает два объекта` card` в виде параметров и возвращает `true`, если они имеют одинаковый костюм и ранги, даже если они не один и тот же объект.\n", + "Другими словами, это проверяет, являются ли они эквивалентными, даже если они не идентичны.\n", "\n", - "When we use the `==` operator with `Card` objects, Python calls the `__eq__` method." + "Когда мы используем оператор `==` с объектами `card`, Python вызывает метод` __eq__`." ] }, { @@ -470,7 +459,7 @@ "id": "23d99d3e", "metadata": {}, "source": [ - "As a second test, let's create a card with the same suit and a different rank." + "В качестве второго теста давайте создадим карту с одним и тем же костюмом и другим рангом." ] }, { @@ -489,7 +478,7 @@ "id": "c5f66404", "metadata": {}, "source": [ - "We can confirm that `queen` and `six` are not equivalent." + "Мы можем подтвердить, что «Queen» и «Six» не эквивалентны." ] }, { @@ -507,8 +496,8 @@ "id": "1dcb561f", "metadata": {}, "source": [ - "If we use the `!=` operator, Python invokes a special method called `__ne__`, if it exists.\n", - "Otherwise it invokes`__eq__` and inverts the result -- so if `__eq__` returns `True`, the result of the `!=` operator is `False`." + "Если мы используем оператор `! =`, Python вызывает специальный метод под названием `__ne__`, если он существует.\n", + "В противном случае он вызывает `__eq__` и инвертирует результат - поэтому, если `__eq__` возвращает` true`, результат оператора `! =` `False`." ] }, { @@ -536,8 +525,8 @@ "id": "77c48464", "metadata": {}, "source": [ - "Now suppose we want to compare two cards to see which is bigger.\n", - "If we use one of the relational operators, we get a `TypeError`." + "Теперь предположим, что мы хотим сравнить две карты, чтобы увидеть, что больше.\n", + "Если мы используем одного из реляционных операторов, мы получим `typeError." ] }, { @@ -559,11 +548,11 @@ "id": "4db0ad52", "metadata": {}, "source": [ - "To change the behavior of the `<` operator, we can define a special method called `__lt__`, which is short for \"less than\".\n", - "For the sake of this example, let's assume that suit is more important than rank -- so all Spades outrank all Hearts, which outrank all Diamonds, and so on.\n", - "If two cards have the same suit, the one with the higher rank wins.\n", + "Чтобы изменить поведение оператора «<», мы можем определить специальный метод под названием «__LT__`, который коротко для« меньше, чем ».\n", + "Ради этого примера давайте предположим, что костюм более важен, чем ранга, - поэтому все пики опережают все сердца, которые опережают все бриллианты и так далее.\n", + "Если две карты имеют одинаковый костюм, то, что с более высоким рангом выигрывает.\n", "\n", - "To implement this logic, we'll use the following method, which returns a tuple containing a card's suit and rank, in that order." + "Чтобы реализовать эту логику, мы будем использовать следующий метод, который в этом порядке возвращает кортеж, содержащий костюм и ранги карты." ] }, { @@ -584,7 +573,7 @@ "id": "d5062348", "metadata": {}, "source": [ - "We can use this method to write `__lt__`." + "Мы можем использовать этот метод для написания `__lt__`." ] }, { @@ -605,10 +594,10 @@ "id": "bd9ef8f5", "metadata": {}, "source": [ - "Tuple comparison compares the first elements from each tuple, which represent the suits.\n", - "If they are the same, it compares the second elements, which represent the ranks.\n", + "Сравнение кортежей сравнивает первые элементы из каждого кортежа, которые представляют костюмы.\n", + "Если они одинаковы, он сравнивает вторые элементы, которые представляют ряды.\n", "\n", - "Now if we use the `<` operator, it invokes the `__lt__` method." + "Теперь, если мы используем оператор «<` », он вызывает метод` __LT__." ] }, { @@ -626,8 +615,8 @@ "id": "83289a77", "metadata": {}, "source": [ - "If we use the `>` operator, it invokes a special method called `__gt__`, if it exists.\n", - "Otherwise it invokes `__lt__` with the arguments in the opposite order." + "Если мы используем оператор `>`, он вызывает специальный метод под названием `__gt__`, если он существует.\n", + "В противном случае он вызывает `__lt__` с аргументами в противоположном порядке." ] }, { @@ -655,7 +644,7 @@ "id": "5d0a91de", "metadata": {}, "source": [ - "Finally, if we use the `<=` operator, it invokes a special method called `__le__`." + "Наконец, если мы используем оператор `<=`, он вызывает специальный метод под названием `__le__`." ] }, { @@ -676,7 +665,7 @@ "id": "6c85ac69", "metadata": {}, "source": [ - "So we can check whether one card is less than or equal to another." + "Таким образом, мы можем проверить, меньше ли одна карта или равна другой." ] }, { @@ -704,7 +693,7 @@ "id": "7af7b289", "metadata": {}, "source": [ - "If we use the `>=` operator, it uses `__ge__` if it exists. Otherwise, it invokes `__le__` with the arguments in the opposite order." + "Если мы используем оператор `> =`, он использует `__ge__`, если он существует. В противном случае он вызывает `__le__` с аргументами в противоположном порядке." ] }, { @@ -722,9 +711,9 @@ "id": "fe2a81cc", "metadata": {}, "source": [ - "As we have defined them, these methods are complete in the sense that we can compare any two `Card` objects, and consistent in the sense that results from different operators don't contradict each other.\n", - "With these two properties, we can say that `Card` objects are **totally ordered**.\n", - "And that means, as we'll see soon, that they can be sorted." + "Как мы их определили, эти методы полны в том смысле, что мы можем сравнить любые два объекта «карты» и последовательны в том смысле, что результаты разных операторов не противоречат друг другу.\n", + "С этими двумя свойствами мы можем сказать, что объекты `card` ** полностью заказаны **.\n", + "И это означает, как мы скоро увидим, что их можно отсортировать." ] }, { @@ -732,11 +721,11 @@ "id": "199f8bfc", "metadata": {}, "source": [ - "## Decks\n", + "## палубы\n", "\n", - "Now that we have objects that represent cards, let's define objects that represent decks.\n", - "The following is a class definition for `Deck` with\n", - "an `__init__` method takes a list of `Card` objects as a parameter and assigns it to an attribute called `cards`." + "Теперь, когда у нас есть объекты, которые представляют карты, давайте определим объекты, которые представляют колоды.\n", + "Ниже приведено определение класса для `deck` с\n", + "Метод `__init__ 'принимает список объектов` card` в качестве параметра и присваивает его атрибуту с именем `cards'." ] }, { @@ -757,7 +746,7 @@ "id": "2d529789", "metadata": {}, "source": [ - "To create a list that contains the 52 cards in a standard deck, we'll use the following static method." + "Чтобы создать список, который содержит 52 карты в стандартной колоде, мы будем использовать следующий статический метод." ] }, { @@ -783,11 +772,11 @@ "id": "47ae8f71", "metadata": {}, "source": [ - "In `make_cards`, the outer loop enumerates the suits from `0` to `3`.\n", - "The inner loop enumerates the ranks from `2` to `14` -- where `14` represents an Ace that outranks a King.\n", - "Each iteration creates a new `Card` with the current suit and rank, and appends it to `cards`.\n", + "В `make_cards` внешний цикл перечисляет костюмы от` 0` до `3`.\n", + "Внутренняя петля перечисляет ряды от `2` до` 14` - где `14` представляет туз, который опередил короля.\n", + "Каждая итерация создает новую «карту» с текущим костюмом и рангом и добавляет ее на «карты».\n", "\n", - "Here's how we make a list of cards and a `Deck` object that contains it." + "Вот как мы составляем список карт и объект «колоды», который содержит его." ] }, { @@ -807,7 +796,7 @@ "id": "032ec302", "metadata": {}, "source": [ - "It contains 52 cards, as intended." + "Он содержит 52 карты, как и предполагалось." ] }, { @@ -817,9 +806,9 @@ "tags": [] }, "source": [ - "## Printing the deck\n", + "## Печать колоды\n", "\n", - "Here is a `__str__` method for `Deck`." + "Вот метод «__str__` для` deck »." ] }, { @@ -843,9 +832,9 @@ "id": "660f18e6", "metadata": {}, "source": [ - "This method demonstrates an efficient way to accumulate a large string -- building a list of strings and then using the string method `join`. \n", + "Этот метод демонстрирует эффективный способ накопления большой строки - создание списка строк, а затем используя метод строки `join '. \n", "\n", - "We'll test this method with a deck that only contains two cards." + "Мы проверяем этот метод с помощью колоды, которая содержит только две карты." ] }, { @@ -863,7 +852,7 @@ "id": "91c7145f", "metadata": {}, "source": [ - "If we call `str`, it invokes `__str__`." + "Если мы называем `str`, это вызывает` __str__`." ] }, { @@ -881,9 +870,10 @@ "id": "00270656", "metadata": {}, "source": [ - "When Jupyter displays a string, it shows the \"representational\" form of the string, which represents a newline with the sequence `\\n`.\n", + "Когда Юпитер отображает строку, он показывает «репрезентативную» форму строки, которая представляет новую линию с последовательности `\n", + "`.\n", "\n", - "However, if we print the result, Jupyter shows the \"printable\" form of the string, which prints the newline as whitespace." + "Однако, если мы печатаем результат, Юпитер показывает форму «печати» строки, которая печатает новую линию в качестве пробела." ] }, { @@ -901,7 +891,7 @@ "id": "e97810c4", "metadata": {}, "source": [ - "So the cards appear on separate lines." + "Таким образом, карты появляются на отдельных строках." ] }, { @@ -909,11 +899,11 @@ "id": "52d3d597", "metadata": {}, "source": [ - "## Add, remove, shuffle and sort\n", + "## Добавить, удалить, перетасовать и сортировать\n", "\n", - "To deal cards, we would like a method that removes a card from the deck\n", - "and returns it. The list method `pop` provides a convenient way to do\n", - "that." + "Для сделки с картами мы хотели бы метод, который удаляет карту из колоды\n", + "и возвращает его. Метод списка `pop` предоставляет удобный способ сделать\n", + "что." ] }, { @@ -934,7 +924,7 @@ "id": "1fcef47b", "metadata": {}, "source": [ - "Here's how we use it." + "Вот как мы его используем." ] }, { @@ -953,7 +943,7 @@ "id": "65427954", "metadata": {}, "source": [ - "We can confirm that there are `51` cards left in the deck." + "Мы можем подтвердить, что в палубе остались карты 51 `." ] }, { @@ -971,7 +961,7 @@ "id": "7ca3614e", "metadata": {}, "source": [ - "To add a card, we can use the list method `append`." + "Чтобы добавить карту, мы можем использовать метод списка `append`." ] }, { @@ -992,7 +982,7 @@ "id": "2ecd8703", "metadata": {}, "source": [ - "As an example, we can put back the card we just popped." + "Например, мы можем вернуть карту, которую мы только что выскочили." ] }, { @@ -1011,7 +1001,7 @@ "id": "8b5af8ce", "metadata": {}, "source": [ - "To shuffle the deck, we can use the `shuffle` function from the `random` module:" + "Чтобы перетасовать палубу, мы можем использовать функцию «shuffle» из модуля `random ':" ] }, { @@ -1057,7 +1047,7 @@ "id": "a8cb1a7f", "metadata": {}, "source": [ - "If we shuffle the deck and print the first few cards, we can see that they are in no apparent order." + "Если мы перетасоваем колоду и распечатываем первые несколько карт, мы увидим, что они не имеют видимости." ] }, { @@ -1077,7 +1067,7 @@ "id": "a198dde3", "metadata": {}, "source": [ - "To sort the cards, we can use the list method `sort`, which sorts the elements \"in place\" -- that is, it modifies the list rather than creating a new list." + "Чтобы сортировать карты, мы можем использовать метод списка `sort`, который сортирует элементы« на месте », то есть он изменяет список, а не создает новый список." ] }, { @@ -1098,7 +1088,7 @@ "id": "d4f017c7", "metadata": {}, "source": [ - "When we invoke `sort`, it uses the `__lt__` method to compare cards." + "Когда мы вызываем `sort`, он использует метод` __LT__` для сравнения карт." ] }, { @@ -1116,7 +1106,7 @@ "id": "2bb966fd", "metadata": {}, "source": [ - "If we print the first few cards, we can confirm that they are in increasing order." + "Если мы распечатаем первые несколько карт, мы можем подтвердить, что они находятся в порядке." ] }, { @@ -1135,8 +1125,8 @@ "id": "5c41ce4d", "metadata": {}, "source": [ - "In this example, `Deck.sort` doesn't do anything other than invoke `list.sort`.\n", - "Passing along responsibility like this is called **delegation**." + "В этом примере `deck.sort` ничего не делает, кроме как вызовать` list.sort`.\n", + "Передача на такую ответственность называется ** делегирование **." ] }, { @@ -1144,18 +1134,18 @@ "id": "0502961b", "metadata": {}, "source": [ - "## Parents and children\n", + "## родители и дети\n", "\n", - "Inheritance is the ability to define a new class that is a modified version of an existing class.\n", - "As an example, let's say we want a class to represent a \"hand\", that is, the cards held by one player.\n", + "Наследование - это способность определить новый класс, который является модифицированной версией существующего класса.\n", + "Например, допустим, мы хотим, чтобы класс представил «руку», то есть карты, удерживаемые одним игроком.\n", "\n", - "* A hand is similar to a deck -- both are made up of a collection of cards, and both require operations like adding and removing cards.\n", + "* Рука похожа на колоду - оба состоят из коллекции карт, и оба требуют таких операций, как добавление и удаление карт.\n", "\n", - "* A hand is also different from a deck -- there are operations we want for hands that don't make sense for a deck. For example, in poker we might compare two hands to see which one wins. In bridge, we might compute a score for a hand in order to make a bid.\n", + "* Рука также отличается от колоды - есть операции, которые мы хотим для рук, которые не имеют смысла для колоды. Например, в покере мы можем сравнить две руки, чтобы увидеть, какая победа. В мосту мы могли бы вычислить счет за руку, чтобы сделать ставку.\n", "\n", - "This relationship between classes -- where one is a specialized version of another -- lends itself to inheritance. \n", + "Эта связь между классами, где одна является специализированной версией другой, поддается наследству. \n", "\n", - "To define a new class that is based on an existing class, we put the name of the existing class in parentheses." + "Чтобы определить новый класс, основанный на существующем классе, мы поместили имя существующего класса в скобках." ] }, { @@ -1174,9 +1164,9 @@ "id": "339295cd", "metadata": {}, "source": [ - "This definition indicates that `Hand` inherits from `Deck`, which means that `Hand` objects can access methods defined in `Deck`, like `take_card` and `put_card`.\n", + "Это определение указывает на то, что «рука» наследует от `deck`, что означает, что объекты` hand 'могут получить доступ к методам, определенным в «Deck», например, `take_card` и` put_card`.\n", "\n", - "`Hand` also inherits `__init__` from `Deck`, but if we define `__init__` in the `Hand` class, it overrides the one in the `Deck` class." + "`Hand 'также наследует` __init__` от `deck`, но если мы определим` __init__` в классе `hand`, он переопределяет тот в классе« Deck »." ] }, { @@ -1198,8 +1188,8 @@ "id": "9b6a763a", "metadata": {}, "source": [ - "This version of `__init__` takes an optional string as a parameter, and always starts with an empty list of cards.\n", - "When we create a `Hand`, Python invokes this method, not the one in `Deck` -- which we can confirm by checking that the result has a `label` attribute." + "Эта версия `__init__` принимает дополнительную строку в качестве параметра и всегда начинается с пустого списка карт.\n", + "Когда мы создаем «руку», Python вызывает этот метод, а не тот, который в «Deck» - который мы можем подтвердить, проверив, что результат имеет атрибут `label '." ] }, { @@ -1218,7 +1208,7 @@ "id": "b1e2a67d", "metadata": {}, "source": [ - "To deal a card, we can use `take_card` to remove a card from a `Deck`, and `put_card` to add the card to a `Hand`." + "Чтобы разобраться с картой, мы можем использовать `take_card`, чтобы удалить карту из` deck 'и `put_card`, чтобы добавить карту в` hand'." ] }, { @@ -1239,7 +1229,7 @@ "id": "dc2ce06b", "metadata": {}, "source": [ - "Let's encapsulate this code in a `Deck` method called `move_cards`." + "Давайте инкапсулируем этот код в метод «Deck» с именем `move_cards`." ] }, { @@ -1262,8 +1252,8 @@ "id": "16e6c404", "metadata": {}, "source": [ - "This method is polymorphic -- that is, it works with more than one type: `self` and `other` can be either a `Hand` or a `Deck`.\n", - "So we can use this method to deal a card from `Deck` to a `Hand`, from one `Hand` to another, or from a `Hand` back to a `Deck`." + "Этот метод является полиморфным, то есть он работает с более чем одним типом: «Self» и «Другое» могут быть либо «рукой», либо «палубой».\n", + "Таким образом, мы можем использовать этот метод, чтобы сдать карту от «палубы» до `hand ', от одной` hand' до другой или от `hand 'обратно в` deck'." ] }, { @@ -1271,18 +1261,18 @@ "id": "e648a722", "metadata": {}, "source": [ - "When a new class inherits from an existing one, the existing one is called the **parent** and the new class is called the **child**. In general:\n", + "Когда новый класс наследует от существующего, существующий называется ** родитель **, а новый класс называется ** ребенок **. В общем:\n", "\n", - "* Instances of the child class should have all of the attributes of the parent class, but they can have additional attributes.\n", + "* Экземпляры детского класса должны иметь все атрибуты родительского класса, но они могут иметь дополнительные атрибуты.\n", "\n", - "* The child class should have all of the methods of the parent class, but it can have additional methods.\n", + "* Дочерний класс должен иметь все методы родительского класса, но он может иметь дополнительные методы.\n", "\n", - "* If a child class overrides a method from the parent class, the new method should take the same parameters and return a compatible result.\n", + "* Если дочерний класс переопределяет метод из родительского класса, новый метод должен принимать одинаковые параметры и вернуть совместимый результат.\n", "\n", - "This set of rules is called the \"Liskov substitution principle\" after computer scientist Barbara Liskov.\n", + "Этот набор правил называется «Принцип замены Лискова» после того, как компьютерный ученый Барбара Лисков.\n", "\n", - "If you follow these rules, any function or method designed to work with an instance of a parent class, like a `Deck`, will also work with instances of a child class, like `Hand`.\n", - "If you violate these rules, your code will collapse like a house of cards (sorry)." + "Если вы следуете этим правилам, любая функция или метод, предназначенные для работы с экземпляром родительского класса, например, «колода», также будут работать с экземплярами детского класса, например, «рука».\n", + "Если вы нарушаете эти правила, ваш код будет рухнуть, как карточный дом (извините)." ] }, { @@ -1290,12 +1280,12 @@ "id": "e80873dd", "metadata": {}, "source": [ - "## Specialization\n", + "## Специализация\n", "\n", - "Let's make a class called `BridgeHand` that represents a hand in bridge -- a widely played card game.\n", - "We'll inherit from `Hand` and add a new method called `high_card_point_count` that evaluates a hand using a \"high card point\" method, which adds up points for the high cards in the hand.\n", + "Давайте сделаем класс под названием «Бриджханд», который представляет руку в мосту - широко воспроизводимая карточная игра.\n", + "Мы наследуем от `hand` и добавим новый метод с именем` high_card_point_count`, который оценивает руку, используя метод «High Card Point», который добавляет точки для высоких карт в руке.\n", "\n", - "Here's a class definition that contains as a class variable a dictionary that maps from card names to their point values." + "Вот определение класса, которое содержит как переменную класса - словарь, который отображает от имен карт до значений их точек." ] }, { @@ -1321,7 +1311,7 @@ "id": "4c038717", "metadata": {}, "source": [ - "Given the rank of a card, like `12`, we can use `Card.rank_names` to get the string representation of the rank, and then use `hcp_dict` to get its score." + "Учитывая ранг карты, например, `12 ', мы можем использовать` card.rank_names`, чтобы получить строку представления ранга, а затем использовать `hcp_dict`, чтобы получить свой счет." ] }, { @@ -1342,7 +1332,7 @@ "id": "c3a7820d", "metadata": {}, "source": [ - "The following method loops through the cards in a `BridgeHand` and adds up their scores." + "Следующий метод проходит через карты в «Бриджханд» и складывает свои результаты." ] }, { @@ -1384,7 +1374,7 @@ "id": "94535d8e", "metadata": {}, "source": [ - "To test it, we'll deal a hand with five cards -- a bridge hand usually has thirteen, but it's easier to test code with small examples." + "Чтобы проверить это, мы рассмотрим руку с пятью картами - мостовая рука обычно имеет тринадцать, но проще протестировать код с небольшими примерами." ] }, { @@ -1406,7 +1396,7 @@ "id": "a1bd2521", "metadata": {}, "source": [ - "And here is the total score for the King and Queen." + "И вот общий результат для короля и королевы." ] }, { @@ -1424,8 +1414,8 @@ "id": "b4f5e107", "metadata": {}, "source": [ - "`BridgeHand` inherits the variables and methods of `Hand` and adds a class variable and a method that are specific to bridge.\n", - "This way of using inheritance is called **specialization** because it defines a new class that is specialized for a particular use, like playing bridge." + "«Бриджханд» наследует переменные и методы «рука» и добавляет переменную класса и метод, специфичный для моста.\n", + "Этот способ использования наследования называется ** Специализация **, потому что он определяет новый класс, который специализируется на конкретном использовании, например, игра в мост." ] }, { @@ -1433,20 +1423,8 @@ "id": "b493622d", "metadata": {}, "source": [ - "## Debugging\n", - "\n", - "Inheritance is a useful feature.\n", - "Some programs that would be repetitive without inheritance can be written more concisely with it.\n", - "Also, inheritance can facilitate code reuse, since you can customize the behavior of a parent class without having to modify it.\n", - "In some cases, the inheritance structure reflects the natural structure of the problem, which makes the design easier to understand.\n", - "\n", - "On the other hand, inheritance can make programs difficult to read.\n", - "When a method is invoked, it is sometimes not clear where to find its definition -- the relevant code may be spread across several modules.\n", - "\n", - "Any time you are unsure about the flow of execution through your program, the simplest solution is to add print statements at the beginning of the relevant methods.\n", - "If `Deck.shuffle` prints a message that says something like `Running Deck.shuffle`, then as the program runs it traces the flow of execution.\n", - "\n", - "As an alternative, you could use the following function, which takes an object and a method name (as a string) and returns the class that provides the definition of the method." + "## Отладка наследования является полезной функцией. Некоторые программы, которые были бы повторяющимися без наследства, могут быть написаны более кратко с ним. Кроме того, наследование может облегчить повторное использование кода, поскольку вы можете настроить поведение родительского класса без необходимости его изменений. В некоторых случаях структура наследования отражает естественную структуру проблемы, которая облегчает понимание дизайна. С другой стороны, наследство может затруднить чтение программ. Когда метод вызывается, иногда неясно, где найти его определение - соответствующий код может распространяться по нескольким модулям. Каждый раз, когда вы не уверены в потоке выполнения через вашу программу, самое простое решение - добавить печатные операторы в начале соответствующих методов. Если `deck.shuffle` напечатает сообщение, в котором говорится что -то вроде` running deck.shuffle ', то, когда программа запускает, она прослеживает поток выполнения. В качестве альтернативы вы можете использовать следующую функцию, которая принимает\n", + "Объект и имя метода (как строка) и возвращает класс, который предоставляет определение метода." ] }, { @@ -1469,10 +1447,10 @@ "id": "1ee8f2da", "metadata": {}, "source": [ - "`find_defining_class` uses the `mro` method to get the list of class objects (types) that will be searched for methods.\n", - "\"MRO\" stands for \"method resolution order\", which is the sequence of classes Python searches to \"resolve\" a method name -- that is, to find the function object the name refers to.\n", + "`find_defining_class` использует метод` mro`, чтобы получить список объектов класса (типы), которые будут искать методы.\n", + "«MRO» означает «Порядок разрешения метода», который представляет собой последовательность классов Python Searchs, чтобы «разрешить» имя метода, то есть найти объект функции, на который ссылается имя, на которое ссылается.\n", "\n", - "As an example, let's instantiate a `BridgeHand` and then find the defining class of `shuffle`." + "В качестве примера давайте создам создание «Бриджханд», а затем найдем определяющий класс «shuffle»." ] }, { @@ -1491,7 +1469,7 @@ "id": "eeb70a14", "metadata": {}, "source": [ - "The `shuffle` method for the `BridgeHand` object is the one in `Deck`." + "Метод `shuffle` для объекта« Бриджханд » - это то, что в« колоде »." ] }, { @@ -1499,31 +1477,31 @@ "id": "07f4c4bb", "metadata": {}, "source": [ - "## Glossary\n", + "## Глоссарий\n", "\n", - "**inheritance:**\n", - " The ability to define a new class that is a modified version of a previously defined class.\n", + "**наследование:**\n", + " Способность определить новый класс, который является модифицированной версией ранее определенного класса.\n", "\n", - "**encode:**\n", - " To represent one set of values using another set of values by constructing a mapping between them.\n", + "** кодировать: **\n", + " Представлять один набор значений, используя другой набор значений, построив картирование между ними.\n", "\n", - "**class variable:**\n", - "A variable defined inside a class definition, but not inside any method.\n", + "** Переменная класса: **\n", + "Переменная, определенная внутри определения класса, но не внутри какого -либо метода.\n", "\n", - "**totally ordered:**\n", - "A set of objects is totally ordered if we can compare any two elements and the results are consistent.\n", + "** Полностью заказано: **\n", + "Набор объектов полностью упорядочен, если мы сможем сравнить любые два элемента, и результаты являются последовательными.\n", "\n", - "**delegation:**\n", - "When one method passes responsibility to another method to do most or all of the work.\n", + "**делегация:**\n", + "Когда один метод передает ответственность за другой метод для выполнения большинства или всей работы.\n", "\n", - "**parent class:**\n", - "A class that is inherited from.\n", + "** Родительский класс: **\n", + "Класс, который унаследован от.\n", "\n", - "**child class:**\n", - "A class that inherits from another class.\n", + "** Детский класс: **\n", + "Класс, который наследует от другого класса.\n", "\n", - "**specialization:**\n", - "A way of using inheritance to create a new class that is a specialized version of an existing class." + "** Специализация: **\n", + "Способ использования наследования для создания нового класса, который является специализированной версией существующего класса." ] }, { @@ -1531,7 +1509,7 @@ "id": "1aea9b2b", "metadata": {}, "source": [ - "## Exercises" + "## Упражнения" ] }, { @@ -1554,25 +1532,27 @@ "id": "7913e6b1", "metadata": {}, "source": [ - "### Ask a Virtual Assistant\n", + "### Спросите виртуального помощника\n", "\n", - "When it goes well, object-oriented programming can make programs more readable, testable, and reusable.\n", - "But it can also make programs complicated and hard to maintain.\n", - "As a result, OOP is a topic of controversy -- some people love it, and some people don't.\n", + "Когда все идет хорошо, объектно-ориентированное программирование может сделать программы более читаемыми, тестируемыми и повторно используемыми.\n", + "Но это также может сделать программы сложными и трудными для поддержания.\n", + "В результате ООП - это тема противоречий - некоторые люди любят это, а некоторые нет.\n", "\n", - "To learn more about the topic, ask a virtual assistant:\n", + "Чтобы узнать больше об этой теме, спросите виртуального помощника:\n", "\n", - "* What are some pros and cons of object-oriented programming?\n", + "* Каковы некоторые плюсы и минусы объектно-ориентированного программирования?\n", "\n", - "* What does it mean when people say \"favor composition over inheritance\"?\n", + "* Что это значит, когда люди говорят «предпочтительность композиции по сравнению с наследством»?\n", "\n", - "* What is the Liskov substitution principle?\n", + "* Каков принцип замены Лискова?\n", "\n", - "* Is Python an object-oriented language?\n", + "* Является ли Python объектно-ори\n", + "578\n", + "ентированным языком?\n", "\n", - "* What are the requirements for a set to be totally ordered?\n", + "* Каковы требования к набору, который будет полностью заказан?\n", "\n", - "And as always, consider using a virtual assistant to help with the following exercises." + "И, как всегда, рассмотрите возможность использования виртуального помощника, чтобы помочь с следующими упражнениями." ] }, { @@ -1580,10 +1560,10 @@ "id": "1af81269", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "In contract bridge, a \"trick\" is a round of play in which each of four players plays one card.\n", - "To represent those cards, we'll define a class that inherits from `Deck`." + "В контрактном мосту «трюк» - это раунд игры, в котором каждый из четырех игроков играет одну карту.\n", + "Чтобы представить эти карты, мы определим класс, который наследует от «колоды»." ] }, { @@ -1602,10 +1582,10 @@ "id": "9916d562", "metadata": {}, "source": [ - "As an example, consider this trick, where the first player leads with the 3 of Diamonds, which means that Diamonds are the \"led suit\".\n", - "The second and third players \"follow suit\", which means they play a card with the led suit.\n", - "The fourth player plays a card of a different suit, which means they cannot win the trick.\n", - "So the winner of this trick is the third player, because they played the highest card in the led suit." + "В качестве примера рассмотрите этот трюк, когда первый игрок ведет с тремя бриллиантами, что означает, что бриллианты являются «светодиодным костюмом».\n", + "Второй и третий игроки «следуют за его примером», что означает, что они играют на карту с светодиодным костюмом.\n", + "Четвертый игрок играет карту другого костюма, что означает, что они не могут выиграть трюк.\n", + "Таким образом, победителем этого трюка является третий игрок, потому что они сыграли самую высокую карту в светодиодном костюме." ] }, { @@ -1628,8 +1608,8 @@ "id": "c94a1337", "metadata": {}, "source": [ - "Write a `Trick` method called `find_winner` that loops through the cards in the `Trick` and returns the index of the card that wins.\n", - "In the previous example, the index of the winning card is `2`." + "Напишите метод «трюка» под названием `find_winner`, который проходит через карты в` trick 'и возвращает индекс выигрышной карты.\n", + "В предыдущем примере индекс выигрышной карты составляет `2`." ] }, { @@ -1639,7 +1619,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Вы можете использовать следующий план, чтобы начать." ] }, { @@ -1676,7 +1656,7 @@ "tags": [] }, "source": [ - "If you test your method with the previous example, the index of the winning card should be `2`." + "Если вы проверяете свой метод с предыдущим примером, индекс выигрышной карты должен быть `2`." ] }, { @@ -1696,11 +1676,11 @@ "id": "b5b9fb4b", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "The next few exercises ask to you write functions that classify poker hands.\n", - "If you are not familiar with poker, I'll explain what you need to know.\n", - "We'll use the following class to represent poker hands." + "Следующие несколько упражнений просят вам написать функции, которые классифицируют покерные руки.\n", + "Если вы не знакомы с покером, я объясню, что вам нужно знать.\n", + "Мы будем использовать следующий класс, чтобы представлять покерные руки." ] }, { @@ -1733,18 +1713,18 @@ "id": "2daecced", "metadata": {}, "source": [ - "`PokerHand` provides two methods that will help with the exercises.\n", + "`PokerHand 'предоставляет два метода, которые помогут с упражнениями.\n", "\n", - "* `get_suit_counts` loops through the cards in the `PokerHand`, counts the number of cards in each suit, and returns a dictionary that maps from each suit code to the number of times it appears.\n", + "* `get_suit_counts` щедет через карты в` pokerhand ', подсчитывает количество карт в каждом костюме и возвращает словарь, который отображает из каждого кода иска в количество раз.\n", "\n", - "* `get_rank_counts` does the same thing with the ranks of the cards, returning a dictionary that maps from each rank code to the number of times it appears.\n", + "* `get_rank_counts` делает то же самое с рядами карт, возвращая словарь, который отображает из каждого кода ранга в количество раз.\n", "\n", - "All of the exercises that follow can be done using only the Python features we have learned so far, but some of them are more difficult than most of the previous exercises.\n", - "I encourage you to ask a virtual assistant for help.\n", + "Все последующие упражнения могут выполняться только с использованием только особенностей Python, которые мы узнали до сих пор, но некоторые из них сложнее, чем большинство предыдущих упражнений.\n", + "Я призываю вас попросить виртуального помощника за помощью.\n", "\n", - "For problems like this, it often works well to ask for general advice about strategies and algorithms.\n", - "Then you can either write the code yourself or ask for code.\n", - "If you ask for code, you might want to provide the relevant class definitions as part of the prompt." + "Для подобных проблем это часто хорошо справляется с общими советами о стратегиях и алгоритмах.\n", + "Затем вы можете либо написать код самостоятельно, либо попросить код.\n", + "Если вы попросите код, вы можете предоставить соответствующие определения класса как часть подсказки." ] }, { @@ -1752,10 +1732,10 @@ "id": "ccc2d8ca", "metadata": {}, "source": [ - "As a first exercise, we'll write a method called `has_flush` that checks whether a hand has a \"flush\" -- that is, whether it contains at least five cards of the same suit.\n", + "В качестве первого упражнения мы напишем метод под названием «has_flush», который проверяет, есть ли рука «промывка», то есть, содержит ли она как минимум пять карт одного и того же костюма.\n", "\n", - "In most varieties of poker, a hand contains either five or seven cards, but there are some exotic variations where a hand contains other numbers of cards.\n", - "But regardless of how many cards there are in a hand, the only ones that count are the five that make the best hand." + "В большинстве разновидностей покера рука содержит пять или семь карт, но есть некоторые экзотические вариации, где рука содержит другие числа карт.\n", + "Но независимо от того, сколько карт есть в руке, единственные, кто считается пятью, которые делают лучшую руку." ] }, { @@ -1765,7 +1745,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Вы можете использовать следующий план, чтобы начать." ] }, { @@ -1803,7 +1783,7 @@ "tags": [] }, "source": [ - "To test this method, we'll construct a hand with five cards that are all Clubs, so it contains a flush." + "Чтобы проверить этот метод, мы построим руку с пятью картами, которые являются всеми клубами, поэтому он содержит флеш." ] }, { @@ -1832,7 +1812,7 @@ "tags": [] }, "source": [ - "If we invoke `get_suit_counts`, we can confirm that the rank code `0` appears `5` times." + "Если мы вызовыте `get_suit_counts`, мы можем подтвердить, что код ранга` 0` появляется `5 'раз." ] }, { @@ -1854,7 +1834,7 @@ "tags": [] }, "source": [ - "So `has_flush` should return `True`." + "Так что `has_flush 'должен вернуть` true`." ] }, { @@ -1876,7 +1856,7 @@ "tags": [] }, "source": [ - "As a second test, we'll construct a hand with three Clubs and two other suits." + "В качестве второго теста мы построим руку с тремя клубами и двумя другими костюмами." ] }, { @@ -1909,7 +1889,7 @@ "tags": [] }, "source": [ - "So `has_flush` should return `False`." + "Так что `has_flush` должен вернуть` false`." ] }, { @@ -1929,13 +1909,13 @@ "id": "ad716880", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "Write a method called `has_straight` that checks whether a hand contains a straight, which is a set of five cards with consecutive ranks.\n", - "For example, if a hand contains ranks `5`, `6`, `7`, `8`, and `9`, it contains a straight.\n", + "Напишите метод под названием «has_straight», который проверяет, содержит ли рука прямая, которая представляет собой набор из пяти карт с последовательными рядами.\n", + "Например, если рука содержит ранги `5`,` 6`, `7`,` 8` и `9`, она содержит прямую.\n", "\n", - "An Ace can come before a two or after a King, so `Ace`, `2`, `3`, `4`, `5` is a straight and so is `10`, `Jack`, `Queen`, `King`, `Ace`.\n", - "But a straight cannot \"wrap around\", so `King`, `Ace`, `2`, `3`, `4` is not a straight." + "Эйс может прийти до двух или после короля, так что `ace`,` 2`, `3`,` 4`, `5` - прямой, а также` 10`, `jack`,` Queen ', `king',` ace '.\n", + "Но прямой не может «обернуть», так что «King», `ace`,` 2`, `3`,` 4` не является прямым." ] }, { @@ -1945,8 +1925,8 @@ "tags": [] }, "source": [ - "You can use the following outline to get started.\n", - "It includes a few lines of code that count the number of Aces -- represented with the code `1` or `14` -- and store the total in both locations of the counter." + "Вы можете использовать следующий план, чтобы начать.\n", + "Он включает в себя несколько строк кода, которые подсчитывают количество тузов, представленных с кодом `1` или` 14`, и хранят общее количество в обоих местах счетчика." ] }, { @@ -1989,8 +1969,8 @@ "tags": [] }, "source": [ - "`good_hand`, which we created for the previous exercise, contains a straight.\n", - "If we use `get_rank_counts`, we can confirm that it has at least one card with each of five consecutive ranks." + "`good_hand`, который мы создали для предыдущего упражнения, содержит прямую.\n", + "Если мы используем `get_rank_counts`, мы можем подтвердить, что у нее есть хотя бы одна карта с каждым из пяти последовательных рангов." ] }, { @@ -2012,7 +1992,7 @@ "tags": [] }, "source": [ - "So `has_straight` should return `True`." + "Так что `has_straight 'должен вернуть` true`." ] }, { @@ -2034,7 +2014,7 @@ "tags": [] }, "source": [ - "`bad_hand` does not contain a straight, so `has_straight` should return `False`." + "`bad_hand` не содержит прямой, поэтому` has_straight 'должен вернуть `false`." ] }, { @@ -2054,10 +2034,10 @@ "id": "c1ecebd3", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "A hand has a straight flush if it contains a set of five cards that are both a straight and a flush -- that is, five cards of the same suit with consecutive ranks.\n", - "Write a `PokerHand` method that checks whether a hand has a straight flush." + "Рука имеет прямой флеш, если она содержит набор из пяти карт, которые являются прямыми и промывками, то есть пять карт одного и того же костюма с последовательными рядами.\n", + "Напишите метод «PokerHand», который проверяет, имеет ли рука прямой промывку." ] }, { @@ -2067,7 +2047,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Вы можете использовать следующий план, чтобы начать." ] }, { @@ -2117,7 +2097,7 @@ "tags": [] }, "source": [ - "Use the following examples to test your method." + "Используйте следующие примеры, чтобы проверить ваш метод." ] }, { @@ -2151,8 +2131,8 @@ "tags": [] }, "source": [ - "Note that it is not enough to check whether a hand has a straight and a flush.\n", - "To see why, consider the following hand." + "Обратите внимание, что недостаточно, чтобы проверить, имеет ли рука прямая и промывка.\n", + "Чтобы понять почему, рассмотрим следующую руку." ] }, { @@ -2179,7 +2159,7 @@ "tags": [] }, "source": [ - "This hand contains a straight and a flush, but they are not the same five cards." + "Эта рука содержит прямую и флеш, но они не те же пять карт." ] }, { @@ -2201,7 +2181,7 @@ "tags": [] }, "source": [ - "So it does not contain a straight flush." + "Таким образом, он не содержит прямой промывки." ] }, { @@ -2221,10 +2201,10 @@ "id": "dd742401", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "A poker hand has a pair if it contains two or more cards with the same rank.\n", - "Write a `PokerHand` method that checks whether a hand contains a pair." + "Покерная рука имеет пару, если она содержит две или более карт с одним и тем же рангом.\n", + "Напишите метод «PokerHand», который проверяет, содержит ли рука пара." ] }, { @@ -2234,7 +2214,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Вы можете использовать следующий план, чтобы начать." ] }, { @@ -2281,7 +2261,7 @@ "id": "9f001207", "metadata": {}, "source": [ - "To test your method, here's a hand that has a pair." + "Чтобы проверить ваш метод, вот рука, у которой есть пара." ] }, { @@ -2331,10 +2311,10 @@ "id": "c4180a64", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "A hand has a full house if it contains three cards of one rank and two cards of another rank.\n", - "Write a `PokerHand` method that checks whether a hand has a full house." + "У руки есть полный дом, если он содержит три карты одного ранга и две карты другого ранга.\n", + "Напишите метод «PokerHand», который проверяет, имеет ли рука полный дом." ] }, { @@ -2344,7 +2324,7 @@ "tags": [] }, "source": [ - "You can use the following outline to get started." + "Вы можете использовать следующий план, чтобы начать." ] }, { @@ -2381,7 +2361,7 @@ "tags": [] }, "source": [ - "You can use this hand to test your method." + "Вы можете использовать эту руку, чтобы проверить свой метод." ] }, { @@ -2440,10 +2420,10 @@ "id": "666340c1", "metadata": {}, "source": [ - "### Exercise\n", + "### Упражнение\n", "\n", - "This exercise is a cautionary tale about a common error that can be difficult to debug.\n", - "Consider the following class definition." + "Это упражнение является предостерегающей историей об общей ошибке, которая может быть трудно отлаживать.\n", + "Рассмотрим следующее определение класса." ] }, { @@ -2487,14 +2467,14 @@ "id": "1e349832", "metadata": {}, "source": [ - "`__init__` takes two parameters: `name` is required, but `contents` is optional -- if it's not provided, the default value is an empty list.\n", + "`__init__` принимает два параметра:« Имя\n", "\n", - "`__str__` returns a string representation of the object that includes the name and the contents of the pouch.\n", + "`__str__` возвращает строковое представление объекта, который включает имя и содержимое мешочка.\n", "\n", - "`put_in_pouch` takes any object and appends it to `contents`.\n", + "`put_in_pouch` принимает любой объект и добавляет его на` contents`.\n", "\n", - "Now let's see how this class works.\n", - "We'll create two `Kangaroo` objects with the names `'Kanga'` and `'Roo'`." + "Теперь посмотрим, как работает этот класс.\n", + "Мы создадим два объекта `kangaroo 'с именами`' kanga' 'и `' roo '." ] }, { @@ -2513,7 +2493,7 @@ "id": "533982d1", "metadata": {}, "source": [ - "To Kanga's pouch we'll add two strings and Roo." + "К мешочке Канги мы добавим две струны и Roo." ] }, { @@ -2533,7 +2513,7 @@ "id": "41cd6d6e", "metadata": {}, "source": [ - "If we print `kanga`, it seems like everything worked." + "Если мы напечатаем `kanga`, кажется, что все сработало." ] }, { @@ -2551,7 +2531,7 @@ "id": "0ba26163", "metadata": {}, "source": [ - "But what happens if we print `roo`?" + "Но что произойдет, если мы напечатаем `roo`?" ] }, { @@ -2569,10 +2549,10 @@ "id": "a2aef813", "metadata": {}, "source": [ - "Roo's pouch contains the same contents as Kanga's, including a reference to `roo`!\n", + "Мешочка Ру содержит то же содержимое, что и Канга, в том числе ссылка на «Ру»!\n", "\n", - "See if you can figure out what went wrong.\n", - "Then ask a virtual assistant, \"What's wrong with the following program?\" and paste in the definition of `Kangaroo`." + "Посмотрите, сможете ли вы выяснить, что пошло не так.\n", + "Затем спросите виртуального помощника: «Что не так со следующей программой?» и вставьте в определение `kangaroo." ] }, { @@ -2590,13 +2570,13 @@ "tags": [] }, "source": [ - "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "[Think Python: 3 -е издание] (https://allendowney.github.io/thinkpython/index.html)\n", "\n", - "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "Copyright 2024 [Аллен Б. Дауни] (https://allendowney.com)\n", "\n", - "Code license: [MIT License](https://mit-license.org/)\n", + "Лицензия кода: [Лицензия MIT] (https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Текстовая лицензия: [Creative Commons attribution-noncommercial-sharealik" ] } ], @@ -2622,4 +2602,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From e3906dc5221de57d0c4257fa1f713ca0fe7869ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 17:00:25 +0300 Subject: [PATCH 43/44] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20Markdown=20=D0=B2=20chap18?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- chapters/chap18.ipynb | 435 +++++++++++++++++++++++++----------------- 1 file changed, 259 insertions(+), 176 deletions(-) diff --git a/chapters/chap18.ipynb b/chapters/chap18.ipynb index 030202a..e35260a 100644 --- a/chapters/chap18.ipynb +++ b/chapters/chap18.ipynb @@ -5,9 +5,9 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать версии печати и электронных книг * Think Python 3e * из\n", + "[Bookshop.org] (https://bookshop.org/a/98697/9781098155438) и\n", + "[Amazon] (https://www.amazon.com/_/dp/1098155432?ng = utf8 & Tag = greenteApre01-20 & linkcode = ur2 & linkid = e2a529f94920295d27ec8a06e757dc7c & camp = 1789 & creative = 9325)." ] }, { @@ -43,7 +43,7 @@ "tags": [] }, "source": [ - "Here are versions of the `Card`, `Deck`, and `Hand` classes from Chapter 17, which we will use in some examples in this chapter." + "Вот версии классов `card`,` deck 'и `’ Hand' из главы 17, которые мы будем использовать в некоторых примерах в этой главе." ] }, { @@ -129,14 +129,14 @@ "id": "27e8d827", "metadata": {}, "source": [ - "# Python Extras\n", + "# Python дополнения\n", "\n", - "One of my goals for this book has been to teach you as little Python as possible. \n", - "When there were two ways to do something, I picked one and avoided mentioning the other.\n", - "Or sometimes I put the second one into an exercise.\n", + "Одна из моих целей для этой книги состояла в том, чтобы научить вас максимально малому питону.\n", + "Когда было два способа что -то сделать, я выбрал один и избегал упоминания другого.\n", + "Или иногда я помещаю второе в упражнение.\n", "\n", - "Now I want to go back for some of the good bits that got left behind.\n", - "Python provides a number of features that are not really necessary -- you can write good code without them -- but with them you can write code that's more concise, readable, or efficient, and sometimes all three." + "Теперь я хочу вернуться к некоторым из хороших кусочков, которые остались позади.\n", + "Python предоставляет ряд функций, которые не являются действительно необходимыми - вы можете написать хороший код без них - но с ними вы можете написать код, который более краткий, читаемый или эффективный, а иногда и все три." ] }, { @@ -144,10 +144,10 @@ "id": "7ddcece8", "metadata": {}, "source": [ - "## Sets\n", + "## set\n", "\n", - "Python provides a class called `set` that represents a collection of unique elements.\n", - "To create an empty set, we can use the class object like a function." + "Python предоставляет класс под названием «Set», который представляет собой коллекцию уникальных элементов.\n", + "Чтобы создать пустой набор, мы можем использовать объект класса как функция." ] }, { @@ -166,7 +166,7 @@ "id": "904e2071", "metadata": {}, "source": [ - "We can use the `add` method to add elements." + "Мы можем использовать метод «Добавить» для добавления элементов." ] }, { @@ -186,7 +186,7 @@ "id": "beee02fc", "metadata": {}, "source": [ - "Or we can pass any kind of sequence to `set`." + "Или мы можем передать любую последовательность в `set`." ] }, { @@ -205,8 +205,8 @@ "id": "42f99153", "metadata": {}, "source": [ - "An element can only appear once in a `set`.\n", - "If you add an element that's already there, it has no effect." + "Элемент может появиться только один раз в `set`.\n", + "Если вы добавите элемент, который уже есть, он не имеет никакого эффекта." ] }, { @@ -225,7 +225,7 @@ "id": "9b0a82ee", "metadata": {}, "source": [ - "Or if you create a set with a sequence that contains duplicates, the result contains only unique elements." + "Или, если вы создаете набор с последовательности, которая содержит дубликаты, результат содержит только уникальные элементы." ] }, { @@ -243,8 +243,8 @@ "id": "328e2009", "metadata": {}, "source": [ - "Some of the exercises in this book can be done concisely and efficiently with sets. \n", - "For example, here is a solution to an exercise in Chapter 11 that uses a dictionary to check whether there are any duplicate elements in a sequence." + "Некоторые из упражнений в этой книге могут быть выполнены кратко и эффективно с наборами.\n", + "Например, вот решение в упражнении в главе 11, в котором используется словарь, чтобы проверить, есть ли какие -либо дублирующие элементы в последовательности." ] }, { @@ -266,8 +266,8 @@ "id": "0b250e58", "metadata": {}, "source": [ - "This version adds the element of `t` as keys in a dictionary, and then checks whether there are fewer keys than elements.\n", - "Using sets, we can write the same function like this." + "Эта версия добавляет элемент `t` как ключи в словаре, а затем проверяет, меньше ключей, чем элементы.\n", + "Используя наборы, мы можем написать ту же функцию, как эта." ] }, { @@ -303,7 +303,7 @@ "Если дубликатов нет, множество будет того же размера, что и `t`.\n", "\n", "Объекты `set` предоставляют методы для выполнения операций над множествами.\n", - "Например, метод `union` вычисляет объединение двух множеств, создавая новое множество, содержащее все элементы, присутствующие хотя бы в одном из них.\n" + "Например, метод `union` вычисляет объединение двух множеств, создавая новое множество, содержащее все элементы, присутствующие хотя бы в одном из них." ] }, { @@ -322,7 +322,7 @@ "metadata": {}, "source": [ "Некоторые арифметические операторы работают с множествами.\n", - "Например, оператор `-` выполняет вычитание множеств — результатом будет новое множество, содержащее все элементы из первого множества, которые *не* входят во второе.\n" + "Например, оператор `-` выполняет вычитание множеств — результатом будет новое множество, содержащее все элементы из первого множества, которые *не* входят во второе." ] }, { @@ -341,7 +341,7 @@ "metadata": {}, "source": [ "В [главе 12](section_dictionary_subtraction) мы использовали словари, чтобы найти слова, которые встречаются в документе, но отсутствуют в словаре слов.\n", - "Мы написали следующую функцию, которая принимает два словаря и возвращает новый словарь, содержащий только те ключи из первого, которые не встречаются во втором.\n" + "Мы написали следующую функцию, которая принимает два словаря и возвращает новый словарь, содержащий только те ключи из первого, которые не встречаются во втором." ] }, { @@ -365,7 +365,7 @@ "metadata": {}, "source": [ "Используя множества, нам не нужно писать эту функцию самостоятельно.\n", - "Если `word_counter` — словарь с уникальными словами из документа, а `word_list` — список допустимых слов, то разность множеств можно вычислить так.\n" + "Если `word_counter` — словарь с уникальными словами из документа, а `word_list` — список допустимых слов, то разность множеств можно вычислить так." ] }, { @@ -404,7 +404,7 @@ "Результатом будет множество слов, встречающихся в документе, но отсутствующих в словаре слов.\n", "\n", "Отношения между множествами проверяются при помощи операторов сравнения.\n", - "Например, оператор `<=` проверяет, является ли одно множество подмножеством другого, включая случай равенства.\n" + "Например, оператор `<=` проверяет, является ли одно множество подмножеством другого, включая случай равенства." ] }, { @@ -422,7 +422,7 @@ "id": "74d4d824", "metadata": {}, "source": [ - "С помощью этих операторов можно решить некоторые упражнения из главы 7. Например, ниже показана версия функции `uses_only`, использующая цикл.\n" + "С помощью этих операторов можно решить некоторые упражнения из главы 7. Например, ниже показана версия функции `uses_only`, использующая цикл." ] }, { @@ -445,7 +445,7 @@ "metadata": {}, "source": [ "Функция `uses_only` проверяет, входят ли все буквы из `word` в `available`.\n", - "С использованием множеств её можно переписать так.\n" + "С использованием множеств её можно переписать так." ] }, { @@ -464,7 +464,7 @@ "id": "01ce8cff", "metadata": {}, "source": [ - "Если буквы из `word` образуют подмножество букв в `available`, это означает, что `word` использует только буквы из `available`.\n" + "Если буквы из `word` образуют подмножество букв в `available`, это означает, что `word` использует только буквы из `available`." ] }, { @@ -477,7 +477,7 @@ "`Counter` похож на множество, за исключением того, что если элемент встречается более одного раза, `Counter` хранит, сколько раз он появился.\n", "Если вам знакома математическая идея «мультимножества», то `Counter` — естественное его представление.\n", "\n", - "Класс `Counter` определён в модуле `collections`, поэтому его нужно импортировать. Затем можно использовать этот класс как функцию, передавая строку, список или любую другую последовательность.\n" + "Класс `Counter` определён в модуле `collections`, поэтому его нужно импортировать. Затем можно использовать этот класс как функцию, передавая строку, список или любую другую последовательность." ] }, { @@ -514,7 +514,7 @@ "source": [ "Объект `Counter` похож на словарь, сопоставляющий каждому ключу количество его появлений. Как и в словарях, ключи должны быть хешируемыми.\n", "\n", - "В отличие от словарей, объекты `Counter` не вызывают исключение при обращении к отсутствующему элементу. Вместо этого возвращается `0`.\n" + "В отличие от словарей, объекты `Counter` не вызывают исключение при обращении к отсутствующему элементу. Вместо этого возвращается `0`." ] }, { @@ -534,7 +534,7 @@ "source": [ "Мы можем использовать объекты `Counter` для решения одного из упражнений из главы 10, в котором требуется функция, проверяющая, являются ли два слова анаграммами — то есть можно ли переставить буквы одного слова, чтобы получилось другое.\n", "\n", - "Ниже приведено решение с использованием `Counter`.\n" + "Ниже приведено решение с использованием `Counter`." ] }, { @@ -553,9 +553,9 @@ "id": "6907f368", "metadata": {}, "source": [ - "If two words are anagrams, they contain the same letters with the same counts, so their `Counter` objects are equivalent.\n", + "Если два слова являются анаграммами, они содержат одинаковые буквы с одинаковыми количествами, поэтому их объекты «счетчика» эквивалентны.\n", "\n", - "`Counter` provides a method called `most_common` that returns a list of value-frequency pairs, sorted from most common to least." + "`Counter 'предоставляет метод под названием` mest_common`, который возвращает список паров частоты стоимости, отсортированный от наиболее распространенного до наименьшего." ] }, { @@ -573,10 +573,10 @@ "id": "b02b7dff", "metadata": {}, "source": [ - "They also provide methods and operators to perform set-like operations, including addition, subtraction, union and intersection.\n", - "For example, the `+` operator combines two `Counter` objects and creates a new `Counter` that contains the keys from both and the sums of the counts.\n", + "Они также предоставляют методы и операторы для выполнения установленных операций, включая сложение, вычитание, объединение и пересечение.\n", + "Например, оператор `+` объединяет два объекта «счетчика» и создает новый «счетчик», который содержит ключи от обоих и суммы количества.\n", "\n", - "We can test it by making a `Counter` with the letters from `'bans'` and adding it to the letters from `'banana'`." + "Мы можем проверить его, сделав «счетчик» с буквами из «запретов» и добавив его в буквы из «банана»." ] }, { @@ -595,7 +595,7 @@ "id": "5461328e", "metadata": {}, "source": [ - "You'll have a chance to explore other `Counter` operations in the exercises at the end of this chapter." + "У вас будет возможность изучить другие операции «встречные» в упражнениях в конце этой главы." ] }, { @@ -605,13 +605,13 @@ "source": [ "## defaultdict\n", "\n", - "The `collections` module also provides `defaultdict`, which is like a dictionary except that if you access a key that doesn't exist, it generates a new value automatically.\n", + "Модуль «Collection» также предоставляет `defaultDict`, который похож на словарь, за исключением того, что, если вы получаете доступ к ключу, который не существует, он автоматически генерирует новое значение.\n", "\n", - "When you create a `defaultdict`, you provide a function that's used to create new values.\n", - "A function that create objects is sometimes called a **factory**.\n", - "The built-in functions that create lists, sets, and other types can be used as factories.\n", + "Когда вы создаете `defaultDict ', вы предоставляете функцию, которая используется для создания новых значений.\n", + "Функция, которая создает объекты, иногда называют ** фабрикой **.\n", + "Встроенные функции, которые создают списки, наборы и другие типы, могут использоваться в качестве заводов.\n", "\n", - "For example, here's a `defaultdict` that creates a new `list` when needed. " + "Например, вот «defaultDict», который при необходимости создает новый список." ] }, { @@ -632,8 +632,8 @@ "id": "9f43d537", "metadata": {}, "source": [ - "Notice that the argument is `list`, which is a class object, not `list()`, which is a function call that creates a new list.\n", - "The factory function doesn't get called unless we access a key that doesn't exist." + "Обратите внимание, что аргумент - «List», который является объектом класса, а не `list ()`, который является функцией вызова, который создает новый список.\n", + "Функция завода не вызывается, если мы не получаем доступ к ключу, которая не существует." ] }, { @@ -652,8 +652,8 @@ "id": "01f87415", "metadata": {}, "source": [ - "The new list, which we're calling `t`, is also added to the dictionary.\n", - "So if we modify `t`, the change appears in `d`:" + "Новый список, который мы называем `t`, также добавляется в словарь.\n", + "Так что, если мы изменим `t`, изменение появляется в` d`:" ] }, { @@ -672,12 +672,12 @@ "id": "3e5d0151", "metadata": {}, "source": [ - "If you are making a dictionary of lists, you can often write simpler\n", - "code using `defaultdict`. \n", + "Если вы делаете словарь списков, вы часто можете писать проще\n", + "Код с помощью `defaultDict`.\n", "\n", - "In one of the exercises in [Chapter 11](chapter_tuples), I made a dictionary that maps from a sorted string of letters to the list of words that can be spelled with those letters.\n", - "For example, the string `'opst'` maps to the list `['opts', 'post', 'pots', 'spot', 'stop', 'tops']`.\n", - "Here's the original code." + "В одном из упражнений в [Глава 11] (Глава_TUPLES) я сделал словарь, который отображает из сортированной строки букв в список слов, которые можно писать этими буквами.\n", + "Например, строка «opst» карты в список `['opts', 'post', 'pots', 'spot', 'stop', 'tops']`.\n", + "Вот оригинальный код." ] }, { @@ -704,7 +704,7 @@ "id": "8e9a0a2b", "metadata": {}, "source": [ - "And here's a simpler version using a `defaultdict`." + "А вот более простая версия с использованием `defaultDict '." ] }, { @@ -728,7 +728,7 @@ "id": "cccdd46c", "metadata": {}, "source": [ - "In the exercises at the end of the chapter, you'll have a chance to practice using `defaultdict` objects." + "В упражнениях в конце главы у вас будет возможность практиковать использование объектов DefaultDict." ] }, { @@ -751,9 +751,9 @@ "id": "610359c1", "metadata": {}, "source": [ - "## Conditional expressions\n", + "## условные выражения\n", "\n", - "Conditional statements are often used to choose one of two values, like this:" + "Условные утверждения часто используются для выбора одного из двух значений, например, это:" ] }, { @@ -799,11 +799,11 @@ "id": "2c5fc3dd", "metadata": {}, "source": [ - "This statement checks whether `x` is positive. If so, it computes its logarithm. \n", - "If not, `math.log` would raise a ValueError.\n", - "To avoid stopping the program, we generate a `NaN`, which is a special floating-point value that represents \"Not a Number\".\n", + "Это утверждение проверяет, является ли `x` положительным.Если так, то он вычисляет его логарифм.\n", + "Если нет, то `math.log` поднимет стоимость.\n", + "Чтобы избежать остановки программы, мы генерируем «NAN», который является специальным значением с плавающей запятой, которая представляет «не число».\n", "\n", - "We can write this statement more concisely using a **conditional expression**." + "Мы можем написать это утверждение более кратко, используя ** условное выражение **." ] }, { @@ -833,10 +833,10 @@ "id": "6a7cf27b", "metadata": {}, "source": [ - "You can almost read this line like English: \"`y` gets log-`x` if `x` is greater than 0; otherwise it gets `NaN`\".\n", + "Вы можете почти прочитать эту строку, как английский: «y` получает log- `x`, если` x` больше 0; в противном случае он получает `nan`».\n", "\n", - "Recursive functions can sometimes be written concisely using conditional expressions. \n", - "For example, here is a version of `factorial` with a conditional _statement_." + "Рекурсивные функции иногда можно писать кратко с использованием условных выражений.\n", + "Например, вот версия `factorial` с условным _statement_." ] }, { @@ -858,7 +858,7 @@ "id": "56052b5c", "metadata": {}, "source": [ - "And here's a version with a conditional _expression_." + "А вот версия с условной _expression_." ] }, { @@ -877,8 +877,8 @@ "id": "d53fbc15", "metadata": {}, "source": [ - "Another use of conditional expressions is handling optional arguments.\n", - "For example, here is class definition with an `__init__` method that uses a conditional statement to check a parameter with a default value." + "Другим использованием условных выражений является обработка дополнительных аргументов.\n", + "Например, вот определение класса с методом `__init__`, который использует условное операцию для проверки параметра со значением по умолчанию." ] }, { @@ -901,7 +901,7 @@ "id": "655bfc46", "metadata": {}, "source": [ - "Here's a version that uses a conditional expression." + "Вот версия, которая использует условное выражение." ] }, { @@ -921,7 +921,7 @@ "id": "fef85229", "metadata": {}, "source": [ - "In general, you can replace a conditional statement with a conditional expression if both branches contain a single expression and no statements." + "В целом, вы можете заменить условное утверждение на условное выражение, если обе ветви содержат одно выражение и отсутствие операторов." ] }, { @@ -929,10 +929,10 @@ "id": "45d3b306", "metadata": {}, "source": [ - "## List comprehensions\n", + "## Список понимания\n", "\n", - "In previous chapters, we've seen a few examples where we start with an empty list and add elements, one at a time, using the `append` method.\n", - "For example, suppose we have a string that contains the title of a movie, and we want to capitalize all of the words." + "В предыдущих главах мы видели несколько примеров, когда мы начинаем с пустого списка и добавляем элементы по одному, используя метод «Приложение».\n", + "Например, предположим, что у нас есть строка, которая содержит название фильма, и мы хотим извлечь выгоду из всех слов." ] }, { @@ -950,7 +950,7 @@ "id": "9eeb45a6", "metadata": {}, "source": [ - "We can split it into a list of strings, loop through the strings, capitalize them, and append them to a list." + "Мы можем разделить его на список строк, проходить через строки, использовать их и добавить их в список." ] }, { @@ -972,7 +972,7 @@ "id": "b96197c2", "metadata": {}, "source": [ - "We can do the same thing more concisely using a **list comprehension**:" + "Мы можем сделать то же самое более кратко, используя ** Понимание списка **:" ] }, { @@ -992,13 +992,13 @@ "id": "e5b565ad", "metadata": {}, "source": [ - "The bracket operators indicate that we are constructing a new list.\n", - "The expression inside the brackets specifies the elements of the list, and the `for` clause indicates what sequence we are looping through.\n", + "Операторы кронштейнов указывают, что мы строим новый список.\n", + "Выражение внутри кронштейнов определяет элементы списка, а пункт «for» указывает на то, через какую последовательность мы проводим.\n", "\n", - "The syntax of a list comprehension might seem strange, because the loop variable -- `word` in this example -- appears in the expression before we get to its definition.\n", - "But you get used to it.\n", + "Синтаксис понимания списка может показаться странным, потому что переменная цикла - `word` в этом примере - появляется в выражении, прежде чем мы достигнем его определения.\n", + "Но вы привыкаете к этому.\n", "\n", - "As another example, in [Chapter 9](section_word_list) we used this loop to read words from a file and append them to a list." + "В качестве другого примера, в [Глава 9] (section_word_list) мы использовали этот цикл для чтения слов из файла и добавления их в список." ] }, { @@ -1044,7 +1044,7 @@ "id": "2d1df49b", "metadata": {}, "source": [ - "Here's how we can write that as a list comprehension." + "Вот как мы можем написать это как понимание списка." ] }, { @@ -1074,8 +1074,8 @@ "id": "92d856ba", "metadata": {}, "source": [ - "A list comprehension can also have an `if` clause that determines which elements are included in the list.\n", - "For example, here's a `for` loop we used in [Chapter 10](section_palindrome_list) to make a list of only the words in `word_list` that are palindromes." + "Понимание списка также может иметь пункт «если», который определяет, какие элементы включены в список.\n", + "Например, вот `for` -цикл, который мы использовали в [главе 10] (section_palindrome_list), чтобы составить список только слов в` word_list`, которые являются палиндромами." ] }, { @@ -1122,7 +1122,7 @@ "id": "151621d8", "metadata": {}, "source": [ - "Here's how we can do the same thing with an list comprehension." + "Вот как мы можем сделать то же самое с пониманием списка." ] }, { @@ -1152,9 +1152,9 @@ "id": "5fc4eab1", "metadata": {}, "source": [ - "When a list comprehension is used as an argument to a function, we can often omit the brackets.\n", - "For example, suppose we want to add up $1 / 2^n$ for values of $n$ from 0 to 9.\n", - "We can use a list comprehension like this." + "Когда понимание списка используется в качестве аргумента для функции, мы часто можем опустить кронштейны.\n", + "Например, предположим, что мы хотим сложить $ 1/2^n $ для значений $ n $ от 0 до 9.\n", + "Мы можем использовать подобное понимание списка." ] }, { @@ -1172,7 +1172,7 @@ "id": "2ee312e0", "metadata": {}, "source": [ - "Or we can leave out the brackets like this." + "Или мы можем оставить такие кронштейны." ] }, { @@ -1190,17 +1190,17 @@ "id": "3d56d584", "metadata": {}, "source": [ - "In this example, the argument is technically a **generator expression**, not a list comprehension, and it never actually makes a list.\n", - "But other than that, the behavior is the same.\n", + "В этом примере аргумент технически является ** генераторным выражением **, а не пониманием списка, и он никогда не составляет список.\n", + "Но кроме этого поведение одинаково.\n", "\n", - "List comprehensions and generator expressions are concise and easy to read, at least for simple expressions.\n", - "And they are usually faster than the equivalent for loops, sometimes much faster.\n", - "So if you are mad at me for not mentioning them earlier, I understand.\n", + "Список понимания и выражения генератора кратко и легко читают, по крайней мере, для простых выражений.\n", + "И они обычно быстрее, чем эквивалент для петель, иногда намного быстрее.\n", + "Так что, если вы злитесь на меня за то, что я не упоминал их раньше, я понимаю.\n", "\n", - "But, in my defense, list comprehensions are harder to debug because you can't put a print statement inside the loop.\n", - "I suggest you use them only if the computation is simple enough that you are likely to get it\n", - "right the first time.\n", - "Or consider writing and debugging a `for` loop and then converting it to a list comprehension." + "Но в моей защите, понимание списка труднее отладить, потому что вы не можете поместить печатное заявление в цикл.\n", + "Я предлагаю вам использовать их, только если вычисление достаточно просты, чтобы вы его получили\n", + "Правильно в первый раз.\n", + "Или рассмотрите возможность написания и отладки цикла «для», а затем преобразовать его в понимание списка." ] }, { @@ -1208,9 +1208,9 @@ "id": "f9fac860", "metadata": {}, "source": [ - "## `any` and `all`\n", + "## `any 'и` all\n", "\n", - "Python provides a built-in function, `any`, that takes a sequence of boolean values and returns `True` if any of the values are `True`." + "Python обеспечивает встроенную функцию, «любой», которая принимает последовательность логических значений и возвращает `true`, если какое-либо из значений является« true »." ] }, { @@ -1228,7 +1228,7 @@ "id": "43217186", "metadata": {}, "source": [ - "`any` is often used with generator expressions." + "«Любой» часто используется с выражениями генератора." ] }, { @@ -1246,8 +1246,8 @@ "id": "22395487", "metadata": {}, "source": [ - "That example isn't very useful because it does the same thing as the `in` operator. \n", - "But we could use `any` to write concise solutions to some of the exercises in [Chapter 7](chapter_search). For example, we can write `uses_none` like this." + "Этот пример не очень полезен, потому что он делает то же самое, что и оператор «в».\n", + "Но мы могли бы использовать «любое», чтобы написать краткие решения для некоторых упражнений в [Глава 7] (глава_SEARCH).Например, мы можем написать `change_none` как это." ] }, { @@ -1291,11 +1291,11 @@ "id": "fbefe3c1", "metadata": {}, "source": [ - "This function loops through the letters in `word` and checks whether any of them are in `forbidden`.\n", - "Using `any` with a generator expression is efficient because it stops immediately if it finds a `True` value, so it doesn't have to loop through the whole sequence.\n", + "Эта функция проходит через буквы в «Word» и проверяет, находятся ли какие -либо из них в «запрещенном».\n", + "Использование «любого» с выражением генератора является эффективным, потому что оно немедленно останавливается, если оно находит значение «истинного», поэтому он не должен проходить через всю последовательность.\n", "\n", - "Python provides another built-in function, `all`, that returns `True` if every element of the sequence is `True`.\n", - "We can use it to write a concise version of `uses_all`." + "Python предоставляет еще одну встроенную функцию, «All», которая возвращает `true`, если каждый элемент последовательности` true '.\n", + "Мы можем использовать его, чтобы написать краткую версию `using_all`." ] }, { @@ -1339,7 +1339,7 @@ "id": "8d9f7364", "metadata": {}, "source": [ - "Expressions using `any` and `all` can be concise, efficient, and easy to read." + "Выражения с использованием «any» и «all» могут быть кратким, эффективным и простым в чтении." ] }, { @@ -1347,11 +1347,11 @@ "id": "911857a3", "metadata": {}, "source": [ - "## Named tuples\n", + "## назван кулак\n", "\n", - "The `collections` module provides a function called `namedtuple` that can be used to create simple classes.\n", - "For example, the `Point` object in [Chapter 16](section_create_point) has only two attributes, `x` and `y`.\n", - "Here's how we defined it." + "Модуль «Коллекции» предоставляет функцию, называемую `nameTuple`, которую можно использовать для создания простых классов.\n", + "Например, объект `point` в [Глава 16] (section_create_point) имеет только два атрибута:` x` и `y`.\n", + "Вот как мы это определили." ] }, { @@ -1377,8 +1377,8 @@ "id": "36f08927", "metadata": {}, "source": [ - "That's a lot of code to convey a small amount of information.\n", - "`namedtuple` provides a more concise way to define classes like this." + "Это много кода, чтобы передать небольшое количество информации.\n", + "`nameTuple` обеспечивает более краткий способ определить такие занятия." ] }, { @@ -1398,12 +1398,12 @@ "id": "942a0877", "metadata": {}, "source": [ - "The first argument is the name of the class you want to create. The\n", - "second is a list of the attributes `Point` objects should have.\n", - "The result is a class object, which is why it is assigned to a capitalized variable name.\n", + "Первый аргумент - это имя класса, который вы хотите создать.А\n", + "Во -вторых, это список объектов атрибутов `point`, которые должны иметь.\n", + "Результатом является объект класса, поэтому он назначен капитализированным именем переменной.\n", "\n", - "A class created with `namedtuple` provides an `__init__` method that assigns values to the attributes and a `__str__` that displays the object in a readable form.\n", - "So we can create and display a `Point` object like this." + "Класс, созданный с помощью `nameTuple`, предоставляет метод` __init__`, который присваивает значения атрибутам и «__str__`, который отображает объект в читаемой форме.\n", + "Таким образом, мы можем создавать и отобразить такой объект «точка»." ] }, { @@ -1422,7 +1422,7 @@ "id": "b42ee9a2", "metadata": {}, "source": [ - "`Point` also provides an `__eq__` method that checks whether two `Point` objects are equivalent -- that is, whether their attributes are the same." + "`Point` также предоставляет метод` __eq__`, который проверяет, эквивалентны ли два объекта «точка», то есть, являются ли их атрибуты одинаковыми." ] }, { @@ -1440,7 +1440,7 @@ "id": "9bcf275a", "metadata": {}, "source": [ - "You can access the elements of a named tuple by name or by index." + "Вы можете получить доступ к элементам названного кортежа по имени или по индексу." ] }, { @@ -1468,7 +1468,7 @@ "id": "0768ff41", "metadata": {}, "source": [ - "You can also treat a named tuple as a tuple, as in this assignment." + "Вы также можете рассматривать названный кортеж как кортеж, как в этом задании." ] }, { @@ -1487,8 +1487,8 @@ "id": "964aa3bd", "metadata": {}, "source": [ - "But `namedtuple` objects are immutable.\n", - "After the attributes are initialized, they can't be changed." + "Но объекты `nameTuple 'неизменны.\n", + "После того, как атрибуты инициализированы, их нельзя изменить." ] }, { @@ -1524,10 +1524,10 @@ "id": "f2db7783", "metadata": {}, "source": [ - "`namedtuple` provides a quick way to define simple classes.\n", - "The drawback is that simple classes don't always stay simple.\n", - "You might decide later that you want to add methods to a named tuple.\n", - "In that case, you can define a new class that inherits from the named tuple." + "`nameTuple` обеспечивает быстрый способ определения простых классов.\n", + "Недостаток в том, что простые занятия не всегда остаются простыми.\n", + "Позже вы можете решить, что хотите добавить методы в названный кортеж.\n", + "В этом случае вы можете определить новый класс, который наследует от названного корпуса." ] }, { @@ -1546,7 +1546,7 @@ "id": "805475ce", "metadata": {}, "source": [ - "Or at that point you could switch to a conventional class definition." + "Или в этот момент вы можете перейти на обычное определение класса." ] }, { @@ -1554,9 +1554,8 @@ "id": "4f3713a0", "metadata": {}, "source": [ - "## Packing keyword arguments\n", - "\n", - "In [Chapter 11](section_argument_pack), we wrote a function that packs its arguments into a tuple." + "## Упаковывать аргументы ключевого слова\n", + "В [Глава 11] (пакет аргументов в разделе) мы пишем функцию, которая упаковывает ее аргументы в кортеж." ] }, { @@ -1575,7 +1574,7 @@ "id": "71e3b049", "metadata": {}, "source": [ - "You can call this function with any number of arguments." + "Вы можете вызвать эту функцию с любым количеством аргументов." ] }, { @@ -1593,8 +1592,8 @@ "id": "486a690f", "metadata": {}, "source": [ - "But the `*` operator doesn't pack keyword arguments.\n", - "So calling this function with a keyword argument causes an error." + "Но оператор `*` не упаковывает аргументы ключевых слов.\n", + "Таким образом, вызов этой функции с помощью аргумента ключевого слова вызывает ошибку." ] }, { @@ -1616,7 +1615,7 @@ "id": "eb7f9281", "metadata": {}, "source": [ - "To pack keyword arguments, we can use the `**` operator:" + "Чтобы упаковать аргументы ключевого слова, мы можем использовать оператор `**`:" ] }, { @@ -1636,8 +1635,8 @@ "id": "067bf7c4", "metadata": {}, "source": [ - "The keyword-packing parameter can have any name, but `kwargs` is a common choice.\n", - "The result is a dictionary that maps from keywords to values." + "Параметр по составлению ключевых слов может иметь любое имя, но `kwargs 'является общим выбором.\n", + "Результатом является словарь, который отображает от ключевых слов к значениям." ] }, { @@ -1655,10 +1654,10 @@ "id": "07be77f3", "metadata": {}, "source": [ - "In this example, the value of `kwargs` is printed, but otherwise is has no effect.\n", + "В этом примере значение «kwargs» напечатано, но в противном случае не имеет никакого эффекта.\n", "\n", - "But the `**` operator can also be used in an argument list to unpack a dictionary.\n", - "For example, here's a version of `mean` that packs any keyword arguments it gets and then unpacks them as keyword arguments for `sum`." + "Но оператор `** также может быть использован в списке аргументов для распаковки словаря.\n", + "Например, вот версия `ead`, в которой есть какие -либо аргументы ключевых слов, которые он получает, а затем распаковывает их как аргументы ключевых слов для` sum '." ] }, { @@ -1677,8 +1676,8 @@ "id": "ba00858c", "metadata": {}, "source": [ - "Now if we call `mean` with `start` as a keyword argument, it gets passed along to sum, which uses it as the starting point of the summation.\n", - "In the following example `start=3` adds `3` to the sum before computing the mean, so the sum is `6` and the result is `3`." + "Теперь, если мы назовут «ead» с «start» в качестве аргумента ключевого слова, он передается на сумму, который использует его в качестве отправной точки суммирования.\n", + "В следующем примере `start = 3` добавляет` 3` к сумме перед вычислением среднего, поэтому сумма равен `6`, а результат -` 3`." ] }, { @@ -1696,7 +1695,7 @@ "id": "949a2ca3", "metadata": {}, "source": [ - "As another example, if we have a dictionary with keys `x` and `y`, we can use it with the unpack operator to create a `Point` object." + "В качестве другого примера, если у нас есть словарь с клавишами `x` и` y`, мы можем использовать его с оператором распаковки для создания объекта «точка»." ] }, { @@ -1715,7 +1714,7 @@ "id": "8aaf128a", "metadata": {}, "source": [ - "Without the unpack operator, `d` is treated as a single positional argument, so it gets assigned to `x`, and we get a `TypeError` because there's no second argument to assign to `y`." + "Без оператора распаков, «D` рассматривается как единый позиционный аргумент, поэтому он назначается« X », и мы получаем« typeerror », потому что нет второго аргумента, чтобы назначить` y`." ] }, { @@ -1738,7 +1737,7 @@ "id": "e8acb958", "metadata": {}, "source": [ - "When you are working with functions that have a large number of keyword arguments, it is often useful to create and pass around dictionaries that specify frequently used options." + "Когда вы работаете с функциями, которые имеют большое количество аргументов ключевых слов, часто полезно создавать и разобраться в словари, которые указывают часто используемые параметры." ] }, { @@ -1759,7 +1758,11 @@ "id": "e046e382", "metadata": {}, "source": [ - "## Отладка\n\nВ предыдущих главах мы использовали `doctest` для тестирования функций.\nНапример, функция `add` принимает два числа и возвращает их сумму.\nВ её строке документа есть doctest, проверяющий, что `2 + 2` равно `4`.\n" + "## Отладка\n", + "\n", + "В предыдущих главах мы использовали `doctest` для тестирования функций.\n", + "Например, функция `add` принимает два числа и возвращает их сумму.\n", + "В её строке документа есть doctest, проверяющий, что `2 + 2` равно `4`." ] }, { @@ -1783,7 +1786,7 @@ "id": "a5e332d3", "metadata": {}, "source": [ - "Эта функция принимает объект функции и запускает её doctest-тесты.\n" + "Эта функция принимает объект функции и запускает её doctest-тесты." ] }, { @@ -1804,7 +1807,7 @@ "id": "2d752a40", "metadata": {}, "source": [ - "Поэтому протестировать `add` можно так.\n" + "Поэтому протестировать `add` можно так." ] }, { @@ -1822,7 +1825,10 @@ "id": "77d36e9b", "metadata": {}, "source": [ - "Выходных данных нет, что означает успешное прохождение всех тестов.\n\nВ Python есть ещё один инструмент для автоматизированного тестирования — `unittest`.\nПользоваться им немного сложнее, но вот пример.\n" + "Выходных данных нет, что означает успешное прохождение всех тестов.\n", + "\n", + "В Python есть ещё один инструмент для автоматизированного тестирования — `unittest`.\n", + "Пользоваться им немного сложнее, но вот пример." ] }, { @@ -1846,7 +1852,15 @@ "id": "59b4212a", "metadata": {}, "source": [ - "Сначала мы импортируем `TestCase` — класс из модуля `unittest`.\nЧтобы воспользоваться им, нужно определить новый класс, наследующий `TestCase`, и добавить хотя бы один метод теста.\nИмя метода теста должно начинаться с `test` и отражать, какую функцию он проверяет.\n\nВ нашем примере `test_add` вызывает `add`, сохраняет результат и использует унаследованный от `TestCase` метод `assertEqual`.\n`assertEqual` принимает два аргумента и проверяет, равны ли они.\n\nЧтобы запустить этот тест, нужно вызвать функцию `main` из `unittest`, передав ей несколько именованных аргументов.\nСледующая функция показывает детали — если интересно, попросите виртуального помощника объяснить, как она работает.\n" + "Сначала мы импортируем `TestCase` — класс из модуля `unittest`.\n", + "Чтобы воспользоваться им, нужно определить новый класс, наследующий `TestCase`, и добавить хотя бы один метод теста.\n", + "Имя метода теста должно начинаться с `test` и отражать, какую функцию он проверяет.\n", + "\n", + "В нашем примере `test_add` вызывает `add`, сохраняет результат и использует унаследованный от `TestCase` метод `assertEqual`.\n", + "`assertEqual` принимает два аргумента и проверяет, равны ли они.\n", + "\n", + "Чтобы запустить этот тест, нужно вызвать функцию `main` из `unittest`, передав ей несколько именованных аргументов.\n", + "Следующая функция показывает детали — если интересно, попросите виртуального помощника объяснить, как она работает." ] }, { @@ -1867,7 +1881,11 @@ "id": "5409ea0c", "metadata": {}, "source": [ - "`run_unittest` не принимает `TestExample` как аргумент — вместо этого она ищет классы, наследующие `TestCase`.\nЗатем она находит методы, начинающиеся с `test`, и выполняет их.\nЭтот процесс называется **обнаружением тестов**.\n\nПосмотрим, что произойдёт при вызове `run_unittest`.\n" + "`run_unittest` не принимает `TestExample` как аргумент — вместо этого она ищет классы, наследующие `TestCase`.\n", + "Затем она находит методы, начинающиеся с `test`, и выполняет их.\n", + "Этот процесс называется **обнаружением тестов**.\n", + "\n", + "Посмотрим, что произойдёт при вызове `run_unittest`." ] }, { @@ -1885,7 +1903,10 @@ "id": "7775304a", "metadata": {}, "source": [ - "`unittest.main` сообщает, сколько тестов было выполнено, и их результат.\nЗдесь `OK` означает, что все тесты прошли.\n\nЧтобы увидеть, что бывает при сбое теста, добавим в `TestExample` ошибочный метод.\n" + "`unittest.main` сообщает, сколько тестов было выполнено, и их результат.\n", + "Здесь `OK` означает, что все тесты прошли.\n", + "\n", + "Чтобы увидеть, что бывает при сбое теста, добавим в `TestExample` ошибочный метод." ] }, { @@ -1907,7 +1928,7 @@ "id": "96810614", "metadata": {}, "source": [ - "Вот что происходит при запуске тестов.\n" + "Вот что происходит при запуске тестов." ] }, { @@ -1925,7 +1946,10 @@ "id": "64b743cb", "metadata": {}, "source": [ - "В отчёте указано, какой тестовый метод провалился, и приведено сообщение об ошибке.\nВ сводке указано, что было запущено два теста и один из них не прошёл.\n\nВ упражнениях ниже я предложу подсказки, с помощью которых можно спросить у виртуального ассистента больше о `unittest`.\n" + "В отчёте указано, какой тестовый метод провалился, и приведено сообщение об ошибке.\n", + "В сводке указано, что было запущено два теста и один из них не прошёл.\n", + "\n", + "В упражнениях ниже я предложу подсказки, с помощью которых можно спросить у виртуального ассистента больше о `unittest`." ] }, { @@ -1933,7 +1957,22 @@ "id": "7d0fb256", "metadata": {}, "source": [ - "## Глоссарий\n\n**фабрика:**\n Функция, создающая объекты; её часто передают как параметр.\n\n**тернарное выражение:**\nВыражение, использующее условие для выбора одного из двух значений.\n\n**списковое включение:**\nКраткий способ пройти по последовательности и создать список.\n\n**генераторное выражение:**\nПохоже на списковое включение, но не создаёт список.\n\n**обнаружение тестов:**\nПроцесс поиска и запуска тестов.\n" + "## Глоссарий\n", + "\n", + "**фабрика:**\n", + "Функция, создающая объекты; её часто передают как параметр.\n", + "\n", + "**тернарное выражение:**\n", + "Выражение, использующее условие для выбора одного из двух значений.\n", + "\n", + "**списковое включение:**\n", + "Краткий способ пройти по последовательности и создать список.\n", + "\n", + "**генераторное выражение:**\n", + "Похоже на списковое включение, но не создаёт список.\n", + "\n", + "**обнаружение тестов:**\n", + "Процесс поиска и запуска тестов." ] }, { @@ -1941,7 +1980,7 @@ "id": "bc03f15d", "metadata": {}, "source": [ - "## Упражнения\n" + "## Упражнение" ] }, { @@ -1964,7 +2003,27 @@ "id": "fe10415e", "metadata": {}, "source": [ - "### Вопросы виртуальному помощнику\n\nЕсть несколько тем из этой главы, о которых вы можете узнать подробнее.\n\n* «Какие методы и операторы есть у класса `set` в Python?»\n\n* «Какие методы и операторы есть у класса `Counter`?»\n\n* «Чем списковое включение отличается от генераторного выражения?»\n\n* «Когда стоит использовать `namedtuple` вместо создания нового класса?»\n\n* «Для чего применяется упаковка и распаковка именованных аргументов?»\n\n* «Как `unittest` выполняет обнаружение тестов?»\n\n* «Какие методы, помимо `assertEqual`, чаще всего используются в `unittest.TestCase`?»\n\n* «Каковы плюсы и минусы `doctest` и `unittest`?»\n\nВ оставшихся упражнениях при необходимости можете обращаться к виртуальному помощнику, но не забывайте проверять полученные ответы.\n" + "### Вопросы виртуальному помощнику\n", + "\n", + "Есть несколько тем из этой главы, о которых вы можете узнать подробнее.\n", + "\n", + "* «Какие методы и операторы есть у класса `set` в Python?»\n", + "\n", + "* «Какие методы и операторы есть у класса `Counter`?»\n", + "\n", + "* «Чем списковое включение отличается от генераторного выражения?»\n", + "\n", + "* «Когда стоит использовать `namedtuple` вместо создания нового класса?»\n", + "\n", + "* «Для чего применяется упаковка и распаковка именованных аргументов?»\n", + "\n", + "* «Как `unittest` выполняет обнаружение тестов?»\n", + "\n", + "* «Какие методы, помимо `assertEqual`, чаще всего используются в `unittest.TestCase`?»\n", + "\n", + "* «Каковы плюсы и минусы `doctest` и `unittest`?»\n", + "\n", + "В оставшихся упражнениях при необходимости можете обращаться к виртуальному помощнику, но не забывайте проверять полученные ответы." ] }, { @@ -1972,7 +2031,9 @@ "id": "c61ecde2", "metadata": {}, "source": [ - "### Упражнение\n\nВ одной из задач главы 7 предлагалось написать функцию `uses_none`, которая принимает слово и строку запрещённых букв и возвращает `True`, если слово не содержит ни одной из них. Ниже приведено решение.\n" + "### Упражнение\n", + "\n", + "В одной из задач главы 7 предлагалось написать функцию `uses_none`, которая принимает слово и строку запрещённых букв и возвращает `True`, если слово не содержит ни одной из них. Ниже приведено решение." ] }, { @@ -1994,7 +2055,8 @@ "id": "b558b8b3", "metadata": {}, "source": [ - "Напишите вариант этой функции, использующий операции множеств вместо цикла `for`.\nПодсказка: спросите у виртуального помощника: «Как найти пересечение множеств в Python?»\n" + "Напишите вариант этой функции, использующий операции множеств вместо цикла `for`.\n", + "Подсказка: спросите у виртуального помощника: «Как найти пересечение множеств в Python?»" ] }, { @@ -2004,7 +2066,7 @@ "tags": [] }, "source": [ - "Можете воспользоваться этой заготовкой.\n" + "Можете воспользоваться этой заготовкой." ] }, { @@ -2071,7 +2133,12 @@ "id": "d2d670cf", "metadata": {}, "source": [ - "### Упражнение\n\nScrabble — настольная игра, в которой нужно составлять слова из буквенных фишек.\nНапример, имея фишки `T`, `A`, `B`, `L`, `E`, можно составить слова `BELT` и `LATE`, используя подмножество фишек, но слово `BEET` не получится — у нас только одна буква `E`.\n\nНапишите функцию, которая принимает строку букв и слово и проверяет, можно ли ими составить слово с учётом количества каждой буквы.\n" + "### Упражнение\n", + "\n", + "Scrabble — настольная игра, в которой нужно составлять слова из буквенных фишек.\n", + "Например, имея фишки `T`, `A`, `B`, `L`, `E`, можно составить слова `BELT` и `LATE`, используя подмножество фишек, но слово `BEET` не получится — у нас только одна буква `E`.\n", + "\n", + "Напишите функцию, которая принимает строку букв и слово и проверяет, можно ли ими составить слово с учётом количества каждой буквы." ] }, { @@ -2081,7 +2148,7 @@ "tags": [] }, "source": [ - "Для начала можно использовать следующую заготовку.\n" + "Для начала можно использовать следующую заготовку." ] }, { @@ -2133,7 +2200,9 @@ "id": "de2dc099", "metadata": {}, "source": [ - "### Упражнение\n\nВ одном из заданий [главы 17](chapter_inheritance) моё решение функции `has_straightflush` использует метод, который разбивает `PokerHand` на список из четырёх рук, каждая из которых содержит карты одной масти.\n" + "### Упражнение\n", + "\n", + "В одном из заданий [главы 17](chapter_inheritance) моё решение функции `has_straightflush` использует метод, который разбивает `PokerHand` на список из четырёх рук, каждая из которых содержит карты одной масти." ] }, { @@ -2160,7 +2229,7 @@ "id": "cd04a7a3", "metadata": {}, "source": [ - "Напишите упрощённую версию этой функции, используя `defaultdict`.\n" + "Напишите упрощённую версию этой функции, используя `defaultdict`." ] }, { @@ -2170,7 +2239,7 @@ "tags": [] }, "source": [ - "Ниже приведена заготовка класса `PokerHand` и функции `partition_suits`, которую можно взять за основу.\n" + "Ниже приведена заготовка класса `PokerHand` и функции `partition_suits`, которую можно взять за основу." ] }, { @@ -2205,7 +2274,7 @@ "tags": [] }, "source": [ - "Чтобы проверить код, создадим колоду и перемешаем её.\n" + "Чтобы проверить код, создадим колоду и перемешаем её." ] }, { @@ -2229,7 +2298,7 @@ "tags": [] }, "source": [ - "Затем создайте `PokerHand` и добавьте в неё семь карт.\n" + "Затем создайте `PokerHand` и добавьте в неё семь карт." ] }, { @@ -2257,7 +2326,7 @@ "tags": [] }, "source": [ - "Если вызвать `partition` и вывести результаты, каждая рука должна содержать карты лишь одной масти.\n" + "Если вызвать `partition` и вывести результаты, каждая рука должна содержать карты лишь одной масти." ] }, { @@ -2281,7 +2350,9 @@ "id": "218798e3", "metadata": {}, "source": [ - "### Упражнение\n\nНиже приведена функция из главы 11, вычисляющая числа Фибоначчи.\n" + "### Упражнение\n", + "\n", + "Ниже приведена функция из главы 11, вычисляющая числа Фибоначчи." ] }, { @@ -2306,7 +2377,7 @@ "id": "6acab624", "metadata": {}, "source": [ - "Напишите вариант этой функции с единственным оператором `return`, используя два тернарных выражения, одно внутри другого.\n" + "Напишите вариант этой функции с единственным оператором `return`, используя два тернарных выражения, одно внутри другого." ] }, { @@ -2348,7 +2419,8 @@ "id": "2deb0e1f", "metadata": {}, "source": [ - "### Упражнение\nНиже показана рекурсивная функция для вычисления биномиального коэффициента.\n" + "### Упражнение\n", + "Ниже показана рекурсивная функция для вычисления биномиального коэффициента." ] }, { @@ -2380,7 +2452,10 @@ "id": "656c61f6", "metadata": {}, "source": [ - "Перепишите тело функции, используя вложенные тернарные выражения.\n\nЭта версия не слишком эффективна, потому что многократно вычисляет одни и те же значения.\nСделайте её быстрее, применив мемоизацию, как описано в [главе 10](section_memos).\n" + "Перепишите тело функции, используя вложенные тернарные выражения.\n", + "\n", + "Эта версия не слишком эффективна, потому что многократно вычисляет одни и те же значения.\n", + "Сделайте её быстрее, применив мемоизацию, как описано в [главе 10](section_memos)." ] }, { @@ -2408,7 +2483,9 @@ "id": "921719dc", "metadata": {}, "source": [ - "### Упражнение\n\nНиже показан метод `__str__` из класса `Deck` в [главе 17](section_print_deck).\n" + "### Упражнение\n", + "\n", + "Ниже показан метод `__str__` из класса `Deck` в [главе 17](section_print_deck)." ] }, { @@ -2432,7 +2509,7 @@ "id": "27f189cf", "metadata": {}, "source": [ - "Напишите более лаконичную версию этого метода, используя списковое или генераторное выражение.\n" + "Напишите более лаконичную версию этого метода, используя списковое или генераторное выражение." ] }, { @@ -2454,7 +2531,7 @@ "tags": [] }, "source": [ - "Этим примером можно воспользоваться для проверки решения.\n" + "Этим примером можно воспользоваться для проверки решения." ] }, { @@ -2486,7 +2563,13 @@ "tags": [] }, "source": [ - "[Think Python: 3-е издание](https://allendowney.github.io/ThinkPython/index.html)\n\n© 2024 [Allen B. Downey](https://allendowney.com)\n\nЛицензия на код: [MIT License](https://mit-license.org/)\n\nЛицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "[Think Python: 3-е издание](https://allendowney.github.io/ThinkPython/index.html)\n", + "\n", + "© 2024 [Allen B. Downey](https://allendowney.com)\n", + "\n", + "Лицензия на код: [MIT License](https://mit-license.org/)\n", + "\n", + "Лицензия на текст: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], @@ -2512,4 +2595,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} \ No newline at end of file +} From a7b25fa91dafffe55f194ed66ab2a7d190bd4d81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= <41776352+jestelf@users.noreply.github.com> Date: Sun, 20 Jul 2025 17:00:45 +0300 Subject: [PATCH 44/44] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20Markdown=20=D1=8F=D1=87=D0=B5=D0=B5=D0=BA=20=D0=B2=20c?= =?UTF-8?q?hap19?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- chapters/chap19.ipynb | 103 ++++++++++++++++++++---------------------- 1 file changed, 50 insertions(+), 53 deletions(-) diff --git a/chapters/chap19.ipynb b/chapters/chap19.ipynb index 4d86fb8..5ede687 100644 --- a/chapters/chap19.ipynb +++ b/chapters/chap19.ipynb @@ -5,9 +5,7 @@ "id": "1331faa1", "metadata": {}, "source": [ - "You can order print and ebook versions of *Think Python 3e* from\n", - "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", - "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + "Вы можете заказать печатную и электронную версии *Think Python 3e* на [Bookshop.org](https://bookshop.org/a/98697/9781098155438) и [Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325).\n" ] }, { @@ -15,7 +13,7 @@ "id": "171aca73", "metadata": {}, "source": [ - "# Final thoughts" + "# Заключительные мысли\n" ] }, { @@ -23,19 +21,19 @@ "id": "4d551c99", "metadata": {}, "source": [ - "Learning to program is not easy, but if you made it this far, you are off to a good start.\n", - "Now I have some suggestions for ways you can keep learning and apply what you have learned.\n", + "Учиться программировать непросто, но если вы дошли до этого места, вы уже неплохо начали.\n", + "Теперь у меня есть несколько предложений, как вы можете продолжать учиться и применять полученные знания.\n", "\n", - "This book is meant to be a general introduction to programming, so we have not focused on specific applications.\n", - "Depending on your interests, there are any number of areas where you can apply your new skills.\n", + "Эта книга предназначена как общее введение в программирование, поэтому мы не сосредотачивались на конкретных приложениях.\n", + "В зависимости от ваших интересов есть множество областей, где вы можете применить свои новые навыки.\n", "\n", - "If you are interested in Data Science, there are three books of mine you might like:\n", + "Если вам интересна Data Science, вот три моих книги, которые вам могут понравиться:\n", "\n", "* *Think Stats: Exploratory Data Analysis*, O'Reilly Media, 2014.\n", "\n", "* *Think Bayes: Bayesian Statistics in Python*, O'Reilly Media, 2021.\n", "\n", - "* *Think DSP: Digital Signal Processing in Python*, O'Reilly Media, 2016." + "* *Think DSP: Digital Signal Processing in Python*, O'Reilly Media, 2016.\n" ] }, { @@ -43,13 +41,13 @@ "id": "cceabe36", "metadata": {}, "source": [ - "If you are interested in physical modeling and complex systems, you might like:\n", + "Если вас интересует физическое моделирование и сложные системы, вам могут понравиться:\n", "\n", "* *Modeling and Simulation in Python: An Introduction for Scientists and Engineers*, No Starch Press, 2023.\n", "\n", "* *Think Complexity: Complexity Science and Computational Modeling*, O'Reilly Media, 2018.\n", "\n", - "These use NumPy, SciPy, pandas, and other Python libraries for data science and scientific computing." + "В этих книгах используются библиотеки NumPy, SciPy, pandas и другие инструменты Python для науки о данных и научных вычислений.\n" ] }, { @@ -57,13 +55,13 @@ "id": "54a39121", "metadata": {}, "source": [ - "This book tries to find a balance between general principles of programming and details of Python.\n", - "As a result, it does not include every feature of the Python language.\n", - "For more about Python, and good advice about how to use it, I recommend *Fluent Python: Clear, Concise, and Effective Programming*, second edition by Luciano Ramalho, O'Reilly Media, 2022.\n", + "Эта книга пытается найти баланс между общими принципами программирования и деталями Python.\n", + "В результате она не включает каждую особенность языка.\n", + "Чтобы узнать больше о Python и получить хорошие советы по его использованию, рекомендую *Fluent Python: Clear, Concise, and Effective Programming*, второе издание, Luciano Ramalho, O'Reilly Media, 2022.\n", "\n", - "After an introduction to programming, a common next step is to learn about data structures and algorithms.\n", - "I have a work in progress on this topic, called *Data Structures and Information Retrieval in Python*.\n", - "A free electronic version is available from Green Tea Press at ." + "После введения в программирование обычный следующий шаг — изучение структур данных и алгоритмов.\n", + "У меня есть рабочий черновик на эту тему под названием *Data Structures and Information Retrieval in Python*.\n", + "Бесплатную электронную версию можно получить на Green Tea Press по адресу .\n" ] }, { @@ -71,11 +69,11 @@ "id": "a1598510", "metadata": {}, "source": [ - "As you work on more complex programs, you will encounter new challenges.\n", - "You might find it helpful to review the sections in this book about debugging.\n", - "In particular, remember the Six R's of debugging from [Chapter 12](section_debugging_12): reading, running, ruminating, rubber-ducking, retreating, and resting.\n", + "Работая над более сложными программами, вы столкнётесь с новыми трудностями.\n", + "Возможно, будет полезно освежить в памяти разделы этой книги о поиске и исправлении ошибок.\n", + "В частности, вспомните шесть 'R' отладки из [главы 12](section_debugging_12): чтение, запуск, размышление, резиновая уточка, отступление и отдых.\n", "\n", - "This book suggests tools to help with debugging, including the `print` and `repr` functions, the `structshape` function in [Chapter 11](section_debugging_11) -- and the built-in functions `isinstance`, `hasattr`, and `vars` in [Chapter 14](section_debugging_14)." + "В этой книге предлагаются инструменты для отладки, включая функции `print` и `repr`, функцию `structshape` в [главе 11](section_debugging_11) и встроенные функции `isinstance`, `hasattr` и `vars` из [главы 14](section_debugging_14).\n" ] }, { @@ -83,12 +81,12 @@ "id": "fb4dd345", "metadata": {}, "source": [ - "It also suggests tools for testing programs, including the `assert` statement, the `doctest` module, and the `unittest` module.\n", - "Including tests in your programs is one of the best ways to prevent and detect errors, and save time debugging.\n", + "Книга также предлагает инструменты для тестирования программ, включая оператор `assert`, модуль `doctest` и модуль `unittest`.\n", + "Включение тестов в программы — один из лучших способов предотвращать и обнаруживать ошибки, экономя время на отладке.\n", "\n", - "But the best kind of debugging is the kind you don't have to do.\n", - "If you use an incremental development process as described in [Chapter 6](section_incremental) -- and test as you go -- you will make fewer errors and find them more quickly when you do.\n", - "Also, remember encapsulation and generalization from [Chapter 4](section_encapsulation), which is particularly useful when you are developing code in Jupyter notebooks." + "Но лучший вид отладки — тот, который вам не приходится делать.\n", + "Если вы будете использовать инкрементальный подход к разработке, описанный в [главе 6](section_incremental), и тестировать код по ходу дела, то допустите меньше ошибок и быстрее найдёте те, что всё же появятся.\n", + "Также помните об инкапсуляции и обобщении из [главы 4](section_encapsulation), что особенно полезно при разработке кода в Jupyter-ноутбуках.\n" ] }, { @@ -96,16 +94,15 @@ "id": "0d29933e", "metadata": {}, "source": [ - "Throughout this book, I've suggested ways to use virtual assistants to help you learn, program, and debug.\n", - "I hope you are finding these tools useful.\n", + "На протяжении всей книги я предлагал способы использовать виртуальных ассистентов, чтобы учиться, программировать и отлаживать код.\n", + "Надеюсь, эти инструменты оказываются вам полезными.\n", "\n", - "In additional to virtual assistants like ChatGPT, you might also want to use a tool like Copilot that autocompletes code as you type.\n", - "I did not recommend using these tools, initially, because they can be overwhelming for beginners.\n", - "But you might want to explore them now.\n", + "В дополнение к виртуальным ассистентам вроде ChatGPT вы можете попробовать инструмент типа Copilot, который дописывает код по мере набора.\n", + "Изначально я не рекомендовал эти инструменты, потому что они могут быть слишком сложными для начинающих, но сейчас вы можете их попробовать.\n", "\n", - "Using AI tools effectively requires some experimentation and reflection to find a flow that works for you.\n", - "If you think it's a nuisance to copy code from ChatGPT to Jupyter, you might prefer something like Copilot.\n", - "But the cognitive work you do to compose a prompt and interpret the response can be as valuable as the code the tool generates, in the same vein as rubber duck debugging." + "Эффективное использование ИИ-тулов требует экспериментирования и размышлений, чтобы найти рабочий процесс, который подойдёт именно вам.\n", + "Если вам кажется неудобным копировать код из ChatGPT в Jupyter, возможно, вам больше понравится Copilot.\n", + "Но умственная работа по составлению запросов и интерпретации ответов может быть так же ценна, как и сгенерированный код — по аналогии с отладкой при помощи резиновой уточки.\n" ] }, { @@ -113,17 +110,17 @@ "id": "c28d6815", "metadata": {}, "source": [ - "As you gain programming experience, you might want to explore other development environments.\n", - "I think Jupyter notebooks are a good place to start, but they are relatively new and not as widely-used as conventional integrated development environments (IDE).\n", - "For Python, the most popular IDEs include PyCharm and Spyder -- and Thonny, which is often recommended for beginners.\n", - "Other IDEs, like Visual Studio Code and Eclipse, work with other programming languages as well.\n", - "Or, as a simpler alternative, you can write Python programs using any text editor you like.\n", - "\n", - "As you continue your programming journey, you don't have to go alone!\n", - "If you live in or near a city, there's a good chance there is a Python user group you can join.\n", - "These groups are usually friendly to beginners, so don't be afraid.\n", - "If there is no group near you, you might be able to join events remotely.\n", - "Also, keep an eye out for regional Python conferences." + "Набираясь опыта, вы можете захотеть освоить другие среды разработки.\n", + "Я считаю, что Jupyter — хорошее место для старта, но это сравнительно новая среда и она не столь широко распространена, как традиционные интегрированные среды разработки (IDE).\n", + "Для Python наиболее популярны PyCharm и Spyder — а также Thonny, который часто рекомендуют новичкам.\n", + "Другие IDE, такие как Visual Studio Code и Eclipse, работают и с другими языками программирования.\n", + "Более простой вариант — писать программы на Python в любом текстовом редакторе.\n", + "\n", + "Продолжая свой путь в программировании, вам не обязательно идти в одиночку!\n", + "Если вы живёте в городе или рядом, вероятно, есть местная группа пользователей Python, к которой можно присоединиться.\n", + "Эти группы обычно дружелюбны к новичкам, так что не бойтесь.\n", + "Если поблизости нет такой группы, возможно, вы сможете участвовать в мероприятиях удалённо.\n", + "Также следите за региональными конференциями по Python.\n" ] }, { @@ -131,12 +128,12 @@ "id": "28cb22bf", "metadata": {}, "source": [ - "One of the best ways to improve your programming skills is to learn another language.\n", - "If you are interested in statistics and data science, you might want to learn R.\n", - "But I particularly recommend learning a functional language like Racket or Elixir.\n", - "Functional programming requires a different kind of thinking, which changes the way you think about programs.\n", + "Один из лучших способов улучшить свои навыки программирования — выучить другой язык.\n", + "Если вас интересует статистика и Data Science, можно изучить R.\n", + "Но особенно рекомендую функциональный язык вроде Racket или Elixir.\n", + "Функциональное программирование требует иного подхода к мышлению, что меняет ваше представление о программах.\n", "\n", - "Good luck!" + "Удачи!\n" ] }, { @@ -160,7 +157,7 @@ "\n", "Code license: [MIT License](https://mit-license.org/)\n", "\n", - "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)\n" ] } ], @@ -185,4 +182,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file