Dancing with Python - Robert S. Sutor - E-Book

Dancing with Python E-Book

Robert S. Sutor

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Dancing with Python helps you learn Python and quantum computing in a practical way. It will help you explore how to work with numbers, strings, collections, iterators, and files.

The book goes beyond functions and classes and teaches you to use Python and Qiskit to create gates and circuits for classical and quantum computing. Learn how quantum extends traditional techniques using the Grover Search Algorithm and the code that implements it. Dive into some advanced and widely used applications of Python and revisit strings with more sophisticated tools, such as regular expressions and basic natural language processing (NLP). The final chapters introduce you to data analysis, visualizations, and supervised and unsupervised machine learning.

By the end of the book, you will be proficient in programming the latest and most powerful quantum computers, the Pythonic way.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 706

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Dancing with Python

Learn to code with Python and Quantum Computing

Robert S. Sutor

BIRMINGHAM - MUMBAI

"Python" and the Python Logo are trademarks of the Python Software Foundation.

Dancing with Python

Copyright © 2021 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Producer: Tushar GuptaAcquisitions Editor – Peer Reviews: Saby D’silvaProject Editor: Parvathy NairContent Development Editor: Bhavesh AminCopy Editor: Safis EditingTechnical Editor: Aditya SawantProof Reader: Safis EditingPresentation Designer: Pranit Padwal

First published: August 2021

Production reference: 3281221

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-80107-785-9

www.packt.com

For my mother and father, Anita and Benjamin Sutor.

Contributors

About the author

Robert S. Sutor has been a technical leader and executive in the IT industry for over 35 years. More than two decades of that have been spent in IBM Research in New York. During his time there, he worked on and led efforts in symbolic mathematical computation, mathematical programming languages, optimization, AI, blockchain, and quantum computing. He is the author of Dancing with Qubits: How quantum computing works and how it can change the world, also with Packt. He is the published co-author of several research papers and the book Axiom: The Scientific Computation System with the late Richard D. Jenks.

Sutor was an IBM executive on the software side of the business in areas including Java web application servers, emerging industry standards, software on Linux, mobile, and open source. He’s a theoretical mathematician by training, has a Ph.D. from Princeton University, and an undergraduate degree from Harvard College. He started coding when he was 15 and has used most of the programming languages that have come along.

I want to thank my wife, Judith Hunter, and children, Katie and William, for their love, patience, and humor while this book was being written.

I also want to thank the following for their conversations, insight, and inspiration regarding coding, Python, Computer Science, and Quantum Computing: Abe Asfaw, Andrew Wack, Aparna Prabhakar, Barry Trager, Blake Johnson, Chris Nay, Christine Vu, Christopher Schnabel, David Bryant, Fran Cabrera, Hanhee Paik, Heather Higgins, Ismael Faro, James Weaver, James Wooten, Jay Gambetta, Jeanette Garcia, Jenn Glick, Jerry Chow, Joseph Broz, Julianna Murphy, Julien Gacon, Katie Pizzolato, Luciano Bello, Matthew B. Treinish, Mark Mattingley-Scott, Matthias Steffen, Michael Houston, Paul Nation, Rajeev Malik, Robert Loredo, Ryan Mandelbaum, Samantha Davis, Sarah Sheldon, Sean Dague, Stefan Woerner, and Zaira Nazario.

About the reviewer

Martin Renou is a Scientific Software Engineer working at QuantStack (Paris, France). Before joining QuantStack, Martin also worked as a Software Developer at Enthought (Cambridge, UK). He studied at the French Aerospace Engineering School ISAE-Supaero, with a major in autonomous systems and programming. As an open source developer, Martin has worked on a variety of projects, mostly around the Jupyter project ecosystem.

Table of Contents

PrefaceWhy did I write this book?For whom did I write this book?What does this book cover?What conventions do I use in this book?Download the example code filesDownload the color imagesGet in touchChapter 1: Doing the Things That Coders Do1.1 Data1.2 Expressions1.3 Functions1.4 Libraries1.5 Collections1.6 Conditional processing1.7 Loops1.8 Exceptions1.9 Records1.10 Objects and classes1.11 Qubits1.12 Circuits1.13 SummaryPart I: Getting to Know PythonChapter 2: Working with Expressions2.1 Numbers2.2 Strings2.3 Lists2.4 Variables and assignment2.5 True and False2.6 Arithmetic2.7 String operations2.8 List operations2.9 Printing2.10 Conditionals2.11 Loops2.12 Functions2.13 SummaryChapter 3: Collecting Things Together3.1 The big three3.2 Lists3.3 The joy of O(1)3.4 Tuples3.5 Comprehensions3.6 What does “Pythonic” mean?3.7 Nested comprehensions3.8 Parallel traverse3.9 Dictionaries3.10 Sets3.11 SummaryChapter 4: Stringing You Along4.1 Single, double, and triple quotes4.2 Testing for substrings4.3 Accessing characters4.4 Creating strings4.5 Strings and iterations4.6 Strings and slicing4.7 String tests4.8 Splitting and stripping4.9 SummaryChapter 5: Computing and Calculating5.1 Using Python modules5.2 Integers5.3 Floating-point numbers5.4 Rational numbers5.5 Complex numbers5.6 Symbolic computation5.7 Random numbers5.8 Quantum randomness5.9 SummaryChapter 6: Defining and Using Functions6.1 The basic form6.2 Parameters and arguments6.3 Naming conventions6.4 Return values6.5 Keyword arguments6.6 Default argument values6.7 Formatting conventions6.8 Nested functions6.9 Variable scope6.10 Functions are objects6.11 Anonymous functions6.12 Recursion6.13 SummaryChapter 7: Organizing Objects into Classes7.1 Objects7.2 Classes, methods, and variables7.3 Object representation7.4 Magic methods7.5 Attributes and properties7.6 Naming conventions and encapsulation7.7 Commenting Python code7.8 Documenting Python code7.9 Enumerations7.10 More polynomial magic7.11 Class variables7.12 Class and static methods7.13 Inheritance7.14 Iterators7.15 Generators7.16 Objects in collections7.17 Creating modules7.18 SummaryChapter 8: Working with Files8.1 Paths and the file system8.2 Moving around the file system8.3 Creating and removing directories8.4 Lists of files and folders8.5 Names and locations8.6 Types of files8.7 Reading and writing files8.8 Saving and restoring data8.9 SummaryPART II: Algorithms and CircuitsChapter 9: Understanding Gates and Circuits9.1 The software stack9.2 Boolean operations and bit logic gates9.3 Logic circuits9.4 Simplifying bit expressions9.5 Universality for bit gates9.6 Quantum gates and operations9.7 Quantum circuits9.8 Universality for quantum gates9.9 SummaryChapter 10: Optimizing and Testing Your Code10.1 Testing your code10.2 Timing how long your code takes to run10.3 Optimizing your code10.4 Looking for orphan code10.5 Defining and using decorators10.6 SummaryChapter 11: Searching for the Quantum Improvement11.1 Classical searching11.2 Quantum searching via Grover11.3 Oracles11.4 Inversion about the mean11.5 Amplitude amplification11.6 Searching over two qubits11.7 SummaryPART III: Advanced Features and LibrariesChapter 12: Searching and Changing Text12.1 Core string search and replace methods12.2 Regular expressions12.3 Introduction to Natural Language Processing12.4 SummaryChapter 13: Creating Plots and Charts13.1 Function plots13.2 Bar charts13.3 Histograms13.4 Pie charts13.5 Scatter plots13.6 Moving to three dimensions13.7 SummaryChapter 14: Analyzing Data14.1 Statistics14.2 Cats and commas14.3 pandas DataFrames14.4 Data cleaning14.5 Statistics with pandas14.6 Converting categorical data14.7 Cats by gender in each locality14.8 Are all tortoiseshell cats female?14.9 Cats in trees and circles14.10 SummaryChapter 15: Learning, Briefly15.1 What is machine learning?15.2 Cats again15.3 Feature scaling15.4 Feature selection and reduction15.5 Clustering15.6 Classification15.7 Linear regression15.8 Concepts of neural networks15.9 Quantum machine learning15.10 SummaryAppendicesAppendix A: ToolsA.1 The operating system command lineA.2 Installing PythonA.3 Installing Python modules and packagesA.4 Installing a virtual environmentA.5 Installing the Python packages used in this bookA.6 The Python interpreterA.7 IDLEA.8 Visual Studio CodeA.9 Jupyter notebooksA.10 Installing and setting up QiskitA.11 The IBM Quantum Composer and LabA.12 LintingAppendix B: Staying CurrentB.1 python.orgB.2 qiskit.orgB.3 Python expert sitesB.4 Asking questions and getting answersAppendix C: The Complete UniPoly ClassAppendix D: The Complete Guitar Class HierarchyAppendix E: NoticesE.1 Photos, images, and diagramsE.2 DataE.3 TrademarksE.4 Python 3 licenseAppendix F: Production NotesReferencesOther Books You May EnjoyIndexIndex Formatting Examples

