0% found this document useful (0 votes)
23 views

Mastering Python 50 Specific Tips For Writing Better Code Practical Strategies For Writing Highquality Python Code Dane Olsen instant download

The document is about 'Mastering Python: 50 Specific Tips for Writing Better Code' by Dane Olsen, which provides practical strategies for writing high-quality Python code. It covers various topics including data structures, functions, classes, concurrency, and best practices, aimed at improving coding skills for developers of all levels. The book emphasizes Pythonic thinking and includes real-world examples to illustrate the concepts discussed.

Uploaded by

krityasailh
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
0% found this document useful (0 votes)
23 views

Mastering Python 50 Specific Tips For Writing Better Code Practical Strategies For Writing Highquality Python Code Dane Olsen instant download

The document is about 'Mastering Python: 50 Specific Tips for Writing Better Code' by Dane Olsen, which provides practical strategies for writing high-quality Python code. It covers various topics including data structures, functions, classes, concurrency, and best practices, aimed at improving coding skills for developers of all levels. The book emphasizes Pythonic thinking and includes real-world examples to illustrate the concepts discussed.

Uploaded by

krityasailh
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/ 83

Mastering Python 50 Specific Tips For Writing

Better Code Practical Strategies For Writing


Highquality Python Code Dane Olsen download

https://ebookbell.com/product/mastering-python-50-specific-tips-
for-writing-better-code-practical-strategies-for-writing-
highquality-python-code-dane-olsen-53193304

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Mastering Python 50 Specific Tips For Writing Better Code Practical


Strategies For Writing Highquality Python Code Dane Olsen

https://ebookbell.com/product/mastering-python-50-specific-tips-for-
writing-better-code-practical-strategies-for-writing-highquality-
python-code-dane-olsen-232014530

Mastering Python Scripting For System Administrators Ganesh Sanjiv


Naik

https://ebookbell.com/product/mastering-python-scripting-for-system-
administrators-ganesh-sanjiv-naik-46242670

Mastering Python Networking Utilize Python Packages And Frameworks For


Network Automation Monitoring Cloud 4th Edition 4th Eric Chou

https://ebookbell.com/product/mastering-python-networking-utilize-
python-packages-and-frameworks-for-network-automation-monitoring-
cloud-4th-edition-4th-eric-chou-47552224

Mastering Python Rick Van Hattem Igor Milovanovi

https://ebookbell.com/product/mastering-python-rick-van-hattem-igor-
milovanovi-49052754
Mastering Python Design Patterns 1st Edition Sakis Kasampalis

https://ebookbell.com/product/mastering-python-design-patterns-1st-
edition-sakis-kasampalis-50950844

Mastering Python 3 Programming Ultimate Guide To Learn Python Coding


Fundamentals And Realworld Applications Subburaj Ramasamy

https://ebookbell.com/product/mastering-python-3-programming-ultimate-
guide-to-learn-python-coding-fundamentals-and-realworld-applications-
subburaj-ramasamy-58472654

Mastering Python Design Patterns Craft Essential Python Patterns By


Following Core Design Principles 3rd Edition 3rd Edition Kamon Ayeva

https://ebookbell.com/product/mastering-python-design-patterns-craft-
essential-python-patterns-by-following-core-design-principles-3rd-
edition-3rd-edition-kamon-ayeva-58477706

Mastering Python Networking Advanced Networking With Python Chou

https://ebookbell.com/product/mastering-python-networking-advanced-
networking-with-python-chou-20640390

Mastering Python For Finance 2nd Edition James Ma Weiming

https://ebookbell.com/product/mastering-python-for-finance-2nd-
edition-james-ma-weiming-22246756
Mastering Python: 50 Specific Tips
for Writing Better Code

- Dane Olsen
ISBN: 9798865196815
Ziyob Publishers.
Mastering Python: 50 Specific Tips
for Writing Better Code
Practical Strategies for Writing High-Quality Python Code

Copyright © 2023 Ziyob Publishers


All rights are reserved for this book, and no part of it may be
reproduced, stored in a retrieval system, or transmitted in any form
or by any means without prior written permission from the publisher.
The only exception is for brief quotations used in critical articles or
reviews.
While every effort has been made to ensure the accuracy of the
information presented in this book, it is provided without any
warranty, either express or implied. The author, Ziyob Publishers, and
its dealers and distributors will not be held liable for any damages,
whether direct or indirect, caused or alleged to be caused by this
book.
Ziyob Publishers has attempted to provide accurate trademark
information for all the companies and products mentioned in this book
by using capitalization. However, the accuracy of this information
cannot be guaranteed.
This book was first published in October 2023 by Ziyob Publishers,
and more information can be found at:
www.ziyob.com
Please note that the images used in this book are borrowed, and
Ziyob Publishers does not hold the copyright for them. For inquiries
about the photos, you can contact:
contact@ziyob.com
About Author:
Dane Olsen
Dane Olsen is an experienced software engineer and Python
enthusiast with over a decade of experience developing applications
across a range of industries. As a technology consultant and
educator, he has helped countless developers and businesses adopt
best practices for Python programming.
In "Mastering Python: 50 Specific Tips for Writing Better Code", Dane
distills his extensive experience into a comprehensive guide for
Python developers of all levels. With a focus on practical, real-world
examples, Dane provides insights and best practices for every stage
of the Python development process, from writing clean and efficient
code to designing effective algorithms and data structures.
Dane is a frequent speaker at industry conferences and events,
where he shares his insights on Python programming and software
development. He is also a contributor to open-source projects,
including popular Python libraries, and an active member of the
Python community.
In addition to his work with Python, Dane has extensive experience
with other modern application development technologies, including
web development frameworks and machine learning libraries. He
holds a degree in computer science from a top-ranked university and
is passionate about using technology to solve real-world problems.

Table of Contents
Chapter 1:
Introduction
1. The Zen of Python
2. Pythonic thinking

Chapter 2:
Pythonic thinking
1. Know your data structures

Tuples
Lists
Dictionaries
Sets
Arrays
Queues
Stacks
Heaps
Trees
Graphs

2. Write expressive code

Choosing good names


Avoiding magic numbers and strings
Using list comprehensions and generator expressions
Leveraging built-in functions
Using the with statement
Using decorators
Writing context managers

3. Take advantage of Python's features


Using named tuples
Leveraging closures
Using properties
Using descriptors
Using metaclasses

4. Writing idiomatic Python

Writing Pythonic loops


Using enumerate and zip
Using the ternary operator
Using multiple assignment
Using the walrus operator
Using context managers

Chapter 3:
Functions
1. Function basics

Function arguments and return values


Documenting functions
Writing doctests
Writing function annotations
Using default arguments
Using keyword arguments
Using *args and **kwargs

2. Function design

Writing pure functions


Writing functions with side effects
Writing functions that modify mutable arguments
Using the @staticmethod and @classmethod decorators
Using partial functions

3. Function decorators and closures

Writing simple decorators


Writing decorators that take arguments
Writing class decorators
Using closures
Using functools.partial

Chapter 4:
Classes and Objects
1. Class basics
Creating and using classes
Defining instance methods
Using instance variables
Understanding class vs instance data
Using slots for memory optimization
Understanding class inheritance
Using multiple inheritance

2. Class design

Writing clean, readable classes


Writing classes with a single responsibility
Using composition over inheritance
Using abstract base classes
Writing metaclasses

3. Advanced class topics


Using descriptors to customize attribute access
Using properties to control attribute access
Writing class decorators
Using the super function
Using slots to optimize memory usage

Chapter 5:
Concurrency and Parallelism
1. Threads and Processes

Understanding the Global Interpreter Lock (GIL)


Using threads for I/O-bound tasks
Using processes for CPU-bound tasks
Using multiprocessing
Using concurrent.futures

2. Coroutines and asyncio

Understanding coroutines
Using asyncio for I/O-bound tasks
Using asyncio for CPU-bound tasks
Using asyncio with third-party libraries
Debugging asyncio code

Chapter 6:
Built-in Modules
1. Collections
Using namedtuple
Using deque
Using defaultdict
Using OrderedDict
Using Counter
Using ChainMap
Using UserDict
Using UserList
Using UserString

2. Itertools
Using count, cycle, and repeat
Using chain, tee, and zip_longest
Using islice, dropwhile, and takewhile
Using groupby
Using starmap and product

3. File and Directory Access


Using os and os.path
Using pathlib
Using shutil
Using glob

4. Dates and Times

Using datetime
Using time
Using timedelta
Using pytz
Using dateutil

5. Serialization and Persistence

Using json
Using pickle
Using shelve
Using dbm
Using SQLite
6. Testing and Debugging

Writing unit tests


Using pytest
Debugging with pdb
Debugging with logging
Using assertions

Chapter 7:
Collaboration and Development
1. Code Quality
Using linters
Using type checkers
Using code formatters
Using docstring conventions
Writing maintainable code

2. Code Reviews
Conducting effective code reviews
Giving and receiving feedback
Improving code quality through reviews

3. Collaboration Tools

Using version control with Git


Using GitHub for collaboration
Using continuous integration
Using code coverage tools

4. Documentation and Packaging

Writing documentation
Using Sphinx
Packaging Python projects
Distributing Python packages
Managing dependencies

Chapter 1:
Introduction
Python is a popular, high-level programming language that is widely
used for web development, scientific computing, artificial intelligence,
data analysis, and many other applications. It is a versatile and
powerful language that offers a lot of flexibility and ease of use to
developers. However, like any other programming language, writing
effective and efficient Python code requires a good understanding of
the language's features and best practices.
"Effective Python: 50 Specific Ways to Write Better Python" is a
comprehensive guide that focuses on providing readers with specific
tips and techniques to improve their Python coding skills. The book
covers a wide range of topics, including data structures, functions,
classes, concurrency, testing, and debugging. Each topic is
presented in a clear and concise manner, with practical examples and
explanations that help readers understand the concepts better.
The book is divided into 50 chapters, each of which covers a specific
aspect of Python programming. The chapters are organized in a
logical and progressive order, with each chapter building upon the
previous one. This makes it easy for readers to follow along and
learn at their own pace.
One of the strengths of the book is its focus on practical examples.
The author, Brett Slatkin, is an experienced Python developer who
has worked at Google for many years. He draws upon his experience
to provide readers with real-world examples that illustrate the
concepts he is explaining. This makes it easy for readers to
understand how the concepts apply to real-world programming
situations.
Another strength of the book is its emphasis on best practices. The
author provides readers with tips and techniques that are widely
accepted as best practices within the Python community. This helps
readers to write code that is more efficient, more maintainable, and
easier to understand.
One of the unique features of the book is its focus on Python 3.
Python 3 is the latest version of the language, and it has many new
features and improvements over Python 2. The author recognizes that
many developers still use Python 2, but he encourages readers to
move to Python 3, as it is a more modern and robust language.
Overall, "Effective Python: 50 Specific Ways to Write Better Python"
is an excellent resource for anyone who wants to improve their
Python coding skills. Whether you are a beginner or an experienced
developer, this book provides valuable insights and techniques that
can help you write better Python code. It is a must-read for anyone
who wants to become a more proficient Python programmer.

The Zen of Python


The Zen of Python is a collection of guiding principles for writing code
in the Python programming language. It was created by Tim Peters, a
well-known Python developer and contributor, and is included as an
Easter egg in the Python interpreter. The Zen of Python provides a
set of rules and guidelines that promote readability, simplicity, and
clarity in Python code.
The Zen of Python provides guidance on several aspects of Python
programming. Let's take a closer look at some of the principles:
"Beautiful is better than ugly": This principle encourages
developers to write code that is visually appealing and easy to
read. This can be achieved by using descriptive variable
names, commenting the code where necessary, and adhering
to a consistent coding style.

"Explicit is better than implicit": This principle encourages


developers to be clear and concise in their code. It's better to
be explicit about what the code does, even if it means writing
a few extra lines of code.

"Simple is better than complex": This principle encourages


developers to write code that is easy to understand and
maintain. This can be achieved by breaking down complex
tasks into smaller, simpler functions or modules.

"Readability counts": This principle emphasizes the importance


of writing code that is easy to read and understand. This can
be achieved by using consistent indentation, commenting the
code where necessary, and adhering to a consistent coding
style.

Let's take a look at some sample code that demonstrates the


principles of the Zen of Python:

# Example 1: Beautiful is better than ugly.


# Instead of using single-letter variable
names, use descriptive names.
# Also, use comments to explain what the
code does.
# Bad code
a=5
b=7
c=a+b
print(c)
# Good code
num1 = 5
num2 = 7
sum = num1 + num2 # Calculate the sum of
num1 and num2
print(sum)
# Example 2: Explicit is better than implicit.
# Instead of using implicit variables or
functions, be explicit.
# Bad code
lst = [1, 2, 3, 4, 5]
result = filter(lambda x: x % 2 == 0, lst)
print(list(result))
# Good code
def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
# Example 3: Simple is better than complex.
# Instead of writing complex code

Pythonic thinking
Pythonic thinking refers to writing code that is idiomatic and natural to
the Python language. It involves using the language's features and
syntax in a way that is efficient, elegant, and easy to read. In this
note, we will discuss some key principles of Pythonic thinking and
demonstrate them with suitable code examples.
Using list comprehensions instead of loops:
List comprehensions are a concise and efficient way to create new
lists by applying a function to each element of an existing list. They
are more Pythonic than using for-loops with append statements to
create a new list. Here is an example:

# Using for loop to create a new list


squares = []
for i in range(10):
squares.append(i**2)
print(squares)
# Using list comprehension to create a new
list
squares = [i**2 for i in range(10)]
print(squares)
Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Using built-in functions and modules:
Python provides many built-in functions and modules that make it
easy to perform common tasks. It is more Pythonic to use these
functions and modules instead of reinventing the wheel. Here is an
example:

# Using built-in function sum() to sum a list


of numbers
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
# Using built-in module math to calculate the
square root of a number
import math
sqrt = math.sqrt(16)
print(sqrt)

Output:

15
4.0
Using generator expressions instead of list comprehensions:
Generator expressions are a memory-efficient way to generate
values on-the-fly. They are more Pythonic than list comprehensions
when you are working with large datasets. Here is an example:

# Using list comprehension to create a list of


squares
squares = [i**2 for i in range(1000000)]
print(len(squares))
# Using generator expression to generate
squares on-the-fly
squares = (i**2 for i in range(1000000))
print(len(squares))
Output:

1000000
<generator object <genexpr> at
0x7f9367040b30>
Using context managers for resource management:
Context managers provide a convenient way to manage resources
such as files, sockets, and database connections. They are more
Pythonic than using try/finally blocks to ensure that resources are
properly released. Here is an example:

# Using try/finally block to manage file


resources
try:
f = open('myfile.txt', 'w')
f.write('Hello, World!')
finally:
f.close()
# Using context manager to manage file
resources
with open('myfile.txt', 'w') as f:
f.write('Hello, World!')
Using the Python standard library:
Python has a rich standard library that provides many useful modules
for various tasks. It is more Pythonic to use these modules instead of
third-party libraries when possible. Here is an example:

