100% found this document useful (1 vote)
12 views47 pages

Functional Python Programming: Use a functional approach to write succinct, expressive, and efficient Python code, 3rd Edition Lott instant download

The document is a promotional text for various Python programming books, including 'Functional Python Programming' by Steven F. Lott, which emphasizes a functional approach to writing efficient Python code. It highlights the versatility of Python and its functional programming capabilities, making it suitable for both beginners and experienced programmers. The document also includes links to download the books and mentions the author's background and contributions to the field.

Uploaded by

dseqxiutw116
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
12 views47 pages

Functional Python Programming: Use a functional approach to write succinct, expressive, and efficient Python code, 3rd Edition Lott instant download

The document is a promotional text for various Python programming books, including 'Functional Python Programming' by Steven F. Lott, which emphasizes a functional approach to writing efficient Python code. It highlights the versatility of Python and its functional programming capabilities, making it suitable for both beginners and experienced programmers. The document also includes links to download the books and mentions the author's background and contributions to the field.

Uploaded by

dseqxiutw116
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Functional Python Programming: Use a functional

approach to write succinct, expressive, and


efficient Python code, 3rd Edition Lott download

https://textbookfull.com/product/functional-python-programming-
use-a-functional-approach-to-write-succinct-expressive-and-
efficient-python-code-3rd-edition-lott/

Download full version ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-
loucas/

Learn Python Programming A beginner s guide to learning


the fundamentals of Python language to write efficient
high quality code Romano

https://textbookfull.com/product/learn-python-programming-a-
beginner-s-guide-to-learning-the-fundamentals-of-python-language-
to-write-efficient-high-quality-code-romano/

Functional Python Programming Discover the power of


functional programming generator functions lazy
evaluation the built in itertools library and monads
2nd Edition Steven F. Lott
https://textbookfull.com/product/functional-python-programming-
discover-the-power-of-functional-programming-generator-functions-
lazy-evaluation-the-built-in-itertools-library-and-monads-2nd-
edition-steven-f-lott/

Functional Programming in C#: How to write better C#


code 1st Edition Enrico Buonanno

https://textbookfull.com/product/functional-programming-in-c-how-
to-write-better-c-code-1st-edition-enrico-buonanno/
Function Python programming discover the power of
functional programming generator functions lazy
evaluation the built in itertools library and monads
Second Edition Lott
https://textbookfull.com/product/function-python-programming-
discover-the-power-of-functional-programming-generator-functions-
lazy-evaluation-the-built-in-itertools-library-and-monads-second-
edition-lott/

A Functional Approach to Java: Augmenting Object-


Oriented Java Code with Functional Principles 1st
Edition Ben Weidig

https://textbookfull.com/product/a-functional-approach-to-java-
augmenting-object-oriented-java-code-with-functional-
principles-1st-edition-ben-weidig/

Python Projects for Beginners: A Ten-Week Bootcamp


Approach to Python Programming Milliken

https://textbookfull.com/product/python-projects-for-beginners-a-
ten-week-bootcamp-approach-to-python-programming-milliken/

Teach Your Kids to Code A Parent Friendly Guide to


Python Programming 1st Edition Bryson Payne

https://textbookfull.com/product/teach-your-kids-to-code-a-
parent-friendly-guide-to-python-programming-1st-edition-bryson-
payne/

Effective Python 90 Specific Ways to Write Better


Python 2nd Edition Brett Slatkin

https://textbookfull.com/product/effective-python-90-specific-
ways-to-write-better-python-2nd-edition-brett-slatkin/
Functional Python
Programming
Third Edition

Use a functional approach to write succinct,


expressive, and efficient Python code

Steven F. Lott

BIRMINGHAM—MUMBAI
“Python” and the Python logo are trademarks of the Python Software Foundation.
Functional Python Programming
Third Edition
Copyright © 2022 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.

Senior Publishing Product Manager: Denim Pinto


Acquisition Editor – Peer Reviews: Gaurav Gavas
Project Editor: Parvathy Nair
Development Editor: Lucy Wan
Copy Editor: Safis Editing
Technical Editor: Karan Sonawane
Indexer: Hemangini Bari
Proofreader: Safis Editing
Presentation Designer: Sandip Tadge

First published: January 2015


Second edition: April 2018
Third edition: December 2022

Production reference: 1221222


Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80323-257-7
www.packt.com
Foreword

Python is an incredibly versatile language that offers a lot of perks for just about every
group. For the object-oriented programming fans, it has classes and inheritance. When
we talk about functional programming, it has functions as a first-class type, higher-order
functions such as map and reduce, and a handy syntax for comprehensions and generators.
Perhaps best of all, it doesn’t force any of those on the user – it’s still totally OK to write a
script in Python without a single class or function and not feel guilty about it.