Preface

Skill is the unified force of experience, intellect and passion in their operation.

—John Ruskin

Coding is the art and engineering of creating software. Code is the collection of written instructions and functionality in one or more programming languages that provides directions for how computing hardware should operate. A coder creates code.

Coders go by other names as well. They are often called software developers or just developers. More traditionally, they have been called programmers.

The range of hardware devices that need code to tell them what to do is astounding. Cars have many computer processors in them to control how they operate and how to entertain you. As you can imagine, a vehicle with any degree of self-driving capability contains a lot of code. It’s not simple programming either: artificial intelligence (AI) software makes many operating decisions.

Your mobile phone is both a computing and a communication device. Low-level code controls how your phone connects to Wi-Fi or cellular networks. Someone wrote that code, but as an app developer, you don’t need to redo it; you call functions that access the Internet. Similarly, someone wrote the low-level graphics routines that put the color dots on the screen in the right places. While you may want to do that in some cases as an app developer, you mostly call higher-level functions that draw lines or shapes, show photos, or play videos.

Even at this level, several kinds of hardware get involved within your phone. There is the communications chip, general processor, arithmetic processor, floating-point processor, and the graphics processing unit (GPU). These are what we call classical computers or classical processors. Their architecture is descended from computers of the 1940s. While there is a range of ways of programming them, it is all called classical coding.

However, there is another kind of computer that has only been available on the cloud for general users since 2016. That is the quantum computer. Coding a quantum computer is radically different from classical device programming at the level close to the hardware. However, if you know or can learn Python, a programming language estimated to be used by over 8 million software developers globally and taught in many universities, you have a tremendous advantage in that you can do both classical and quantum computing together.

Classical hardware and software have proven themselves over the last seven decades, while quantum computing is new. It promises to help solve some kinds of problems that would take too much time, too much processing power, or too much memory, even for a classical supercomputer. Experts expect quantum computing to be useful in the future in areas including financial services, logistics, chemistry, materials science, drug discovery, scientific simulation of physical systems, optimization, and artificial intelligence.

If you plan to be a professional software developer or someone who needs high-performance computing for research, you should learn about quantum computing systems and how to code for them.

Why did I write this book?

How do you learn to code in this new world that involves both classical and quantum hardware?

One way to do it is to learn classical computing by itself. This is the traditional way of doing it, using a language such as C, C++, JavaScript, Java, Go, or Python. Along the way, you would learn how to use extra functionality in libraries of code along with the programming tools or from a third-party provider. Examples of these are the C++ Standard Library; the Java Platform, Enterprise Edition; the Python Standard Library; or the thousands of Python packages listed in the Python Package Index. [PYPI]

Once you have the philosophy, syntax, structure, and idioms of the classical programming language understood, you then learn quantum computing on top of that. For example, you could use the Qiskit open source quantum computing software development kit (SDK) along with Python. [QIS] These mesh together and operate exceptionally well. Thousands of people are already Qiskit coders. If you know Python, this is a great approach.

Figure 0.1: Our learning strategy

But what if you are learning to code or have only a small amount of experience? What if I could offer you the chance to learn classical and quantum computing in a unified manner? Would it be useful if I could help you understand the concepts of both so that you don’t see them as different disciplines? That’s what I do in this book.

For whom did I write this book?

I believe this book will be useful and engaging if one or more of these descriptions apply to you:

You are learning to code as part of a class or course.Through self-study, you want to learn to think like someone who writes software.You want to understand and use the fundamentals of modern Python programming.You recognize that quantum computing will be one of the most important technologies of this century, and you want to learn the basics of how to code for it.You think that solving a problem through software means you use all the tools available to you, and you want to employ both classical and the newer quantum coding techniques.

Assumed reader prerequisites

I do not expect you to have any experience in coding or using Python. Some of the discussion and implementation in Chapter 11, Searching for the Quantum Improvement, presumes comfort with some mathematics, but nothing that isn’t typically covered before a calculus course. This includes algebra, geometry, trigonometry, and logarithms.

This book does not cover the detailed mathematics and theory of quantum computing. For that, I direct you to my book Dancing with Qubits if you wish to learn more. [DWQ]

What does this book cover?

Given the wide use of Python and the wide variety of learning and reference materials, I have chosen to structure this book into three main parts. I give you the information you need as you need it.

Before jumping into those, however, we together explore what coders do, how they think about using programming languages, and what they expect from the tools they use. That chapter,

1. Doing the Things That Coders Do