# Using the built-in module datetime to work


with dates and times
import datetime
today = datetime.datetime.today()
print(today)
Output:

2023-03-13 13:44:55.881958

Chapter 2:
Pythonic thinking

Python is a popular high-level programming language known for its


simplicity, readability, and ease of use. It is widely used in various
fields, from web development to data science, and has a large and
supportive community. One of the key aspects that make Python
unique is the concept of "Pythonic thinking."
Pythonic thinking refers to the mindset of writing code in a way that
aligns with the core principles and design philosophy of Python. It is a
set of guidelines that encourage developers to write clean, concise,
and efficient code that is easy to read and maintain. Pythonic code is
not only efficient, but it is also elegant and easy to understand.
The concept of Pythonic thinking is deeply rooted in the Python
community, and it is often considered a way of life for Python
developers. It is not just about writing code, but also about
understanding the essence of Python and its design philosophy.
One of the core principles of Pythonic thinking is "Readability counts."
Python code is designed to be easy to read and understand, even by
non-programmers. This is achieved through the use of simple and
clear syntax, meaningful variable names, and well-structured code.
Python's design philosophy emphasizes the importance of writing
code that is easy to read and understand, even by someone who has
never seen it before.
Another key principle of Pythonic thinking is "Don't repeat yourself"
(DRY). This principle encourages developers to write code that is
reusable and modular. In other words, instead of writing the same
code over and over again, Python developers are encouraged to
write code that can be reused in different parts of the program. This
not only saves time but also reduces the chances of introducing
errors in the code.
Pythonic thinking also emphasizes the importance of simplicity.
Python code is designed to be simple and straightforward. Python
developers are encouraged to write code that is as simple as
possible, without sacrificing functionality. This not only makes the
code easier to read and understand, but it also makes it easier to
maintain and modify.
Pythonic thinking also encourages the use of built-in functions and
libraries. Python has a large number of built-in functions and libraries
that can be used to perform common tasks. By using these built-in
functions and libraries, Python developers can save time and avoid
reinventing the wheel.
Finally, Pythonic thinking encourages the use of idiomatic Python
code. Idiomatic Python code is code that is written in a way that is
consistent with the core principles and design philosophy of Python.
Python developers are encouraged to write code that is not only
efficient but also follows the conventions and style of the Python
community.
In summary, Pythonic thinking is a way of approaching programming
in Python that emphasizes simplicity, readability, and efficiency. It is a
mindset that encourages developers to write code that is easy to
read, maintain, and understand. By following the core principles of
Pythonic thinking, Python developers can write code that is not only
efficient but also elegant and easy to understand.

Know your data structures


Tuples

In Pythonic thinking, it is essential to know the data structures


available in the Python programming language and how to use them
effectively. In this note, we will discuss tuples, one of the most
commonly used data structures in Python, and provide code
examples to demonstrate their usage.
A tuple is an ordered collection of elements that can be of any data
type. However, tuples are immutable, which means their elements
cannot be changed once they are created. Tuples are typically used
for grouping related data together.
Here are some examples of tuples and how to use them:
Creating a tuple:
Tuples can be created using parentheses or the tuple() function.

# Creating a tuple using parentheses


mytuple = (1, 2, 3, 4, 5)
# Creating a tuple using the tuple() function
mytuple = tuple([1, 2, 3, 4, 5])
Accessing tuple elements:
Tuple elements can be accessed using indexing. Indexing starts at 0
for the first element.

# Accessing tuple elements


mytuple = (1, 2, 3, 4, 5)
print(mytuple[0]) # Output: 1
print(mytuple[2]) # Output: 3
Slicing a tuple:
Tuples can be sliced using the same syntax as lists.

# Slicing a tuple
mytuple = (1, 2, 3, 4, 5)
print(mytuple[1:3]) # Output: (2, 3)

Unpacking a tuple:
Tuples can be unpacked into multiple variables.

# Unpacking a tuple
mytuple = (1, 2, 3)
a, b, c = mytuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
Concatenating tuples:
Tuples can be concatenated using the + operator.

# Concatenating tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
newtuple = tuple1 + tuple2
print(newtuple) # Output: (1, 2, 3, 4, 5, 6)
Using tuples as keys in dictionaries
Since tuples are immutable, they can be used
as keys in dictionaries.
python
Copy code
# Using tuples as keys in dictionaries
mydict = {(1, 2): 'value1', (3, 4): 'value2'}
print(mydict[(1, 2)]) # Output: 'value1'
print(mydict[(3, 4)]) # Output: 'value2'
In summary, tuples are an essential data structure in Pythonic
thinking, and they can be used for a wide range of applications. They
are particularly useful for grouping related data together, and their
immutability makes them ideal for use as keys in dictionaries or as
elements in sets.
Lists
In Pythonic thinking, it is crucial to know the available data structures
and how to use them effectively. One of the most commonly used
data structures in Python is the list. A list is an ordered collection of
elements that can be of any data type. Lists are mutable, which
means their elements can be changed once they are created. Lists
are typically used for storing data that can be modified or changed.
Here are some examples of lists and how to use them:
Creating a list:
Lists can be created using square brackets [] or the list() function.

# Creating a list using square brackets


mylist = [1, 2, 3, 4, 5]
# Creating a list using the list() function
mylist = list([1, 2, 3, 4, 5])
Accessing list elements:
List elements can be accessed using indexing. Indexing starts at 0 for
the first element.

# Accessing list elements


mylist = [1, 2, 3, 4, 5]
print(mylist[0]) # Output: 1
print(mylist[2]) # Output: 3
Slicing a list:
Lists can be sliced using the syntax start:end. Slicing a list returns a
new list containing the selected elements.

# Slicing a list
mylist = [1, 2, 3, 4, 5]
print(mylist[1:3]) # Output: [2, 3]
Modifying list elements:
Since lists are mutable, their elements can be modified.

# Modifying list elements


mylist = [1, 2, 3, 4, 5]
mylist[2] = 7
print(mylist) # Output: [1, 2, 7, 4, 5]
Adding elements to a list:
Elements can be added to a list using the append() method or the
extend() method to add multiple elements at once.

# Adding elements to a list


mylist = [1, 2, 3]
mylist.append(4)
print(mylist) # Output: [1, 2, 3, 4]
mylist.extend([5, 6])
print(mylist) # Output: [1, 2, 3, 4, 5, 6]
Removing elements from a list:
Elements can be removed from a list using the remove() method or
the pop() method to remove an element at a specific index.

# Removing elements from a list


mylist = [1, 2, 3, 4, 5]
mylist.remove(3)
print(mylist) # Output: [1, 2, 4, 5]
mylist.pop(2)
print(mylist) # Output: [1, 2, 5]
Sorting a list:
Lists can be sorted using the sort() method or the sorted() function.

# Sorting a list
mylist = [4, 2, 3, 1, 5]
mylist.sort()
print(mylist) # Output: [1, 2, 3, 4, 5]
sortedlist = sorted(mylist, reverse=True)
print(sortedlist) # Output: [5, 4, 3, 2, 1]

Dictionaries

In Pythonic thinking, it is essential to know the available data


structures and how to use them effectively. One of the most
commonly used data structures in Python is the dictionary. A
dictionary is an unordered collection of key-value pairs, where each
key is unique. Dictionaries are mutable, which means their elements
can be changed once they are created. Dictionaries are typically
used for storing data that can be looked up using a key.
Here are some examples of dictionaries and how to use them:
Creating a dictionary:
Dictionaries can be created using curly braces {} or the dict()
function.

# Creating a dictionary using curly braces