Thinking in terms of functional programming, having in mind the goals of minimizing state
and side effects, writing pure functions, reducing intermediary data, and what depends on
what else will also allow you to see your code under a new light. It’ll also allow you to
write more compact, performant, testable, and maintainable code, where instead of writing
a program to solve your problem, you “write the language up”, adding new functions to
it until expressing the solution you designed is simple and straightforward. This is an
extremely powerful mind shift – and an exercise worth doing. It’s a bit like learning a
new language, such as Lisp or Forth (or German, or Irish), but without having to leave the
comfort of your Python environment.

Not being a pure functional language has its costs, however. Python lacks many features
functional languages can use to provide better memory efficiency and speed. Python’s
strongest point remains its accessibility – you can fire up your Python interpreter and
start playing with the examples in this book right away. This interactive approach allows
exploratory programming, where you test ideas easily, and only later need to incorporate
them into a more complex program (or not – like I said, it’s totally OK to write a simple
script).

This book is intended for people already familiar with Python. You don’t need to know
much about functional programming – the book will guide you through many common
approaches, techniques, and patterns used in functional programming and how they can
be best expressed in Python. Think of this book as an introduction – it’ll give you the basic
tools to see, think, and express your ideas in functional terms using Python.

Ricardo Bánffy

Software Engineer, Architect, Evangelist, and Passionate Pythonista


Contributors

About the author


Steven F. Lott has been programming since computers were large, expensive, and rare.
Working for decades in high tech has given him exposure to a lot of ideas and techniques;
some are bad, but most are useful and helpful to others.

Steven has been working with Python since the ‘90s, building a variety of tools and
applications. He’s written a number of titles for Packt Publishing, include Mastering
Object-Oriented Python, Modern Python Cookbook, and Functional Python Programming.

He’s a technomad, and lives on a boat that’s usually located on the east coast of the US. He
tries to live by the words, “Don’t come home until you have a story.”
About the reviewers
Alex Martelli is a Fellow of the Python Software Foundation, a winner of the Frank
Willison Memorial Award for contributions to the Python community, and a top-page
reputation hog on Stack Overflow. He spent 8 years with IBM Research, then 13 years
at Think3 Inc., followed by 4 years as a consultant, and lately 17 years at Google. He
has taught programming languages, development methods, and numerical computing at
Ferrara University and other venues.

Books he has authored or co-authored include two editions of Python Cookbook, four
editions of Python in a Nutshell, and a chapter in Beautiful Teams. Dozens of his interviews
and tech talks at conferences are available on YouTube. Alex’s proudest achievement are
the articles that appeared in Bridge World (January and February 2000), which were hailed
as giant steps towards solving issues that had haunted contract bridge theoreticians for
decades, and still get quoted in current bridge-theoretical literature.

Tiago Antao has a BEng in Informatics and a PhD in Life Sciences. He works in the
Big Data space, analyzing very large datasets and implementing complex data processing
algorithms. He leverages Python with all its libraries to carry out scientific computing and
data engineering tasks. He also uses low-level programming languages like C, C++, and
Rust to optimize critical parts of algorithms. Tiago develops on an infrastructure based on
AWS, but has used on-premises computing and scientific clusters for most of his career.

While he currently works in industry, he also has exposure to the academic side of scientific
computing, with two data analysis postdocs at the universities of Cambridge and Oxford,
and a research scientist position at the University of Montana, where he set up, from
scratch, the scientific computing infrastructure for the analysis of biological data.

He is one of the co-authors of Biopython, a major bioinformatics package written in Python.


He wrote Bioinformatics with Python Cookbook, which is on its third edition. He has also
authored and co-authored many high-impact scientific articles in the field of bioinformatics.
Join our community Discord space
Join our Python Discord workspace to discuss and know more about the book:
https://packt.link/dHrHU
Table of Contents

Preface xxi

Chapter 1: Understanding Functional Programming 1

The functional style of programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3


Comparing and contrasting procedural and functional styles . . . . . . . . . . . . . . . . . . . . . 4
Using the functional paradigm • 5
Using a functional hybrid • 8
The stack of turtles • 9
A classic example of functional programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Exploratory data analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Convert an imperative algorithm to functional code • 18
Convert step-wise computation to functional code • 18
Revise the sqrt() function • 20
Data cleansing steps • 20
(Advanced) Optimize this functional code • 23

Chapter 2: Introducing Essential Functional Concepts 25

Functions as first-class objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26


Pure functions • 27
Higher-order functions • 29
Immutable data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Strict and non-strict evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Lazy and eager evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Recursion instead of an explicit loop state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Functional type systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Familiar territory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Learning some advanced concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Apply map() to a sequence of values • 44
Function vs. lambda design question • 45
Optimize a recursion • 45

Chapter 3: Functions, Iterators, and Generators 47

Writing pure functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


Functions as first-class objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Using strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Using tuples and named tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Using generator expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Exploring the limitations of generators • 63
Combining generator expressions • 65
Cleaning raw data with generator functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Applying generators to built-in collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Generators for lists, dicts, and sets • 69
Using stateful mappings • 73
Using the bisect module to create a mapping • 76
Using stateful sets • 78
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Rewrite the some_function() function • 79
Alternative Mersenne class definition • 80
Alternative algorithm implementations • 81
Map and filter • 82
Dictionary comprehension • 82
Raw data cleanup • 82

Chapter 4: Working with Collections 85

An overview of function varieties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86


Working with iterables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Parsing an XML file • 89
Parsing a file at a higher level • 92
Pairing up items from a sequence • 95
Using the iter() function explicitly • 98
Extending an iteration • 100
Applying generator expressions to scalar functions • 104
Using any() and all() as reductions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Using len() and sum() on collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Using sums and counts for statistics • 111
Using zip() to structure and flatten sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Unzipping a zipped sequence • 117
Flattening sequences • 118
Structuring flat sequences • 120
Structuring flat sequences – an alternative approach • 124
Using sorted() and reversed() to change the order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Using enumerate() to include a sequence number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Palindromic numbers • 129
Hands of cards • 130
Replace legs() with pairwise() • 131
Expand legs() to include processing • 132

Chapter 5: Higher-Order Functions 133

Using max() and min() to find extrema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134


Using Python lambda forms • 138
Lambdas and the lambda calculus • 140
Using the map() function to apply a function to a collection . . . . . . . . . . . . . . . . . . . . . . 141
Working with lambda forms and map() • 143
Using map() with multiple sequences • 144
Using the filter() function to pass or reject data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Using filter() to identify outliers • 149
The iter() function with a sentinel value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Using sorted() to put data in order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Overview of writing higher-order functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Writing higher-order mappings and filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Unwrapping data while mapping • 156
Wrapping additional data while mapping • 159
Flattening data while mapping • 161
Structuring data while filtering • 164
Building higher-order functions with callables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Assuring good functional design • 168
Review of some design patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Classification of state • 173
Classification of state, Part II • 174
Optimizing a file parser • 175
Chapter 6: Recursions and Reductions 177

Simple numerical recursions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178


Implementing manual tail-call optimization • 180
Leaving recursion in place • 181
Handling difficult tail-call optimization • 182
Processing collections through recursion • 184
Tail-call optimization for collections • 185
Using the assignment (sometimes called the “walrus”) operator in recursions • 187
Reductions and folding a collection from many items to one . . . . . . . . . . . . . . . . . . . . . . 188
Tail-call optimization using deques • 190
Group-by reduction from many items to fewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Building a mapping with Counter • 195
Building a mapping by sorting • 196
Grouping or partitioning data by key values • 198
Writing more general group-by reductions • 203
Writing higher-order reductions • 205
Writing file parsers • 207
Parsing CSV files • 211
Parsing plain text files with headers • 214
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Multiple recursion and caching • 219
Refactor the all_print() function • 219
Parsing CSV files • 219
Classification of state, Part III • 220
Diesel engine data • 220

Chapter 7: Complex Stateless Objects 223

Using tuples to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224


Using NamedTuple to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Using frozen dataclasses to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Complicated object initialization and property computations . . . . . . . . . . . . . . . . . . . . . 237
Using pyrsistent to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Avoiding stateful classes by using families of tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
Computing Spearman’s rank-order correlation • 252
Polymorphism and type pattern matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Frozen dictionaries • 263
Dictionary-like sequences • 264
Revise the rank_xy() function to use native types • 265
Revise the rank_corr() function • 265
Revise the legs() function to use pyrsistent • 265

Chapter 8: The Itertools Module 267

Working with the infinite iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269


Counting with count() • 269
Counting with float arguments • 271
Re-iterating a cycle with cycle() • 275
Using cycle() for data sampling • 276
Repeating a single value with repeat() • 278
Using the finite iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Assigning numbers with enumerate() • 281
Running totals with accumulate() • 284
Combining iterators with chain() • 286
Partitioning an iterator with groupby() • 287
Merging iterables with zip_longest() and zip() • 290
Creating pairs with pairwise()) • 290
Filtering with compress() • 291
Picking subsets with islice() • 293
Stateful filtering with dropwhile() and takewhile() • 295
Two approaches to filtering with filterfalse() and filter() • 297
Applying a function to data via starmap() and map() • 298
Cloning iterators with tee() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
The itertools recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Optimize the find_first() function • 306
Compare Chapter 4 with the itertools.pairwise() recipe • 306
Compare Chapter 4 with itertools.tee() recipe • 307
Splitting a dataset for training and testing purposes • 307
Rank ordering • 307

Chapter 9: Itertools for Combinatorics – Permutations and Combina-


tions 309

Enumerating the Cartesian product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310


Reducing a product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Computing distances • 314
Getting all pixels and all colors • 318
Performance improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Rearranging the problem • 323
Combining two transformations • 324
Permuting a collection of values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Generating all combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Combinations with replacement • 333
Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Alternative distance computations • 336
Another Random Scribd Document
with Unrelated Content
si no (de pesar me aflijo),
ni te has de llamar mi hijo,
ni yo te he de conocer.
Enrico. Bueno está, padre querido;
que más el alma ha sentido
(buen testigo de ello es Dios)
el pesar que tenéis vos
que el mal que espero afligido.
Confieso, padre, que erré;
pero yo confesaré
mis pecados, y después
besaré a todos los pies,
para mostraros mi fe.
Basta que vos lo mandéis,
padre mío de mis ojos.
Anareto. Pues ya mi hijo seréis.
Enrico. No os quisiera dar enojos.
Anareto. Vamos, porque os confeséis.
Enrico. ¡Oh cuánto siento el dejaros!
Anareto. ¡Oh cuánto siento el perderos!
Enrico. ¡Ay, ojos! Espejos claros,
antes hermosos luceros,
pero ya de luz avaros.
Anareto. Vamos, hijo.
Enrico. A morir voy:
todo el valor he perdido.
Anareto. Sin juicio y sin alma estoy.
Enrico. Aguardad, padre querido.
Anareto. ¡Qué desdichado que soy!
Enrico. Señor piadoso y eterno,
que en vuestro alcázar pisáis
cándidos montes de estrellas,
mi petición escuchad.
Yo he sido el hombre más malo
que la luz llegó a alcanzar
de este mundo, el que os ha hecho
más que arenas tiene el mar
ofensas; mas, Señor mío,
mayor es vuestra piedad.
Vos, por redimir el mundo,
por el pecado de Adán,
en una cruz os pusisteis;
pues merezca yo alcanzar
una gota solamente
de aquella sangre real.
· · · · · · · · · · · · · · ·
¡Gran Señor, misericordia!
No puedo deciros más.
Anareto. ¡Que esto llegue a ver un padre!
Enrico. (Para sí.) La enigma he entendido ya
de la voz y de la sombra:
la voz era angelical,
y la sombra era el demonio.
Anareto. Vamos, hijo.
Enrico. ¿Quién oirá
ese nombre, que no haga
de sus dos ojos un mar?
No os apartéis, padre mío,
hasta que hayan de expirar
mis ojos.
Anareto. No hayas miedo.
Dios te dé favor.
Enrico. Sí hará,
que es mar de misericordia,
aunque yo voy muerto ya.
Anareto. Ten valor.
Enrico. En Dios confío.
Vamos, padre, donde están
los que han de quitarme el ser
que vos me pudisteis dar.

ESCENA XVI
(Paulo en el monte.)

Paulo. Cansado de correr vengo


por este monte intrincado;
atrás la gente he dejado
que a ajena costa mantengo.
Al pie deste sauce verde
quiero un poco descansar,
por ver si acaso el pesar
de mi memoria se pierde.
Tú, fuente, que murmurando
vas entre guijas corriendo,
en tu fugitivo estruendo
plantas y aves alegrando,
dame algún contento ahora,
infunde al alma alegría
con esa corriente fría
y con esa voz sonora.
Lisonjeros pajarillos
que no entendidos cantáis,
y holgazanes gorjeáis
entre juncos y tomillos;
dad con picos sonorosos
y con acentos süaves
gloria a mis pesares graves
y sucesos lastimosos.
En este verde tapete,
jironado de cristal,
quiero divertir mi mal
que mi triste fin promete.

(Echase a dormir y sale el Pastor con la corona, deshaciéndola.)

ESCENAS XVII y XVIII


Pastor. Selvas intrincadas,
verdes alamedas,
a quien de esperanzas
adorna Amaltea;
fuentes que corréis
murmurando apriesa
por menudas guijas,
por blandas arenas;
ya vuelvo otra vez
a mirar la selva,
a pisar los valles
que tanto me cuestan.
Yo soy el pastor
que en vuestras riberas
guardé un tiempo alegre
cándidas ovejas.
Sus blancos vellones
entre verdes felpas
jirones de plata
a los ojos eran.
Era yo envidiado,
por ser guarda buena,
de muchos zagales
que ocupan la selva;
y mi mayoral,
que en ajena tierra
vive, me tenía
voluntad inmensa,
porque le llevaba,
cuando quería verlas,
las ovejas blancas
como nieve en pellas.
Pero desde el día
que una, la más buena,
huyó del rebaño,
lágrimas me anegan.
Mis contentos todos
convertí en tristezas,
mis placeres vivos
en memorias muertas.
Cantaba en los valles
canciones y letras;
mas ya en triste llanto
funestas endechas.
Por tenerla amor,
en esta floresta
aquesta guirnalda
comencé a tejerla.
Mas no la gozó;
que engañada y necia
dejó a quien la amaba
con mayor firmeza.
Y pues no la quiso
fuerza es que ya vuelva,
por venganza justa,
hoy a deshacerla.
Paulo. Pastor, que otra vez
te vi en esta sierra,
si no muy alegre,
no con tal tristeza,
el verte me admira.
Pastor. ¡Ay perdida oveja!
¡De qué gloria huyes,
y a qué mal te allegas!
Paulo. ¿No es esa guirnalda
la que en las florestas
entonces tejías
con gran diligencia?
Pastor. Esta misma es;
mas la oveja, necia,
no quiere volver
al bien que le espera,
y ansí la deshago.
Paulo. Si acaso volviera,
zagalejo amigo,
¿no la recibieras?
Pastor. Enojado estoy,
mas la gran clemencia
de mi mayoral
dice que aunque vuelvan,
si antes fueron blancas,
al rebaño negras,
que las dé mis brazos
y, sin extrañeza,
requiebros las diga
y palabras tiernas.
Paulo. Pues es superior,
fuerza es que obedezcas.
Pastor. Yo obedeceré;
pero no quiere ella
volver a mis voces,
en sus vicios ciega.
Ya de aquestos montes
en las altas peñas
la llamé con silbos
y avisé con señas.
Ya por los jarales,
por incultas selvas,
la anduve a buscar:
¡qué de ello me cuesta!
Ya traigo las plantas
de jaras diversas,
y agudos espinos
rotas y sangrientas.
No puedo hacer más.
Paulo. En lágrimas tiernas
baña el pastorcillo
las mejillas bellas.
Pues te desconoce,
olvídate de ella
y no llores más.
Pastor. Que lo haga es fuerza.
Volved, bellas flores,
a cubrir la tierra,
pues que no fué digna
de vuestra belleza.
Veamos si allá
con la tierra nueva
la pondrán guirnalda
tan rica y tan bella.
Quedaos, montes míos,
desiertos y selvas,
adiós, porque voy
con la triste nueva
a mi mayoral;
y cuando lo sepa
(aunque ya lo sabe)
sentirá su mengua,
no la ofensa suya,
aunque es tanta ofensa.
Lleno voy a verle
de miedo y vergüenza:
lo que ha de decirme
fuerza es que lo sienta.
Diráme: “Zagal,
¿ansí las ovejas
que yo os encomiendo
guardáis?” ¡Triste pena!
Yo responderé...
No hallaré respuesta,
si no es que mi llanto
la respuesta sea. (Vase.)
Paulo. La historia parece
de mi vida aquesta.
De este pastorcillo
no sé lo que sienta;
que tales palabras
fuerza es que prometan
oscuras enigmas.
Mas ¿qué luz es esta
que a la luz del sol
sus rayos se afrentan?

(Con la música suben dos ángeles el alma de Enrico por una


apariencia, y prosigue Paulo:)

Música celeste
en los aires suena,
y, a lo que diviso,
dos ángeles llevan
una alma gloriosa
a la excelsa esfera,
¡Dichosa mil veces,
alma, pues hoy llegas
donde tus trabajos
fin alegre tengan!
Grutas y plantas agrestes,
a quien el hielo corrompe,
¿no veis cómo el cielo rompe
ya sus cortinas celestes?
Ya rompiendo densas nubes
y esos transparentes velos,
alma, a gozar de los cielos
feliz y gloriosa subes.
Ya vas a gozar la palma
que la ventura te ofrece:
¡triste del que no merece
lo que tú mereces, alma!
Muerte me han dado villanos.
ESCENA XIX

(Sale Galván.)

Galván. Advierte, Paulo famoso,


que por el monte ha bajado
un escuadrón concertado,
de gente y armas copioso,
que viene sólo a prendernos.
Si no pretendes morir,
solamente, Pablo, huír
es lo que puede valernos.

[Paulo y Galván se disponen a hacerles frente.]

ESCENAS XX y XXI
[El Juez y los villanos armados persiguen a Paulo, el cual, herido, cae
rodando por las peñas. Sale Pedrisco.]

Pedrisco. ¿Cómo estás ansí?


Paulo. ¡Ay de mí!
Muerte me han dado villanos.
Pero ya que estoy muriendo,
saber de ti, amigo, aguardo
qué hay del suceso de Enrico.
Pedrisco. En la plaza le ahorcaron
de Nápoles.
Paulo. Pues ansí,
¿quién duda que condenado
estará al Infierno ya?
Pedrisco. Mira lo que dices, Paulo;
que murió cristianamente,
confesado y comulgado
y abrazado con un Cristo,
en cuya vista enclavados
los ojos, pidió perdón
y misericordia, dando
tierno llanto a sus mejillas,
y a los presentes espanto.
Fuera de aqueso, en muriendo
resonó en los aires claros
una música divina;
y para mayor milagro
y evidencia más notoria,
dos paraninfos alados
se vieron patentemente,
que llevaban entre ambos
el alma de Enrico al Cielo.
Paulo. ¡A Enrico, el hombre más malo
que crió naturaleza!
Pedrisco. ¿De aquesto te espantas, Paulo,
cuando es tan piadoso Dios?
Paulo. Pedrisco, eso ha sido engaño:
otra alma fué la que vieron,
no la de Enrico.
Pedrisco. ¡Dios santo,
reducidle vos!
Paulo. Yo muero.
Pedrisco. Mira que Enrico gozando
está de Dios: pide a Dios
perdón.
Paulo. ¿Y cómo ha de darlo
a un hombre que le ha ofendido
como yo?
Pedrisco. ¿Qué estás dudando?
¿No perdonó a Enrico?
Paulo. Dios
es piadoso...
Pedrisco. Es muy claro.
Paulo. Pero no con tales hombres.
Ya muero, llega tus brazos.
Pedrisco. Procura tener su fin.
Paulo. Esa palabra me ha dado
Dios; si Enrico se salvó,
también yo salvarme aguardo. (Muere.)

ESCENA XXII
[Los villanos rodean el cadáver de Paulo. Descúbrese fuego, y Paulo
lleno de llamas.]

Paulo. Si a Paulo buscando vais


bien podéis ya ver a Paulo
ceñido el cuerpo de fuego
y de culebras cercado.
No doy la culpa a ninguno
de los tormentos que paso;
sólo a mí me doy la culpa,
pues fuí causa de mi daño.
Pedí a Dios que me dijese
el fin que tendría, en llegando
de mi vida el postrer día:
ofendíle, caso es llano;
y como la ofensa vió
de las almas el contrario,
incitóme con querer
perseguirme con engaños.
Forma de un ángel tomó,
y engañóme; que a ser sabio,
con su engaño me salvara;
pero fuí desconfiado
de la gran piedad de Dios,
que hoy a su juicio llegando,
me dijo: “Baja, maldito
de mi padre, al centro airado
de los oscuros abismos,
adonde has de estar penando.”
¡Malditos mis padres sean
mil veces, pues me engendraron!
¡Y yo también sea maldito,
pues que fuí desconfiado!

(Húndese por el tablado, y sale fuego.)

Juez. Misterios son del Señor.


Galván. ¡Pobre y desdichado Paulo!
Pedrisco. ¡Y venturoso de Enrico,
que de Dios está gozando!
Juez. Por que toméis escarmiento,
no pretendo castigaros;
libertad doy a los dos.
· · · · · · · · · · · · · · ·
No más: a Nápoles vamos
a contar este suceso.
Pedrisco. Y porque éste es tan arduo
y difícil de creer,
siendo verdadero el caso,
vaya el que fuese curioso
(porque sin ser escribano
dé fe de ello), a Belarmino;
y si no, más dilatado
en la vida de los padres
podrá fácilmente hallarlo.
Y con aquesto da fin
El Mayor Desconfiado,
y pena y gloria trocadas.
El cielo os guarde mil años.
LA PRUDENCIA
EN LA MUJER
La escena es en Toledo, León y otros puntos.

JORNADA PRIMERA
Sala en el alcázar de Toledo.

ESCENA I
El infante don Enrique, el infante don Juan, don Diego de Haro.

D. Enrique. Será la viuda reina esposa mía,


y daráme Castilla su corona.
O España volverá a llorar el día
que al conde don Julián traidor pregona.
¿Con quién puede casar doña María,
si de valor y hazañas se aficiona,
como conmigo, sin hacerme agravio?
Enrique soy; mi hermano, Alfonso el Sabio.
Don Juan. La Reina y la corona pertenece
a don Juan, de don Sancho el Bravo hermano:
mientras el niño rey Fernando crece,
yo he de regir el cetro castellano.
Pruebe, si algún traidor se desvanece,
a quitarme la espada de la mano;
que mientras gobernare su cuchilla,
sólo don Juan gobernará a Castilla.
Don Diego. Está vivo don Diego López de Haro,
que vuestras pretensiones tendrá a raya,
y dando al tierno Rey seguro amparo,
casará con su madre; y cuando vaya
algún traidor contra el derecho claro
que defiendo, señor soy de Vizcaya:
minas son las entrañas de sus cerros,
que hierro dan con que castigue yerros.
· · · · · · · · · · · · · · ·
D. Enrique. Vos, caballero pobre, cuyo Estado
cuatro silvestres son, toscos y rudos,
montes de hierro, para el vil arado,
hidalgos por Adán, como él desnudos,
adonde en vez de Baco sazonado,
manzanos llenos de groseros ñudos
dan mosto insulso, siendo silla rica,
en vez de trono, el árbol de Garnica,
¡Intentáis de la Reina ser consorte,
sabiendo que pretende don Enrique
casar con ella, ennoblecer su corte
y que por rey España le publique!
Don Juan. Cuando su intento loco no reporte
y edificios quiméricos fabrique,
mientras el reino gozo y su hermosura,
se podrá desposar con su locura.
· · · · · · · · · · · · · · ·
Don Diego. Cuatro bárbaros tengo por vasallos,
a quien Roma jamás conquistar pudo,
que sin armas, sin muros, sin caballos,
libres conservan su valor desnudo.
Montes de hierro habitan, que a estimallos,
valiente en obras, y en palabras mudo,
a sus miras guardárades decoro,
pues por su hierro España goza su oro.
Si su aspereza tosca no cultiva
aranzadas a Baco, hazas a Ceres,
es porque Venus huya, que lasciva
hipoteca en sus frutos sus placeres.
La encina hercúlea, no la blanda oliva,
teje coronas para sus mujeres,
que aunque diversas en el sexo y nombres
en guerra y paz se igualan a sus hombres.
El árbol de Garnica ha conservado
sin que tiranos le hayan deshojado,
la antigüedad que ilustra a sus señores,
ni haga sombra a confesos ni a traidores.
En su tronco, no en silla real sentado,
nobles, puesto que pobres, electores
tan sólo un señor juran, cuyas leyes
libres conservan de tiranos reyes.
Suyo lo soy ahora, y del Rey tío,
leal en defendelle, y pretendiente
de su madre, a quien dar la mano fío,
aunque la deslealtad su ofensa intente.
Infantes, si a la lengua iguala el brío,
intérprete es la espada del valiente;
vizcaíno es el hierro que os encargo,
corto en palabras, pero en obras largo.

¡Ser mis esposos queréis...!

ESCENA II
La reina doña María, de viuda; don Enrique, don Juan, don Diego.
Reina. ¿Qué es aquesto, caballeros,
defensa y valor de España,
espejos de lealtad,
gloria y luz de las hazañas?
Cuando muerto el rey don Sancho,
mi esposo y señor, las galas
truecan León y Castilla
por jergas negras y bastas;
cuando el moro granadino
moriscos pendones saca
contra el reino sin cabeza,
y las fronteras asalta
por la lealtad defendidas,
y abriéndose su Granada,
por las católicas vegas
blasfemos granos derrama;
¡en civiles competencias,
pretensiones mal fundadas,
bandos que la paz destruyen,
ambiciosas arrogancias,
cubrís de temor los reinos,
tiranizáis vuestra patria,
dando en vuestra ofensa lenguas
a las naciones contrarias!
¡Ser mis esposos queréis,
y como mujer ganada
en buena guerra, al derecho
me reducís de las armas!
¡Casarme intentáis por fuerza,
e ilustrándoos sangre hidalga,
la libertad de mi gusto
hacéis pechera y villana!
· · · · · · · · · · · · · · ·
Os engañáis, caballeros,
que no está desamparada
de estos reinos la corona,
ni del Rey la tierna infancia.
Don Sancho el Bravo aún no es muerto;
que como me entregó el alma,
en mi pecho se conservan
fieles y amorosas llamas.
Si, porque es el Rey un niño
y una mujer quien le ampara,
os atrevéis ambiciosos
contra la fe castellana,
tres almas viven en mí:
la de Sancho, que Dios haya;
la de mi hijo, que habita
en mis maternas entrañas,
y la mía, en quien se suman
esotras dos: ved si basta
a la defensa de un reino
una mujer con tres almas.
Intentad guerras civiles,
sacad gentes a campaña,
vuestra deslealtad pregonen
contra vuestro Rey las cajas;
que aunque mujer, yo sabré
en vez de las tocas largas
y el negro monjil, vestirme
el arnés y la celada.
Infanta soy de León;
salgan traidores a caza
del hijo de una leona,
que el reino ha puesto en su guarda,
veréis si en vez de la aguja
sabré ejercitar la espada,
y abatir lienzos de muros
quien labra lienzos de Holanda.
· · · · · · · · · · · · · · ·

