Python Crash Course Strings, Math
Python Crash Course Strings, Math
strings, math
Bachelors
V1.0
dd 12-12-2014
Hour 6
>>>
>>>
>>>
>>>
>>>
triple-quotes (docstrings)
-h
Hostname to connect to\n'
raw string
String Methods
SN
1
2
3
6
7
String Methods
SN Methods with Description
19 ljust(width[, fillchar])
Returns a space-padded string with the original
string left-justified to a total of width columns
20 lower()
Converts all uppercase letters in string to lowercase
21 lstrip()
Removes all leading whitespace in string
22 maketrans()
Returns a translation table to be used in translate
function.
23 max(str)
Returns the max alphabetical character from the
string str
24 min(str)
Returns the min alphabetical character from the
string str
25 replace(old, new [, max])
Replaces all occurrences of old in string with new, or
at most max occurrences if max given
26 rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string
27 rindex( str, beg=0, end=len(string))
Same as index(), but search backwards in string
28 rjust(width,[, fillchar])
Returns a space-padded string with the original
string right-justified to a total of width columns.
29 rstrip()
Removes all trailing whitespace of string
30 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not
provided) and returns list of substrings; split into at
most num substrings if given
Escape characters
Backslash
notation
Hexadecimal
character
Description
\a
0x07
Bell or alert
\b
0x08
Backspace
\cx
Control-x
\C-x
Control-x
\e
0x1b
Escape
\f
0x0c
Formfeed
\M-\C-x
\n
Meta-Control-x
0x0a
\nnn
Newline
Octal notation, where n is in the range 0.7
\r
0x0d
Carriage return
\s
0x20
Space
\t
0x09
Tab
\v
0x0b
Vertical tab
\x
Character x
\xnn
String formatting
Symbol
Conversion
Symbol Functionality
%c
character
%s
left justification
%i
%d
<sp>
%u
%o
octal integer
%x
%X
%e
%E
(var)
%f
m.n.
%g
%G
str.format()
>>> li = [12,45,78,784,2,69,1254,4785,984]
>>> print map('the number is {}'.format,li)
['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the
number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the
number is 984']
Unicode strings
# Numbers to strings:
str(123), str(2**1000)
str(1.e10), str(1.+2j)
# Strings to numbers:
int("123"), int("1234567890"*100)
float("1.23"), float("1.23e10")
float("1.23 e10") # Error
"123".isdigit()
"1.23".isdigit() # :-(
abs(-2.)
abs(1+1j)
max(1,2,3,4)
min(1,2,3,4)
hex(17), oct(-5)
round(1.23456, 2) # negative precision allowed
Comparisons:
>>> 5 * 2 == 4 + 6
True
>>> 0.12 * 2 == 0.1 + 0.14
False
>>> a = 0.12 * 2; b = 0.1 + 0.14
>>> eps = 0.0001
>>> a - eps < b < a + eps
True
Returns ( description )
abs(x)
ceil(x)
Function
Description
acos(x)
asin(x)
cmp(x, y)
atan(x)
exp(x)
The exponential of x: ex
atan2(y, x)
fabs(x)
floor(x)
cos(x)
hypot(x, y)
log(x)
log10(x)
sin(x)
tan(x)
degrees(x)
radians(x)
The fractional and integer parts of x in a twoitem tuple. Both parts have the same sign as x.
The integer part is returned as a float.
pow(x, y)
Comparson operators
Assume variable a holds 10 and variable b holds 20 then:
Operator Description
Example
==
(a == b) is not true.
<>
>
<
>=
!=
<=
(a != b) is true.
(a < b) is true.
Bitwise Operators
Bitwise operator works on
bits and perform bit by bit
operation.
Example
&
<<
>>
a = 0011 1100
b = 0000 1101
----------------a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Logical Operators
How logical operators work in Python:
Operator
Description
and
(a and b) is false.
or
(a or b) is true.
not
Called Logical NOT Operator. Use not(a and b) is false. not(a and b) is true.
to reverses the logical state of
its operand. If a condition is true
then Logical NOT operator will
make false.
Number formatting
>>> print "Today's stock price: %f" % 50.4625
50.462500
>>> print "Today's stock price: %.2f" % 50.4625
50.46
>>> print "Change since yesterday: %+.2f" % 1.5
+1.50
Accuracy
Our society depends on software. This may be an obvious statement.
Software bugs cost the U.S. economy 60 billion dollars each year. It is
stated that a third of that cost could be eliminated by improved testing.
Bugs can cause accidents, also in science, although in astronomy
people usually do not end up in a hospital.
In this lecture we focus on floating point numbers. It is important to
realize that these numbers are represented by a limited number of bits
and therefore are limited to a certain precision. We discuss two sources
of error:
Rounding,
and
Cancellation.
Internal representation
>>> 0.1+0.2
0.30000000000000004
>>> from decimal import Decimal
>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal (0.2)
Decimal('0.200000000000000011102230246251565404236316680908203125')
>>> Decimal (0.1+0.2)
Decimal('0.3000000000000000444089209850062616169452667236328125')
Rounding
Rounding
Enhancing the accuracy
Replacing the condition in the while statement with a better one.
def step( a, b, n ):
""" Function to calculate intermediate steps in an interval """
eps = 1.0e-8
h = (b-a) / n
x = a
print "%.18f" % (x)
while (abs(x b) > eps):
x = x + h
print "%.18f" % (x)
step(1.0, 2.0, 3)
1.000000000000000000
1.333333333333333259
1.666666666666666519
1.999999999999999778
Rounding
Enhancing the accuracy
Replacing the while with a for loop using an integer.
def step( a, b, n ):
""" Function to calculate intermediate steps in an interval """
eps = 1.0e-8
h = (b-a) / n
x = a
print "%.18f" % (x)
for i in range(0,n+1):
x = x + h
print "%.18f" % (x)
step(1.0, 2.0, 3)
1.000000000000000000
1.333333333333333259
1.666666666666666519
1.999999999999999778
Cancellation
Cancellation occurs from the subtraction of two almost equal numbers. If
you subtract two numbers with approximate equal values then the errors are
also comparable and in the subtraction we get a small value with a relatively
big error (which can be demonstrated with simple error analysis). This effect
is demonstrated when you try to calculate the roots of the equation:
This equation has two analytical expressions for finding the roots:
Cancellation
Consider the following code
import math
a=1.0e-5; b = 1.0e3; c = 1.0e3
sq = math.sqrt(b*b-4.0*a*c)
xa1 = (-b + sq)/(2.0*a)
xa2 = (-b - sq)/(2.0*a)
print "\nx1,x2: ", xa1,xa2
print "We expect: x1*x2-c/a=0, but result is:", xa1*xa2-c/a
print "x1 from c/(a*x2)=", c/(a*xa2)
xb1 = (-2.0*c) / (b + sq)
xb2 = (-2.0*c) / (b - sq)
print "\nx1,x2: ", xb1,xb2
print "We expect x1*x2-c/a=0, but result is:", xb1*xb2-c/a
print "x2 from c/(a*x1)", c/(a*xb1)
print "\nsqrt should be 999.99998, and result is: %12f "% sq
x1,x2: -1.00000001 -99999999.1156
We expect x1*x2-c/a=0, but result is: 0.115607380867
x2 from c/(a*x1) -99999999.0
sqrt should be 999.99998, and result is:
999.999980
Logical Operators
End