mydict = {'apple': 1, 'banana': 2, 'orange': 3}
# Creating a dictionary using the dict()
function
mydict = dict(apple=1, banana=2, orange=3)
Accessing dictionary elements:
Dictionary elements can be accessed using the key. If the key does
not exist, a KeyError will be raised.

# Accessing dictionary elements


mydict = {'apple': 1, 'banana': 2, 'orange': 3}
print(mydict['apple']) # Output: 1
print(mydict['watermelon']) # Raises
KeyError: 'watermelon'
Modifying dictionary elements:
Since dictionaries are mutable, their elements can be modified.

# Modifying dictionary elements


mydict = {'apple': 1, 'banana': 2, 'orange': 3}
mydict['orange'] = 4
print(mydict) # Output: {'apple': 1, 'banana':
2, 'orange': 4}

Adding elements to a dictionary:


Elements can be added to a dictionary using the key-value syntax.

# Adding elements to a dictionary


mydict = {'apple': 1, 'banana': 2}
mydict['orange'] = 3
print(mydict) # Output: {'apple': 1, 'banana':
2, 'orange': 3}
Removing elements from a dictionary:
Elements can be removed from a dictionary using the del keyword or
the pop() method to remove an element using its key.

# Removing elements from a dictionary


mydict = {'apple': 1, 'banana': 2, 'orange': 3}
del mydict['orange']
print(mydict) # Output: {'apple': 1, 'banana':
2}
mydict.pop('banana')
print(mydict) # Output: {'apple': 1}
Checking if a key exists in a dictionary:
To check if a key exists in a dictionary, you can use the in keyword.

# Checking if a key exists in a dictionary


mydict = {'apple': 1, 'banana': 2, 'orange': 3}
print('banana' in mydict) # Output: True
print('watermelon' in mydict) # Output: False
Iterating over a dictionary:
To iterate over a dictionary, you can use the items() method to get
the key-value pairs or the keys() method to get the keys.
# Iterating over a dictionary
mydict = {'apple': 1, 'banana': 2, 'orange': 3}
for key, value in mydict.items():
print(key, value)
for key in mydict.keys():
print(key)
for value in mydict.values():
print(value)
Sets

In Pythonic thinking, it is important to know the available data


structures and how to use them effectively. One of the commonly
used data structures in Python is the set. A set is an unordered
collection of unique elements. Sets are mutable, which means their
elements can be changed once they are created. Sets are typically
used for operations that require finding the intersection, union, or
difference between two collections.
Here are some examples of sets and how to use them:
Creating a set:
Sets can be created using curly braces {} or the set() function.

# Creating a set using curly braces


myset = {1, 2, 3, 4}
# Creating a set using the set() function
myset = set([1, 2, 3, 4])
Accessing set elements:
Set elements can be accessed using a for loop or the in keyword.

# Accessing set elements


myset = {1, 2, 3, 4}
for element in myset:
print(element)
print(1 in myset) # Output: True
print(5 in myset) # Output: False

Modifying set elements:


Since sets are mutable, their elements can be modified.

# Modifying set elements


myset = {1, 2, 3, 4}
myset.add(5)
print(myset) # Output: {1, 2, 3, 4, 5}
myset.remove(4)
print(myset) # Output: {1, 2, 3, 5}
Combining sets:
Sets can be combined using union(), intersection(), and difference()
methods.

# Combining sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5, 6}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3, 4}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
Checking if a set is a subset or superset:
To check if a set is a subset or superset of another set, you can use
the issubset() and issuperset() methods.

# Checking if a set is a subset or superset


set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}
print(set1.issubset(set2)) # Output: True
print(set2.issuperset(set1)) # Output: True

Removing duplicate elements:


Sets can be used to remove duplicate elements from a list.

# Removing duplicate elements from a list


mylist = [1, 2, 2, 3, 3, 4, 5, 5]
myset = set(mylist)
print(myset) # Output: {1, 2, 3, 4, 5}
In summary, sets are a useful data structure in Python for operations
that require finding the intersection, union, or difference between two
collections.
Arrays

In Pythonic thinking, it is important to know the available data


structures and how to use them effectively. One of the commonly
used data structures in Python is the array. An array is a collection of
elements of the same data type, arranged in contiguous memory
locations. Arrays are typically used for operations that require
efficient element-wise computations, such as linear algebra
operations.
Here are some examples of arrays and how to use them:
Creating an array:
Arrays can be created using the array() function from the array
module.

import array as arr


# Creating an array of integers
myarr = arr.array('i', [1, 2, 3, 4, 5])
# Creating an array of floats
myarr = arr.array('f', [1.0, 2.0, 3.0, 4.0, 5.0])
Accessing array elements:
Array elements can be accessed using indexing, just like in a list.

# Accessing array elements


myarr = arr.array('i', [1, 2, 3, 4, 5])
print(myarr[0]) # Output: 1
print(myarr[4]) # Output: 5
Modifying array elements:
Array elements can be modified by assigning new values to their
corresponding indices.

# Modifying array elements


myarr = arr.array('i', [1, 2, 3, 4, 5])
myarr[0] = 10
print(myarr) # Output: array('i', [10, 2, 3, 4, 5])
Performing element-wise computations:
Arrays can be used to perform element-wise computations efficiently
using NumPy, a powerful Python library for scientific computing.

import numpy as np
# Performing element-wise computations
myarr = arr.array('f', [1.0, 2.0, 3.0, 4.0, 5.0])
myarr = np.square(myarr)
print(myarr) # Output: array([ 1., 4., 9., 16.,
25.], dtype=float32)
Converting arrays to lists:
Arrays can be converted to lists using the tolist() method.

# Converting arrays to lists


myarr = arr.array('i', [1, 2, 3, 4, 5])
mylist = myarr.tolist()
print(mylist) # Output: [1, 2, 3, 4, 5]
In summary, arrays are a useful data structure in Python for
operations that require efficient element-wise computations, such as
linear algebra operations. They can be created using the array()
function from the array module, accessed and modified using
indexing, and converted to lists using the tolist() method. To perform
more advanced computations with arrays, NumPy is a powerful
library that is widely used in scientific computing.

Queues

Queues are a fundamental data structure in computer science that


are used to store a collection of elements in a first-in, first-out (FIFO)
order. They are commonly used in algorithms for tasks such as
breadth-first search, job scheduling, and message passing. In Python,
queues can be implemented using the built-in deque class from the
collections module or using the queue module.
Here are some examples of using queues in Python:
Creating a queue:
To create a queue in Python, we can use the deque class from the
collections module or the Queue class from the queue module.

from collections import deque


# or
from queue import Queue
# Creating a queue using deque
myqueue = deque()
# Creating a queue using Queue
myqueue = Queue()
Adding elements to a queue:
We can add elements to a queue using the append() method of the
deque class or the put() method of the Queue class.

# Adding elements to a queue


myqueue = deque()
myqueue.append(1)
myqueue.append(2)
myqueue.append(3)
# or
myqueue = Queue()
myqueue.put(1)
myqueue.put(2)
myqueue.put(3)

Removing elements from a queue:


We can remove elements from a queue using the popleft() method of
the deque class or the get() method of the Queue class.

# Removing elements from a queue


myqueue = deque([1, 2, 3])
myqueue.popleft() # Output: 1
# or
myqueue = Queue()
myqueue.put(1)
myqueue.put(2)
myqueue.put(3)
myqueue.get() # Output: 1
Checking the size of a queue:
We can check the size of a queue using the len() function.

# Checking the size of a queue


myqueue = deque([1, 2, 3])

