mystr = "\n" mystr = r"\n" mystr = "Jon 'Maddog' Orwant" mystr = 'Jon "Maddog" Orwant' mystr = 'Jon \'Maddog\' Orwant' mystr = "Jon \"Maddog\" Orwant" mystr = """
This is a multiline string literal
enclosed in triple double quotes.
"""
mystr = '''
And this is a multiline string literal
enclosed in triple single quotes.
'''
import struct
(lead, s1, s2), tail = struct.unpack("5s 3x 8s 8s", data[:24]), data[24:]
fivers = struct.unpack("5s" * (len(data)//5), data)
fivers = print [x[i*5:i*5+5] for i in range(len(x)/5)]
chars = list(data)
mystr = "This is what you have"
first = mystr[0] start = mystr[5:7] rest = mystr[13:] last = mystr[-1] end = mystr[-4:] piece = mystr[-8:-5] mystr = "This is what you have"
mystr = mystr[:5] + "wasn't" + mystr[7:]
mystr = "This is what you have"
mystr = mystr.replace(" is ", " wasn't ")
import array
mystr = array.array("c", "This is what you have")
mystr[5:7] = array.array("c", "wasn't")
from UserString import MutableString
mystr = MutableString("This is what you have")
mystr[-12:] = "ondrous"
if txt in mystr[-10:]:
print "'%s' found in last 10 characters"%txt
if mystr.startswith(txt):
print "%s starts with %s."%(mystr, txt)
if mystr.endswith(txt):
print "%s ends with %s."%(mystr, txt)
myvar = myvar or some_default
myvar2 = myvar or some_default
myvar |= some_default
myvar = default_value
if some_condition:
pass
myvar = somefunc()
if not myvar:
myvar = default_value
def myfunc(myvar="a"):
return myvar + "b"
print myfunc(), myfunc("c")
def myfunc(myvar=[]):
myvar.append("x")
return myvar
print myfunc(), myfunc()
def myfunc(myvar=None):
if myvar is None:
myvar = []
myvar.append("x")
return myvar
print myfunc(), myfunc()
a = b or c
if b:
a = b
else:
a = c
if not x:
x = y
try:
a = b
except NameError:
a = c
foo = bar or "DEFAULT VALUE"
import getpass
user = getpass.getuser()
import os
user = os.environ.get("USER")
if user is None:
user = os.environ.get("LOGNAME")
if not starting_point:
starting_point = "Greenwich"
if not a: a = b
if b: a = b
else:
a = c
v1, v2 = v2, v1
temp = a
a = b
b = temp
a = "alpha"
b = "omega"
a, b = b, a alpha, beta, production = "January March August".split()
alpha, beta, production = beta, production, alpha
num = ord(char)
char = chr(num)
char = "%c" % num
print "Number %d is character %c" % (num, num)
print "Number %(n)d is character %(n)c" % {"n": num}
print "Number %(num)d is character %(num)c" % locals()
ascii_character_numbers = [ord(c) for c in "sample"]
print ascii_character_numbers
word = "".join([chr(n) for n in ascii_character_numbers])
word = "".join([chr(n) for n in [115, 97, 109, 112, 108, 101]])
print word
hal = "HAL"
ibm = "".join([chr(ord(c)+1) for c in hal]) print ibm
mylist = list(mystr)
for char in mystr:
pass mystr = "an apple a day"
uniq = sorted(set(mystr))
print "unique chars are: '%s'" % "".join(uniq)
ascvals = [ord(c) for c in mystr]
print "total is %s for '%s'."%(sum(ascvals), mystr)
def checksum(myfile):
values = [ord(c) for line in myfile for c in line]
return sum(values)%(2**16) - 1
import fileinput
print checksum(fileinput.input())
print checksum(open("C:/test.txt") print checksum("sometext") import sys, select
import re
DELAY = 1
if re.match("^-\d+$",sys.argv[1]):
DELAY=-int(sys.argv[1])
del sys.argv[1]
for ln in fileinput.input():
for c in ln:
sys.stdout.write(c)
sys.stdout.flush()
select.select([],[],[], 0.005 * DELAY)
revchars = mystr[::-1] revwords = " ".join(mystr.split(" ")[::-1])
mylist = list(mystr)
mylist.reverse()
revbytes = "".join(mylist)
mylist = mystr.split()
mylist.reverse()
revwords = ' '.join(mylist)
revchars = "".join(reversed(mystr))
revwords = " ".join(reversed(mystr.split(" ")))
for char in reversed(mystr):
pass word = "reviver"
is_palindrome = (word == word[::-1])
def get_palindromes(fname):
for line in open(fname):
word = line.rstrip()
if len(word) > 5 and word == word[::-1]:
yield word
long_palindromes = list(get_palindromes("/usr/share/dict/words"))
def rev_string(mystr):
mylist = list(mystr)
mylist.reverse()
return "".join(mylist)
long_palindromes=[]
for line in open("/usr/share/dict/words"):
word = line.rstrip()
if len(word) > 5 and word == rev_string(word):
long_palindromes.append(word)
print long_palindromes
mystr.expandtabs()
mystr.expandtabs(4)
text = "I am %(rows)s high and %(cols)s long"%{"rows":24, "cols":80)
print text
rows, cols = 24, 80
text = "I am %(rows)s high and %(cols)s long"%locals()
print text
import re
print re.sub("\d+", lambda i: str(2 * int(i.group(0))), "I am 17 years old")
class SafeDict(dict):
def __getitem__(self, key):
return self.get(key, "[No Variable: %s]"%key)
hi = "Hello"
text = "%(hi)s and %(bye)s!"%SafeDict(locals())
print text
from string import Template
x = Template("$hi and $bye!")
hi = "Hello"
print x.safe_substitute(locals())
print x.substitute(locals())
mystr = "bo peep".upper() mystr = mystr.lower() mystr = mystr.capitalize() beast = "python"
caprest = beast.capitalize().swapcase() print "thIS is a loNG liNE".title()
if a.upper() == b.upper():
print "a and b are the same"
import random
def randcase_one(letter):
if random.randint(0,5): return letter.lower()
else:
return letter.upper()
def randcase(myfile):
for line in myfile:
yield "".join(randcase_one(letter) for letter in line[:-1])
for line in randcase(myfile):
print line
"I have %d guanacos." % (n + 1)
print "I have", n+1, "guanacos."
from string import Template
email_template = Template("""\
To: $address
From: Your Bank
CC: $cc_number
Date: $date
Dear $name,
Today you bounced check number $checknum to us.
Your account is now closed.
Sincerely,
the management
""")
import random
import datetime
person = {"address":"Joe@somewhere.com",
"name": "Joe",
"cc_number" : 1234567890,
"checknum" : 500+random.randint(0,99)}
print email_template.substitute(person, date=datetime.date.today())
var = """
your text
goes here
"""
import re
re_leading_blanks = re.compile("^\s+",re.MULTILINE)
var1 = re_leading_blanks.sub("",var)[:-1]
var2 = "\n".join([line.lstrip() for line in var.split("\n")[1:-1]])
poem = """
Here's your poem:
Now far ahead the Road has gone,
And I must follow, if I can,
Pursuing it with eager feet,
Until it joins some larger way
Where many paths and errand meet.
And whither then? I cannot say.
--Bilbo in /usr/src/perl/pp_ctl.c
"""
import textwrap
print textwrap.dedent(poem)[1:-1]
from textwrap import wrap
output = wrap(para,
initial_indent=leadtab
subsequent_indent=nexttab)
txt = """\
Folding and splicing is the work of an editor,
not a mere collection of silicon
and
mobile electrons!
"""
from textwrap import TextWrapper
wrapper = TextWrapper(width=20,
initial_indent=" "*4,
subsequent_indent=" "*2)
print "0123456789" * 2
print wrapper.fill(txt)
"""Expected result:
01234567890123456789
Folding and
splicing is the
work of an editor,
not a mere
collection of
silicon and mobile
electrons!
"""
from textwrap import fill
import fileinput
print fill("".join(fileinput.input()))
from termwrap import wrap
import struct, fcntl
def getheightwidth():
height, width = struct.unpack(
"hhhh", fcntl.ioctl(0, TERMIOS.TIOCGWINSZ ,"\000"*8))[0:2]
return height, width
import fileinput
import re
_, width = getheightwidth()
for para in re.split(r"\n{2,}", "".join(fileinput.input())):
print fill(para, width)
mystr = '''Mom said, "Don't do that."''' #"
re.sub("['\"]", lambda i: "\\" + i.group(0), mystr)
re.sub("[A-Z]", lambda i: "\\" + i.group(0), mystr)
re.sub("\W", lambda i: "\\" + i.group(0), "is a test!")
mystr = mystr.lstrip() mystr = mystr.rstrip() mystr = mystr.strip()
import csv
def parse_csv(line):
reader = csv.reader([line], escapechar='\\')
return reader.next()
line = '''XYZZY,"","O'Reilly, Inc","Wall, Larry","a \\"glug\\" bit,",5,"Error, Core Dumped,",''' #"
fields = parse_csv(line)
for i, field in enumerate(fields):
print "%d : %s" % (i, field)
import re
def parse_csv(text):
pattern = re.compile('''"([^"\\\]*(?:\\\.[^"\\\]*)*)",?|([^,]+),?|,''')
mylist = ["".join(elem)
for elem in re.findall(pattern, text)]
if text[-1] == ",":
mylist += ['']
return mylist
for fields in cvs.reader(lines, dialect="some"):
for num, field in enumerate(fields):
print num, ":", field
def soundex(name, len=4):
""" soundex module conforming to Knuth's algorithm
implementation 2000-12-24 by Gregory Jorgensen
public domain
"""
digits = '01230120022455012623010202'
sndx = ''
fc = ''
for c in name.upper():
if c.isalpha():
if not fc:
fc = c d = digits[ord(c)-ord('A')]
if not sndx or (d != sndx[-1]):
sndx += d
sndx = fc + sndx[1:]
sndx = sndx.replace('0','')
return (sndx + (len * '0'))[:len]
user = raw_input("Lookup user: ")
if user == "":
raise SystemExit
name_code = soundex(user)
for line in open("/etc/passwd"):
line = line.split(":")
for piece in line[4].split():
if name_code == soundex(piece):
print "%s: %s\n" % line[0], line[4])
import sys, fileinput, re
data = """\
analysed => analyzed
built-in => builtin
chastized => chastised
commandline => command-line
de-allocate => deallocate
dropin => drop-in
hardcode => hard-code
meta-data => metadata
multicharacter => multi-character
multiway => multi-way
non-empty => nonempty
non-profit => nonprofit
non-trappable => nontrappable
pre-define => predefine
preextend => pre-extend
re-compiling => recompiling
reenter => re-enter
turnkey => turn-key
"""
mydict = {}
for line in data.split("\n"):
if not line.strip():
continue
k, v = [word.strip() for word in line.split("=>")]
mydict[k] = v
pattern_text = "(" + "|".join([re.escape(word) for word in mydict.keys()]) + ")"
pattern = re.compile(pattern_text)
args = sys.argv[1:]
verbose = 0
if args and args[0] == "-v":
verbose = 1
args = args[1:]
if not args:
sys.stderr.write("%s: Reading from stdin\n" % sys.argv[0])
for line in fileinput.input(args, inplace=1, backup=".orig"):
output = ""
pos = 0
while True:
match = pattern.search(line, pos)
if not match:
output += line[pos:]
break
output += line[pos:match.start(0)] + mydict[match.group(1)]
pos = match.end(0)
sys.stdout.write(output)
import sys, os, re
class PsLineMatch:
fieldnames = ("flags","uid","pid","ppid","pri","nice","size", \
"rss","wchan","stat","tty","time","command")
numeric_fields = ("flags","uid","pid","ppid","pri","nice","size","rss")
def __init__(self):
self._fields = {}
def new_line(self, ln):
self._ln = ln.rstrip()
"""
F UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY TIME COMMAND"
004 0 1 0 15 0 448 236 schedu S ? 0:07 init"
. . . . . . . . . . . . .
"""
data = self._ln.split(None,12)
for fn, elem in zip(self.fieldnames, data):
if fn in self.numeric_fields: self._fields[fn] = int(elem)
else:
self._fields[fn] = elem
def set_query(self, args):
conds=[]
m = re.compile("(\w+)([=<>]+)(.+)")
for a in args:
try:
(field,op,val) = m.match(a).groups()
except:
print "can't understand query \"%s\"" % (a)
raise SystemExit
if field in self.numeric_fields:
conds.append(a)
else:
conds.append("%s%s'%s'",(field,op,val))
self._desirable = compile("(("+")and(".join(conds)+"))", "<string>","eval")
def is_desirable(self):
return eval(self._desirable, {}, self._fields)
def __str__(self):
return self._ln
if len(sys.argv)<=1:
print """usage: %s criterion ...
Each criterion is a Perl expression involving:
%s
All criteria must be met for a line to be printed.""" \
% (sys.argv[0], " ".join(PsLineMatch().fieldnames))
raise SystemExit
psln = PsLineMatch()
psln.set_query(sys.argv[1:])
p = os.popen("ps wwaxl")
print p.readline()[:-1] for ln in p.readlines():
psln.new_line(ln)
if psln.is_desirable():
print psln
p.close()
try:
myfloat = float(mystr)
print "is a decimal number"
except TypeError:
print "is not a decimal number"
try:
myint = int(mystr)
print "is an integer"
except TypeError:
print "is not an integer"
if mystr.isdigit(): print 'is a positive integer'
else:
print 'is not'
if re.match("[+-]?\d+$", mystr): print 'is an integer'
else:
print 'is not'
if re.match("-?(?:\d+(?:\.\d*)?|\.\d+)$", mystr): print 'is a decimal number'
else:
print 'is not'
def equal(num1, num2, accuracy):
return abs(num1 - num2) < 10**(-accuracy)
from __future__ import division
wage = 536 week = 40 * wage print "One week's wage is: $%.2f" % (week/100)
rounded = round(num) a = 0.255
b = "%.2f" % a
print "Unrounded: %f\nRounded: %s" % (a, b)
print "Unrounded: %f\nRounded: %.2f" % (a, a)
from math import floor, ceil
print "number\tint\tfloor\tceil"
a = [3.3, 3.5, 3.7, -3.3]
for n in a:
print "% .1f\t% .1f\t% .1f\t% .1f" % (n, int(n), floor(n), ceil(n))
num = int('0110110', 2)
import baseconvert
def dec2bin(i):
return baseconvert.baseconvert(i, baseconvert.BASE10, baseconvert.BASE2)
binstr = dec2bin(54)
for i in range(x,y):
pass
for i in range(x, y, 7):
pass
print "Infancy is:",
for i in range(0,3):
print i,
print
print "Toddling is:",
for i in range(3,5):
print i,
print
print "Childhood is:",
i = 5
while i <= 12:
print i
i += 1
import random
rand = random.randint(x, y)
rand = random.randint(25, 76)
print rand
elt = random.choice(mylist)
import string
chars = string.letters + string.digits + "!@$%^&*"
password = "".join([random.choice(chars) for i in range(8)])
random.seed()
gen1 = random.Random(6)
gen2 = random.Random(6)
gen3 = random.Random(10)
a1, b1 = gen1.random(), gen1.random()
a2, b2 = gen2.random(), gen2.random()
a3, b3 = gen3.random(), gen3.random()
import random
mean = 25
sdev = 2
salary = random.gauss(mean, sdev)
print "You have been hired at %.2f" % salary
radians = math.radians(degrees)
degrees = math.degrees(radians)
from __future__ import division
import math
def deg2rad(degrees):
return (degrees / 180) * math.pi
def rad2deg(radians):
return (radians / math.pi) * 180
import math
def degree_sine(degrees):
radians = math.radians(degrees)
return math.sin(radians)
import math
def tan(theta):
return math.sin(theta) / math.cos(theta)
try:
y = math.tan(math.pi/2)
except ValueError:
y = None
import math
log_e = math.log(VALUE)
log_10 = math.log10(VALUE)
def log_base(base, value):
return math.log(value) / math.log(base)
answer = log_base(10, 10000)
print "log10(10,000) =", answer
import Numeric
a = Numeric.array( ((3, 2, 3),
(5, 9, 8) ), "d")
b = Numeric.array( ((4, 7),
(9, 3),
(8, 1) ), "d")
c = Numeric.matrixmultiply(a, b)
print c
print a.shape, b.shape, c.shape
a = 3+5j
b = 2-2j
c = a * b
print "c =", c
print c.real, c.imag, c.conjugate()
import cmath
print cmath.sqrt(3+4j)
number = int(hexadecimal, 16)
number = int(octal, 8)
s = hex(number)
s = oct(number)
num = raw_input("Gimme a number in decimal, octal, or hex: ").rstrip()
if num.startswith("0x"):
num = int(num[2:], 16)
elif num.startswith("0"):
num = int(num[1:], 8)
else:
num = int(num)
print "%(num)d %(num)x %(num)o\n" % { "num": num }
def commify(amount):
amount = str(amount)
firstcomma = len(amount)%3 or 3 first, rest = amount[:firstcomma], amount[firstcomma:]
segments = [first] + [rest[i:i+3] for i in range(0, len(rest), 3)]
return ",".join(segments)
print commify(12345678)
import re
def commify(amount):
amount = str(amount)
amount = amount[::-1]
amount = re.sub(r"(\d\d\d)(?=\d)(?!\d*\.)", r"\1,", amount)
return amount[::-1]
def pluralise(value, root, singular="", plural="s"):
if value == 1:
return root + singular
else:
return root + plural
print "It took", duration, pluralise(duration, 'hour')
print "%d %s %s enough." % (duration,
pluralise(duration, 'hour'),
pluralise(duration, '', 'is', 'are'))
import re
def noun_plural(word):
endings = [("ss", "sses"),
("([psc]h)", r"\1es"),
("z", "zes"),
("ff", "ffs"),
("f", "ves"),
("ey", "eys"),
("y", "ies"),
("ix", "ices"),
("([sx])", r"\1es"),
("", "s")]
for singular, plural in endings:
ret, found = re.subn("%s$"%singular, plural, word)
if found:
return ret
verb_singular = noun_plural;
import sys
def factorise(num):
factors = {}
orig = num
print num, '\t',
i, sqi = 2, 4
while sqi <= num:
while not num%i:
num /= i
factors[i] = factors.get(i, 0) + 1
sqi += 2*i + 1
i += 1
if num != 1 and num != orig:
factors[num] = factors.get(num, 0) + 1
if not factors:
print "PRIME"
for factor in sorted(factors):
if factor:
tmp = str(factor)
if factors[factor]>1: tmp += "**" + str(factors[factor])
print tmp,
print
if __name__ == '__main__':
if len(sys.argv) == 1:
print "Usage:", sys.argv[0], " number [number, ]"
else:
for strnum in sys.argv[1:]:
try:
num = int(strnum)
factorise(num)
except ValueError:
print strnum, "is not an integer"
def format_factor(base, exponent):
if exponent > 1:
return "%s**%s"%(base, exponent)
return str(base)
def factorise(num):
factors = {}
orig = num
i, sqi = 2, 4
while sqi <= num:
while not num%i:
num /= i
factors[i] = factors.get(i, 0) + 1
sqi += 2*i + 1
i += 1
if num not in (1, orig):
factors[num] = factors.get(num, 0) + 1
if not factors:
return ["PRIME"]
out = [format_factor(base, exponent)
for base, exponent in sorted(factors.items())]
return out
def print_factors(value):
try:
num = int(value)
if num != float(value):
raise ValueError
except (ValueError, TypeError):
raise ValueError("Can only factorise an integer")
factors = factorise(num)
print num, "\t", " ".join(factors)
import time
import datetime
print "Today is day", time.localtime()[7], "of the current year"
today = datetime.date.today()
print "Today is day", today.timetuple()[7], "of ", today.year
print "Today is day", today.strftime("%j"), "of the current year"
today = datetime.date.today()
print "The date is", today
print t.strftime("four-digit year: %Y, two-digit year: %y, month: %m, day: %d")
t = datetime.datetime.now()
print "Epoch Seconds:", time.mktime(t.timetuple())
t = datetime.datetime.utcnow()
print "Epoch Seconds:", time.mktime(t.timetuple())
now = datetime.datetime.fromtimestamp(EpochSeconds)
print now
print now.ctime()
oldtimetuple = time.localtime(EpochSeconds)
print oldtimetuple
now = datetime.date(2003, 8, 6)
difference1 = datetime.timedelta(days=1)
difference2 = datetime.timedelta(weeks=-2)
print "One day in the future is:", now + difference1
print "Two weeks in the past is:", now + difference2
print datetime.date(2003, 8, 6) - datetime.date(2000, 8, 6)
birthtime = datetime.datetime(1973, 01, 18, 3, 45, 50)
interval = datetime.timedelta(seconds=5, minutes=17, hours=2, days=55)
then = birthtime + interval
print "Then is", then.ctime()
print "Then is", then.strftime("%A %B %d %I:%M:%S %p %Y")
when = datetime.datetime(1973, 1, 18) + datetime.timedelta(days=55)
print "Nat was 55 days old on:", when.strftime("%m/%d/%Y").lstrip("0")
diff = date2 - date1
diff = datetime.date(year1, month1, day1) - datetime.date(year2, month2, day2)
bree = datetime.datetime(1981, 6, 16, 4, 35, 25)
nat = datetime.datetime(1973, 1, 18, 3, 45, 50)
difference = bree - nat
print "There were", difference, "minutes between Nat and Bree"
weeks, days = divmod(difference.days, 7)
minutes, seconds = divmod(difference.seconds, 60)
hours, minutes = divmod(minutes, 60)
print "%d weeks, %d days, %d:%d:%d" % (weeks, days, hours, minutes, seconds)
print "There were", difference.days, "days between Bree and Nat."
when = datetime.date(1981, 6, 16)
print "16/6/1981 was:"
print when.strftime("Day %w of the week (a %A). Day %d of the month (%B).")
print when.strftime("Day %j of the year (%Y), in week %W of the year.")
time.strptime("Tue Jun 16 20:18:03 1981")
time.strptime("16/6/1981", "%d/%m/%Y")
now = datetime.datetime(*time.strptime("16/6/1981", "%d/%m/%Y")[0:5])
print datetime.datetime.now().strftime("The date is %A (%a) %d/%m/%Y")
t1 = time.clock()
t2 = time.clock()
print t2 - t1
time.clock(); time.clock()
import timeit
code = '[x for x in range(10) if x % 2 == 0]'
eval(code)
t = timeit.Timer(code)
print "10,000 repeats of that code takes:", t.timeit(10000), "seconds"
print "1,000,000 repeats of that code takes:", t.timeit(), "seconds"
import timeit
code = 'import random; l = random.sample(xrange(10000000), 1000); l.sort()'
t = timeit.Timer(code)
print "Create a list of a thousand random numbers. Sort the list. Repeated a thousand times."
print "Average Time:", t.timeit(1000) / 1000
seconds = 3.1
time.sleep(seconds)
print "boo"
import datetime, email, email.Utils
import os, sys, time
def extract_date(hop):
date_string = hop[hop.find(';')+2:]
date_string = date_string.strip()
time_tuple = email.Utils.parsedate(date_string)
EpochSeconds = time.mktime(time_tuple)
dt = datetime.datetime.fromtimestamp(EpochSeconds)
return dt
def process(filename):
f = file(filename, 'rb')
msg = email.message_from_file(f)
hops = msg.get_all('received')
hops.reverse()
results = []
for hop in hops:
hop = hop.lower()
if hop.startswith('by'): sender = "start"
receiver = hop[3:hop.find(' ',3)]
date = extract_date(hop)
else: sender = hop[5:hop.find(' ',5)]
by = hop.find('by ')+3
receiver = hop[by:hop.find(' ', by)]
date = extract_date(hop)
results.append((sender, receiver, date))
output(results)
def output(results):
print "Sender, Recipient, Time, Delta"
print
previous_dt = delta = 0
for (sender, receiver, date) in results:
if previous_dt:
delta = date - previous_dt
print "%s, %s, %s, %s" % (sender,
receiver,
date.strftime("%Y/%d/%m %H:%M:%S"),
delta)
print
previous_dt = date
def main():
if len(sys.argv) != 2:
print "Usage: mailhop.py FILENAME"
else:
filename = sys.argv[1]
if os.path.isfile(filename):
process(filename)
else:
print filename, "doesn't seem to be a valid file."
if __name__ == '__main__':
main()
non_nested = ["this", "that", "the", "other"]
nested = ["this", "that", ["the", "other"]]
tune = ["The", "Star-Spangled", "Banner"]
a = ["quick", "brown", "fox"]
a = "Why are you teasing me?".split()
text = """
The boy stood on the burning deck,
It was as hot as glass.
"""
lines = [line.lstrip() for line in text.strip().split("\n")]
biglist = [line.rstrip() for line in open("mydatafile")]
banner = "The Mines of Moria"
banner = 'The Mines of Moria'
name = "Gandalf"
banner = "Speak, " + name + ", and enter!"
banner = "Speak, %s, and welcome!" % name
his_host = "www.python.org"
import os
host_info = os.popen("nslookup " + his_host).read()
python_info = os.popen("ps %d" % os.getpid()).read()
shell_info = os.popen("ps $$").read()
banner = ["Costs", "only", "$4.95"]
banner = "Costs only $4.95".split()
brax = """ ' " ( ) < > { } [ ] """.split() #"""
brax = list("""'"()<>{}[]""") #"""
rings = '''They're "Nenya Narya Vilya"'''.split() #'''
tags = 'LI TABLE TR TD A IMG H1 P'.split()
sample = r'The backslash (\) is often used in regular expressions.'.split()
banner = "The backslash (\\) is often used in regular expressions.".split()
ships = u"Niña Pinta Santa María".split() ships = [u"Niña", u"Pinta", u"Santa María"]
def commify_series(args):
n = len(args)
if n == 0:
return ""
elif n == 1:
return args[0]
elif n == 2:
return args[0] + " and " + args[1]
return ", ".join(args[:-1]) + ", and " + args[-1]
commify_series([])
commify_series(["red"])
commify_series(["red", "yellow"])
commify_series(["red", "yellow", "green"])
mylist = ["red", "yellow", "green"]
print "I have", mylist, "marbles."
print "I have", " ".join(mylist), "marbles."
data = (
( 'just one thing', ),
( 'Mutt Jeff'.split() ),
( 'Peter Paul Mary'.split() ),
( 'To our parents', 'Mother Theresa', 'God' ),
( 'pastrami', 'ham and cheese', 'peanut butter and jelly', 'tuna' ),
( 'recycle tired, old phrases', 'ponder big, happy thoughts' ),
( 'recycle tired, old phrases',
'ponder big, happy thoughts',
'sleep and dream peacefully' ),
)
def commify_series(terms):
for term in terms:
if "," in term:
sepchar = "; "
break
else:
sepchar = ", "
n = len(terms)
if n == 0:
return ""
elif n == 1:
return terms[0]
elif n == 2:
return " and ".join(terms)
return "%s%sand %s" % (sepchar.join(terms[:-1]), sepchar, terms[-1])
for item in data:
print "The list is: %s." % commify_series(item)
del mylist[size:] mylist += [None] * size
mylist.append(4)
mylist.insert(0, 10)
list2 = [1,2,3]
mylist.extend(list2)
mylist[1:1] = list2 mylist[2:3] = list2
del mylist[idx1:idx2] x = mylist.pop(idx)
def what_about_that_list(terms):
print "The list now has", len(terms), "elements."
print "The index of the last element is", len(terms)-1, "(or -1)."
print "Element #3 is %s." % terms[3]
people = "Crosby Stills Nash Young".split()
what_about_that_list(people)
people.pop()
what_about_that_list(people)
people += [None] * (10000 - len(people))
for item in mylist:
pass for user in bad_users:
complain(user)
import os
for (key, val) in sorted(os.environ.items()):
print "%s=%s" % (key, val)
for user in all_users:
disk_space = get_usage(user) if disk_space > MAX_QUOTA: complain(user) import os
for line in os.popen("who"):
if "dalke" in line:
print line,
print "".join([line for line in os.popen("who")
if "dalke" in line]),
for line in myfile:
for word in line.split(): print word[::-1], print
for line in myfile:
for word in line.split(): chars = list(word) chars.reverse()
print "".join(chars),
print
for item in mylist:
print "i =", item
data = [1, 2, 3]
data = [i-1 for i in data]
print data
for i, elem in enumerate(data):
data[i] = elem - 1
s = s.strip()
data = [s.strip() for s in data]
for k, v in mydict.items():
mydict[k] = v.strip()
fruits = ["Apple", "Blackberry"]
for fruit in fruits:
print fruit, "tastes good in a pie."
for i in range(len(fruits)):
print fruits[i], "tastes good in a pie."
for i, fruit in enumerate(fruits):
print "%s) %s tastes good in a pie."%(i+1, fruit)
rogue_cats = ["Morris", "Felix"]
namedict = { "felines": rogue_cats }
for cat in namedict["felines"]:
print cat, "purrs hypnotically."
print "--More--\nYou are controlled."
for i in range(len(namedict["felines"])):
print namedict["felines"][i], "purrs hypnotically."
uniq = list(set(mylist))
seen = {}
for item in mylist:
seen[item] = seen.get(item, 0) + 1
uniq = seen.keys()
seen = {}
uniq = []
for item in mylist:
count = seen.get(item, 0)
if count == 0:
uniq.append(item)
seen[item] = count + 1
import os
usernames = [line.split()[0] for line in os.popen("who")]
uniq = sorted(set(usernames))
print "users logged in:", " ".join(uniq)
import os
ucnt = {}
for line in os.popen("who"):
username = line.split()[0] ucnt[username] = ucnt.get(username, 0) + 1
users = ucnt.keys()
users.sort()
print "users logged in:", " ".join(users)
aonly = [item for item in a_list if item not in b_list]
a_set = set(a_list)
b_set = set(b_list)
aonly = list(a_set - b_set)
seen = {} aonly = []
for item in b_list:
seen[item] = 1
for item in a_list:
if not item not in seen:
aonly.append(item)
seen = {} aonly = []
[seen.update({x: 1}) for x in b_list]
aonly = [item for item in a_list if item not in seen]
aonly = list(set(a_list))
seen = {}
aonly = []
for item in a_list:
if item not in seen:
aonly.append(item)
seen[item] = 1 mydict["key1"] = 1
mydict["key2"] = 2
mydict[("key1", "key2")] = (1,2)
seen = dict.fromkeys(B.keys())
seen = {}
for term in B:
seen[term] = None
seen = {}
for k, v in B:
seen[k] = 1
a = (1, 3, 5, 6, 7, 8)
b = (2, 3, 5, 7, 9)
a_set = set(a)
b_set = set(b)
union = a_set | b_set isect = a_set & b_set diff = a_set ^ b_set
union_list = []; isect_list = []; diff = []
union_dict = {}; isect_dict = {}
count = {}
for e in a:
union_dict[e] = 1
for e in b:
if union_dict.has_key(e):
isect_dict[e] = 1
union_dict[e] = 1
union_list = union_dict.keys()
isect_list = isect_dict.keys()
for e in a + b:
if union.get(e, 0) == 0:
isect[e] = 1
union[e] = 1
union = union.keys()
isect = isect.keys()
count = {}
for e in a + b:
count[e] = count.get(e, 0) + 1
union = []; isect = []; diff = []
for e in count.keys():
union.append(e)
if count[e] == 2:
isect.append(e)
else:
diff.append(e)
isect = []; diff = []; union = []
count = {}
for e in a + b:
count[e] = count.get(e, 0) + 1
for e, num in count.items():
union.append(e)
[None, diff, isect][num].append(e)
mylist1.extend(mylist2)
mylist1 = mylist1 + mylist2
mylist1 += mylist2
members = ["Time", "Flies"]
initiates = ["An", "Arrow"]
members.extend(initiates)
members[2:] = ["Like"] + initiates
print " ".join(members)
members[:1] = ["Fruit"] members[-2:] = ["A", "Banana"]
print " ".join(members)
revlist = mylist[::-1]
revlist = list(reversed(mylist))
revlist = mylist[:] revlist.reverse()
for elem in reversed(mylist):
pass
for elem in mylist[::-1]:
pass
for i, elem in reversed(list(enumerate(mylist))):
pass
for i in range(len(mylist)-1, -1, -1):
pass
descending = sorted(users, reverse=True)
mylist[:n] = []
front, mylist[:n] = mylist[:n], []
front = mylist.pop(0)
mylist[-n:] = []
end, mylist[-n:] = mylist[-n:], []
end = mylist.pop()
def shift2(terms):
front = terms[:2]
terms[:2] = []
return front
def pop2(terms):
back = terms[-2:]
terms[-2:] = []
return back
friends = "Peter Paul Mary Jim Tim".split()
this, that = shift2(friends)
beverages = "Dew Jolt Cola Sprite Fresca".split()
pair = pop2(beverages)
for item in mylist:
if criterion:
pass break
else:
pass for idx, elem in enumerate(mylist):
if criterion:
pass break
else:
pass for employee in employees:
if employee.category == 'engineer':
highest_engineer = employee
break
print "Highest paid engineer is:", highest_engineer.name
for i, employee in enumerate(employees):
if employee.category == 'engineer':
highest_engineer = employee
break
print "Highest paid engineer is: #%s - %s" % (i, highest_engineer.name)
for i in range(len(mylist)):
if criterion:
pass break
else:
pass
matching = [term for term in mylist if test(term)]
matching = []
for term in mylist:
if test(term):
matching.append(term)
bigs = [num for num in nums if num > 1000000]
pigs = [user for (user, val) in users.items() if val > 1e7]
import os
matching = [line for line in os.popen("who")
if line.startswith("gnat ")]
engineers = [employee for employee in employees
if employee.position == "Engineer"]
secondary_assistance = [applicant for applicant in applicants
if 26000 <= applicant.income < 30000]
sorted_list = sorted(unsorted_list)
import os, signal, time
for pid in sorted(pids):
print pid
pid = raw_input("Select a process ID to kill: ")
try:
pid = int(pid)
except ValueError:
raise SystemExit("Exiting ... ")
os.kill(pid, signal.SIGTERM)
time.sleep(2)
try:
os.kill(pid, signal.SIGKILL)
except OSError, err:
if err.errno != 3: raise
descending = sorted(unsorted_list, reverse=True)
allnums = [4, 19, 8, 3]
allnums.sort(reverse=True) allnums.sort() allnums.reverse() allnums = sorted(allnums, reverse=True)
ordered = sorted(unordered, cmp=compare)
ordered = sorted(unordered, key=compute)
precomputed = [(compute(x), x) for x in unordered]
precomputed.sort(lambda a, b: cmp(a[0], b[0]))
ordered = [v for k,v in precomputed.items()]
def functional_sort(mylist, function):
mylist.sort(function)
return mylist
ordered = [v for k,v in functional_sort([(compute(x), x) for x in unordered],
lambda a, b: cmp(a[0], b[0]))]
ordered = sorted(employees, key=lambda x: x.name)
for employee in sorted(employees, key=lambda x: x.name):
print "%s earns $%s" % (employee.name, employee.salary)
sorted_employees = sorted(employees, key=lambda x: x.name):
for employee in sorted_employees:
print "%s earns $%s" % (employee.name, employee.salary)
for employee in sorted_employees:
if bonus(employee.ssn):
print employee.name, "got a bonus!"
sorted_employees = sorted(employees, key=lambda x: (x.name, x.age)):
import pwd
users = pwd.getpwall()
for user in sorted(users, key=lambda x: x[0]):
print user[0]
sorted_list = sorted(names, key=lambda x: x[:1])
sorted_list = sorted(strings, key=len)
temp = [(len(s), s) for s in strings]
temp.sort(lambda a, b: cmp(a[0], b[0]))
sorted_list = [x[1] for x in temp]
def functional_sort(mylist, function):
mylist.sort(function)
return mylist
sorted_fields = [v for k,v in functional_sort(
[(int(re.search(r"(\d+)", x).group(1)), x) for x in fields],
lambda a, b: cmp(a[0], b[0]))]
entries = [line[:-1].split() for line in open("/etc/passwd")]
for entry in sorted(entries, key=lambda x: (x[3], x[2], x[0])):
print entry
import itertools
for process in itertools.cycle([1, 2, 3, 4, 5]):
print "Handling process", process
time.sleep(1)
import time
class Circular(object):
def __init__(self, data):
assert len(data) >= 1, "Cannot use an empty list"
self.data = data
def __iter__(self):
while True:
for elem in self.data:
yield elem
circular = Circular([1, 2, 3, 4, 5])
for process in circular:
print "Handling process", process
time.sleep(1)
import time
class Circular(object):
def __init__(self, data):
assert len(data) >= 1, "Cannot use an empty list"
self.data = data
def next(self):
head = self.data.pop(0)
self.data.append(head)
return head
circular = Circular([1, 2, 3, 4, 5])
while True:
process = circular.next()
print "Handling process", process
time.sleep(1)
import random
random.shuffle(mylist)
import sys
def make_columns(mylist, screen_width=78):
if mylist:
maxlen = max([len(elem) for elem in mylist])
maxlen += 1
cols = max(1, screen_width/maxlen)
rows = 1 + len(mylist)/cols
mask = "%%-%ds " % (maxlen-1)
for n in range(rows):
row = [mask%elem
for elem in mylist[n::rows]]
yield "".join(row).rstrip()
for row in make_columns(sys.stdin.readlines(), screen_width=50):
print row
import sys
def EOL(item):
return (item+1) % cols == 0
def getwinsize():
try:
import curses
stdscr = curses.initscr()
rows, cols = stdscr.getmaxyx()
return cols
except ImportError:
pass
try:
import termios
TIOCGWINSZ = termios.TIOCGWINSZ
except ImportError:
TIOCGWINSZ = 0x40087468
import struct, fcntl
s = struct.pack("HHHH", 0, 0, 0, 0)
try:
x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
except IOError:
return 80
rows, cols = struct.unpack("HHHH", x)[:2]
return cols
cols = getwinsize()
data = [s.rstrip() for s in sys.stdin.readlines()]
if not data:
maxlen = 1
else:
maxlen = max(map(len, data))
maxlen += 1
cols = (cols / maxlen) or 1
rows = (len(data)+cols) / cols
mask = "%%-%ds " % (maxlen-1)
for item in range(rows * cols):
target = (item % cols) * rows + (item/cols)
if target < len(data):
piece = mask % data[target]
else:
piece = mask % ""
if EOL(item):
piece = piece.rstrip() sys.stdout.write(piece)
if EOL(item):
sys.stdout.write("\n")
if EOL(item):
sys.stdout.write("\n")
def factorial(n):
s = 1
while n:
s *= n
n -= 1
return s
def permute(alist, blist=[]):
if not alist:
yield blist
for i, elem in enumerate(alist):
for elem in permute(alist[:i] + alist[i+1:], blist + [elem]):
yield elem
for permutation in permute(range(4)):
print permutation
import fileinput
def print_list(alist, blist=[]):
if not alist:
print ' '.join(blist)
for i in range(len(alist)):
blist.append(