Michael Inden

Python Challenges

100 Proven Programming Tasks Designed to Prepare You for Anything

Michael Inden
Zurich, Switzerland
ISBN 978-1-4842-7397-5e-ISBN 978-1-4842-7398-2
© Michael Inden 2022
This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher, whether the whole or part of the material is concerned, specifically the rights of reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use.
The publisher, the authors and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, expressed or implied, with respect to the material contained herein or for any errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress Media, LLC part of Springer Nature.

The registered company address is: 1 New York Plaza, New York, NY 10004, U.S.A.

For our lovely princess Sophie Jelena

Preface

First of all, thank you for choosing this book. In it you will find a wide range of practice exercises on a broad mix of topics that will help you improve your Python coding skills in an enjoyable manner.

Practice Makes Perfect

We all know the saying practice makes perfect. In crafts and other areas of real life, there is a lot of practice, but the serious case is rare, such as in sports, music, and other fields. Oddly enough, this is often significantly different for us software developers. We actually spend almost all of our time implementing and tend to rarely spend time practicing and learning—sometimes not at all. Why is that?

Presumably, this is due to the time pressure that usually dominates our professional lives, and the fact that there isn’t much suitable exercise material available, even if there are textbooks on algorithms and coding. Those tend to be either too theoretical or too source code-focused and contain too little explanation of the solutions. This book aims to change that.

Why This Book?

So how did I come to tackle this book project? There are several reasons. On the one hand, I was asked again and again by mail or personally by participants of my workshops for a tutorial book as a supplement to my book Der Weg zum Java-Profi [Ind20]. That’s how the first idea came about.

What really triggered the whole thing was that a recruiter from Google approached me quite by surprise with an employment opportunity. As preparation for the upcoming interviews and to refresh my knowledge, I started to search for suitable material. Additionally, I developed some exercises for myself. In the process, I discovered the great, but also partly quite challenging book Cracking the Coding Interview by Gayle Laakmann McDowell [McD16], which inspired me further.

As a result, I initially set out on a Java-focused book project called Java Challenges in German and later in English. In the meantime, the idea came up to implement something similar for Python, first as a German version and later as an English version. So this Python edition is based on the Java version, but the whole book was revised and “Pythonified.” For this purpose, I added, slightly modified, or partially removed things in some places. In particular, I show (if appropriate) how to use Python features like List Comprehensions and so on to make solutions more concise.

Who Is This Book Aimed At?

This book is explicitly not intended for programming novices. It is aimed at readers who already have basic or even good knowledge of Python and want to deepen it with exercises. By solving small programming exercises, you will expand your knowledge about Python, algorithms, and sound OO design in an entertaining way.

The following target groups are addresses in particular:
  • High school and college students: First of all, this book is meant for pupils with an interest in computer science as well as for students of computer science who already know Python quite well as a language and now want to deepen their knowledge by tackling some exercises.

  • Teachers and lecturers: Of course, teachers and lecturers may also benefit from this book and its large number of exercises of varying difficulty, either as a stimulus for their own teaching or as a template for exercises or exams.

  • Hobby programmers and young professionals: In addition, the book is aimed at dedicated hobby programmers and also young professionals who like to program with Python and want to develop themselves further. Furthermore, solving the exercises will help them to be well prepared for potential questions in job interviews.

  • Experienced software developers and architects: Finally, the book is intended for experienced software developers and architects who want to supplement or refresh their knowledge to be able to assist their junior colleagues more effectively and are looking for some inspiration and fresh ideas to do so. In addition, various exercises can also be used in job interviews, with the convenience of having the sample solutions directly at hand for comparison. Also, for the old hands there should be one or two “aha” experiences while finding solutions and rethinking about algorithms and data structures.

What Does This Book Teach?

This book provides a widespread mix of exercises on different topics. Some puzzles may not be of direct, practical importance, but indirectly they help improve your creativity and your ability to find solutions.

In addition to exercises and documented solutions, each topic covered in the book starts with a short introduction. You can use the introductions to get up to speed with the exercises to about the level of difficulty. In each subject area, there are always a few easier exercises to get you started. With a little practice, you should also be able to tackle more difficult problems. Occasionally there are some really challenging exercises, which experts can try their hand at (or those who want to become experts).

Practical Tips and Advice

This book is packed with various practical tips. They include interesting background information as well as pitfalls to avoid.

HINT: TIP FROM THE TRENCHES

In boxes formatted like this you will find some tips worth knowing and additional hints to the actual text later in the book.

Difficulty Level at a Glance

A well-balanced, appealing exercise book needs a large number of tasks of different levels of difficulty, which offer you as a reader the possibility to improve your knowledge step by step. Although I assume a good understanding of Python, the solutions never require deep knowledge of a specific topic or special language features.

To keep the level of difficulty obvious and straightforward, I use the star categorization known from other areas, whose meaning in this context is explained in more detail in Table 0-1.
Table 0-1

Levels of Diffiulty

Stars (meaning)

Estimation

Duration

★✩✩✩✩ (very easy)