print(len(myqueue)) # Output: 3
In summary, queues are a useful data structure in Python for tasks
that require a collection of elements to be processed in a first-in, first-
out order. They can be implemented using the built-in deque class
from the collections module or using the Queue class from the queue
module. To add elements to a queue, we can use the append()
method of the deque class or the put() method of the Queue class.
To remove elements from a queue, we can use the popleft() method
of the deque class or the get() method of the Queue class. Finally,
we can check the size of a queue using the len() function.
Stacks

Stacks are a fundamental data structure in computer science that are


used to store a collection of elements in a last-in, first-out (LIFO)
order. They are commonly used in algorithms for tasks such as
expression evaluation, function call management, and undo/redo
operations. In Python, stacks can be implemented using the built-in
list class.
Here are some examples of using stacks in Python:
Creating a stack:
To create a stack in Python, we can use an empty list.

# Creating a stack
mystack = []
Adding elements to a stack:
We can add elements to a stack using the append() method of the list
class.

# Adding elements to a stack


mystack = []
mystack.append(1)
mystack.append(2)
mystack.append(3)
Removing elements from a stack:
We can remove elements from a stack using the pop() method of the
list class.

# Removing elements from a stack


mystack = [1, 2, 3]
mystack.pop() # Output: 3
mystack.pop() # Output: 2
Checking the size of a stack:
We can check the size of a stack using the len() function.

# Checking the size of a stack


mystack = [1, 2, 3]
print(len(mystack)) # Output: 3
In summary, stacks are a useful data structure in Python for tasks
that require a collection of elements to be processed in a last-in, first-
out order. They can be implemented using an empty list. To add
elements to a stack, we can use the append() method of the list
class. To remove elements from a stack, we can use the pop()
method of the list class. Finally, we can check the size of a stack
using the len() function.
Heaps

Heaps are a fundamental data structure in computer science that are


used to efficiently maintain the minimum (or maximum) element in a
collection of elements. In Python, heaps can be implemented using
the built-in heapq module.
Here are some examples of using heaps in Python:
Creating a heap:
To create a heap in Python, we can use the heapify() function of the
heapq module to convert a list into a heap.

import heapq
# Creating a heap
myheap = [3, 1, 4, 1, 5, 9, 2, 6, 5]
heapq.heapify(myheap)
Alternatively, we can use the heappush() function of the heapq
module to add elements to an empty heap.

import heapq
# Creating a heap
myheap = []
heapq.heappush(myheap, 3)
heapq.heappush(myheap, 1)
heapq.heappush(myheap, 4)
heapq.heappush(myheap, 1)
heapq.heappush(myheap, 5)
heapq.heappush(myheap, 9)
heapq.heappush(myheap, 2)
heapq.heappush(myheap, 6)
heapq.heappush(myheap, 5)
Getting the minimum element from a heap:
To get the minimum element from a heap, we can use the heappop()
function of the heapq module.

import heapq
# Getting the minimum element from a heap
myheap = [3, 1, 4, 1, 5, 9, 2, 6, 5]
heapq.heapify(myheap)
print(heapq.heappop(myheap)) # Output: 1
print(heapq.heappop(myheap)) # Output: 1
Adding elements to a heap:
We can add elements to a heap using the heappush() function of the
heapq module.

import heapq
# Adding elements to a heap
myheap = [3, 1, 4, 1, 5, 9, 2, 6, 5]
heapq.heapify(myheap)
heapq.heappush(myheap, 0)
heapq.heappush(myheap, 7)
print(myheap) # Output: [0, 1, 2, 3, 5, 9, 4, 6,
5, 7]
Checking the size of a heap:
We can check the size of a heap using the len() function.

import heapq
# Checking the size of a heap
myheap = [3, 1, 4, 1, 5, 9, 2, 6, 5]
heapq.heapify(myheap)
print(len(myheap)) # Output: 9
In summary, heaps are a useful data structure in Python for efficiently
maintaining the minimum (or maximum) element in a collection of
elements. They can be implemented using the heapq module. To
create a heap, we can use the heapify() function of the heapq module
to convert a list into a heap, or we can use the heappush() function to
add elements to an empty heap. To get the minimum element from a
heap, we can use the heappop() function. Finally, we can check the
size of a heap using the len() function.

Trees

Trees are a fundamental data structure in computer science that are


used to represent hierarchical relationships between elements. In
Python, trees can be implemented using classes and objects.
Here is an example of using trees in Python:
Creating a tree:
To create a tree in Python, we can define a class for the nodes of the
tree, and use objects of this class to represent the nodes.

class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Creating a tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
Traversing a tree:
To traverse a tree in Python, we can use recursive functions to visit
each node in the tree in a specific order. Here are three common
ways to traverse a tree:
Inorder traversal: Visit the left subtree, then the current node, then
the right subtree.

def inorder(node):
if node is not None:
inorder(node.left)
print(node.data)
inorder(node.right)
# Inorder traversal of the tree
inorder(root)
Preorder traversal: Visit the current node, then the left subtree, then
the right subtree.

def preorder(node):
if node is not None:
print(node.data)
preorder(node.left)
preorder(node.right)
# Preorder traversal of the tree
preorder(root)
Postorder traversal: Visit the left subtree, then the right subtree, then
the current node.

def postorder(node):
if node is not None:
postorder(node.left)
postorder(node.right)
print(node.data)
# Postorder traversal of the tree
postorder(root)
Finding elements in a tree:
To find an element in a tree in Python, we can use a recursive
function to traverse the tree and search for the element.

def find(node, data):


if node is None:
return False
elif node.data == data:
return True
elif data < node.data:
return find(node.left, data)
else:
return find(node.right, data)
# Finding elements in the tree
print(find(root, 2)) # Output: True
print(find(root, 6)) # Output: False
In summary, trees are a useful data structure in Python for
representing hierarchical relationships between elements. They can
be implemented using classes and objects. To traverse a tree, we
can use recursive functions to visit each node in the tree in a specific
order. To find an element in a tree, we can use a recursive function to
traverse the tree and search for
the element.
Graphs

Graphs are an important data structure in computer science that are


used to represent relationships between objects. A graph consists of
a set of vertices (or nodes) and a set of edges that connect pairs of
vertices. In Python, graphs can be implemented using classes and
objects.
Here is an example of using graphs in Python:
Creating a graph:
To create a graph in Python, we can define a class for the nodes of
the graph, and use objects of this class to represent the nodes. Each
node can have a list of neighbors that represents the edges
connecting it to other nodes.

class Node:
def __init__(self, data):
self.data = data
self.neighbors = []
# Creating a graph
A = Node('A')
B = Node('B')
C = Node('C')
D = Node('D')
E = Node('E')
F = Node('F')
G = Node('G')
H = Node('H')
A.neighbors = [B, C, D]
B.neighbors = [A, E]
C.neighbors = [A, F]
D.neighbors = [A, G, H]
E.neighbors = [B]
F.neighbors = [C]
G.neighbors = [D, H]
H.neighbors = [D, G]
Traversing a graph:
To traverse a graph in Python, we can use a recursive function to visit
each node in the graph in a specific order. Here are two common
ways to traverse a graph:
Depth-first search (DFS): Visit the current node, then recursively visit
each of its neighbors.

def dfs(node, visited):


visited.add(node)
print(node.data)
for neighbor in node.neighbors:
if neighbor not in visited:
dfs(neighbor, visited)
# DFS traversal of the graph
visited = set()
dfs(A, visited)
Breadth-first search (BFS): Visit all nodes at a given distance from
the starting node, then all nodes at the next distance, and so on.

