Some Snippets of Python
A bunch of bits of code (all jammed together in one file) showing bits and pieces of python. Just do "python python-snippets.py" or grab pieces and try running them.
Size 7.5 kB - File type text/python-sourceFile contents
# three quotes makes a long string, with (potentially) newlines and quotes in it
# this defines a function that takes two strings, prints both of them and then
# evaluates the second.
#
# note too that I've tried to leave the code aligned up to the front of the
# line and without quotes, so you can copy and paste it into a running python
# interpreter
#
def msg(s) :
print "\n\n-------------------------"
print s
msg("lists are nice")
l10 = [0,1,2,3,4,5,6,7,8,9]
print "l10 =", l10
print "print them all"
for i in l10 :
print i
msg("make the same list more easily")
r10 = range(10)
print "r10=", r10
print "print them all"
for i in r10 :
print i
msg("standard a..(b-1) for loop\na=10 ,b=20")
for i in range(10,20) :
print i
msg("""list comprehensions are a way to generate lists with
given elements
how about the squares of 0..9 """)
print [i*i for i in range(10) ]
msg("how about the squares of the even numbers from 0 to 9?")
print [i*i for i in range(10) if i%2 == 0 ]
msg("""squares of the numbers divisible by both 3 and 5 from 0 to 99,
note that "and" is the logical and (&& in java and C and ...)""")
print [i*i for i in range(100) if i%3 == 0 and i%5==0 ]
msg("define the factorial function, and try it")
def fact(i) :
if i < 2 : return 1
return i * fact(i-1)
print "10!=", fact(10)
msg("factorial defined iteratively")
def ifact(i) :
res = 1
for j in range(1,i+1) :
res *= j
return res
print "ifact(100)", ifact(100)
msg("another list comprehension using factorial")
print [fact(i) for i in range(100) ]
msg("even nested list comprehensions using the math.log function")
import math
print [math.log(j) for j in [fact(i) for i in range(100)]]
msg("""or use log without the math prefix by doing :
from math import *""")
from math import *
print [log(j) for j in [fact(i) for i in range(100)]]
msg("use : to extract 'slices' from a list")
l = range(10)
print "l=",l
print "l[2:5]", l[2:5]
print "l[:3]", l[:3]
print "l[-4:]", l[-4:]
print "l[:]", l[:]
msg("strings slice too")
print '"hello"[-3:]', "hello"[-3:]
msg("use append to add a single element")
print "l=", l
l.append(5)
print "l =", l
msg("append has no value though")
print l.append(7)
msg("use del to delete an element")
del l[4]
print l
msg("use + to concatenate lists or strings")
l = range(10) + range(10)
print l
s = "hello" + "--" + "goodbye"
print s
msg("import the sys library and see whats in it")
import sys
dir(sys)
msg("look again at sys, but this time print nicely")
for i in dir(sys) :
print i
msg("import a file (this file, in fact), read the lines and print them ")
for i in open(sys.argv[0]) :
print i
msg("break out space separated words in this file")
for i in open(sys.argv[0]) :
for j in i.split() :
print j
msg("tuples are nice ways to hold elements too")
t=(4,5)
print "t=", t
msg("you can do strange and wondrous things with tuples")
a=4
b=7
print "a=",a,"b=", b
(a,b) = (b,a)
print "a=",a,"b=", b
print "Strictly speaking the parens are not needed here."
a,b = b,a
print "a=",a,"b=", b
msg("tuples are very nice in list comprehensions too")
print [(i, i*i) for i in range(100) if i%3 == 0 and i%5==0 ]
msg("""tuples are also useful in string formatting
formatting codes look like C
%d for decimal %05d for 5 decimal digits and leading zeros
%s for string (and general datatypes)""")
for j in [(i, i*i) for i in range(100) if i%3 == 0 and i%5==0 ] :
print j
print "%2d -> %4d" % j
msg("""dictionaries are useful, look at /usr/share/dict/words and arrange the
words by length with differing lengths""")
d = {}
for i in open("/usr/share/dict/words") :
j = i.strip() # strip off whitespace (spaces and newlines)
l = len(j) # get length
if l in d :
d[l].append(j)
else :
d[l] = [j]
# print all two letter words
print "two letter words"
print d[2]
#print all words of each length
if False : # no, lets not, it is rather long
for i in d.items() :
print "%d -> %s" % i
# better still, sort the lengths
l = d.keys()
# sort is in place and by whatever is the natural sort order
l.sort()
# only for longest words
for j in l[-5:] :
print "words of length :", j
d[j].sort()
for k in d[j] :
print " ", k
# but let's not print the ones with trailing "s"
# either possessive or plural
print "but not the s's"
for j in l[-5:] :
nl = [ k for k in d[j] if not k.endswith("s") ]
if nl != [] :
print "words of length :", j
d[j].sort()
for k in nl :
print " ", k
msg("""
we can also build generators.
generators are like functions, but "yield" results and continue where they
left off
""")
def gen() :
yield 1
yield 2
yield 3
for i in gen() :
print i
def factorials() :
fact = 1
j = 1
while True :
yield fact
j = j+1
fact = fact* j
# don't do this
if False :
for i in factorials() :
print i
# a bit more polite
# this time generate tuples of (j, j!)
def factorialsToN(n) :
fact = 1
j = 1
while j < n :
yield (j, fact)
j = j+1
fact = fact* j
# we can use that in a list
factorialList = [f for f in factorialsToN(2000)]
for i in factorialList[-10:] : # just the last few
print "%04d %d" % i
msg("""lets find out how many zeros there are at the end of those factorials.
We'll write it to "zeros.out" so gnuplot can plot it""")
def zerosAtEndOf(n) :
s = str(n) # make a string
l = list(s) # make a list of it
l.reverse() # reverse the list, in place
c = 0
for i in l :
if i != '0' : break
c += 1
return c
# write the stuff to a file as a sequence of lines
# note the newline in the write string
outf = open("zeros.out", "w")
for j in factorialList :
outf.write( "%04d %03d\n" % (j[0], zerosAtEndOf(j[1])))
msg("""
regular expressions are nice too, and are a nice way to solve
the same problem rather more concisely
"compile" the regexp
"^[0-9]*[1-9](?P<trailzeros>0*)$"
that matches a complete string (^ at front and $ at end)
that contains a bunch of digits [0-9]* followed by one
nonzero digit [1-9]
then a named pattern (so we can extract it later from
the match) which matches a bunch of zeros 0* right up
to the end of the string
""")
import re
pat = re.compile("^[0-9]*[1-9](?P<trailzeros>0*)$")
# a simple test
# get a "match object"
mo = pat.match("12300002000")
print "there are ", len(mo.group("trailzeros")), "trailing zeros in 12300002000"
def newZerosAtEndOf(n) :
return len(pat.match(str(n)).group("trailzeros"))
print "there are ", newZerosAtEndOf(factorialList[999][1]), "trailing zeros in 1000!"
msg("""
Python is object oriented, but in a rather different way than (for instance) Java
the constructor in a class is always named __init__(self, arg1, arg2...)
and methods always refer to self in their definition -- but not when called
""")
class foo :
def __init__(self, x) :
self.x = x # this is how instance variables are defined and initialized
def getX(self) : # this is how methods are defined
return self.x # not just "x"
def setY(self, y) :
self.y = y # instance vars can be made whenever
def getY(self) :
return self.y
def squareY(self) :
x = self.y*self.y # local var to method, not class
return x
x = foo(17) # make one
print x.getX() # x.getX is transformed into a call to getX(x)
x.setY(19)
print x.getY()
print x.squareY()
print x.getX() # see, x is not changed
for i in dir(x):
print i
Click here to get the file