These tasks should be solvable in a few minutes with simple Python knowledge.

< 15 min

★★✩✩✩

(easy)

The tasks require a little bit of thinking, but then they are directly solvable.

< 30 min

★★★✩✩

(medium)

The tasks are not overly challenging, but need some thinking, a little bit of strategy and sometimes a look at different constraints.

~ 30 – 45 min

★★★★✩

(difficult)

Proven problem-solving strategies, good knowledge of data structures, and Python knowledge are required for the solution.

~ 45 – 90 min

★★★★★ (very difficult)

The tasks are really tricky and difficult to solve. These exercises should only be tried once you’re able to solve the book’s easier exercises without difficulty.

> 60 min

These ratings are only estimations from my side and are rather rough classifications. Please keep in mind that the difficulty perceived by each individual also depends very much on their background and level of knowledge. I have seen colleagues have a hard time with tasks that I considered quite easy. But I also know the opposite: While others seem to solve a task easily, you are in despair yourself because the penny just won’t drop. Sometimes a break with a coffee or a short walk helps. Do not get demotivated! Everyone struggles with some task at some time or another.

NOTE: POSSIBLE ALTERNATIVES TO THE SAMPLE SOLUTIONS

Please note that for some problems there are almost always some variants, which might be even be more catchy for you. Therefore I will present interesting alternatives to the (sample) solution from time to time as food for thought.

Structure of This Book

Now that you have a rough picture of the contents of this book, I will introduce the topics of each chapter briefly. As indicated, the exercises are grouped thematically. In this context, the six chapters after the introduction build the basis and the subsequent three chapters deal with more advanced topics.

Chapter 1: This chapter describes the basic structure of the following chapters with an introduction, exercises, and solutions. Additionally, it provides a framework for the unit tests that are often used to prove that the solutions are working. Finally, I give some hints for trying out the examples and solutions.

Chapter 2: The second chapter is dedicated to mathematical operations as well as tasks about prime numbers and the Roman numeral system. Besides, I present a few ideas for number games.

Chapter 3: Recursion is an important basic building block concerning the definition of algorithms. This chapter provides a short introduction, and the various exercises should help you to understand recursion.

Chapter 4: Strings are known to be sequences of characters that offer a variety of methods. A solid understanding is important since almost no program can operate without strings. Therefore you will get to know the processing of strings through various exercises.

Chapter 5: Python offers lists, sets, and dictionaries by default. For everyday programming, a proficient use of all three containers is of great advantage, and you’ll get training through the exercises.

Chapter 6: Arrays form basic building blocks in many programming languages. In Python, lists are more common. Regarding performance and memory consumption, arrays have advantages, which is reason enough to take a closer look at the whole thing in this chapter.

Chapter 7: Chapter 3 covered the topic of recursion in an introductory manner. This chapter reveals more advanced aspects of recursion. You start with the optimization technique called memoization. After that, you look at backtracking as a problem-solving strategy, which is based on trial and error. Just trying out possible solutions may help keep various algorithms fairly understandable and elegant.

Chapter 8: Tree structures play an important role in computer science theory and practice. In many application contexts, trees can be used profitably. This is the case, for example, for the administration of a file system, the representation of a project with subprojects and tasks, or a book with chapters, subchapters, and sections.

Chapter 9: Searching and sorting are two elementary topics in computer science in the area of algorithms and data structures. The Python standard library implements both of them and thus does the work for you. However, it is also worth looking behind the scenes, for example, at different sorting methods and their specific strengths and weaknesses.

Chapter 10: In this chapter, I summarize the book and give an outlook on supplementary literature. To expand your skills, besides the training in programming, it is recommended to study further books. A selection of helpful titles closes the main part of this book.

Appendix A: Unit tests have proven to be useful for testing smaller modules. Many of the solutions created in this book are tested with unit tests using pytest. This appendix provides an introduction to the topic.

Appendix B: This appendix describes decorators. They allow elegant realizations of cross-cutting functionality to be done transparently (i. e., without extensions in the implementation of a function itself). For example, decorators can be used for parameter checks and for memoization, an advanced recursion topic.

Appendix C: In this book, I sometimes estimate the running time behavior and classify the complexity of algorithms. This appendix presents essentials about it.

Appendix D: This appendix presents some of the enhancements coming with the current Python 3.10 that may be relevant to you.

Conventions and Executable Programs

Fonts Used

Throughout the text, the following conventions are applied concerning fonts:
  • Normal text appears in the present font.

  • Important text passages are marked italic or italic and bold.

  • Sourcecode listings are written in this font to clarify that this text is a part of a Python program. Also, classes, methods, function, and parameters are displayed in this font.

Abbreviations Used

In the book, I use the abbreviations shown in Table 0-2. Other abbreviations are listed in parentheses in the running text after their first definition and subsequently used as needed.
Table 0-2

Abbreviations

Abbreviation

Meaning

API

Application programming interface

ASCII

American Standard Code for Information Interchange

(G)UI

(Graphical) user interface

IDE

Integrated development environment

Python Version Used