def bfs(node):
visited = set()
queue = [node]
visited.add(node)
while queue:
curr_node = queue.pop(0)
print(curr_node.data)
for neighbor in curr_node.neighbors:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
# BFS traversal of the graph
bfs(A)
Finding paths in a graph:
To find a path between two nodes in a graph in Python, we can use a
recursive function to traverse the graph and search for the path. We
can use either DFS or BFS to perform the traversal.

def find_path(start_node, end_node, visited,


path):
visited.add(start_node)
path.append(start_node)
if start_node == end_node:
return path
for neighbor in start_node.neighbors:
if neighbor not in visited:
result = find_path(neighbor, end_node,
visited, path)
if result:
return result
path.pop()
# Finding a path in the graph
visited = set()
path = []
result = find_path(A, H, visited, path)
if result:
print('Path found:', [node.data for node in
result])
else:
print('Path not found')
In summary, graphs are a versatile data structure in Python for
representing relationships between objects. They can be
implemented using classes and objects. To traverse a graph, we can
use either DFS or BFS to visit each node in the graph in a specific
order. To find a path between two nodes in a graph, we can use a
recursive function to traverse the graph and search for the path.

Write expressive code


Choosing good names

In Pythonic thinking, writing expressive and readable code is


important for maintaining code quality and making it easier for others
to understand and work with. One key aspect of this is choosing
good variable and function names that are descriptive and meaningful.
In this note, we will explore some best practices for choosing good
names in Python, along with some examples of suitable code.
Use descriptive names: Names should be clear and descriptive,
making it easier for other developers to understand what they
represent. For example, instead of naming a variable "data", consider
naming it "user_data" or "sales_data".
Follow naming conventions: Python has some established naming
conventions that are widely used, such as using lowercase letters for
variables and using underscores to separate words in a name.
Following these conventions can make your code more readable and
easier to understand for other developers.
Avoid abbreviations: While it may be tempting to use abbreviations to
save space, it can actually make your code harder to understand. For
example, instead of using "usr" for "user", use the full word "user".
Be consistent: Consistency in naming conventions is important for
maintaining readability and making your code easy to understand. If
you choose to use a certain naming convention, make sure to apply it
consistently throughout your code.
Use meaningful function names: Function names should be descriptive
and indicate what the function does. For example, if a function
calculates the average of a set of numbers, consider naming it
"calculate_average" instead of just "average".
Use comments sparingly: While comments can be helpful for
providing context to code, they should not be relied upon to make up
for poorly named variables or functions. Instead, focus on choosing
descriptive names that communicate the purpose of the code.
Here is an example of code that follows these best practices for
choosing good names:

# calculate the average of a list of numbers


def calculate_average(numbers_list):
sum = 0
for number in numbers_list:
sum += number
return sum / len(numbers_list)
# get user data from database
def get_user_data(user_id):
query = "SELECT * FROM users WHERE id
= %s"
result = execute_query(query, user_id)
return result
# generate a random password for a user
def generate_password():
alphabet =
"abcdefghijklmnopqrstuvwxyz0123456789"
password = ""
for i in range(8):
password += random.choice(alphabet)
return password
In summary, choosing good names is an important aspect of writing
expressive and readable code in Python. By following best practices
such as using descriptive names, following naming conventions,
avoiding abbreviations, being consistent, using meaningful function
names, and using comments sparingly, you can create code that is
easy for other developers to understand and work with.
Avoiding magic numbers and strings

When writing code, it is important to avoid the use of magic numbers


and strings. Magic numbers and strings are hard-coded values that
appear throughout your code and have no clear meaning or
explanation. These values can make your code difficult to understand
and maintain, and can lead to errors and bugs. In this note, we will
explore some best practices for avoiding magic numbers and strings
in Python, along with some examples of suitable code.
Define constants: Instead of using hard-coded values throughout your
code, define constants to hold these values. This makes it easier to
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Miracle by
Price
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: Miracle by Price

Author: Irving E. Cox

Release date: January 19, 2019 [eBook #58730]

Language: English

Credits: Produced by Greg Weeks, Mary Meehan and the Online


Distributed Proofreading Team at http://www.pgdp.net

*** START OF THE PROJECT GUTENBERG EBOOK MIRACLE BY


PRICE ***
MIRACLE BY PRICE
BY IRVING E. COX, JR.

They said old Doctor Price was an inventive


genius but no miracle worker. Yet—if he didn't
work miracles in behalf of an over-worked
little guy named Cupid, what was he doing?

Transcriber's Note: This etext was produced from


Worlds of If Science Fiction, October 1954.
Extensive research did not uncover any evidence that
the U.S. copyright on this publication was renewed.]
Memo to: Clayton, Croyden and Hammerstead, Attorneys
Attention: William Clayton
From: Walter Gordon
Dear Bill:
Enclosed is the itemized inventory of the furnishings of the late Dr.
Edward Price's estate. As you requested, I personally examined the
laboratory. Candidly, Bill, you needed a psychiatrist for the job, not a
graduate physicist. Dr. Price was undoubtedly an inventive genius a
decade ago when he was still active in General Electronics, but his
lab was an embarrassing example of senile clutter.
You had an idea, Bill, that before he died Price might have been
playing around with a new invention which the estate could develop
and patent. I found a score of gadgets in the lab, none of them
finished and none of them built for any functional purpose that I
could discover.
Only two seemed to be completed. One resembled a small, portable
radio. It was a plastic case with two knobs and a two-inch speaker
grid. There was no cord outlet. The machine may have been
powered by batteries, for I heard a faint humming when I turned the
knobs. Nothing else. Dr. Price had left a handwritten card on the
box. He intended to call it a Semantic-Translator, but he had noted
that the word combination was awkward for commercial exploitation,
and I suppose he held up a patent application until he could think of
a catchier name. One sentence on that card would have amused
you, Bill. Price wrote, "Should wholesale for about three-fifty per
unit." Even in his dotage, he had an eye for profit.
The Semantic-Translator—whatever that may mean—might have had
possibilities. I fully intended to take it back with me to General
Electronics and examine it thoroughly.
The second device, which Price had labeled a Transpositor, was large
and rather fragile. It was a hollow cylinder of very small wires,
perhaps a foot in diameter, fastened to an open-faced console
crowded with a weird conglomeration of vacuum tubes, telescopic
lenses and mirrors. The cylinder of wires was so delicate that the
motion of my body in the laboratory caused it to quiver. Standing in
front of the wire coil were two brass rods. A kind of shovel-like chute
was fixed to one rod (Price called it the shipping board). Attached to
the second rod was a long-handled pair of tongs which he called the
grapple.
The Transpositor was, I think, an outgrowth of Price's investigation
of the relationship between light and matter. You may recall, Bill, the
brilliant technical papers he wrote on that subject when he was still
working in the laboratories of General Electronics. At the time Price
was considered something of a pioneer. He believed that light and
matter were different forms of the same basic element; he said that
eventually science would learn how to change one into the other.
I seriously believe that the Transpositor was meant to do precisely
that. In other words, Price had expected to transpose the atomic
structure of solid matter into light, and later to reconstruct the
original matter again. Now don't assume, Bill, that Price was
wandering around in a senile delusion of fourth dimensional
nonsense. The theory may be sound. Our present knowledge of the
physical world makes the basic structure of matter more of a
mystery than it has ever been.
Not that I think Price achieved the miracle. Even in his most brilliant
and productive period he could not have done it. As yet our
accumulation of data is too incomplete for such an experiment. I
believe that Price created no more than a very realistic illusion with
his arrangement of lenses and mirrors.
I saw the illusion, too; I used the machine.
There were two dials on the front of the console. One was lettered
"time", and the other "distance". The "time" dial could be set for
eons, centuries or hours, depending upon the position of a three-
way switch beneath it; the "distance" dial could be adjusted to light
years, thousand-mile units, or kilometers by a similar device. Since
there was no indication which position would produce what results, I
left the dials untouched. I plugged the machine into an electric
outlet and pushed the starter button. The coil of wire blazed with
light and the chute slid rapidly in and out of the cylinder.
That was all, at first. The starter button was labeled "the shipper",
and I gathered that Price had visualized the practical application of
the Transpositor as a device for transporting goods from one point to
another.
I looked around the lab for something I could put into the chute.
There was a card, written in red, warning me not to load beyond the
dimensional limits of the chute. The only thing I saw that was small
enough was the little radio-like gadget Price had called a Semantic-
Translator. Loaded horizontally, it just barely fit the chute.
I pushed the shipper button a second time. Again there was a blaze
of light, brighter than before, which temporarily blinded me. For a
moment I saw the Semantic-Translator in the heart of the fragile,
wire cylinder. It had the glow of molten steel, pouring from a blast
furnace.
Then it was gone. The chute shot back to the front of the machine.
The tray was empty.
Was it an illusion? I believe that, Bill, because later on, when I
thought of using the grapple....

