12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

mixed in expressions, <strong>Python</strong> converts up to the largest number of decimal digitsautomatically:>>> Decimal('0.1') + Decimal('0.10') + Decimal('0.10') - Decimal('0.30')Decimal("0.00")Other tools in the decimal module can be used to set the precision of all decimalnumbers, and more. For instance, a context object in this module allows for specifyingprecision (number of decimal digits), and rounding modes (down, ceiling, etc.):>>> decimal.Decimal(1) / decimal.Decimal(7)Decimal("0.1428571428571428571428571429")>>> decimal.getcontext( ).prec = 4>>> decimal.Decimal(1) / decimal.Decimal(7)Decimal("0.1429")Because use of the decimal type is still somewhat rare in practice, I’ll defer to<strong>Python</strong>’s standard library manuals and interactive help for more details.Sets<strong>Python</strong> 2.4 also introduced a new collection type, the set. Because they are collectionsof other objects, sets are arguably outside the scope of this chapter. But becausethey support mathematical set operations, we’ll take a look at their basic utility here.To make a set object, pass in a sequence or other iterable object to the built-in setfunction (similar utility is available in a module prior to <strong>Python</strong> 2.4, but no import isrequired as of 2.4):>>> x = set('abcde')>>> y = set('bdxyz')You get back a set object, which contains all the items in the object passed in (noticethat sets do not have a positional ordering, and so are not sequences):>>> xset(['a', 'c', 'b', 'e', 'd'])Sets made this way support the common mathematical set operations with expressionoperators. Note that we can’t perform these operations on plain sequences—wemust create sets from them in order to apply these tools:>>> 'e' in x # Set membershipTrue>>> x – y # Set differenceset(['a', 'c', 'e'])>>> x | y # Set unionset(['a', 'c', 'b', 'e', 'd', 'y', 'x', 'z'])>>> x & y # Set intersectionset(['b', 'd'])108 | Chapter 5: Numbers

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!