ESCENAS III a V
[Los pretendientes, al verse rechazados, reúnen sus partidarios y
alzan bandera de rebelión contra el Rey y la Regente. Don Juan busca
el apoyo de los árabes granadinos: don Enrique acude en demanda
de ayuda a su sobrino el Rey de Portugal; don Diego de Haro espera
tropas de Aragón y Navarra.
La Reina llama a sus vasallos a palacio y les presenta al niño
Fernando IV como rey legítimo de Castilla y León; pero mientras les
habla excitándoles a la lealtad, las tropas rebeldes cercan el palacio
y lo toman por asalto. La Reina y su hijo huyen precipitadamente a
León.]

ESCENAS VI a VIII
(En Valencia de Alcántara.)

[Las familias Benavides y Caravajal tienen desde antiguo profundos


resentimientos. Don Alonso Caravajal consigue el amor de doña Teresa
de Benavides y se desposa secretamente con ella. Don Juan de
Benavides se siente afrentado por esta unión y reta a don Alonso:
cuando están a punto de llegar a las manos se presenta la Reina,
fugitiva.]
ESCENA IX

Reina. Ilustres Caravajales,


Benavides excelentes,
mis deudos sois y parientes.
Blasones os honran reales:
mostrad hoy que sois leales.
Un árbol sirve de silla
a la inocencia sencilla
de vuestro Rey incapaz.

(Descubre al Rey niño encerrado en el tronco de un árbol.)

No permitáis que en agraz


os le malogre Castilla.
Como la aurora, amanece
entre la tiniebla oscura
de la traición, que procura
matárosle y le oscurece.
Si este tierno sol merece
glorias de una ilustre hazaña,
lograd el que os acompaña,
y con valor español
defended los dos un sol
que os da el oriente de España.
Benavid. ¡Oh retrato del amor,
niño Rey, humilde Alteza!
Con tu angélica belleza
se enternece mi rigor.
No tuviera yo valor
si el socorro que me pides,
a las perlas que despides
negaran mis fieles labios.
Por los tuyos sus agravios
olvidan los Benavides.
Famosos Caravajales,
treguas al enojo demos,
y para después dejemos
guerras y bandos parciales.
No salgan los desleales
con su bárbaro consejo.
A estos pies mi agravio dejo
para volverle a tomar,
que mal se podrá olvidar
el odio heredado y viejo.
Juntemos nuestros amigos
y de dos un campo hagamos;
que mientras al Rey sirvamos
no hemos de ser enemigos.
Serán los cielos testigos,
para ilustrarnos después,
de que hoy el valor leonés,
con lealtad y con amor,
el bien del Rey su señor
antepone a su interés.
Don Al. Fénix de España, nacido
para que su gloria aumente,
pájaro sois inocente,
en ese árbol como en nido.
¿Quién, mi perla, os ha escondido
desa suerte?
Rey. Hanme quitado
mi reino, y no me han dejado
aun la cuna en que nací;
y como a Herodes temí,
vengo huyendo al despoblado.
Don Pedr. No temáis del gavilán,
pájaro tierno y hermoso,
por más que intente ambicioso
hacer presa en vos don Juan.
Benavid. Todos por ti morirán,
sol de España, hasta que quedes
libre de las viles redes
de ambiciosos cazadores.
· · · · · · · · · · · · · · ·
Alto, hidalgos, a León:
muera el Infante tirano.
Y vos, ejemplo cristiano, (A la Reina.)
regidnos desde este día,
y será, pues de vos fía
el cielo una ilustre hazaña,
la Semíramis de España
la reina doña María. (Vanse.)
ESCENAS X a XII

(Sala en el palacio de León.)

[Los Infantes vencedores están gozando de su triunfo. Han decidido


repartirse el reino entre ambos: Don Juan reinará en León, y don
Enrique, en Murcia y Sevilla. Entre tanto, los Caravajales y Benavides
derrotan a las tropas de los Infantes, los cuales son sorprendidos y
presos. Custódianlos don Alonso y don Pedro Caravajal y don Juan de
Benavides, mientras esperan la sentencia que contra ellos ha de dictar
la enojada Reina.]

ESCENA XIII
(Don Luis, con una fuente de plata, y en ella un papel.)

Don Luis. La Reina ha mandado, Infantes,


que entréis en esa capilla,
donde os esperan dos padres
que vuestras almas dispongan,
porque quiere en esta tarde
mostrar a España del modo
que allanar rebeldes sabe.
Don Enr. ¿La Reina, nuestra señora,
es posible que eso mande?
¡La piadosa! ¡La clemente!
¡A dos primos! ¡A dos grandes!
¡Ah mujeres! ¡Qué bien hizo
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like