This book was initially developed and tested with Python 3.9.6 but rechecked with the new Python 3.10, which was released in October 2021 and is briefly covered in Appendix D. Many of the solutions should also run in Python 2.7 with minimal adjustments. However, I have only randomly checked this. In general, it makes sense to use the more modern Python 3 for new projects.

Download, Source Code, and Executables

The source code of the examples is available at www.apress.com/python-challenges.

There is a PyCharm project1 integrated. Because this is a hands-on book, many of the programs are executable—it is possible to run them in the IDE or as a unit test.

However, many code snippets are great to try out in the Python command line interpreter. To ensure this, functions that have already been developed are shown again at suitable places.

Some examples use special libraries that must be installed up front, like numpy, pytest, and others, as follows:2
pip install pytest
pip install numpy

Please consult the installation instructions provided on the download site for further information.

Acknowledgments (English Book)

First of all, I am very grateful to all the people mentioned below in the acknowledgments section for the German version of this book. Making this English version more than a dream and realizing it was possible due to the effort of Steve Anglin of APress. He organized a lot to finalize the contract and all the nitty-gritty details around publishing rights. Additionally, Mark Powers was a great help by offering information on the process and many other things around finalizing the manuscript. Guys, my warm thanks go to you.

Acknowledgments (German Book)

Writing a technical book is a beautiful but laborious and tedious task. You can hardly do it on your own. Therefore, I would like to thank those who have directly or indirectly contributed to the book’s emergence. In particular, I benefited from a strong team of proofreaders during the preparation of the manuscript. It is helpful to learn from different perspectives and experiences.

Many thanks to Martin Stypinski for various valuable hints and suggestions. Also, I want to thank Jean-Claude Brantschen for his practical proposals. You have Pythonified me even more :-) Multiple comments by Rainer Grimm and Tobias Overkamp around Python and elegant solutions have further improved the book. Finally, as with many of my books, Michael Kulla critically reviewed this Python version. Many thanks to all of them!

Since this book was written based on the Java version, the acknowledgments in Java Challenge are repeated below:

First of all, I would like to thank Michael Kulla, who is well known as a trainer for Java SE and Java EE, for his multiple, thorough reviews of many chapters, the well-founded comments, and great effort. I am also very grateful to Prof. Dr. Dominik Gruntz for a multitude of suggestions for improvements. Besides, I received one or the other helpful suggestions from Jean-Claude Brantschen, Prof. Dr. Carsten Kern, and Christian Heitzmann. Once again, Ralph Willenborg read it very carefully and found several typing errors. Many thanks for that!

Thanks also go to the team at dpunkt.verlag (Dr. Michael Barabas, Anja Weimer, and Veronika Schnabel) for great cooperation. Also, I would like to thank Torsten Horn for his sound professional review and Ursula Zimpfer for her eagle eyes in copy editing.

Finally, I would like to thank my wife, Lilija, for her understanding and support, especially for several nudges to get on the bike and go for a ride instead of just working on the book.

Suggestions and Criticism

Although great care has been taken and the text was proofread several times, misunderstandable formulations or even errors can unfortunately not be completely excluded. If any of these should be noticeable to you, please do not hesitate to let me know. I am also happy to receive suggestions or ideas for improvement. Please contact me by mail at [email protected].

Zurich, April 2022

Michael Inden

Table of Contents
Part I: Fundamentals15
Part II: More Advanced and Tricky Topics381
About the Author
Michael Inden
is an Oracle-certified Java developer with over 20 years of professional experience designing complex software systems for international companies, where he has worked in various roles such as SW developer, SW architect, consultant, team leader, CTO, head of academy, and trainer. After being a freelancer for more than a year, he is currently working as a Head of Development.

His special interests are creating high-quality applications with ergonomic GUIs, developing and solving programming puzzles, and coaching. He likes to pass on his knowledge and has led various courses and talks, both internally and externally, as well as at conferences such as JAX/W-JAX, JAX London, and Oracle Code One.

He is also an author of technical books. His German books Der Weg zum Java-Profi, Java Challenge, and Python Challenge are all published by dpunkt.verlag.

 
About the Technical Reviewers
Aravind Medamoni

is an experienced software developer. He works as a freelance mobile application developer. He has proficiency in Java, Kotlin, Flutter, Dart, PHP, JavaScript, Nodejs, MongoDB, and SQL. He worked as Tech Lead at OpenStackDC for one year as a backend and Android developer. Aravind has trained many students to start their career in the software domain. He has won a national level Hackathon.

 
Charles Bell

conducts research in emerging technologies. He is a member of the Oracle MySQL development team and is a principal developer for the MySQL cloud services team. He lives in a small town in rural Virginia with his loving wife. He received his Doctor of Philosophy in Engineering from Virginia Commonwealth University in 2005. Dr. Bell is an expert in the database field and has extensive knowledge and experience in software development and systems engineering. His research interests include 3D printers, microcontrollers, three-dimensional printing, database systems, software engineering, and sensor networks. He spends his limited free time as a practicing maker focusing on microcontroller projects and refinement of three-dimensional printers.

 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset