Text stringlengths 1 9.41k |
|---|
They are also why
we were able to raise 2 to such large powers in the examples in Chapter 3. |
Here are the
3.0 and 2.6 cases:
```
>>> 2 ** 200
1606938044258990275541962092341162602522202993782792835301376
>>> 2 ** 200
1606938044258990275541962092341162602522202993782792835301376L
```
Because Python must do extra work to support their extended precision, integer math
is usually substantially slower than... |
However, if you
need the precision, the fact that it’s built in for you to use will likely outweigh its
performance penalty.
**|**
-----
###### Complex Numbers
Although less widely used than the types we’ve been exploring thus far, complex numbers are a distinct core object type in Python. |
If you know what they are, you know
why they are useful; if not, consider this section optional reading.
Complex numbers are represented as two floating-point numbers—the real and imaginary parts—and are coded by adding a j or J suffix to the imaginary part. |
We can also
write complex numbers with a nonzero real part by adding the two parts with a +. For
example, the complex number with a real part of 2 and an imaginary part of −3 is written
```
2 + −3j. |
Here are some examples of complex math at work:
>>> 1j * 1J
(-1+0j)
>>> 2 + 1j * 3
(2+3j)
>>> (2 + 1j) * 3
(6+3j)
```
Complex numbers also allow us to extract their parts as attributes, support all the usual
mathematical expressions, and may be processed with tools in the standard `cmath`
module (the compl... |
Complex numbers typically
find roles in engineering-oriented programs. |
Because they are advanced tools, check
Python’s language reference manual for additional details.
###### Hexadecimal, Octal, and Binary Notation
As described earlier in this chapter, Python integers can be coded in hexadecimal, octal,
and binary notation, in addition to the normal base 10 decimal coding. |
The coding
rules were laid out at the start of this chapter; let’s look at some live examples here.
Keep in mind that these literals are simply an alternative syntax for specifying the value
of an integer object. |
For example, the following literals coded in Python 3.0 or 2.6
produce normal integers with the specified values in all three bases:
`>>> 0o1, 0o20, 0o377` _# Octal literals_
```
(1, 16, 255)
```
`>>> 0x01, 0x10, 0xFF` _# Hex literals_
```
(1, 16, 255)
```
`>>> 0b1, 0b10000, 0b11111111` _# Binary literals_
```
... |
Python prints in decimal (base 10) by default but provides built-in functions that allow you to convert integers to other bases’ digit strings:
```
>>> oct(64), hex(64), bin(64)
('0100', '0x40', '0b1000000')
```
**|**
-----
The oct function converts decimal to octal, hex to hexadecimal, and bin to binary. |
To
go the other way, the built-in int function converts a string of digits to an integer, and
an optional second argument lets you specify the numeric base:
```
>>> int('64'), int('100', 8), int('40', 16), int('1000000', 2)
(64, 64, 64, 64)
```
`>>> int('0x40', 16), int('0b1000000', 2)` _# Literals okay too_
```
... |
Therefore, it has a similar effect (but usually runs more slowly—it
actually compiles and runs the string as a piece of a program, and it assumes you can
trust the source of the string being run; a clever user might be able to submit a string
that deletes files on your machine!):
```
>>> eval('64'), eval('0o100'), ev... |
First, Python 2.6 users should remember that you can
code octals with simply a leading zero, the original octal format in Python:
`>>> 0o1, 0o20, 0o377` _# New octal format in 2.6 (same as 3.0)_
```
(1, 16, 255)
```
`>>> 01, 020, 0377` _# Old octal literals in 2.6 (and earlier)_
```
(1, 16, 255)
```
In 3.0, the ... |
Even though it’s
not an error in 2.6, be careful not to begin a string of digits with a leading zero unless
you really mean to code an octal value. |
Python 2.6 will treat it as base 8, which may
not work as you’d expect—010 is always decimal 8 in 2.6, not decimal 10 (despite what
you may or may not think!). |
This, along with symmetry with the hex and binary forms,
is why the octal format was changed in 3.0—you must use 0o010 in 3.0, and probably
should in 2.6.
Secondly, note that these literals can produce arbitrarily long integers. |
The following,
for instance, creates an integer with hex notation and then displays it first in decimal
and then in octal and binary with converters:
```
>>> X = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF
>>> X
5192296858534827628530496329220095L
>>> oct(X)
```
**|**
-----
```
'017777777777777777777777777777777777777... |
This includes
operators that treat integers as strings of binary bits. |
For instance, here it is at work
performing bitwise shift and Boolean operations:
`>>> x = 1` _# 0001_
`>>> x << 2` _# Shift left 2 bits: 0100_
```
4
```
`>>> x | 2` _# Bitwise OR: 0011_
```
3
```
`>>> x & 1` _# Bitwise AND: 0001_
```
1
```
In the first expression, a binary 1 (in base 2, 0001) is shifted left... |
The last two operations perform a binary OR (0001|0010 = 0011) and a
binary AND (0001&0001 = 0001). |
Such bit-masking operations allow us to encode multiple flags and other values within a single integer.
This is one area where the binary and hexadecimal number support in Python 2.6 and
3.0 become especially useful—they allow us to code and inspect numbers by bit-strings:
`>>> X = 0b0001` _# Binary literals_
`>>> X ... |
It’s supported if you need
it, and it comes in handy if your Python code must deal with things like network packets
or packed binary data produced by a C program. |
Be aware, though, that bitwise operations are often not as important in a high-level language such as Python as they are in
a low-level language such as C. |
As a rule of thumb, if you find yourself wanting to flip
bits in Python, you should think about which language you’re really coding. |
In general,
there are often better ways to encode information in Python than bit strings.
In the upcoming Python 3.1 release, the integer bit_length method also
allows you to query the number of bits required to represent a number’s
value in binary. |
The same effect can often be achieved by subtracting 2
from the length of the bin string using the len built-in function we met
in Chapter 4, though it may be less efficient:
```
>>> X = 99
>>> bin(X), X.bit_length()
('0b1100011', 7)
>>> bin(256), (256).bit_length()
('0... |
The pow and abs built-in functions,
for instance, compute powers and absolute values, respectively. |
Here are some examples of the built-in math module (which contains most of the tools in the C language’s
math library) and a few built-in functions at work:
```
>>> import math
```
`>>> math.pi, math.e` _# Common constants_
```
(3.1415926535897931, 2.7182818284590451)
```
`>>> math.sin(2 * math.pi / 180)` _# Sine... |
There are a variety of ways to drop the
**|**
-----
decimal digits of floating-point numbers. |
We met truncation and floor earlier; we can
also round, both numerically and for display purposes:
`>>> math.floor(2.567), math.floor(-2.567)` _# Floor (next-lower integer)_
```
(2, −3)
```
`>>> math.trunc(2.567), math.trunc(−2.567)` _# Truncate (drop decimal digits)_
```
(2, −2)
```
`>>> int(2.567), int(−2.567)... |
As also described earlier, the second to last
test here will output (3, 2, 2.57) if we wrap it in a print call to request a more userfriendly display. |
The last two lines still differ, though—round rounds a floating-point
number but still yields a floating-point number in memory, whereas string formatting
produces a string and doesn’t yield a modified number:
```
>>> (1 / 3), round(1 / 3, 2), ('%.2f' % (1 / 3))
(0.33333333333333331, 0.33000000000000002, '0.33')
`... |
In other words, modules are external components, but built-in functions live in an implied namespace that
Python automatically searches to find names used in your program. |
This namespace
corresponds to the module called builtins in Python 3.0 (__builtin__ in 2.6). |
There
**|**
-----
is much more about name resolution in the function and module parts of this book;
for now, when you hear “module,” think “import.”
The standard library random module must be imported as well. |
This module provides
tools for picking a random floating-point number between 0 and 1, selecting a random
integer between two numbers, choosing an item at random from a sequence, and more:
```
>>> import random
>>> random.random()
0.44694718823781876
>>> random.random()
0.28970426439292829
>>> random.randin... |
For more details, see Python’s library manual.
###### Other Numeric Types
So far in this chapter, we’ve been using Python’s core numeric types—integer, floating
point, and complex. |
These will suffice for most of the number crunching that most
programmers will ever need to do. |
Python comes with a handful of more exotic numeric
types, though, that merit a quick look here.
###### Decimal Type
Python 2.4 introduced a new core numeric type: the decimal object, formally known
as Decimal. |
Syntactically, decimals are created by calling a function within an imported
module, rather than running a literal expression. |
Functionally, decimals are like
floating-point numbers, but they have a fixed number of decimal points. |
Hence, decimals are fixed-precision floating-point values.
For example, with decimals, we can have a floating-point value that always retains just
two decimal digits. |
Furthermore, we can specify how to round or truncate the extra
decimal digits beyond the object’s cutoff. |
Although it generally incurs a small performance penalty compared to the normal floating-point type, the decimal type is well suited
to representing fixed-precision quantities like sums of money and can help you achieve
better numeric accuracy.
**|**
-----
###### The basics
The last point merits elaboration. |
As you may or may not already know, floating-point
math is less than exact, because of the limited space used to store values. For example,
the following should yield zero, but it does not. |
The result is close to zero, but there
are not enough bits to be precise here:
```
>>> 0.1 + 0.1 + 0.1 - 0.3
5.5511151231257827e-17
```
Printing the result to produce the user-friendly display format doesn’t completely help
either, because the hardware related to floating-point math is inherently limited in
terms ... |
When decimals of different precision are mixed in expressions, Python converts up to the largest number of decimal digits automatically:
```
>>> Decimal('0.1') + Decimal('0.10') + Decimal('0.10') - Decimal('0.30')
Decimal('0.00')
```
In Python 3.1 (to be released after this book’s publication), it’s also
possible ... |
The conversion is
exact but can sometimes yield a large number of digits.
###### Setting precision globally
Other tools in the decimal module can be used to set the precision of all decimal numbers, set up error handling, and more. |
For instance, a context object in this module
allows for specifying precision (number of decimal digits) and rounding modes (down,
ceiling, etc.). |
The precision is applied globally for all decimals created in the calling
thread:
```
>>> import decimal
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.1428571428571428571428571429')
>>> decimal.getcontext().prec = 4
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.1429')
```
**|**
-----
T... |
Decimals are essentially an alternative to manual rounding and string
formatting in this context:
```
>>> 1999 + 1.33
2000.3299999999999
>>>
>>> decimal.getcontext().prec = 2
>>> pay = decimal.Decimal(str(1999 + 1.33))
>>> pay
Decimal('2000.33')
###### Decimal context manager
```
In Python 2.6 and 3.0 (... |
The precision is reset to its original value
on statement exit:
```
C:\misc> C:\Python30\python
>>> import decimal
>>> decimal.Decimal('1.00') / decimal.Decimal('3.00')
Decimal('0.3333333333333333333333333333')
>>>
>>> with decimal.localcontext() as ctx:
... |
ctx.prec = 2
... |
decimal.Decimal('1.00') / decimal.Decimal('3.00')
...
Decimal('0.33')
>>>
>>> decimal.Decimal('1.00') / decimal.Decimal('3.00')
Decimal('0.3333333333333333333333333333')
```
Though useful, this statement requires much more background knowledge than you’ve
obtained at this point; watch for coverage of the wit... |
And because decimals
address some of the same floating-point accuracy issues as the fraction type, let’s move
on to the next section to see how the two compare.
###### Fraction Type
Python 2.6 and 3.0 debut a new numeric type, Fraction, which implements a rational
_number object. |
It essentially keeps both a numerator and a denominator explicitly, so_
as to avoid some of the inaccuracies and limitations of floating-point math.
###### The basics
```
Fraction is a sort of cousin to the existing Decimal fixed-precision type described in the
```
prior section, as both can be used to control numeri... |
It’s also used in similar ways—like
**|**
-----
```
Decimal, Fraction resides in a module; import its constructor and pass in a numerator
```
and a denominator to make one. |
The following interaction shows how:
```
>>> from fractions import Fraction
```
`>>> x = Fraction(1, 3)` _# Numerator, denominator_
`>>> y = Fraction(4, 6)` _# Simplified to 2, 3 by gcd_
```
>>> x
Fraction(1, 3)
>>> y
Fraction(2, 3)
>>> print(y)
2/3
```
Once created, Fractions can be used in mathematica... |
To compare, here are the same operations run with floating-point objects, and notes on their limited accuracy:
`>>> a = 1 / 3.0` _# Only as accurate as floating-point hardware_
`>>> b = 4 / 6.0` _# Can lose precision over calculations_
```
>>> a
0.33333333333333331
>>> b
0.66666666666666663
>>> a + b
1.0
... |
Both `Fraction and`
**|**
-----
```
Decimal provide ways to get exact results, albeit at the cost of some speed. |
For instance,
```
in the following example (repeated from the prior section), floating-point numbers do
not accurately give the zero answer expected, but both of the other types do:
`>>> 0.1 + 0.1 + 0.1 - 0.3` _# This should be zero (close, but not exact)_
```
5.5511151231257827e-17
>>> from fractions import Frac... |
Continuing
the preceding interaction:
`>>> (1 / 3) + (6 / 12)` _# Use ".0" in Python 2.6 for true "/"_
```
0.83333333333333326
```
`>>> Fraction(6, 12)` _# Automatically simplified_
```
Fraction(1, 2)
>>> Fraction(1, 3) + Fraction(6, 12)
Fraction(5, 6)
>>> decimal.Decimal(str(1/3)) + decimal.Decimal(str(6/1... |
Trace through the following interaction to
```
see how this pans out (the * in the second test is special syntax that expands a tuple
into individual arguments; more on this when we study function argument passing in
Chapter 18):
`>>> (2.5).as_integer_ratio()` _# float object method_
```
(5, 2)
>>> f = 2.5
```
`... |
Study the following interaction to see how
this works:
```
>>> x
Fraction(1, 3)
```
`>>> x + 2` _# Fraction + int -> Fraction_
```
Fraction(7, 3)
```
`>>> x + 2.0` _# Fraction + float -> float_
```
2.3333333333333335
```
`>>> x + (1./3)` _# Fraction + float -> float_
```
0.66666666666666663
>>> x + (4./3... |
When needed, you can simplify such results by limiting
the maximum denominator value:
**|**
-----
```
>>> 4.0 / 3
1.3333333333333333
```
`>>> (4.0 / 3).as_integer_ratio()` _# Precision loss from float_
```
(6004799503160661, 4503599627370496)
>>> x
Fraction(1, 3)
>>> a = x + Fraction(*(4.0 / 3).as_inte... |
By definition, an item appears only once in a set, no matter how many
times it is added. |
As such, sets have a variety of applications, especially in numeric and
database-focused work.
Because sets are collections of other objects, they share some behavior with objects
such as lists and dictionaries that are outside the scope of this chapter. |
For example,
sets are iterable, can grow and shrink on demand, and may contain a variety of object
types. |
As we’ll see, a set acts much like the keys of a valueless dictionary, but it supports
extra operations.
However, because sets are unordered and do not map keys to values, they are neither
sequence nor mapping types; they are a type category unto themselves. |
Moreover, because sets are fundamentally mathematical in nature (and for many readers, may seem
more academic and be used much less often than more pervasive objects like dictionaries), we’ll explore the basic utility of Python’s set objects here.
###### Set basics in Python 2.6
There are a few ways to make sets toda... |
Since this book covers both, let’s begin with the 2.6 case, which also is
available (and sometimes still required) in 3.0; we’ll refine this for 3.0 extensions in a
moment. |
To make a set object, pass in a sequence or other iterable object to the builtin set function:
```
>>> x = set('abcde')
>>> y = set('bdxyz')
```
**|**
-----
You get back a set object, which contains all the items in the object passed in (notice
that sets do not have a positional ordering, and so are not sequenc... |
Note that we can’t perform these expressions on plain sequences—we_
must create sets from them in order to apply these tools:
`>>> 'e' in x` _# Membership_
```
True
```
`>>> x – y` _# Difference_
```
set(['a', 'c', 'e'])
```
`>>> x | y` _# Union_
```
set(['a', 'c', 'b', 'e', 'd', 'y', 'x', 'z'])
```
`>>> x & ... |
Assuming x and
```
y are still as they were in the prior interaction:
```
`>>> z = x.intersection(y)` _# Same as x & y_
```
>>> z
set(['b', 'd'])
```
`>>> z.add('SPAM')` _# Insert one item_
```
>>> z
set(['b', 'd', 'SPAM'])
```
`>>> z.update(set(['X', 'Y']))` _# Merge: in-place union_
```
>>> z
set(['Y',... |
Because they are unordered, though, they don’t support sequence
operations like indexing and slicing:
```
>>> for item in set('abc'): print(item * 3)
...
aaa
```
**|**
-----
```
ccc
bbb
```
Finally, although the set expressions shown earlier generally require two sets, their
method-based counterparts can... |
Although set operations can be coded manually in Python with other types, like
lists and dictionaries (and often were in the past), Python’s built-in sets use efficient
algorithms and implementation techniques to provide quick and standard operation.
###### Set literals in Python 3.0
If you think sets are “cool,” the... |
In Python 3.0 we
can still use the set built-in to make set objects, but 3.0 also adds a new set literal form,
using the curly braces formerly reserved for dictionaries. |
In 3.0, the following are
equivalent:
```
set([1, 2, 3, 4]) # Built-in call
{1, 2, 3, 4} # 3.0 set literals
```
This syntax makes sense, given that sets are essentially like _valueless dictionaries—_
because they are unordered, unique, and immutable, a set’s items behave much like a
dictionary’s k... |
This operational similarity is even more striking given that dictionary
key lists in 3.0 are view objects, which support set-like behavior such as intersections
and unions (see Chapter 8 for more on dictionary view objects).
In fact, regardless of how a set is made, 3.0 displays it using the new literal format. |
The
```
set built-in is still required in 3.0 to create empty sets and to build sets from existing
```
iterable objects (short of using set comprehensions, discussed later in this chapter), but
the new literal is convenient for initializing sets of known structure:
```
C:\Misc> c:\python30\python
```
`>>> set([1, 2... |
Empty sets must be created with the set
built-in, and print the same way:
`>>> S1 - {1, 2, 3, 4}` _# Empty sets print differently_
```
set()
```
`>>> type({})` _# Because {} is an empty dictionary_
```
<class 'dict'>
```
`>>> S = set()` _# Initialize an empty set_
```
>>> S.add(1.23)
>>> S
{1.23}
```
As i... |
Hence, lists and dictionaries
cannot be embedded in sets, but tuples can if you need to store compound values.
Tuples compare by their full values when used in set operations:
```
>>> S
{1.23}
```
`>>> S.add([1, 2, 3])` _# Only mutable objects work in a set_
```
TypeError: unhashable type: 'list'
>>> S.add({'a... |
Sets themselves are mutable
too, and so cannot be nested in other sets directly; if you need to store a set inside
another set, the frozenset built-in call works just like set but creates an immutable set
that cannot change and thus can be embedded in other sets.
###### Set comprehensions in Python 3.0
In addition to... |
Set comprehensions
run a loop and collect the result of an expression on each iteration; a loop variable gives
access to the current iteration value for use in the collection expression. |
The result is a
new set created by running the code, with all the normal set behavior:
`>>> {x ** 2 for x in [1, 2, 3, 4]}` _# 3.0 set comprehension_
```
{16, 1, 4, 9}
```
In this expression, the loop is coded on the right, and the collection expression is coded
on the left (x ** 2). |
As for list comprehensions, we get back pretty much what this
expression says: “Give me a new set containing X squared, for every X in a list.” Comprehensions can also iterate across other kinds of objects, such as strings (the first of
the following examples illustrates the comprehension-based way to make a set from a... |
In
Chapter 8, we’ll meet a first cousin in 3.0, the dictionary comprehension, and I’ll have
much more to say about all comprehensions (list, set, dictionary, and generator) later,
especially in Chapters14 and 20. |
As we’ll learn later, all comprehensions, including
sets, support additional syntax not shown here, including nested loops and if tests,
which can be difficult to understand until you’ve had a chance to study larger
statements.
###### Why sets?
Set operations have a variety of common uses, some more practical than ma... |
Simply convert the collection to a set, and then
convert it back again (because sets are iterable, they work in the list call here):
```
>>> L = [1, 2, 1, 3, 2, 4, 5]
>>> set(L)
{1, 2, 3, 4, 5}
```
`>>> L = list(set(L))` _# Remove duplicates_
```
>>> L
[1, 2, 3, 4, 5]
```
Sets can also be used to keep track... |
For example, the transitive module reloader and inheritance tree lister examples we’ll study in Chapters 24 and 30, respectively, must keep
track of items visited to avoid loops. |
Although recording states visited as keys in a
dictionary is efficient, sets offer an alternative that’s essentially equivalent (and may be
more or less intuitive, depending on who you ask).
Finally, sets are also convenient when dealing with large data sets (database query
results, for example)—the intersection of tw... |
To illustrate, here’s a somewhat more realistic example of set operations at work, applied to lists of people in a
hypothetical company, using 3.0 set literals (use set in 2.6):
```
>>> engineers = {'bob', 'sue', 'ann', 'vic'}
>>> managers = {'tom', 'sue'}
```
`>>> 'bob' in engineers` _# Is bob an engineer?_
```
... |
(superset)_
```
False
```
`>>> {'bob', 'sue'} < engineers` _# Are both engineers? |
(subset)_
```
True
```
`>>> (managers | engineers) > managers` _# All people is a superset of managers_
```
True
```
`>>> managers ^ engineers` _# Who is in one but not both?_
```
{'vic', 'bob', 'ann', 'tom'}
```
`>>> (managers | engineers) - (managers ^ engineers)` _# Intersection!_
```
{'sue'}
```
You can... |
Also stay tuned for Chapter 8’s
revival of some of the set operations we’ve seen here, in the context of dictionary view
objects in Python 3.0.
###### Booleans
Some argue that the Python Boolean type, bool, is numeric in nature because its two
values, True and False, are just customized versions of the integers 1 and... |
Although that’s all most programmers need to know, let’s explore this type in a bit more detail.
More formally, Python today has an explicit Boolean data type called bool, with the
values True and False available as new preassigned built-in names. |
Internally, the names
```
True and False are instances of bool, which is in turn just a subclass (in the object
```
oriented sense) of the built-in integer type int. |
True and False behave exactly like the
integers 1 and 0, except that they have customized printing logic—they print themselves as the words True and False, instead of the digits 1 and 0. |
bool accomplishes this
by redefining str and repr string formats for its two objects.
Because of this customization, the output of Boolean expressions typed at the interactive prompt prints as the words True and False instead of the older and less obvious 1
and 0. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.