Miss Bertha Kent walked back the gravel trail from the dressing
room. The early morning sun was bright and warm, but she held her
woolen robe tight across her throat. She tried to avoid looking at the
other camps—at the sleepy-eyed women coming out of tents, and
the men starting morning fires in the stone rings.
Bitterness was etched in acid in her soul. She made herself believe it
was because she hated Yosemite. The vacation had been such a
disappointment. She had expected so much and—as usual—it had all
gone wrong.
Her hope had been so high when school closed; this year was going
to be different!
"Are you going anywhere this summer?" Miss Emmy asked after the
last faculty meeting in June.
"To Yosemite for a couple of weeks, I think."
"The Park's always crowded. You ought to meet a nice man up
there, Bertha."
"I'm not interested in men," Miss Kent had replied frostily. "I'm a
botany teacher and it helps me professionally if I spend part of the
summer observing the phenomenon of nature."
"Don't kid me, Bertha. You can drop the fancy lingo, too; school's
out. You want a man as much as I do."
That was true, Miss Kent admitted—in the quiet of her own mind.
Never aloud; never to anyone else. Six years ago, when Bertha Kent
had first started to teach, she had been optimistic about it. She
wanted to marry; she wanted a family of her own—instead of
wasting her lifetime in a high school classroom playing baby sitter
for other people's kids. She had saved her money for all sorts of
exotic summer vacations—tours, cruises, luxury hotels—but
somehow something always went wrong.
To be sure, she had met men. She was pretty; she danced well; she
was never prudish; she liked the out-of-doors. All positive qualities:
she knew that. The fault lay always with the men. When she first
met a stranger, everything was fine. Then, slowly, Miss Kent began
to see his faults. Men were simply adult versions of the muscle-
bound knot-heads the administration loaded into her botany classes.
Bertha Kent wanted something better, an ideal she had held in her
mind since her childhood. The dream-man was real, too. She had
met him once and actually talked to him when she was a child. She
couldn't remember where; she couldn't recall his face. But the
qualities of his personality she knew as she did her own heart. If
they had existed once in one man, she would find them again,
somewhere. That was the miracle she prayed for every summer.
She thought the miracle had happened again when she first came to
Yosemite.
She found an open campsite by the river. While she was putting up
her tent, the man from the camp beside hers came to help. At first
he seemed the prototype of everything she hated—a good-looking,
beautifully co-ordinated physical specimen, as sharp-witted as a
jellyfish. The front of his woolen shirt hung carelessly unbuttoned.
She saw the mat of dark hair on his chest, the sculpted curves of
sun-tanned muscle. No doubt he considered himself quite attractive.
Then, that evening after the fire-fall, the young man asked her to go
with him to the ranger's lecture at Camp Curry. Bertha discovered
that he was a graduate physicist, employed by a large, commercial
laboratory. They had at least the specialized area of science in
common. By the time they returned from the lecture, they were
calling each other by first names. The next day Walt asked her to
hike up the mist trail with him to Nevada Falls.
The familiar miracle began to take shape. She lay awake a long time
that night, looking at the dancing pattern of stars visible through the
open flap of her tent. This was it; Walt was the reality of her dream.
She made herself forget that every summer for six years the same
thing had happened. She always believed she had found her miracle;
and always something happened to destroy it.
For two days the idyll lasted. The inevitable awakening began the
afternoon they drove along the Wawona highway to see the
Mariposa Grove of giant sequoias. They left their car in the parking
area and walked through the magnificent stand of cathedral trees.
The trail was steep and sometimes treacherous. Twice Walt took her
arm to help her. For some reason that annoyed her; finally she told
him,
"I'm quite able to look after myself, Walt."
"So you've told me before."
"After all, I've been hiking most of my life. I know exactly what to do
—"
"There isn't much you can't take care of for yourself, is there,
Bertha?" His voice was suddenly very cold.
"I'm not one of these rattle-brained clinging vines, if that's what you
mean. I detest a woman who is always yelping to a man for help."
"Independence is one thing, Bertha; I like that in a woman. But
somehow you make a man feel totally inadequate. You set yourself
up as his superior in everything."
"That's nonsense, Walt. I'm quite ready to grant that you know a
good deal more about physics than I do."
"Say it right, Bertha. You respect the fact that I hold a PhD." He
smiled. "That isn't the same thing as respecting me for a person. I
knew you didn't need my help on the trail, but it was a normal
courtesy to offer it. It seems to me it would be just as normal for
you to accept it. Little things like that are important in relations
between people."
"Forget it, Walt." She slipped her hand through his. "There, see? I'll
do it just the way you want."
She was determined not to quarrel over anything so trivial, though
what he said seemed childish and it tarnished the dream a little. But
the rest was still good; the miracle could still happen.
Yet, in spite of all her effort, they disagreed twice more before they
left the Mariposa Grove. Bertha began to see Walt as he was:
brilliant, no doubt, in the single area of physical science, but
basically no different from any other man. She desperately wished
that she could love him; she earnestly wished that the ideal, fixed so
long in her mind, might be destroyed.
But slowly she saw the miracle slip away from her. That night, after
the fire-fall, Walt did not ask her to go with him to the lecture.
Miserable and angry, Bertha Kent went into her tent, but not to
sleep.
She lay staring at the night sky, and thinking how ugly the pin-point
lights of distant suns were on the velvet void. As the hours passed,
she heard the clatter of pans and voices as people at the other
campsites retired. She heard Walt when he returned, whistling
tunelessly. He banged around for nearly an hour in the camp next to
hers. He dropped a stack of pans; he overturned a box of food; he
tripped over a tent line. She wondered if he were drunk. Had their
quarreling driven him to that? Walt must have loved her, then.
After a time all the Coleman lanterns in the camp were out. Still
Bertha Kent did not sleep. The acid grief and bitterness tormented
her with the ghost of another failure, another shattered dream. She
listened to the soft music of the flowing stream, the gentle whisper
of summer wind in the pines, but it gave her no peace.
Suddenly she heard quiet footsteps and the crackling of twigs behind
her tent. She was terrified. It must be Walt. If he had come home
drunk, he could have planned almost any kind of violence by way of
revenge.
The footsteps moved closer. Bertha shook off the paralysis of fear
and reached for her electric lantern. She flashed the beam into the
darkness. She saw the black bulk of a bear who was pawing through
her food box.
She was so relieved she forgot that a bear might also be a legitimate
cause of fear. She ran from the tent, swinging the light and shooing
the animal away as she would have chased a puppy. The bear
swung toward her, roaring and clawing at the air. She backed away.
The bear swung its paws again, and her food box shattered on the
ground, in a crescendo of sound.
Bertha heard rapid footsteps under the pines. In the pale moonlight
she saw Walt. He was wearing only a pair of red-striped boxer
shorts. He was swinging his arms and shouting, but the noise of the
falling box had already frightened the bear away.
Walt stood in the moonlight, smiling foolishly.
"I guess I came too late," he said.
"I'm quite sure the bear would have left of its own accord, Walt.
They're always quite tame in the national parks, you know." As soon
as she said it, she knew it was a mistake. Even though he had done
nothing, it would have cost her little to thank him. The words had
come instinctively; she hadn't thought how her answer would affect
him. Walt turned on his heel stiffly and walked back to his tent.
With a little forethought—a little kindness—Bertha might even then
have rescued her miracle. She knew that. She knew she had lost him
now, for good. For the first time in her life she saw the dream as a
barrier to her happiness, not an ideal. It held her imprisoned; it gave
her nothing in exchange.
She slept fitfully for the rest of the night. As soon as the sun was up,
she pulled on her woolen robe and went to the dressing room to
wash. She walked back along the gravel path, averting her eyes
from the other camps and the men hunched over the smoking
breakfast fires. She hated Yosemite. She hated all the people
crowded around her. She had made up her mind to pack her tent
and head for home. This was just another vacation lost, another
year wasted.
She went into her tent and put on slacks and a bright, cotton blouse.
Then she sat disconsolate at her camp table surveying the mess the
bear had made of her food box. There was nothing that she could
rescue. She could drive to the village for breakfast, but the shops
wouldn't open for another hour.
Behind her she heard Walt starting his Coleman stove. Yesterday he
would have offered her breakfast; now he'd ignored her. All along
the stream camp fires were blazing in the stone rings. Bertha
wondered if she could ask the couple on the other side of her
campsite for help. They had attempted to be friendly once before,
and Bertha hadn't responded with a great deal of cordiality. They
weren't the type she liked—a frizzy-headed, coarse-voiced blonde,
and a paunchy old man who hadn't enough sense to know what a
fool he looked parading around camp in the faded bathing trunks he
wore all day.
Suddenly a light flashed in Bertha's face. A metal shovel slid out of
nothingness and deposited a tiny, rectangular box on the table. For a
long minute she stared at the box stupidly, vaguely afraid. Her mind
must be playing her tricks. Such things didn't happen.
She reached out timidly and touched the box. It seemed real
enough. A miniature radio of some sort, with a two-inch speaker.
She turned the dials. She heard a faint humming.
The coarse-voiced blonde came toward the table.
"We just heard what happened last night, Miss Kent," she said. "Me
and George. About the bear, I mean."
Bertha forced a smile. "It made rather a shambles, didn't it?"
"Gee, you can't make breakfast out of a mess like this. Why don't
you come and eat with us?"
The blonde went on talking, apologizing for what she was serving
and at the same time listing it with a certain pride. Strangely, Miss
Kent heard not one voice, but two. The second came tinnily from the
little box on the table,
"You poor, dried-up old maid. That guy who's been hanging around
would have been over long before this, if you knew the first thing
about being nice to a man."
Bertha gasped. "Really, if that's the way you feel—"
"Why, honey, I just asked you over for breakfast," the blonde
answered; at the same time the voice from the machine said,
"I suppose George and me ain't good enough for you. O.K. by me,
sister. I didn't really want you to come anyway."
Trembling, Miss Kent stood up. "I've never been so insulted!"
"What's eating you, Miss Kent?" The blonde seemed genuinely
puzzled, but again the voice came from the plastic box,
"The old maid's off her rocker. You'd think she was reading my
mind."
Switching her trim little hips, the blonde walked back to her own
camp. Bertha Kent dropped numbly on the bench, staring at the ugly
box. "Reading my mind," the woman had said. Somehow the
machine had done precisely that, translating the blonde's spoken
words into the real, emotional meaning behind them. It was a
terrifying gadget. Bertha was hypnotized by its potential horror—like
the brutal, devastating truth spoken by a child.
A camper walked past on the road, waving at Miss Kent and calling
out a cheerful good morning. But again the machine read the real
meaning behind the pleasant words.
"So you've finally lost your man, Miss Kent. The way you dished out
the orders, it's a wonder he stayed around as long as he did. And a
pity: you're an attractive woman. You should make some man a
good wife."
They all thought that. The whole camp had been watching her,
laughing at her. Bertha felt helpless and alone. She needed—wanted
—someone else; it surprised her when she faced that fact.
Then it dawned on her: the camper was right; the blonde was right.
She had lost Walt through her own ridiculous bull-headedness. In
order to assert herself. To be an individualist, she had always
thought. And what did that matter, if it imposed this crushing
loneliness?
For a moment a kind of madness seized her. It was the diabolical
machine that was tormenting her, not the truth it told. She snatched
a piece of her broken food box and struck at the plastic case blindly.
There was a splash of fire; the gadget broke.
She saw Walt look up from his stove. She saw him move toward her.
But she stood paralyzed by a shattering trauma of pain. The voice
still came from the speaker, and this time it was her own. Her mind
was stripped naked; she saw herself whole, unsheltered by the
protective veneer of rationalization.
And she knew the pattern of the dream-man she had loved since her
childhood; she knew why the dream had been self-defeating.
For the idealization was her own father. That impossible paragon
created by the worship of a child.
The shock was its own cure. She was too well-balanced to accept
the tempting escape of total disorientation. Grimly she fought back
the tide of madness, and in that moment she found maturity. She
ran toward Walt, tears of gratitude in her eyes. She felt his arms
around her, and she clung to him desperately.
"I was terrified; I needed you, Walt; I never want to be alone
again."
"Needed me?" he repeated doubtfully.
"I love you." After a split-second's hesitation, she felt his lips warm
on hers.
From the corner of her eye she saw a chute dart out of nowhere and
scoop up the broken plastic box from the camp table. They both
vanished again. That was a miracle, too, she supposed; but not
nearly as important as hers.
Then the reason of a logical mind asserted its own form of realism:
of course, none of it had happened. The mind-reading gadget had
been a device created in her own subconscious, a psychological trick
to by-pass the dream that had held her imprisoned. She knew
enough psychology to understand that.
She ran her fingers through Walt's dark hair and repeated softly,
"I love you, Walt Gordon."

Was it an illusion? I believe that, Bill, because later on, when I


thought of using the grapple, I brought the Semantic-Translator back
from nowhere. Apparently the smaller gadget had been in the
console or behind it. I hadn't seen it when I searched, because my
eyes had been hurt by the glare of light.
In the process the Translator somehow got twisted around, for the
chute dragged it back vertically through the coil of wire. It touched
the wall of the cylinder, and the whole machine exploded.
It was impossible to save anything from the wreckage. But as a
physicist I assure you, Bill, the transposition of matter into light is, in
terms of our present science, a physical impossibility. It is certainly
not the sort of invention that could have been produced by a senile
old man, pottering around in a home laboratory. The only thing I
regret is that I had no opportunity to examine the Semantic-
Translator, but I'm sure it would have proved just as much nonsense.
I'm going up to Yosemite tomorrow for a couple of weeks. If you
want any further details on the Price inventory, look me up at the
office when I come home.
Yours,
Walt Gordon
*** END OF THE PROJECT GUTENBERG EBOOK MIRACLE BY PRICE
***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like