35,99 €
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:
Seitenzahl: 706
Veröffentlichungsjahr: 2021
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.
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.
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.
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.
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.
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 strategyBut 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.
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.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]
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 Dois 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 FilesThe 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 ImprovementThe 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, BrieflyThe Python modules we introduce in this part include flashtext, matplotlib, nltk, pandas, pillow, pytorch, re, scikit-learn, spacy, string, and textblob.
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**501125899906842624The 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]
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!
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.
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.
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.