is not specific to Python and is occasionally philosophical about the art and engineering of writing code.

After that introduction, the rest of the book proceeds in the following way.

Part I. Getting to Know Python

Being a full-featured programming language, Python implements the features described in the first chapter mentioned above. In this part, we learn how to write basic expressions including numbers and textual strings, collect objects together using data structures such as lists, and explore Python’s core and extended mathematical facilities.

We then jump into defining functions to organize and make our code reusable, introduce object-oriented coding through classes, and finally interact with information within the computing environment via files.

2. Working with Expressions3. Collecting Things Together4. Stringing You Along5. Computing and Calculating6. Defining and Using Functions7. Organizing Objects into Classes8. Working with Files

The Python modules we introduce in this part include abc, cmath, collections, datetime, enum, fractions, functools, glob, json, math, os, pickle, random, shutil, sympy, and time.

Part II. Algorithms and Circuits

Now that we understand Python’s core features, we’re ready to explore how to make it useful to solve problems. Although many books only speak about functions and classes, we enlarge our discussion to include gates and circuits for classical and quantum computing. It’s then a good time to see how we can test our code and make it run faster.

We then look at traditional problems and see how we can attack them classically. Quantum computing’s reason for existence and development is that it might solve some of those problems significantly faster. We explore the how and why of that, and I point you to further reading on the topic.

9. Understanding Gates and Circuits10. Optimizing and Testing Your Code11. Searching for the Quantum Improvement

The Python modules we introduce in this part include coverage, pytest, qiskit, time, timeit, and wrapt.

Part III. Advanced Features and Libraries

In the final part, we address some heavy-duty but frequent applications of Python. Though we worked with text as strings earlier in the book, we revisit it with more sophisticated tools such as regular expressions and natural language processing (NLP).

The final three chapters focus on data: how to bring it into an application and manipulate it, how to visualize what it represents, and how to gain insights from it through machine learning. Machine learning itself is worth a book or two (or three or ten), so I introduce the key concepts and tools, and you can then jump off into more sophisticated Python and AI applications.

12. Searching and Changing Text13. Creating Plots and Charts14. Analyzing Data15. Learning, Briefly

The Python modules we introduce in this part include flashtext, matplotlib, nltk, pandas, pillow, pytorch, re, scikit-learn, spacy, string, and textblob.

What conventions do I use in this book?

This book uses version 3.9 of Python or later. Most of the features are available in earlier versions of Python 3, but we do not show nor further mention the now-unsupported Python 2.

Executable Python code and its produced results are shown in a monospace font and are marked off in the text in the following way:

2**501125899906842624

The second expression shown is indented and is the result of running the code.

Code can also span several lines as in this example where we create and display a set of numbers that contains no duplicates:

print({1, 2, 3, 2, 4, 1, 5, 3, 6, 7, 1, 3, 8, 2}) {1, 2, 3, 4, 5, 6, 7, 8}

For long function, method, and class definitions, I number the lines so I can refer to them more easily in the text. The numbers are not part of the Python input, and you should not enter them if you type in the code.

defdisplay_string(the_string, put_in_uppercase=False): if put_in_uppercase: print(the_string.upper()) else: print(the_string)

When I refer to Python function, method, and property names in text, they appear like this: print, __add__, and left. Example Python type and class names in the text are int, Fraction, and Guitar. Python module and package names appear like math, os.path, and qiskit.

This book has exercises throughout the text. Work them out as you encounter them before proceeding.

Exercise 0.1

Is this a sample exercise?

The exercises are numbered within chapters.

Exercise 0.2

Is this another sample exercise?

Due to some typographical restrictions, square roots in mathematical expressions within sentences may not have lines over them. For example, an expression like √(x + y) in a sentence is the same as

when it appears within a standalone centered formula.

Occasionally, you may see something like [DWQ] or [DWQ, Section 3.5]. This is a reference to a book, article, or web content. The References section provides details about the works cited.

Dancing with Qubits covers the mathematics for and of quantum computing in great detail. That book is not a prerequisite to this, but I point you to sections in Qubits that pertain to any related material here for your convenience. For example:

I cover real numbers, including floating-point numbers, in section 3.5 of Dancing with Qubits section 3.5. [DWQ]

Download the example code files

The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/Dancing-with-Python. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781801077859_ColorImages.pdf.

Get in touch

Feedback from my readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure our content’s accuracy, mistakes do happen. If you have found an error in this book, we would be grateful if you report this to us. Please visit http://www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

Share your thoughts

Once you’ve read Dancing with Python, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.