Text stringlengths 1 9.41k |
|---|
We can do that in one line using groupby:
**max([len(list(group)) for key,group in groupby(L) if key==1])**
Second, suppose we have a function called easter that returns the date of Easter in a given year.
The following code will produce a histogram of which dates occur most often from 1900 to 2099.
L = [easter(Y)... |
For example, if you
have three lists, L, M, and N and want to print out all the elements of each, one after another, you
can do the following:
**for i in chain(L,M,N):**
**print(i)**
As another example, in Section 8.6 we used list comprehensions to flatten a list of lists, that is to
return a list of all the elemen... |
Here is another way to do that using chain:
L = [[1,2,3], [2,5,5], [7,8,3]]
**list(chain(*tuple(L)))**
###### [1, 2, 3, 2, 5, 5, 7, 8, 3]
count The function count() behaves like range(∞). |
It takes an optional argument so that
count(x) behaves like range(x, ).
_∞_
###### cycle The cycle function cycles over the elements of the iterator continuously. |
When it gets to
the end, it starts over at the beginning, and keeps doing this forever. |
The following simple example
prints the numbers 0 through 4 continuously until the user enters an 'n':
**for x in cycle(range(5)):**
z = input('Keep going? |
y or n: ')
**if z=='n':**
**break**
**print(x)**
**More about iterators** There are a number of other functions in the itertools module. See the
Python documentation [1] for more. |
It has a nice table summarizing what the various functions do.
-----
_24.5. COUNTING THINGS_ 241
###### 24.5 Counting things
The collections module has a useful class called Counter. |
You feed it an iterable and the
Counter object that is created is something very much like a dictionary whose keys are items from
the sequence and whose values are the number of occurrences of the keys. |
In fact, Counter is a
subclass of dict, Python’s dictionary class. |
Here is an example:
Counter('aababcabcdabcde')
Since Counter is a subclass of dict, you can access items just like in a dictionary, and most of the
usual dictionary methods work. |
For example:
c = Counter('aababcabcdabcde')
c['a']
**list(c.keys())**
**list(c.values())**
###### 5
['a', 'c', 'b', 'e', 'd']
[5, 3, 4, 1, 2]
**Getting the most common items** This most_common method takes an integer n and returns a list
of the n most common items, arranged as (key, value) tuples. |
For example:
c = Counter('aababcabcdabcde')
c.most_common(2)
###### [('a', 5), ('b', 4)]
If we omit the argument, it returns tuples for every item, arranged in decreasing order of frequency. |
To get the least common elements, we can use a slice from the end of the list returned by
most_common. |
Here is some examples:
c = Counter('aababcabcdabcde')
c.most_common()
c.most_common()[-2:]
c.most_common()[-2::-1]
###### [('a', 5), ('b', 4), ('c', 3), ('d', 2), ('e', 1)]
[('d', 2), ('e', 1)]
[('d', 2), ('c', 3), ('b', 4), ('a', 5)]
The last example uses a negative slice index to reverse the order to least to mo... |
THE ITERTOOLS AND COLLECTIONS MODULES_
**from collections import Counter**
**import re**
s = open('filename.txt).read()
words = re.findall('\w+', s.lower())
c = Counter(words)
To print the ten most common words, we can do the following:
**for word, freq in c.most_common(10):**
**print(word, ':', freq)**
|Col1|Col2... |
Here is some examples:
c = Counter('aabbb')
d = Counter('abccc')
c+d
c-d
c&d
c|d
###### Counter({'b': 4, 'a': 3, 'c': 3}) Counter({'b': 2, 'a': 1}) Counter({'a': 1, 'b': 1}) Counter({'c': 3, 'b': 3, 'a': 2})
Doing c+d combines the counts from c and d, whereas c-d subtracts the counts from d from the
corresponding co... |
Note that the Counter returned by c-d does not include 0 or negative
counts. |
The & stands for intersection and returns the minimum of the two values for each item, and
| stands for union and returns the maximum of the two values.
###### 24.6 defaultdict
The collections module has another dictionary-like class called defaultdict. |
It is almost
exactly like an ordinary dictionary except that when you create a new key, a default value is given
to the key. |
Here is an example that mimics what the Counter class does.
s = 'aababcabcdabcd'
dd = defaultdict(int)
**for c in s:**
dd[c]+=1
-----
_24.6. |
DEFAULTDICT_ 243
If we had tried this with dd just a regular dictionary, we would have gotten an error the first time
the program reached dd[c]+=1 because dd[c] did not yet exist. |
But since we declared dd to be
defaultdict(int), each value is automatically assigned a value of 0 upon creation, and so we
avoid the error. |
Note that we could use a regular dictionary if we add an if statement into the
loop, and there is also a function of regular dictionaries that allows you to set a default value, but
defaultdict runs faster.
We can use types other than integers. |
Here is an example with strings:
s = 'aababcabcdabcd'
dd = defaultdict(str)
**for c in s:**
dd[c]+='*'
###### defaultdict(<class 'str'>, {'a': '*****', 'c': '***',
'b': '****', 'd': '**'})
Use list for lists, set for sets, dict for dictionaries, and float for floats. |
You can use various
other classes, too. The default value for integers is 0, for lists is [], for sets is set(), for dictionaries
is {} and for floats is 0.0. |
If you would like a different default value, you can use an anonymous
function like below:
dd = defaultdict(lambda:100)
Used with the code from the first example, this will produce:
-----
244 _CHAPTER 24. |
THE ITERTOOLS AND COLLECTIONS MODULES_
-----
### Chapter 25
## Exceptions
This chapter provides a brief introduction to exceptions.
###### 25.1 Basics
If you are writing a program that someone else is going to use, you don’t want it to crash if an error
occurs. |
Say your program is doing a bunch of calculations, and at some point you have the line
c=a/b. |
If b ever happens to be 0, you will get a division by zero error and the program will crash.
Here is an example:
a = 3
b = 0
c = a/b
**print('Hi there')**
###### ZeroDivisionError: int division or modulo by zero
Once the error occurs, none of the code after c=a/b will get executed. |
In fact, if the user is not
running the program in IDLE or some other editor, they won’t even see the error. |
The program will
just stop running and probably close.
When an error occurs, an exception is generated. You can catch this exception and allow your program to recover from the error without crashing. |
Here is an example:
a = 3
b = 0
**try:**
c=a/b
**except ZeroDivisionError:**
**print('Calculation error')**
**print('Hi there')**
###### Calculation error
245
-----
246 _CHAPTER 25. |
EXCEPTIONS_
###### Hi There
**Different possibilities** We can have multiple statements in the try block and also and multiple
**except blocks, like below:**
**try:**
a = eval(input('Enter a number: '))
**print (3/a)**
**except NameError:**
**print('Please enter a number.')**
**except ZeroDivisionError:**
**... |
This will make it hard
to debug your program.
**Using the exception** When you catch an exception, information about the exception is stored in
an Exception object. |
Below is an example that passes the name of the exception to the user:
**try:**
c = a/0
**except Exception as e:**
**print(e)**
###### 25.2 Try/except/else
You can use an else clause along with try/except. |
Here is an example:
**try:**
file = open('filename.txt', 'r')
**except IOError:**
**print('Could not open file')**
**else:**
s = file.read()
**print(s)**
-----
_25.3. |
TRY/FINALLY AND WITH/AS_ 247
In this example, if filename.txt does not exist, an input/output exception called IOError is
generated. |
On the other hand, if the file does exist, there may be certain things that we want to do
with it. |
We can put those in the else block.
###### 25.3 try/finally and with/as
There is one more block you can use called finally. |
Things in the finally block are things that
must be executed whether or not an exception occurs. |
So even if an exception occurs and your
program crashes, the statements in the finally block will be executed. One such thing is closing
a file. |
If you just put the file closing after the try block and not in the finally block, the program
would crash before getting to close the file.
f = open('filename.txt', 'w')
s = 'hi'
**try:**
_# some code that could potentially fail goes here_
**finally:**
f.close()
The finally block can be used along with except and... |
This sort of thing with files
is common enough that it is has its own syntax:
s = 'hi'
with open('filename.txt') as f:
**print(s, file=f)**
This is an example of something called a context manager. |
Context managers and try/finally are
mostly used in more complicated applications, like network programming.
###### 25.4 More with exceptions
There is a lot more that can be done with exceptions. |
See the Python documentation [1] for all the
different types of exceptions. In fact, not all exceptions come from errors. |
There is even a statement
called raise that you can use to raise your own exceptions. |
This is useful if you are writing your
own classes to be used in other programs and you want to send messages, like error messages, to
people who are using your class. |
# AN INTRODUCTION TO PROGRAMMING AND COMPUTER SCIENCE WITH PYTHON
#### Chapter 1
### Introduction
Computer science is a science of abstraction—creating
the right model for a problem and devising the appropriate mechanizable techniques to solve it.
–Alfred V. |
Aho
The goal of this book is to provide an introduction to computer programming with Python. |
This includes
- functional decomposition and a structured approach to programming,
- writing idiomatic Python,
- understanding the importance of abstraction,
- practical problem-solving exercises, and
- a brief introduction to plotting with Matplotlib.
When you get to know it, Python is a peculiar progr... |
This is part of what makes Python a great first
language—and it’s fun!
###### Organization of this book
The book is organized into chapters which roughly correspond to a week’s
worth of material (with some deviations). |
Some chapters, particularly
the first few, should be consumed at a rate of two a week. |
We present
below a brief description of each chapter, followed by mention of some
conventions used in the book.
**Programming and the Python shell**
This chapter provides some motivation for why programming languages
are useful, and gives a general outline of how a program is executed by the
1It’s not quite sui gene... |
This chapter also introduces the two modes of using
Python. The interactive mode allows the user to interact with the Python
interpreter using the Python shell. |
Python statements and expressions
are entered one at a time, and the interpreter evaluates or executes the
code entered by the user. |
This is an essential tool for experimentation
and learning the details of various language features. Script mode allows
the user to write, save, and execute Python programs. |
This is convenient
since in this mode we can save our work, and run it multiple times
without having to type it again and again at the Python shell.
This chapter also includes a brief introduction to binary numbers and
binary arithmetic.
**Types and literals**
The concept of type is one of the most important in all c... |
Other types are introduced later in the text (for example, function, range, enumerate, etc.).
As types are introduced, examples of literals of each type are given.
Since representation error is a common cause of bewilderment among
beginners, there is some discussion of why this occurs with float objects.
**Variables, ... |
Functional decomposition is a crucial requirement of writing
reliable, robust, correct code.
This chapter explains why we use functions, how functions are defined,
how functions are called, and how values are returned. |
We’ve tried to
keep this “non-technical” and so there’s no discussion of a call stack,
though there is discussion of scope.
Because beginning programmers often introduce side effects into functions where they are undesirable or unnecessary, this chapter makes clear
the distinction between pure functions (those without ... |
In this way, we
also reinforce the idea of information hiding and good functional design.
Do we need to know how the math module implements its sqrt() function?
Of course not. |
Should we have to know how a function is implemented
-----
in order to use it? |
Apart from knowing what constitutes a valid input
and what it returns as an output, no, we do not!
**Style**
Our goal here is to encourage the writing of idiomatic Python. |
Accordingly, we address the high points of PEP 8—the de facto style guide for
Python—and provide examples of good and bad style.
Students don’t always understand how important style is for the readability of one’s code. |
By following style guidelines we can reduce the
cognitive load that’s required to read code, thereby making it easier to
reason about and understand our code.
**Console I/O (input/output)**
This chapter demonstrates how to get input from the user (in command
line programs) and how to format output using f-strings. |
Because fstrings have been around so long now, and because they allow for more
readable code, we’ve avoided presentation of older, and now seldom used,
C-style string formatting.
**Branching**
_Branching is a programming language’s way of handling conditional ex-_
_ecution of code. |
In this chapter, we cover conditions (Boolean expres-_
sions) which evaluate to a true or false (or a value which is “truthy”
or “falsey”—like true or like false). |
Python uses these conditions to determine whether a block of code should be executed. |
In many cases we
have multiple branches—multiple paths of execution that might be taken.
These are implemented with if, elif (a portmanteau of “else if”), and
often else.
One common confusion that beginners face is understanding which
branch is executed in an if/elif/else structure, and hopefully the chapter
makes this... |
This chapter gives clear
guidelines for structuring code based on common idioms in Python. |
It
also addresses how we can incrementally build and test our code.
Unlike many introductory texts, we present assertions in this chapter.
Assertions are easy to understand and their use has great pedagogical
value. |
In order to write an assertion, a programmer must understand
clearly what behavior or output is expected for a given input. |
Using
assertions helps you reason about what should be happening when your
code is executed.
-----
**Sequences**
Sequences—lists, tuples, and strings—are presented in this chapter. |
It
makes sense to present these before presenting loops for two reasons.
First, sequences are iterable, and as such are used in for loops, and without a clear understanding of what constitutes an iterable, understanding
such loops may present challenges. |
Second, we often do work within a
loop which might involve constructing or filtering a list of objects.
Common features of sequences—for example, they are all indexed,
support indexed reads, and are iterable—are highlighted throughout the
chapter.
As this chapter introduces our first mutable type, the Python list, we
p... |
In this chapter we present
the two kinds of loop supported by Python—while loops and for loops.
At this point, students have seen iterables (in the form of sequences)
and Boolean expressions, which are a necessary foundation for a proper
presentation of loops.
Also, this chapter introduces two new types—range and enume... |
Presentation of range entails discussion of arithmetic sequences, and presentation of enumerate works
nicely with tuple unpacking (or more generally, sequence unpacking),
and so these are presented first in this chapter.
This chapter also provides a brief introduction to stacks and queues,
which are trivially implement... |
Students love to write programs
which implement games, and many games involve some chance element or
elements—rolling dice, spinning a wheel, tossing a coin, shuffling a deck,
and so on. |
Another application is in simulations, which may also include
some chance elements. |
All manner of physical and other phenomena can
be simulated with some randomness built in.
This chapter presents Python’s random module, and some of the more
commonly used methods within this module—random.random(), ran```
dom.randint(), random.choice(), and random.shuffle(). |
Much of this is
```
done within the context of games of chance, but we also include some simulations (for example, random walk and Gambler’s Ruin). |
There is also
some discussion of pseudo-random numbers and how Python’s pseudorandom number generator is seeded.
**File I/O (input/output)**
This chapter shows you how to read data from and write data to a file.
File I/O is best accomplished using a context manager. |
Context man
-----
agers were introduced with Python 2.5 in 2006, and are a much preferred
idiom (as compared to using try/finally). |
Accordingly, all file I/O demonstrations make use of context managers created with the Python keyword
```
with.
```
Because so much data is in CSV format (or can be exported to this
format easily), we introduce the csv module in this chapter. |
Using the
```
csv module reduces some of the complexity we face when reading data
```
from a file, since we don’t have to parse it ourselves.
**Exception handling**
In this chapter, we present simple exception handling (using try/except,
but not finally), and explain that some exceptions should not be handled since ... |
We also demonstrate the use of exception handling in input validation. |
When you reach this chapter, you’ll already have seen
```
while loops for input validation, so the addition of exception handling
```
represents only an incremental increase in complexity in this context.
**Data analysis and presentation**
This chapter is motivated in large part by the University of Vermont’s
QD (qu... |
Accordingly, we present some very basic descriptive statistics and introduce Python’s statistics module including
```
statistics.mean(), statistics.pstdev(), and statistics.quantiles().
```
The presentation component of this chapter is done using Matplotlib,
which is the de facto standard for plotting and visualizatio... |
Dictionaries
store information using a key/value model—we look up values in a dictionary by their keys. |
Like sequences, dictionaries are iterable, but since
they have keys rather than indices, this works a little differently. |
We’ll
see three different ways to iterate over a dictionary.
We’ll also learn about hashability in the context of dictionary keys.
**Graphs**
Since graphs are so commonplace in computer science, it seems appropriate to include a basic introduction to graphs in this text. |
Plus, graphs
are really fun!
A graph is a collection of vertices (also called nodes) and edges, which
connect the vertices of the graph. |
The concrete example of a highway map
is used, and an algorithm for breadth-first search (BFS) is demonstrated.
Since queues were introduced in chapter 11, the conceptual leap here—
using a queue in the BFS algorithm—shouldn’t be too great.
-----
###### Assumptions regarding prior knowledge of mathematics
This text... |
Prior exposure to summations and subscripts would help the reader
but is not essential, as these are introduced in the text. The same goes
for mean, standard deviation, and quantiles. |
You might find it helpful if
you’ve seen these before, but these, too, are introduced in the text.
The minimum expectation is that you can add, subtract, multiply
and divide; that you understand exponents and square roots; and that
you understand the precedence of operations, grouping of expressions
with parentheses, a... |
If you
don’t know what a file is, or what a directory is, see Appendix D, or
consult documentation for your operating system. |
Writing and running
programs requires that you understand the basics of a computer file
system.
###### Typographic conventions used in this book
Names of functions, variables, and modules are rendered in fixed-pitch
```
typeface, as are Python keywords, code snippets, and sample output.
print("Hello, World!")
```
... |
Examples: if/else, if/elif, if/elif/else, try/except, try/finally,
_etc._
File names, for example, hello_world.py, and module names, for example, math, are also rendered in fixed-pitch typeface.
Where it is understood that code is entered into the Python shell,
the interactive Python prompt >>> is shown. |
Wherever you see this, you
should understand we’re working in Python shell. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.