Kaydet (Commit) 946c53ed authored tarafından Andrew M. Kuchling's avatar Andrew M. Kuchling

Run these demo scripts through reindent.py to give them 4-space indents. I've…

Run these demo scripts through reindent.py to give them 4-space indents.  I've verified that their output is unchanged.
üst 4f237b68
This diff is collapsed.
...@@ -6,61 +6,61 @@ ...@@ -6,61 +6,61 @@
class Dbm: class Dbm:
def __init__(self, filename, mode, perm): def __init__(self, filename, mode, perm):
import dbm import dbm
self.db = dbm.open(filename, mode, perm) self.db = dbm.open(filename, mode, perm)
def __repr__(self): def __repr__(self):
s = '' s = ''
for key in self.keys(): for key in self.keys():
t = `key` + ': ' + `self[key]` t = `key` + ': ' + `self[key]`
if s: t = ', ' + t if s: t = ', ' + t
s = s + t s = s + t
return '{' + s + '}' return '{' + s + '}'
def __len__(self): def __len__(self):
return len(self.db) return len(self.db)
def __getitem__(self, key): def __getitem__(self, key):
return eval(self.db[`key`]) return eval(self.db[`key`])
def __setitem__(self, key, value): def __setitem__(self, key, value):
self.db[`key`] = `value` self.db[`key`] = `value`
def __delitem__(self, key): def __delitem__(self, key):
del self.db[`key`] del self.db[`key`]
def keys(self): def keys(self):
res = [] res = []
for key in self.db.keys(): for key in self.db.keys():
res.append(eval(key)) res.append(eval(key))
return res return res
def has_key(self, key): def has_key(self, key):
return self.db.has_key(`key`) return self.db.has_key(`key`)
def test(): def test():
d = Dbm('@dbm', 'rw', 0600) d = Dbm('@dbm', 'rw', 0600)
print d print d
while 1: while 1:
try: try:
key = input('key: ') key = input('key: ')
if d.has_key(key): if d.has_key(key):
value = d[key] value = d[key]
print 'currently:', value print 'currently:', value
value = input('value: ') value = input('value: ')
if value == None: if value == None:
del d[key] del d[key]
else: else:
d[key] = value d[key] = value
except KeyboardInterrupt: except KeyboardInterrupt:
print '' print ''
print d print d
except EOFError: except EOFError:
print '[eof]' print '[eof]'
break break
print d print d
test() test()
...@@ -7,17 +7,17 @@ ...@@ -7,17 +7,17 @@
# Wrapper function to emulate the complicated range() arguments # Wrapper function to emulate the complicated range() arguments
def range(*a): def range(*a):
if len(a) == 1: if len(a) == 1:
start, stop, step = 0, a[0], 1 start, stop, step = 0, a[0], 1
elif len(a) == 2: elif len(a) == 2:
start, stop = a start, stop = a
step = 1 step = 1
elif len(a) == 3: elif len(a) == 3:
start, stop, step = a start, stop, step = a
else: else:
raise TypeError, 'range() needs 1-3 arguments' raise TypeError, 'range() needs 1-3 arguments'
return Range(start, stop, step) return Range(start, stop, step)
# Class implementing a range object. # Class implementing a range object.
# To the user the instances feel like immutable sequences # To the user the instances feel like immutable sequences
...@@ -25,47 +25,47 @@ def range(*a): ...@@ -25,47 +25,47 @@ def range(*a):
class Range: class Range:
# initialization -- should be called only by range() above # initialization -- should be called only by range() above
def __init__(self, start, stop, step): def __init__(self, start, stop, step):
if step == 0: if step == 0:
raise ValueError, 'range() called with zero step' raise ValueError, 'range() called with zero step'
self.start = start self.start = start
self.stop = stop self.stop = stop
self.step = step self.step = step
self.len = max(0, int((self.stop - self.start) / self.step)) self.len = max(0, int((self.stop - self.start) / self.step))
# implement `x` and is also used by print x # implement `x` and is also used by print x
def __repr__(self): def __repr__(self):
return 'range' + `self.start, self.stop, self.step` return 'range' + `self.start, self.stop, self.step`
# implement len(x) # implement len(x)
def __len__(self): def __len__(self):
return self.len return self.len
# implement x[i] # implement x[i]
def __getitem__(self, i): def __getitem__(self, i):
if 0 <= i < self.len: if 0 <= i < self.len:
return self.start + self.step * i return self.start + self.step * i
else: else:
raise IndexError, 'range[i] index out of range' raise IndexError, 'range[i] index out of range'
# Small test program # Small test program
def test(): def test():
import time, __builtin__ import time, __builtin__
print range(10), range(-10, 10), range(0, 10, 2) print range(10), range(-10, 10), range(0, 10, 2)
for i in range(100, -100, -10): print i, for i in range(100, -100, -10): print i,
print print
t1 = time.time() t1 = time.time()
for i in range(1000): for i in range(1000):
pass pass
t2 = time.time() t2 = time.time()
for i in __builtin__.range(1000): for i in __builtin__.range(1000):
pass pass
t3 = time.time() t3 = time.time()
print t2-t1, 'sec (class)' print t2-t1, 'sec (class)'
print t3-t2, 'sec (built-in)' print t3-t2, 'sec (built-in)'
test() test()
This diff is collapsed.
...@@ -5,13 +5,13 @@ ...@@ -5,13 +5,13 @@
# #
# >>> for c in Rev( 'Hello World!' ) : sys.stdout.write( c ) # >>> for c in Rev( 'Hello World!' ) : sys.stdout.write( c )
# ... else: sys.stdout.write( '\n' ) # ... else: sys.stdout.write( '\n' )
# ... # ...
# !dlroW olleH # !dlroW olleH
# #
# The .forw is so you can use anonymous sequences in __init__, and still # The .forw is so you can use anonymous sequences in __init__, and still
# keep a reference the forward sequence. ) # keep a reference the forward sequence. )
# If you give it a non-anonymous mutable sequence, the reverse sequence # If you give it a non-anonymous mutable sequence, the reverse sequence
# will track the updated values. ( but not reassignment! - another # will track the updated values. ( but not reassignment! - another
# good reason to use anonymous values in creating the sequence to avoid # good reason to use anonymous values in creating the sequence to avoid
# confusion. Maybe it should be change to copy input sequence to break # confusion. Maybe it should be change to copy input sequence to break
# the connection completely ? ) # the connection completely ? )
...@@ -19,14 +19,14 @@ ...@@ -19,14 +19,14 @@
# >>> nnn = range( 0, 3 ) # >>> nnn = range( 0, 3 )
# >>> rnn = Rev( nnn ) # >>> rnn = Rev( nnn )
# >>> for n in rnn: print n # >>> for n in rnn: print n
# ... # ...
# 2 # 2
# 1 # 1
# 0 # 0
# >>> for n in range( 4, 6 ): nnn.append( n ) # update nnn # >>> for n in range( 4, 6 ): nnn.append( n ) # update nnn
# ... # ...
# >>> for n in rnn: print n # prints reversed updated values # >>> for n in rnn: print n # prints reversed updated values
# ... # ...
# 5 # 5
# 4 # 4
# 2 # 2
...@@ -35,55 +35,55 @@ ...@@ -35,55 +35,55 @@
# >>> nnn = nnn[1:-1] # >>> nnn = nnn[1:-1]
# >>> nnn # >>> nnn
# [1, 2, 4] # [1, 2, 4]
# >>> for n in rnn: print n # prints reversed values of old nnn # >>> for n in rnn: print n # prints reversed values of old nnn
# ... # ...
# 5 # 5
# 4 # 4
# 2 # 2
# 1 # 1
# 0 # 0
# >>> # >>>
# #
# WH = Rev( 'Hello World!' ) # WH = Rev( 'Hello World!' )
# print WH.forw, WH.back # print WH.forw, WH.back
# nnn = Rev( range( 1, 10 ) ) # nnn = Rev( range( 1, 10 ) )
# print nnn.forw # print nnn.forw
# print nnn # print nnn
# #
# produces output: # produces output:
# #
# Hello World! !dlroW olleH # Hello World! !dlroW olleH
# [1, 2, 3, 4, 5, 6, 7, 8, 9] # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# [9, 8, 7, 6, 5, 4, 3, 2, 1] # [9, 8, 7, 6, 5, 4, 3, 2, 1]
# #
# >>>rrr = Rev( nnn ) # >>>rrr = Rev( nnn )
# >>>rrr # >>>rrr
# <1, 2, 3, 4, 5, 6, 7, 8, 9> # <1, 2, 3, 4, 5, 6, 7, 8, 9>
from string import joinfields from string import joinfields
class Rev: class Rev:
def __init__( self, seq ): def __init__( self, seq ):
self.forw = seq self.forw = seq
self.back = self self.back = self
def __len__( self ): def __len__( self ):
return len( self.forw ) return len( self.forw )
def __getitem__( self, j ): def __getitem__( self, j ):
return self.forw[ -( j + 1 ) ] return self.forw[ -( j + 1 ) ]
def __repr__( self ): def __repr__( self ):
seq = self.forw seq = self.forw
if type(seq) == type( [] ) : if type(seq) == type( [] ) :
wrap = '[]' wrap = '[]'
sep = ', ' sep = ', '
elif type(seq) == type( () ) : elif type(seq) == type( () ) :
wrap = '()' wrap = '()'
sep = ', ' sep = ', '
elif type(seq) == type( '' ) : elif type(seq) == type( '' ) :
wrap = '' wrap = ''
sep = '' sep = ''
else: else:
wrap = '<>' wrap = '<>'
sep = ', ' sep = ', '
outstrs = [] outstrs = []
for item in self.back : for item in self.back :
outstrs.append( str( item ) ) outstrs.append( str( item ) )
return wrap[:1] + joinfields( outstrs, sep ) + wrap[-1:] return wrap[:1] + joinfields( outstrs, sep ) + wrap[-1:]
...@@ -2,63 +2,63 @@ ...@@ -2,63 +2,63 @@
def vec(*v): def vec(*v):
return apply(Vec, v) return apply(Vec, v)
class Vec: class Vec:
def __init__(self, *v): def __init__(self, *v):
self.v = [] self.v = []
for x in v: for x in v:
self.v.append(x) self.v.append(x)
def fromlist(self, v): def fromlist(self, v):
self.v = [] self.v = []
if type(v) <> type([]): if type(v) <> type([]):
raise TypeError raise TypeError
self.v = v[:] self.v = v[:]
return self return self
def __repr__(self): def __repr__(self):
return 'vec(' + `self.v`[1:-1] + ')' return 'vec(' + `self.v`[1:-1] + ')'
def __len__(self): def __len__(self):
return len(self.v) return len(self.v)
def __getitem__(self, i): def __getitem__(self, i):
return self.v[i] return self.v[i]
def __add__(a, b): def __add__(a, b):
# Element-wise addition # Element-wise addition
v = [] v = []
for i in range(len(a)): for i in range(len(a)):
v.append(a[i] + b[i]) v.append(a[i] + b[i])
return Vec().fromlist(v) return Vec().fromlist(v)
def __sub__(a, b): def __sub__(a, b):
# Element-wise subtraction # Element-wise subtraction
v = [] v = []
for i in range(len(a)): for i in range(len(a)):
v.append(a[i] - b[i]) v.append(a[i] - b[i])
return Vec().fromlist(v) return Vec().fromlist(v)
def __mul__(self, scalar): def __mul__(self, scalar):
# Multiply by scalar # Multiply by scalar
v = [] v = []
for i in range(len(self.v)): for i in range(len(self.v)):
v.append(self.v[i]*scalar) v.append(self.v[i]*scalar)
return Vec().fromlist(v) return Vec().fromlist(v)
def test(): def test():
a = vec(1, 2, 3) a = vec(1, 2, 3)
b = vec(3, 2, 1) b = vec(3, 2, 1)
print a print a
print b print b
print a+b print a+b
print a*3.0 print a*3.0
test() test()
This diff is collapsed.
#! /usr/bin/env python #! /usr/bin/env python
# 1) Regular Expressions Test # 1) Regular Expressions Test
# #
# Read a file of (extended per egrep) regular expressions (one per line), # Read a file of (extended per egrep) regular expressions (one per line),
# and apply those to all files whose names are listed on the command line. # and apply those to all files whose names are listed on the command line.
# Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns # Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns
# against a five /etc/termcap files. Tests using more elaborate patters # against a five /etc/termcap files. Tests using more elaborate patters
# would also be interesting. Your code should not break if given hundreds # would also be interesting. Your code should not break if given hundreds
# of regular expressions or binary files to scan. # of regular expressions or binary files to scan.
# This implementation: # This implementation:
# - combines all patterns into a single one using ( ... | ... | ... ) # - combines all patterns into a single one using ( ... | ... | ... )
...@@ -24,27 +24,27 @@ from regex_syntax import * ...@@ -24,27 +24,27 @@ from regex_syntax import *
regex.set_syntax(RE_SYNTAX_EGREP) regex.set_syntax(RE_SYNTAX_EGREP)
def main(): def main():
pats = map(chomp, sys.stdin.readlines()) pats = map(chomp, sys.stdin.readlines())
bigpat = '(' + string.joinfields(pats, '|') + ')' bigpat = '(' + string.joinfields(pats, '|') + ')'
prog = regex.compile(bigpat) prog = regex.compile(bigpat)
for file in sys.argv[1:]: for file in sys.argv[1:]:
try: try:
fp = open(file, 'r') fp = open(file, 'r')
except IOError, msg: except IOError, msg:
print "%s: %s" % (file, msg) print "%s: %s" % (file, msg)
continue continue
lineno = 0 lineno = 0
while 1: while 1:
line = fp.readline() line = fp.readline()
if not line: if not line:
break break
lineno = lineno + 1 lineno = lineno + 1
if prog.search(line) >= 0: if prog.search(line) >= 0:
print "%s:%s:%s" % (file, lineno, line), print "%s:%s:%s" % (file, lineno, line),
def chomp(s): def chomp(s):
if s[-1:] == '\n': return s[:-1] if s[-1:] == '\n': return s[:-1]
else: return s else: return s
main() main()
#! /usr/bin/env python #! /usr/bin/env python
# 2) Sorting Test # 2) Sorting Test
# #
# Sort an input file that consists of lines like this # Sort an input file that consists of lines like this
# #
# var1=23 other=14 ditto=23 fred=2 # var1=23 other=14 ditto=23 fred=2
# #
# such that each output line is sorted WRT to the number. Order # such that each output line is sorted WRT to the number. Order
# of output lines does not change. Resolve collisions using the # of output lines does not change. Resolve collisions using the
# variable name. e.g. # variable name. e.g.
# #
# fred=2 other=14 ditto=23 var1=23 # fred=2 other=14 ditto=23 var1=23
# #
# Lines may be up to several kilobytes in length and contain # Lines may be up to several kilobytes in length and contain
# zillions of variables. # zillions of variables.
...@@ -28,23 +28,23 @@ import string ...@@ -28,23 +28,23 @@ import string
import sys import sys
def main(): def main():
prog = regex.compile('^\(.*\)=\([-+]?[0-9]+\)') prog = regex.compile('^\(.*\)=\([-+]?[0-9]+\)')
def makekey(item, prog=prog): def makekey(item, prog=prog):
if prog.match(item) >= 0: if prog.match(item) >= 0:
var, num = prog.group(1, 2) var, num = prog.group(1, 2)
return string.atoi(num), var return string.atoi(num), var
else: else:
# Bad input -- pretend it's a var with value 0 # Bad input -- pretend it's a var with value 0
return 0, item return 0, item
while 1: while 1:
line = sys.stdin.readline() line = sys.stdin.readline()
if not line: if not line:
break break
items = string.split(line) items = string.split(line)
items = map(makekey, items) items = map(makekey, items)
items.sort() items.sort()
for num, var in items: for num, var in items:
print "%s=%s" % (var, num), print "%s=%s" % (var, num),
print print
main() main()
#! /usr/bin/env python #! /usr/bin/env python
# 3) System Test # 3) System Test
# #
# Given a list of directories, report any bogus symbolic links contained # Given a list of directories, report any bogus symbolic links contained
# anywhere in those subtrees. A bogus symbolic link is one that cannot # anywhere in those subtrees. A bogus symbolic link is one that cannot
# be resolved because it points to a nonexistent or otherwise # be resolved because it points to a nonexistent or otherwise
...@@ -21,54 +21,54 @@ import sys ...@@ -21,54 +21,54 @@ import sys
from stat import * from stat import *
def main(): def main():
try: try:
# Note: can't test for presence of lstat -- it's always there # Note: can't test for presence of lstat -- it's always there
dummy = os.readlink dummy = os.readlink
except AttributeError: except AttributeError:
print "This system doesn't have symbolic links" print "This system doesn't have symbolic links"
sys.exit(0) sys.exit(0)
if sys.argv[1:]: if sys.argv[1:]:
prefix = sys.argv[1] prefix = sys.argv[1]
else: else:
prefix = '' prefix = ''
if prefix: if prefix:
os.chdir(prefix) os.chdir(prefix)
if prefix[-1:] != '/': prefix = prefix + '/' if prefix[-1:] != '/': prefix = prefix + '/'
reportboguslinks(prefix) reportboguslinks(prefix)
else: else:
reportboguslinks('') reportboguslinks('')
def reportboguslinks(prefix): def reportboguslinks(prefix):
try: try:
names = os.listdir('.') names = os.listdir('.')
except os.error, msg: except os.error, msg:
print "%s%s: can't list: %s" % (prefix, '.', msg) print "%s%s: can't list: %s" % (prefix, '.', msg)
return return
names.sort() names.sort()
for name in names: for name in names:
if name == os.curdir or name == os.pardir: if name == os.curdir or name == os.pardir:
continue continue
try: try:
mode = os.lstat(name)[ST_MODE] mode = os.lstat(name)[ST_MODE]
except os.error: except os.error:
print "%s%s: can't stat: %s" % (prefix, name, msg) print "%s%s: can't stat: %s" % (prefix, name, msg)
continue continue
if S_ISLNK(mode): if S_ISLNK(mode):
try: try:
os.stat(name) os.stat(name)
except os.error: except os.error:
print "%s%s -> %s" % \ print "%s%s -> %s" % \
(prefix, name, os.readlink(name)) (prefix, name, os.readlink(name))
elif S_ISDIR(mode): elif S_ISDIR(mode):
try: try:
os.chdir(name) os.chdir(name)
except os.error, msg: except os.error, msg:
print "%s%s: can't chdir: %s" % \ print "%s%s: can't chdir: %s" % \
(prefix, name, msg) (prefix, name, msg)
continue continue
try: try:
reportboguslinks(prefix + name + '/') reportboguslinks(prefix + name + '/')
finally: finally:
os.chdir('..') os.chdir('..')
main() main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment