ÿØÿà JFIF    ÿÛ „ ( %!1!%*+...983,7(-.- Dates.py000064400000017215152344456200006171 0ustar00# Class Date supplies date objects that support date arithmetic. # # Date(month,day,year) returns a Date object. An instance prints as, # e.g., 'Mon 16 Aug 1993'. # # Addition, subtraction, comparison operators, min, max, and sorting # all work as expected for date objects: int+date or date+int returns # the date `int' days from `date'; date+date raises an exception; # date-int returns the date `int' days before `date'; date2-date1 returns # an integer, the number of days from date1 to date2; int-date raises an # exception; date1 < date2 is true iff date1 occurs before date2 (& # similarly for other comparisons); min(date1,date2) is the earlier of # the two dates and max(date1,date2) the later; and date objects can be # used as dictionary keys. # # Date objects support one visible method, date.weekday(). This returns # the day of the week the date falls on, as a string. # # Date objects also have 4 read-only data attributes: # .month in 1..12 # .day in 1..31 # .year int or long int # .ord the ordinal of the date relative to an arbitrary staring point # # The Dates module also supplies function today(), which returns the # current date as a date object. # # Those entranced by calendar trivia will be disappointed, as no attempt # has been made to accommodate the Julian (etc) system. On the other # hand, at least this package knows that 2000 is a leap year but 2100 # isn't, and works fine for years with a hundred decimal digits . # Tim Peters tim@ksr.com # not speaking for Kendall Square Research Corp # Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary) # by Guido van Rossum # Note that as of Python 2.3, a datetime module is included in the stardard # library. # vi:set tabsize=8: _MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] _DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday' ] _DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] _DAYS_BEFORE_MONTH = [] dbm = 0 for dim in _DAYS_IN_MONTH: _DAYS_BEFORE_MONTH.append(dbm) dbm = dbm + dim del dbm, dim _INT_TYPES = type(1), type(1L) def _is_leap(year): # 1 if leap year, else 0 if year % 4 != 0: return 0 if year % 400 == 0: return 1 return year % 100 != 0 def _days_in_year(year): # number of days in year return 365 + _is_leap(year) def _days_before_year(year): # number of days before year return year*365L + (year+3)//4 - (year+99)//100 + (year+399)//400 def _days_in_month(month, year): # number of days in month of year if month == 2 and _is_leap(year): return 29 return _DAYS_IN_MONTH[month-1] def _days_before_month(month, year): # number of days in year before month return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year)) def _date2num(date): # compute ordinal of date.month,day,year return _days_before_year(date.year) + \ _days_before_month(date.month, date.year) + \ date.day _DI400Y = _days_before_year(400) # number of days in 400 years def _num2date(n): # return date with ordinal n if type(n) not in _INT_TYPES: raise TypeError, 'argument must be integer: %r' % type(n) ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj del ans.ord, ans.month, ans.day, ans.year # un-initialize it ans.ord = n n400 = (n-1)//_DI400Y # # of 400-year blocks preceding year, n = 400 * n400, n - _DI400Y * n400 more = n // 365 dby = _days_before_year(more) if dby >= n: more = more - 1 dby = dby - _days_in_year(more) year, n = year + more, int(n - dby) try: year = int(year) # chop to int, if it fits except (ValueError, OverflowError): pass month = min(n//29 + 1, 12) dbm = _days_before_month(month, year) if dbm >= n: month = month - 1 dbm = dbm - _days_in_month(month, year) ans.month, ans.day, ans.year = month, n-dbm, year return ans def _num2day(n): # return weekday name of day with ordinal n return _DAY_NAMES[ int(n % 7) ] class Date: def __init__(self, month, day, year): if not 1 <= month <= 12: raise ValueError, 'month must be in 1..12: %r' % (month,) dim = _days_in_month(month, year) if not 1 <= day <= dim: raise ValueError, 'day must be in 1..%r: %r' % (dim, day) self.month, self.day, self.year = month, day, year self.ord = _date2num(self) # don't allow setting existing attributes def __setattr__(self, name, value): if self.__dict__.has_key(name): raise AttributeError, 'read-only attribute ' + name self.__dict__[name] = value def __cmp__(self, other): return cmp(self.ord, other.ord) # define a hash function so dates can be used as dictionary keys def __hash__(self): return hash(self.ord) # print as, e.g., Mon 16 Aug 1993 def __repr__(self): return '%.3s %2d %.3s %r' % ( self.weekday(), self.day, _MONTH_NAMES[self.month-1], self.year) # Python 1.1 coerces neither int+date nor date+int def __add__(self, n): if type(n) not in _INT_TYPES: raise TypeError, 'can\'t add %r to date' % type(n) return _num2date(self.ord + n) __radd__ = __add__ # handle int+date # Python 1.1 coerces neither date-int nor date-date def __sub__(self, other): if type(other) in _INT_TYPES: # date-int return _num2date(self.ord - other) else: return self.ord - other.ord # date-date # complain about int-date def __rsub__(self, other): raise TypeError, 'Can\'t subtract date from integer' def weekday(self): return _num2day(self.ord) def today(): import time local = time.localtime(time.time()) return Date(local[1], local[2], local[0]) class DateTestError(Exception): pass def test(firstyear, lastyear): a = Date(9,30,1913) b = Date(9,30,1914) if repr(a) != 'Tue 30 Sep 1913': raise DateTestError, '__repr__ failure' if (not a < b) or a == b or a > b or b != b: raise DateTestError, '__cmp__ failure' if a+365 != b or 365+a != b: raise DateTestError, '__add__ failure' if b-a != 365 or b-365 != a: raise DateTestError, '__sub__ failure' try: x = 1 - a raise DateTestError, 'int-date should have failed' except TypeError: pass try: x = a + b raise DateTestError, 'date+date should have failed' except TypeError: pass if a.weekday() != 'Tuesday': raise DateTestError, 'weekday() failure' if max(a,b) is not b or min(a,b) is not a: raise DateTestError, 'min/max failure' d = {a-1:b, b:a+1} if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913): raise DateTestError, 'dictionary failure' # verify date<->number conversions for first and last days for # all years in firstyear .. lastyear lord = _days_before_year(firstyear) y = firstyear while y <= lastyear: ford = lord + 1 lord = ford + _days_in_year(y) - 1 fd, ld = Date(1,1,y), Date(12,31,y) if (fd.ord,ld.ord) != (ford,lord): raise DateTestError, ('date->num failed', y) fd, ld = _num2date(ford), _num2date(lord) if (1,1,y,12,31,y) != \ (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year): raise DateTestError, ('num->date failed', y) y = y + 1 if __name__ == '__main__': test(1850, 2150) Vec.py000064400000002515152344456200005643 0ustar00class Vec: """ A simple vector class Instances of the Vec class can be constructed from numbers >>> a = Vec(1, 2, 3) >>> b = Vec(3, 2, 1) added >>> a + b Vec(4, 4, 4) subtracted >>> a - b Vec(-2, 0, 2) and multiplied by a scalar on the left >>> 3.0 * a Vec(3.0, 6.0, 9.0) or on the right >>> a * 3.0 Vec(3.0, 6.0, 9.0) """ def __init__(self, *v): self.v = list(v) @classmethod def fromlist(cls, v): if not isinstance(v, list): raise TypeError inst = cls() inst.v = v return inst def __repr__(self): args = ', '.join(repr(x) for x in self.v) return 'Vec({0})'.format(args) def __len__(self): return len(self.v) def __getitem__(self, i): return self.v[i] def __add__(self, other): # Element-wise addition v = [x + y for x, y in zip(self.v, other.v)] return Vec.fromlist(v) def __sub__(self, other): # Element-wise subtraction v = [x - y for x, y in zip(self.v, other.v)] return Vec.fromlist(v) def __mul__(self, scalar): # Multiply by scalar v = [x * scalar for x in self.v] return Vec.fromlist(v) __rmul__ = __mul__ def test(): import doctest doctest.testmod() test() Dbm.py000064400000003046152344456200005630 0ustar00# A wrapper around the (optional) built-in class dbm, supporting keys # and values of almost any type instead of just string. # (Actually, this works only for keys and values that can be read back # correctly after being converted to a string.) class Dbm: def __init__(self, filename, mode, perm): import dbm self.db = dbm.open(filename, mode, perm) def __repr__(self): s = '' for key in self.keys(): t = repr(key) + ': ' + repr(self[key]) if s: t = ', ' + t s = s + t return '{' + s + '}' def __len__(self): return len(self.db) def __getitem__(self, key): return eval(self.db[repr(key)]) def __setitem__(self, key, value): self.db[repr(key)] = repr(value) def __delitem__(self, key): del self.db[repr(key)] def keys(self): res = [] for key in self.db.keys(): res.append(eval(key)) return res def has_key(self, key): return self.db.has_key(repr(key)) def test(): d = Dbm('@dbm', 'rw', 0600) print d while 1: try: key = input('key: ') if d.has_key(key): value = d[key] print 'currently:', value value = input('value: ') if value is None: del d[key] else: d[key] = value except KeyboardInterrupt: print '' print d except EOFError: print '[eof]' break print d test() Range.pyo000064400000007773152344456200006354 0ustar00 ^c@sNdZdZdZdddYZdZedkrJendS( s Example of a generator: re-implement the built-in range function without actually constructing the list of values. OldStyleRange is coded in the way required to work in a 'for' loop before iterators were introduced into the language; using __getitem__ and __len__ . cCsyt|dkr,dt|ddfSt|dkr_t|dt|ddfSt|dkr|ddkrtdntd|DStdt|Wntk rtdnXd S( sgTake list of arguments and extract/create proper start, stop, and step values and return in a tupleiiiisstep argument must not be zerocss|]}t|VqdS(N(tint(t.0tx((s*/usr/lib64/python2.7/Demo/classes/Range.pys ss$range() accepts 1-3 arguments, givensArange() arguments must be numbers or strings representing numbersN(tlenRt ValueErrorttuplet TypeError(targlist((s*/usr/lib64/python2.7/Demo/classes/Range.pyt handleargss! cgsAt|\}}}|}x||kr<|V||7}qWdS(s,Function to implement 'range' as a generatorN(R(tatstarttstoptsteptvalue((s*/usr/lib64/python2.7/Demo/classes/Range.pytgenranges toldrangecBs2eZdZdZdZdZdZRS(sClass implementing a range object. To the user the instances feel like immutable sequences (and you can't concatenate or slice them) Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop. cGsEt|\|_|_|_td|j|j|j|_dS(s Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the rangeiN(RR R R tmaxR(tselfR ((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__init__,scCsd|j|j|jfS(s-implement repr(x) which is also used by printsrange(%r, %r, %r)(R R R (R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__repr__2scCs|jS(simplement len(x)(R(R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__len__6scCs>d|ko|jknr1|j|j|StddS(simplement x[i]isrange[i] index out of rangeN(RR R t IndexError(Rti((s*/usr/lib64/python2.7/Demo/classes/Range.pyt __getitem__:s(t__name__t __module__t__doc__RRRR(((s*/usr/lib64/python2.7/Demo/classes/Range.pyR"s    c Cs9ddl}ddl}|jddd}ttddd}ttddd}||ksu||krtd|||fndGH|j}xtdD]}qW|j}xtdD]}qW|j}x|jdD]}qW|j} ||GdGH||Gd GH| |Gd GHdS( NiiidisEerror in implementation: correct = %s old-style = %s generator = %ssTimings for range(1000):issec (old-style class)ssec (generator)ssec (built-in)(ttimet __builtin__trangetlistRRt Exception( RRtcorrect_resulttoldrange_resulttgenrange_resulttt1Rtt2tt3tt4((s*/usr/lib64/python2.7/Demo/classes/Range.pyttestBs*      t__main__N((RRRRR'R(((s*/usr/lib64/python2.7/Demo/classes/Range.pyts     Dbm.pyc000064400000004730152344456200005774 0ustar00 ^c@s'dddYZdZedS(tDbmcBsPeZdZdZdZdZdZdZdZdZ RS(cCs(ddl}|j||||_dS(Ni(tdbmtopentdb(tselftfilenametmodetpermR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__init__ s cCsdd}xO|jD]A}t|dt||}|rJd|}n||}qWd|dS(Nts: s, t{t}(tkeystrepr(Rtstkeytt((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__repr__ s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__len__scCst|jt|S(N(tevalRR (RR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt __getitem__scCst||jt|s$ README000064400000001012152344456200005423 0ustar00Examples of classes that implement special operators (see reference manual): Complex.py Complex numbers Dates.py Date manipulation package by Tim Peters Dbm.py Wrapper around built-in dbm, supporting arbitrary values Range.py Example of a generator: re-implement built-in range() Rev.py Yield the reverse of a sequence Vec.py A simple vector class bitvec.py A bit-vector class by Jan-Hein B\"uhrman (For straightforward examples of basic class features, such as use of methods and inheritance, see the library code.) Complex.py000064400000023342152344456200006536 0ustar00# Complex numbers # --------------- # [Now that Python has a complex data type built-in, this is not very # useful, but it's still a nice example class] # This module represents complex numbers as instances of the class Complex. # A Complex instance z has two data attribues, z.re (the real part) and z.im # (the imaginary part). In fact, z.re and z.im can have any value -- all # arithmetic operators work regardless of the type of z.re and z.im (as long # as they support numerical operations). # # The following functions exist (Complex is actually a class): # Complex([re [,im]) -> creates a complex number from a real and an imaginary part # IsComplex(z) -> true iff z is a complex number (== has .re and .im attributes) # ToComplex(z) -> a complex number equal to z; z itself if IsComplex(z) is true # if z is a tuple(re, im) it will also be converted # PolarToComplex([r [,phi [,fullcircle]]]) -> # the complex number z for which r == z.radius() and phi == z.angle(fullcircle) # (r and phi default to 0) # exp(z) -> returns the complex exponential of z. Equivalent to pow(math.e,z). # # Complex numbers have the following methods: # z.abs() -> absolute value of z # z.radius() == z.abs() # z.angle([fullcircle]) -> angle from positive X axis; fullcircle gives units # z.phi([fullcircle]) == z.angle(fullcircle) # # These standard functions and unary operators accept complex arguments: # abs(z) # -z # +z # not z # repr(z) == `z` # str(z) # hash(z) -> a combination of hash(z.re) and hash(z.im) such that if z.im is zero # the result equals hash(z.re) # Note that hex(z) and oct(z) are not defined. # # These conversions accept complex arguments only if their imaginary part is zero: # int(z) # long(z) # float(z) # # The following operators accept two complex numbers, or one complex number # and one real number (int, long or float): # z1 + z2 # z1 - z2 # z1 * z2 # z1 / z2 # pow(z1, z2) # cmp(z1, z2) # Note that z1 % z2 and divmod(z1, z2) are not defined, # nor are shift and mask operations. # # The standard module math does not support complex numbers. # The cmath modules should be used instead. # # Idea: # add a class Polar(r, phi) and mixed-mode arithmetic which # chooses the most appropriate type for the result: # Complex for +,-,cmp # Polar for *,/,pow import math import sys twopi = math.pi*2.0 halfpi = math.pi/2.0 def IsComplex(obj): return hasattr(obj, 're') and hasattr(obj, 'im') def ToComplex(obj): if IsComplex(obj): return obj elif isinstance(obj, tuple): return Complex(*obj) else: return Complex(obj) def PolarToComplex(r = 0, phi = 0, fullcircle = twopi): phi = phi * (twopi / fullcircle) return Complex(math.cos(phi)*r, math.sin(phi)*r) def Re(obj): if IsComplex(obj): return obj.re return obj def Im(obj): if IsComplex(obj): return obj.im return 0 class Complex: def __init__(self, re=0, im=0): _re = 0 _im = 0 if IsComplex(re): _re = re.re _im = re.im else: _re = re if IsComplex(im): _re = _re - im.im _im = _im + im.re else: _im = _im + im # this class is immutable, so setting self.re directly is # not possible. self.__dict__['re'] = _re self.__dict__['im'] = _im def __setattr__(self, name, value): raise TypeError, 'Complex numbers are immutable' def __hash__(self): if not self.im: return hash(self.re) return hash((self.re, self.im)) def __repr__(self): if not self.im: return 'Complex(%r)' % (self.re,) else: return 'Complex(%r, %r)' % (self.re, self.im) def __str__(self): if not self.im: return repr(self.re) else: return 'Complex(%r, %r)' % (self.re, self.im) def __neg__(self): return Complex(-self.re, -self.im) def __pos__(self): return self def __abs__(self): return math.hypot(self.re, self.im) def __int__(self): if self.im: raise ValueError, "can't convert Complex with nonzero im to int" return int(self.re) def __long__(self): if self.im: raise ValueError, "can't convert Complex with nonzero im to long" return long(self.re) def __float__(self): if self.im: raise ValueError, "can't convert Complex with nonzero im to float" return float(self.re) def __cmp__(self, other): other = ToComplex(other) return cmp((self.re, self.im), (other.re, other.im)) def __rcmp__(self, other): other = ToComplex(other) return cmp(other, self) def __nonzero__(self): return not (self.re == self.im == 0) abs = radius = __abs__ def angle(self, fullcircle = twopi): return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi) phi = angle def __add__(self, other): other = ToComplex(other) return Complex(self.re + other.re, self.im + other.im) __radd__ = __add__ def __sub__(self, other): other = ToComplex(other) return Complex(self.re - other.re, self.im - other.im) def __rsub__(self, other): other = ToComplex(other) return other - self def __mul__(self, other): other = ToComplex(other) return Complex(self.re*other.re - self.im*other.im, self.re*other.im + self.im*other.re) __rmul__ = __mul__ def __div__(self, other): other = ToComplex(other) d = float(other.re*other.re + other.im*other.im) if not d: raise ZeroDivisionError, 'Complex division' return Complex((self.re*other.re + self.im*other.im) / d, (self.im*other.re - self.re*other.im) / d) def __rdiv__(self, other): other = ToComplex(other) return other / self def __pow__(self, n, z=None): if z is not None: raise TypeError, 'Complex does not support ternary pow()' if IsComplex(n): if n.im: if self.im: raise TypeError, 'Complex to the Complex power' else: return exp(math.log(self.re)*n) n = n.re r = pow(self.abs(), n) phi = n*self.angle() return Complex(math.cos(phi)*r, math.sin(phi)*r) def __rpow__(self, base): base = ToComplex(base) return pow(base, self) def exp(z): r = math.exp(z.re) return Complex(math.cos(z.im)*r,math.sin(z.im)*r) def checkop(expr, a, b, value, fuzz = 1e-6): print ' ', a, 'and', b, try: result = eval(expr) except: result = sys.exc_type print '->', result if isinstance(result, str) or isinstance(value, str): ok = (result == value) else: ok = abs(result - value) <= fuzz if not ok: print '!!\t!!\t!! should be', value, 'diff', abs(result - value) def test(): print 'test constructors' constructor_test = ( # "expect" is an array [re,im] "got" the Complex. ( (0,0), Complex() ), ( (0,0), Complex() ), ( (1,0), Complex(1) ), ( (0,1), Complex(0,1) ), ( (1,2), Complex(Complex(1,2)) ), ( (1,3), Complex(Complex(1,2),1) ), ( (0,0), Complex(0,Complex(0,0)) ), ( (3,4), Complex(3,Complex(4)) ), ( (-1,3), Complex(1,Complex(3,2)) ), ( (-7,6), Complex(Complex(1,2),Complex(4,8)) ) ) cnt = [0,0] for t in constructor_test: cnt[0] += 1 if ((t[0][0]!=t[1].re)or(t[0][1]!=t[1].im)): print " expected", t[0], "got", t[1] cnt[1] += 1 print " ", cnt[1], "of", cnt[0], "tests failed" # test operators testsuite = { 'a+b': [ (1, 10, 11), (1, Complex(0,10), Complex(1,10)), (Complex(0,10), 1, Complex(1,10)), (Complex(0,10), Complex(1), Complex(1,10)), (Complex(1), Complex(0,10), Complex(1,10)), ], 'a-b': [ (1, 10, -9), (1, Complex(0,10), Complex(1,-10)), (Complex(0,10), 1, Complex(-1,10)), (Complex(0,10), Complex(1), Complex(-1,10)), (Complex(1), Complex(0,10), Complex(1,-10)), ], 'a*b': [ (1, 10, 10), (1, Complex(0,10), Complex(0, 10)), (Complex(0,10), 1, Complex(0,10)), (Complex(0,10), Complex(1), Complex(0,10)), (Complex(1), Complex(0,10), Complex(0,10)), ], 'a/b': [ (1., 10, 0.1), (1, Complex(0,10), Complex(0, -0.1)), (Complex(0, 10), 1, Complex(0, 10)), (Complex(0, 10), Complex(1), Complex(0, 10)), (Complex(1), Complex(0,10), Complex(0, -0.1)), ], 'pow(a,b)': [ (1, 10, 1), (1, Complex(0,10), 1), (Complex(0,10), 1, Complex(0,10)), (Complex(0,10), Complex(1), Complex(0,10)), (Complex(1), Complex(0,10), 1), (2, Complex(4,0), 16), ], 'cmp(a,b)': [ (1, 10, -1), (1, Complex(0,10), 1), (Complex(0,10), 1, -1), (Complex(0,10), Complex(1), -1), (Complex(1), Complex(0,10), 1), ], } for expr in sorted(testsuite): print expr + ':' t = (expr,) for item in testsuite[expr]: checkop(*(t+item)) if __name__ == '__main__': test() Rev.pyc000064400000005461152344456200006030 0ustar00 ^c@s<dZdddYZdZedkr8endS(s A class which presents the reverse of a sequence without duplicating it. From: "Steven D. Majewski" It works on mutable or inmutable sequences. >>> chars = list(Rev('Hello World!')) >>> print ''.join(chars) !dlroW olleH The .forw is so you can use anonymous sequences in __init__, and still keep a reference the forward sequence. ) If you give it a non-anonymous mutable sequence, the reverse sequence will track the updated values. ( but not reassignment! - another good reason to use anonymous values in creating the sequence to avoid confusion. Maybe it should be change to copy input sequence to break the connection completely ? ) >>> nnn = range(3) >>> rnn = Rev(nnn) >>> for n in rnn: print n ... 2 1 0 >>> for n in range(4, 6): nnn.append(n) # update nnn ... >>> for n in rnn: print n # prints reversed updated values ... 5 4 2 1 0 >>> nnn = nnn[1:-1] >>> nnn [1, 2, 4] >>> for n in rnn: print n # prints reversed values of old nnn ... 5 4 2 1 0 # >>> WH = Rev('Hello World!') >>> print WH.forw, WH.back Hello World! !dlroW olleH >>> nnn = Rev(range(1, 10)) >>> print nnn.forw [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print nnn.back [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> rrr = Rev(nnn) >>> rrr <1, 2, 3, 4, 5, 6, 7, 8, 9> tRevcBs,eZdZdZdZdZRS(cCs||_||_dS(N(tforwtback(tselftseq((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__init__?s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__len__CscCs|j|d S(Ni(R(Rtj((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt __getitem__FscCs|j}t|tr'd}d}nHt|trEd}d}n*t|trcd}d}n d}d}g|jD]}t|^qy}|d |j||dS(Ns[]s, s()ts<>ii(Rt isinstancetlistttupletstrRtjoin(RRtwraptseptitemtoutstrs((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__repr__Is    "(t__name__t __module__RRR R(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyR>s   cCs%ddl}ddl}|j|S(Ni(tdoctestRttestmod(RR((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt_testZst__main__N((t__doc__RRR(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt<s  Range.py000064400000006066152344456200006167 0ustar00"""Example of a generator: re-implement the built-in range function without actually constructing the list of values. OldStyleRange is coded in the way required to work in a 'for' loop before iterators were introduced into the language; using __getitem__ and __len__ . """ def handleargs(arglist): """Take list of arguments and extract/create proper start, stop, and step values and return in a tuple""" try: if len(arglist) == 1: return 0, int(arglist[0]), 1 elif len(arglist) == 2: return int(arglist[0]), int(arglist[1]), 1 elif len(arglist) == 3: if arglist[2] == 0: raise ValueError("step argument must not be zero") return tuple(int(x) for x in arglist) else: raise TypeError("range() accepts 1-3 arguments, given", len(arglist)) except TypeError: raise TypeError("range() arguments must be numbers or strings " "representing numbers") def genrange(*a): """Function to implement 'range' as a generator""" start, stop, step = handleargs(a) value = start while value < stop: yield value value += step class oldrange: """Class implementing a range object. To the user the instances feel like immutable sequences (and you can't concatenate or slice them) Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop. """ def __init__(self, *a): """ Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the range""" self.start, self.stop, self.step = handleargs(a) self.len = max(0, (self.stop - self.start) // self.step) def __repr__(self): """implement repr(x) which is also used by print""" return 'range(%r, %r, %r)' % (self.start, self.stop, self.step) def __len__(self): """implement len(x)""" return self.len def __getitem__(self, i): """implement x[i]""" if 0 <= i <= self.len: return self.start + self.step * i else: raise IndexError, 'range[i] index out of range' def test(): import time, __builtin__ #Just a quick sanity check correct_result = __builtin__.range(5, 100, 3) oldrange_result = list(oldrange(5, 100, 3)) genrange_result = list(genrange(5, 100, 3)) if genrange_result != correct_result or oldrange_result != correct_result: raise Exception("error in implementation:\ncorrect = %s" "\nold-style = %s\ngenerator = %s" % (correct_result, oldrange_result, genrange_result)) print "Timings for range(1000):" t1 = time.time() for i in oldrange(1000): pass t2 = time.time() for i in genrange(1000): pass t3 = time.time() for i in __builtin__.range(1000): pass t4 = time.time() print t2-t1, 'sec (old-style class)' print t3-t2, 'sec (generator)' print t4-t3, 'sec (built-in)' if __name__ == '__main__': test() Complex.pyo000064400000023446152344456200006722 0ustar00 ^c@sddlZddlZejdZejdZdZdZddedZdZdZ d dd YZ d Z d d Z dZ edkre ndS(iNg@cCst|dot|dS(Ntretim(thasattr(tobj((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt IsComplexGscCs7t|r|St|tr)t|St|SdS(N(Rt isinstancettupletComplex(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt ToComplexJs   icCs5|t|}ttj||tj||S(N(ttwopiRtmathtcostsin(trtphit fullcircle((s,/usr/lib64/python2.7/Demo/classes/Complex.pytPolarToComplexRscCst|r|jS|S(N(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytReVs cCst|r|jSdS(Ni(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytIm[s RcBseZdddZdZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZe ZZedZeZdZeZdZdZdZeZdZdZddZdZRS(icCsd}d}t|r-|j}|j}n|}t|r\||j}||j}n ||}||jd<||jdcCsdG|GdG|Gyt|}Wntj}nXdG|GHt|tsZt|tri||k}nt|||k}|sdG|GdGt||GHndS(Ns tands->s!! !! !! should betdiff(tevaltsystexc_typeRtstrR@(texprtatbRtfuzztresulttok((s,/usr/lib64/python2.7/Demo/classes/Complex.pytcheckops  cCsdGHdtfd tfd!tdfd"tddfd#ttddfd$ttdddfd%tdtddfd&tdtdfd'tdtddfd(ttddtdd ff }ddg}x|D]x}|dcd7<|dd|djksH|dd|djkrd G|dGd G|dGH|dcd7As           J Range.pyc000064400000007773152344456200006340 0ustar00 ^c@sNdZdZdZdddYZdZedkrJendS( s Example of a generator: re-implement the built-in range function without actually constructing the list of values. OldStyleRange is coded in the way required to work in a 'for' loop before iterators were introduced into the language; using __getitem__ and __len__ . cCsyt|dkr,dt|ddfSt|dkr_t|dt|ddfSt|dkr|ddkrtdntd|DStdt|Wntk rtdnXd S( sgTake list of arguments and extract/create proper start, stop, and step values and return in a tupleiiiisstep argument must not be zerocss|]}t|VqdS(N(tint(t.0tx((s*/usr/lib64/python2.7/Demo/classes/Range.pys ss$range() accepts 1-3 arguments, givensArange() arguments must be numbers or strings representing numbersN(tlenRt ValueErrorttuplet TypeError(targlist((s*/usr/lib64/python2.7/Demo/classes/Range.pyt handleargss! cgsAt|\}}}|}x||kr<|V||7}qWdS(s,Function to implement 'range' as a generatorN(R(tatstarttstoptsteptvalue((s*/usr/lib64/python2.7/Demo/classes/Range.pytgenranges toldrangecBs2eZdZdZdZdZdZRS(sClass implementing a range object. To the user the instances feel like immutable sequences (and you can't concatenate or slice them) Done using the old way (pre-iterators; __len__ and __getitem__) to have an object be used by a 'for' loop. cGsEt|\|_|_|_td|j|j|j|_dS(s Initialize start, stop, and step values along with calculating the nubmer of values (what __len__ will return) in the rangeiN(RR R R tmaxR(tselfR ((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__init__,scCsd|j|j|jfS(s-implement repr(x) which is also used by printsrange(%r, %r, %r)(R R R (R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__repr__2scCs|jS(simplement len(x)(R(R((s*/usr/lib64/python2.7/Demo/classes/Range.pyt__len__6scCs>d|ko|jknr1|j|j|StddS(simplement x[i]isrange[i] index out of rangeN(RR R t IndexError(Rti((s*/usr/lib64/python2.7/Demo/classes/Range.pyt __getitem__:s(t__name__t __module__t__doc__RRRR(((s*/usr/lib64/python2.7/Demo/classes/Range.pyR"s    c Cs9ddl}ddl}|jddd}ttddd}ttddd}||ksu||krtd|||fndGH|j}xtdD]}qW|j}xtdD]}qW|j}x|jdD]}qW|j} ||GdGH||Gd GH| |Gd GHdS( NiiidisEerror in implementation: correct = %s old-style = %s generator = %ssTimings for range(1000):issec (old-style class)ssec (generator)ssec (built-in)(ttimet __builtin__trangetlistRRt Exception( RRtcorrect_resulttoldrange_resulttgenrange_resulttt1Rtt2tt3tt4((s*/usr/lib64/python2.7/Demo/classes/Range.pyttestBs*      t__main__N((RRRRR'R(((s*/usr/lib64/python2.7/Demo/classes/Range.pyts     Vec.pyo000064400000005404152344456200006022 0ustar00 ^c@s'dddYZdZedS(tVeccBsbeZdZdZedZdZdZdZdZ dZ dZ e Z RS( sx A simple vector class Instances of the Vec class can be constructed from numbers >>> a = Vec(1, 2, 3) >>> b = Vec(3, 2, 1) added >>> a + b Vec(4, 4, 4) subtracted >>> a - b Vec(-2, 0, 2) and multiplied by a scalar on the left >>> 3.0 * a Vec(3.0, 6.0, 9.0) or on the right >>> a * 3.0 Vec(3.0, 6.0, 9.0) cGst||_dS(N(tlisttv(tselfR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__init__scCs.t|tstn|}||_|S(N(t isinstanceRt TypeErrorR(tclsRtinst((s(/usr/lib64/python2.7/Demo/classes/Vec.pytfromlists    cCs)djd|jD}dj|S(Ns, css|]}t|VqdS(N(trepr(t.0tx((s(/usr/lib64/python2.7/Demo/classes/Vec.pys %ssVec({0})(tjoinRtformat(Rtargs((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__repr__$scCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__len__(scCs |j|S(N(R(Rti((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt __getitem__+scCs?gt|j|jD]\}}||^q}tj|S(N(tzipRRR (RtotherR tyR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__add__.s2cCs?gt|j|jD]\}}||^q}tj|S(N(RRRR (RRR RR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__sub__3s2cCs-g|jD]}||^q }tj|S(N(RRR (RtscalarR R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__mul__8s ( t__name__t __module__t__doc__Rt classmethodR RRRRRRt__rmul__(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyRs       cCsddl}|jdS(Ni(tdoctestttestmod(R!((s(/usr/lib64/python2.7/Demo/classes/Vec.pyttest@s N((RR#(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyts? Complex.pyc000064400000023446152344456200006706 0ustar00 ^c@sddlZddlZejdZejdZdZdZddedZdZdZ d dd YZ d Z d d Z dZ edkre ndS(iNg@cCst|dot|dS(Ntretim(thasattr(tobj((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt IsComplexGscCs7t|r|St|tr)t|St|SdS(N(Rt isinstancettupletComplex(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pyt ToComplexJs   icCs5|t|}ttj||tj||S(N(ttwopiRtmathtcostsin(trtphit fullcircle((s,/usr/lib64/python2.7/Demo/classes/Complex.pytPolarToComplexRscCst|r|jS|S(N(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytReVs cCst|r|jSdS(Ni(RR(R((s,/usr/lib64/python2.7/Demo/classes/Complex.pytIm[s RcBseZdddZdZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZe ZZedZeZdZeZdZdZdZeZdZdZddZdZRS(icCsd}d}t|r-|j}|j}n|}t|r\||j}||j}n ||}||jd<||jdcCsdG|GdG|Gyt|}Wntj}nXdG|GHt|tsZt|tri||k}nt|||k}|sdG|GdGt||GHndS(Ns tands->s!! !! !! should betdiff(tevaltsystexc_typeRtstrR@(texprtatbRtfuzztresulttok((s,/usr/lib64/python2.7/Demo/classes/Complex.pytcheckops  cCsdGHdtfd tfd!tdfd"tddfd#ttddfd$ttdddfd%tdtddfd&tdtdfd'tdtddfd(ttddtdd ff }ddg}x|D]x}|dcd7<|dd|djksH|dd|djkrd G|dGd G|dGH|dcd7As           J bitvec.pyo000064400000024065152344456200006565 0ustar00 ^c@s{ddlZejjZdefdYZdZddlZdZdZ dZ dfd YZ e Z dS( iNterrorcBseZRS((t__name__t __module__(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR scCsEt|tdks5d|ko/dkn rAtdndS(Niis)bitvec() items must have int value 0 or 1(ttypeR(tvalue((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_value s5cCstjt|\}}d|>}||krMtd||ffnx,|r{|d?}||@rnPn|d}qPW|S(Nls(param, l) = %ri(tmathtfrexptfloatt RuntimeError(tparamtmanttltbitmask((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _compute_lens     cCsit|tdkr$tdn|dkr=||}nd|koT|knsetdn|S(Nissequence subscript not intslist index out of range(Rt TypeErrort IndexError(tlentkey((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_key!s    cCs>t|dt||}}||kr4|}n||fS(Ni(tmaxtmin(Rtitj((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_slice*s  tBitVeccBs eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(cGsd|_d|_t|s!nt|dkr|\}t|tgkrd}d}x+|D]#}|r||B}n|d>}qgW||_t||_qt|tdkr|dkrtdn||_t||_qtdnt|dkr|\}}t|tdkr|dkrNtdn||_t|tdkr{td nt|}||krd GH|jd|>d@|_n||_qtdn td dS( Nliils$bitvec() can't handle negative longss)bitvec() requires array or long parameteriscan't handle negative longss$bitvec()'s 2nd parameter must be intsMwarning: bitvec() value is longer than the length indicates, truncating values%bitvec() requires 0 -- 2 parameter(s)(t_datat_lenRRRR(tselftparamsR Rtbit_masktitemtlengthtcomputed_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__init__4sL                    cCs(tt| d||j|j+dS(Ni(RtlongR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytappendbscCsR|r|j}n |j}d}x)|rM|d?||d@dk}}q%W|S(Nii(R(RRtdatatcount((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR&is   #cCs^|r|j}n |j}d}|s4tdnx#|d@sY|d?|d}}q7W|S(Nislist.index(x): x not in listi(Rt ValueError(RRR%tindex((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR(us    cCs"tt| d|||+dS(Ni(RR#(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytinsertscCs||j|=dS(N(R((RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytremovescCso|jd}}xOt|jD]>}|sA||j|>}Pn|d>|d@B|d?}}q W||_dS(Nli(RtrangeR(RR%tresultR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytreverses!cCs/|jd}d|>d|j|>|_dS(Nil(R&RR(Rtc((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytsortscCst|j|jS(N(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytcopyscCs(g}x|D]}|j|q W|S(N(R$(RR,R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytseqs cCsd|j|jfS(Nsbitvec(%r, %r)(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__repr__scGs#t|t|kr1tt|f|}n|j}|dksU|jdkret||jS||jkrt||j}t|| || pt||||S|j|jkrdS|dkrt|d|dS|d?}t|| || pt||||SdS(Nii(RtapplytbitvecRtcmpRR(RtothertrestR t min_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__cmp__s    cCs|jS(N(R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__len__scCs't|j|}|jd|>@dkS(Nli(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getitem__scCsHt|j|}|r/|jd|>B|_n|jd|>@|_dS(Nl(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setitem__scCsIt|j|}|| j||dj|?B|_|jd|_dS(Ni(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delitem__s#cCst|j||\}}||kr4tddS|rJ|j|?}n |j}||}||jkr|d|>d@}nt||S(Nlili(RRRR(RRRtndatatnlength((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getslice__s    cGst|j||\}}t|t|krLtt|f|}n|| }||}|j|j|j|j>B|j>B|_|j|||j|_dS(N(RRRR3R4R(RRRtsequenceR7tls_parttms_part((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setslice__s  cCst|j||\}}|dkrK||jkrKd\|_|_nB||kr|| j||j|?B|_|j|||_ndS(Nil(li(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delslice__s  cCs#|j}|||j|j+|S(N(R0R(RR6tretval((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__add__s cCst|tdkr$tdn|dkr=tddS|dkrS|jS|jdkrvtd|j|S|jdkrtd|j|Stdd}x|r|||d}}qW|S(Nissequence subscript not intli(RRRR0RR(Rt multiplierRF((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__mul__ s      cGsWt|t|kr1tt|f|}nt|j|j@t|j|jS(N(RR3R4RRRR(RtotherseqR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__and__scGsWt|t|kr1tt|f|}nt|j|jAt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__xor__%scGsWt|t|kr1tt|f|}nt|j|jBt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__or__.scCs#t|jd|j>d@|jS(Nli(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __invert__7scGs;t|t|kr1tt|f|}n||fS(N(RR3R4(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __coerce__<scCs t|jS(N(tintR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__int__CscCs t|jS(N(R#R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__long__FscCs t|jS(N(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __float__Is(RRR"R$R&R(R)R*R-R/R0R1R2R9R:R;R<R=R@RDRERGRIRKRLRMRNRORQRRRS(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR2s: .                   ( tsyststderrtwritetrprtt ExceptionRRRRRRRR4(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyts    bitvec.py000064400000024377152344456200006414 0ustar00# # this is a rather strict implementation of a bit vector class # it is accessed the same way as an array of python-ints, except # the value must be 0 or 1 # import sys; rprt = sys.stderr.write #for debugging class error(Exception): pass def _check_value(value): if type(value) != type(0) or not 0 <= value < 2: raise error, 'bitvec() items must have int value 0 or 1' import math def _compute_len(param): mant, l = math.frexp(float(param)) bitmask = 1L << l if bitmask <= param: raise RuntimeError('(param, l) = %r' % ((param, l),)) while l: bitmask = bitmask >> 1 if param & bitmask: break l = l - 1 return l def _check_key(len, key): if type(key) != type(0): raise TypeError, 'sequence subscript not int' if key < 0: key = key + len if not 0 <= key < len: raise IndexError, 'list index out of range' return key def _check_slice(len, i, j): #the type is ok, Python already checked that i, j = max(i, 0), min(len, j) if i > j: i = j return i, j class BitVec: def __init__(self, *params): self._data = 0L self._len = 0 if not len(params): pass elif len(params) == 1: param, = params if type(param) == type([]): value = 0L bit_mask = 1L for item in param: # strict check #_check_value(item) if item: value = value | bit_mask bit_mask = bit_mask << 1 self._data = value self._len = len(param) elif type(param) == type(0L): if param < 0: raise error, 'bitvec() can\'t handle negative longs' self._data = param self._len = _compute_len(param) else: raise error, 'bitvec() requires array or long parameter' elif len(params) == 2: param, length = params if type(param) == type(0L): if param < 0: raise error, \ 'can\'t handle negative longs' self._data = param if type(length) != type(0): raise error, 'bitvec()\'s 2nd parameter must be int' computed_length = _compute_len(param) if computed_length > length: print 'warning: bitvec() value is longer than the length indicates, truncating value' self._data = self._data & \ ((1L << length) - 1) self._len = length else: raise error, 'bitvec() requires array or long parameter' else: raise error, 'bitvec() requires 0 -- 2 parameter(s)' def append(self, item): #_check_value(item) #self[self._len:self._len] = [item] self[self._len:self._len] = \ BitVec(long(not not item), 1) def count(self, value): #_check_value(value) if value: data = self._data else: data = (~self)._data count = 0 while data: data, count = data >> 1, count + (data & 1 != 0) return count def index(self, value): #_check_value(value): if value: data = self._data else: data = (~self)._data index = 0 if not data: raise ValueError, 'list.index(x): x not in list' while not (data & 1): data, index = data >> 1, index + 1 return index def insert(self, index, item): #_check_value(item) #self[index:index] = [item] self[index:index] = BitVec(long(not not item), 1) def remove(self, value): del self[self.index(value)] def reverse(self): #ouch, this one is expensive! #for i in self._len>>1: self[i], self[l-i] = self[l-i], self[i] data, result = self._data, 0L for i in range(self._len): if not data: result = result << (self._len - i) break result, data = (result << 1) | (data & 1), data >> 1 self._data = result def sort(self): c = self.count(1) self._data = ((1L << c) - 1) << (self._len - c) def copy(self): return BitVec(self._data, self._len) def seq(self): result = [] for i in self: result.append(i) return result def __repr__(self): ##rprt('.' + '__repr__()\n') return 'bitvec(%r, %r)' % (self._data, self._len) def __cmp__(self, other, *rest): #rprt('%r.__cmp__%r\n' % (self, (other,) + rest)) if type(other) != type(self): other = apply(bitvec, (other, ) + rest) #expensive solution... recursive binary, with slicing length = self._len if length == 0 or other._len == 0: return cmp(length, other._len) if length != other._len: min_length = min(length, other._len) return cmp(self[:min_length], other[:min_length]) or \ cmp(self[min_length:], other[min_length:]) #the lengths are the same now... if self._data == other._data: return 0 if length == 1: return cmp(self[0], other[0]) else: length = length >> 1 return cmp(self[:length], other[:length]) or \ cmp(self[length:], other[length:]) def __len__(self): #rprt('%r.__len__()\n' % (self,)) return self._len def __getitem__(self, key): #rprt('%r.__getitem__(%r)\n' % (self, key)) key = _check_key(self._len, key) return self._data & (1L << key) != 0 def __setitem__(self, key, value): #rprt('%r.__setitem__(%r, %r)\n' % (self, key, value)) key = _check_key(self._len, key) #_check_value(value) if value: self._data = self._data | (1L << key) else: self._data = self._data & ~(1L << key) def __delitem__(self, key): #rprt('%r.__delitem__(%r)\n' % (self, key)) key = _check_key(self._len, key) #el cheapo solution... self._data = self[:key]._data | self[key+1:]._data >> key self._len = self._len - 1 def __getslice__(self, i, j): #rprt('%r.__getslice__(%r, %r)\n' % (self, i, j)) i, j = _check_slice(self._len, i, j) if i >= j: return BitVec(0L, 0) if i: ndata = self._data >> i else: ndata = self._data nlength = j - i if j != self._len: #we'll have to invent faster variants here #e.g. mod_2exp ndata = ndata & ((1L << nlength) - 1) return BitVec(ndata, nlength) def __setslice__(self, i, j, sequence, *rest): #rprt('%s.__setslice__%r\n' % (self, (i, j, sequence) + rest)) i, j = _check_slice(self._len, i, j) if type(sequence) != type(self): sequence = apply(bitvec, (sequence, ) + rest) #sequence is now of our own type ls_part = self[:i] ms_part = self[j:] self._data = ls_part._data | \ ((sequence._data | \ (ms_part._data << sequence._len)) << ls_part._len) self._len = self._len - j + i + sequence._len def __delslice__(self, i, j): #rprt('%r.__delslice__(%r, %r)\n' % (self, i, j)) i, j = _check_slice(self._len, i, j) if i == 0 and j == self._len: self._data, self._len = 0L, 0 elif i < j: self._data = self[:i]._data | (self[j:]._data >> i) self._len = self._len - j + i def __add__(self, other): #rprt('%r.__add__(%r)\n' % (self, other)) retval = self.copy() retval[self._len:self._len] = other return retval def __mul__(self, multiplier): #rprt('%r.__mul__(%r)\n' % (self, multiplier)) if type(multiplier) != type(0): raise TypeError, 'sequence subscript not int' if multiplier <= 0: return BitVec(0L, 0) elif multiplier == 1: return self.copy() #handle special cases all 0 or all 1... if self._data == 0L: return BitVec(0L, self._len * multiplier) elif (~self)._data == 0L: return ~BitVec(0L, self._len * multiplier) #otherwise el cheapo again... retval = BitVec(0L, 0) while multiplier: retval, multiplier = retval + self, multiplier - 1 return retval def __and__(self, otherseq, *rest): #rprt('%r.__and__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type return BitVec(self._data & otherseq._data, \ min(self._len, otherseq._len)) def __xor__(self, otherseq, *rest): #rprt('%r.__xor__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type return BitVec(self._data ^ otherseq._data, \ max(self._len, otherseq._len)) def __or__(self, otherseq, *rest): #rprt('%r.__or__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) #sequence is now of our own type return BitVec(self._data | otherseq._data, \ max(self._len, otherseq._len)) def __invert__(self): #rprt('%r.__invert__()\n' % (self,)) return BitVec(~self._data & ((1L << self._len) - 1), \ self._len) def __coerce__(self, otherseq, *rest): #needed for *some* of the arithmetic operations #rprt('%r.__coerce__%r\n' % (self, (otherseq,) + rest)) if type(otherseq) != type(self): otherseq = apply(bitvec, (otherseq, ) + rest) return self, otherseq def __int__(self): return int(self._data) def __long__(self): return long(self._data) def __float__(self): return float(self._data) bitvec = BitVec bitvec.pyc000064400000024065152344456200006551 0ustar00 ^c@s{ddlZejjZdefdYZdZddlZdZdZ dZ dfd YZ e Z dS( iNterrorcBseZRS((t__name__t __module__(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR scCsEt|tdks5d|ko/dkn rAtdndS(Niis)bitvec() items must have int value 0 or 1(ttypeR(tvalue((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_value s5cCstjt|\}}d|>}||krMtd||ffnx,|r{|d?}||@rnPn|d}qPW|S(Nls(param, l) = %ri(tmathtfrexptfloatt RuntimeError(tparamtmanttltbitmask((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _compute_lens     cCsit|tdkr$tdn|dkr=||}nd|koT|knsetdn|S(Nissequence subscript not intslist index out of range(Rt TypeErrort IndexError(tlentkey((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_key!s    cCs>t|dt||}}||kr4|}n||fS(Ni(tmaxtmin(Rtitj((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt _check_slice*s  tBitVeccBs eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZRS(cGsd|_d|_t|s!nt|dkr|\}t|tgkrd}d}x+|D]#}|r||B}n|d>}qgW||_t||_qt|tdkr|dkrtdn||_t||_qtdnt|dkr|\}}t|tdkr|dkrNtdn||_t|tdkr{td nt|}||krd GH|jd|>d@|_n||_qtdn td dS( Nliils$bitvec() can't handle negative longss)bitvec() requires array or long parameteriscan't handle negative longss$bitvec()'s 2nd parameter must be intsMwarning: bitvec() value is longer than the length indicates, truncating values%bitvec() requires 0 -- 2 parameter(s)(t_datat_lenRRRR(tselftparamsR Rtbit_masktitemtlengthtcomputed_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__init__4sL                    cCs(tt| d||j|j+dS(Ni(RtlongR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytappendbscCsR|r|j}n |j}d}x)|rM|d?||d@dk}}q%W|S(Nii(R(RRtdatatcount((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR&is   #cCs^|r|j}n |j}d}|s4tdnx#|d@sY|d?|d}}q7W|S(Nislist.index(x): x not in listi(Rt ValueError(RRR%tindex((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR(us    cCs"tt| d|||+dS(Ni(RR#(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytinsertscCs||j|=dS(N(R((RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytremovescCso|jd}}xOt|jD]>}|sA||j|>}Pn|d>|d@B|d?}}q W||_dS(Nli(RtrangeR(RR%tresultR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytreverses!cCs/|jd}d|>d|j|>|_dS(Nil(R&RR(Rtc((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytsortscCst|j|jS(N(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytcopyscCs(g}x|D]}|j|q W|S(N(R$(RR,R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pytseqs cCsd|j|jfS(Nsbitvec(%r, %r)(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__repr__scGs#t|t|kr1tt|f|}n|j}|dksU|jdkret||jS||jkrt||j}t|| || pt||||S|j|jkrdS|dkrt|d|dS|d?}t|| || pt||||SdS(Nii(RtapplytbitvecRtcmpRR(RtothertrestR t min_length((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__cmp__s    cCs|jS(N(R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__len__scCs't|j|}|jd|>@dkS(Nli(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getitem__scCsHt|j|}|r/|jd|>B|_n|jd|>@|_dS(Nl(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setitem__scCsIt|j|}|| j||dj|?B|_|jd|_dS(Ni(RRR(RR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delitem__s#cCst|j||\}}||kr4tddS|rJ|j|?}n |j}||}||jkr|d|>d@}nt||S(Nlili(RRRR(RRRtndatatnlength((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __getslice__s    cGst|j||\}}t|t|krLtt|f|}n|| }||}|j|j|j|j>B|j>B|_|j|||j|_dS(N(RRRR3R4R(RRRtsequenceR7tls_parttms_part((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __setslice__s  cCst|j||\}}|dkrK||jkrKd\|_|_nB||kr|| j||j|?B|_|j|||_ndS(Nil(li(RRR(RRR((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __delslice__s  cCs#|j}|||j|j+|S(N(R0R(RR6tretval((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__add__s cCst|tdkr$tdn|dkr=tddS|dkrS|jS|jdkrvtd|j|S|jdkrtd|j|Stdd}x|r|||d}}qW|S(Nissequence subscript not intli(RRRR0RR(Rt multiplierRF((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__mul__ s      cGsWt|t|kr1tt|f|}nt|j|j@t|j|jS(N(RR3R4RRRR(RtotherseqR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__and__scGsWt|t|kr1tt|f|}nt|j|jAt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__xor__%scGsWt|t|kr1tt|f|}nt|j|jBt|j|jS(N(RR3R4RRRR(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__or__.scCs#t|jd|j>d@|jS(Nli(RRR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __invert__7scGs;t|t|kr1tt|f|}n||fS(N(RR3R4(RRJR7((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __coerce__<scCs t|jS(N(tintR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__int__CscCs t|jS(N(R#R(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt__long__FscCs t|jS(N(RR(R((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyt __float__Is(RRR"R$R&R(R)R*R-R/R0R1R2R9R:R;R<R=R@RDRERGRIRKRLRMRNRORQRRRS(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyR2s: .                   ( tsyststderrtwritetrprtt ExceptionRRRRRRRR4(((s+/usr/lib64/python2.7/Demo/classes/bitvec.pyts    Dates.pyc000064400000016246152344456200006337 0ustar00 ^c @spdddddddddd d d g Zd d dddddgZddddddddddddg ZgZdZx%eD]ZejeeeZqW[[ededfZdZ dZ dZ dZ dZ dZe dZd Zd!Zd"d,d#YZd$Zd%efd&YZd'Zed(krled)d*nd+S(-tJanuarytFebruarytMarchtApriltMaytJunetJulytAugustt SeptembertOctobertNovembertDecembertFridaytSaturdaytSundaytMondaytTuesdayt WednesdaytThursdayiiiiilcCs6|ddkrdS|ddkr(dS|ddkS(Niiiiid((tyear((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_is_leap>s cCsdt|S(Nim(R(R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _days_in_yearCscCs,|d|dd|dd|ddS(Nlmiiicidii((R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_yearFscCs(|dkrt|rdSt|dS(Niii(Rt_DAYS_IN_MONTH(tmonthR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_in_monthIscCs"t|d|dko t|S(Nii(t_DAYS_BEFORE_MONTHR(RR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_monthMscCs't|jt|j|j|jS(N(RRRRtday(tdate((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _date2numPsicCs}t|tkr(tdt|ntddd}|`|`|`|`||_|dt}d||t|}}|d}t |}||kr|d}|t |}n||t ||}}yt |}Wnt t fk rnXt|ddd}t||}||krX|d}|t||}n|||||_|_|_|S(Nsargument must be integer: %riiimii (ttypet _INT_TYPESt TypeErrortDatetordRRRt_DI400YRRtintt ValueErrort OverflowErrortminRR(tntanstn400RtmoretdbyRtdbm((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _num2dateWs0       !cCstt|dS(Ni(t _DAY_NAMESR%(R)((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_num2daytsR"cBs_eZdZdZdZdZdZdZeZdZ dZ dZ RS( cCsd|kodkns/td|fnt||}d|koU|knsptd||fn||||_|_|_t||_dS(Nii smonth must be in 1..12: %rsday must be in 1..%r: %r(R&RRRRRR#(tselfRRRtdim((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt__init__yscCs3|jj|r"td|n||j|num failedsnum->date failed(R"treprRMR!R@tmaxR(RRR#R/RRR( t firstyeartlastyeartatbtxtdtlordtytfordtfdtld((s*/usr/lib64/python2.7/Demo/classes/Dates.pyttestsP 1            * 8   %-t__main__i:ifN((RAR0RRR.R3tappendRR RRRRRRR$R/R1R"RLt ExceptionRMR[RF(((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt,s6  *           4  . Dates.pyo000064400000016246152344456200006353 0ustar00 ^c @spdddddddddd d d g Zd d dddddgZddddddddddddg ZgZdZx%eD]ZejeeeZqW[[ededfZdZ dZ dZ dZ dZ dZe dZd Zd!Zd"d,d#YZd$Zd%efd&YZd'Zed(krled)d*nd+S(-tJanuarytFebruarytMarchtApriltMaytJunetJulytAugustt SeptembertOctobertNovembertDecembertFridaytSaturdaytSundaytMondaytTuesdayt WednesdaytThursdayiiiiilcCs6|ddkrdS|ddkr(dS|ddkS(Niiiiid((tyear((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_is_leap>s cCsdt|S(Nim(R(R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _days_in_yearCscCs,|d|dd|dd|ddS(Nlmiiicidii((R((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_yearFscCs(|dkrt|rdSt|dS(Niii(Rt_DAYS_IN_MONTH(tmonthR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_in_monthIscCs"t|d|dko t|S(Nii(t_DAYS_BEFORE_MONTHR(RR((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_days_before_monthMscCs't|jt|j|j|jS(N(RRRRtday(tdate((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _date2numPsicCs}t|tkr(tdt|ntddd}|`|`|`|`||_|dt}d||t|}}|d}t |}||kr|d}|t |}n||t ||}}yt |}Wnt t fk rnXt|ddd}t||}||krX|d}|t||}n|||||_|_|_|S(Nsargument must be integer: %riiimii (ttypet _INT_TYPESt TypeErrortDatetordRRRt_DI400YRRtintt ValueErrort OverflowErrortminRR(tntanstn400RtmoretdbyRtdbm((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt _num2dateWs0       !cCstt|dS(Ni(t _DAY_NAMESR%(R)((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt_num2daytsR"cBs_eZdZdZdZdZdZdZeZdZ dZ dZ RS( cCsd|kodkns/td|fnt||}d|koU|knsptd||fn||||_|_|_t||_dS(Nii smonth must be in 1..12: %rsday must be in 1..%r: %r(R&RRRRRR#(tselfRRRtdim((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt__init__yscCs3|jj|r"td|n||j|num failedsnum->date failed(R"treprRMR!R@tmaxR(RRR#R/RRR( t firstyeartlastyeartatbtxtdtlordtytfordtfdtld((s*/usr/lib64/python2.7/Demo/classes/Dates.pyttestsP 1            * 8   %-t__main__i:ifN((RAR0RRR.R3tappendRR RRRRRRR$R/R1R"RLt ExceptionRMR[RF(((s*/usr/lib64/python2.7/Demo/classes/Dates.pyt,s6  *           4  . Vec.pyc000064400000005404152344456200006006 0ustar00 ^c@s'dddYZdZedS(tVeccBsbeZdZdZedZdZdZdZdZ dZ dZ e Z RS( sx A simple vector class Instances of the Vec class can be constructed from numbers >>> a = Vec(1, 2, 3) >>> b = Vec(3, 2, 1) added >>> a + b Vec(4, 4, 4) subtracted >>> a - b Vec(-2, 0, 2) and multiplied by a scalar on the left >>> 3.0 * a Vec(3.0, 6.0, 9.0) or on the right >>> a * 3.0 Vec(3.0, 6.0, 9.0) cGst||_dS(N(tlisttv(tselfR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__init__scCs.t|tstn|}||_|S(N(t isinstanceRt TypeErrorR(tclsRtinst((s(/usr/lib64/python2.7/Demo/classes/Vec.pytfromlists    cCs)djd|jD}dj|S(Ns, css|]}t|VqdS(N(trepr(t.0tx((s(/usr/lib64/python2.7/Demo/classes/Vec.pys %ssVec({0})(tjoinRtformat(Rtargs((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__repr__$scCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__len__(scCs |j|S(N(R(Rti((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt __getitem__+scCs?gt|j|jD]\}}||^q}tj|S(N(tzipRRR (RtotherR tyR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__add__.s2cCs?gt|j|jD]\}}||^q}tj|S(N(RRRR (RRR RR((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__sub__3s2cCs-g|jD]}||^q }tj|S(N(RRR (RtscalarR R((s(/usr/lib64/python2.7/Demo/classes/Vec.pyt__mul__8s ( t__name__t __module__t__doc__Rt classmethodR RRRRRRt__rmul__(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyRs       cCsddl}|jdS(Ni(tdoctestttestmod(R!((s(/usr/lib64/python2.7/Demo/classes/Vec.pyttest@s N((RR#(((s(/usr/lib64/python2.7/Demo/classes/Vec.pyts? Rev.py000064400000004004152344456200005655 0ustar00''' A class which presents the reverse of a sequence without duplicating it. From: "Steven D. Majewski" It works on mutable or inmutable sequences. >>> chars = list(Rev('Hello World!')) >>> print ''.join(chars) !dlroW olleH The .forw is so you can use anonymous sequences in __init__, and still keep a reference the forward sequence. ) If you give it a non-anonymous mutable sequence, the reverse sequence will track the updated values. ( but not reassignment! - another good reason to use anonymous values in creating the sequence to avoid confusion. Maybe it should be change to copy input sequence to break the connection completely ? ) >>> nnn = range(3) >>> rnn = Rev(nnn) >>> for n in rnn: print n ... 2 1 0 >>> for n in range(4, 6): nnn.append(n) # update nnn ... >>> for n in rnn: print n # prints reversed updated values ... 5 4 2 1 0 >>> nnn = nnn[1:-1] >>> nnn [1, 2, 4] >>> for n in rnn: print n # prints reversed values of old nnn ... 5 4 2 1 0 # >>> WH = Rev('Hello World!') >>> print WH.forw, WH.back Hello World! !dlroW olleH >>> nnn = Rev(range(1, 10)) >>> print nnn.forw [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print nnn.back [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> rrr = Rev(nnn) >>> rrr <1, 2, 3, 4, 5, 6, 7, 8, 9> ''' class Rev: def __init__(self, seq): self.forw = seq self.back = self def __len__(self): return len(self.forw) def __getitem__(self, j): return self.forw[-(j + 1)] def __repr__(self): seq = self.forw if isinstance(seq, list): wrap = '[]' sep = ', ' elif isinstance(seq, tuple): wrap = '()' sep = ', ' elif isinstance(seq, str): wrap = '' sep = '' else: wrap = '<>' sep = ', ' outstrs = [str(item) for item in self.back] return wrap[:1] + sep.join(outstrs) + wrap[-1:] def _test(): import doctest, Rev return doctest.testmod(Rev) if __name__ == "__main__": _test() Dbm.pyo000064400000004730152344456200006010 0ustar00 ^c@s'dddYZdZedS(tDbmcBsPeZdZdZdZdZdZdZdZdZ RS(cCs(ddl}|j||||_dS(Ni(tdbmtopentdb(tselftfilenametmodetpermR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__init__ s cCsdd}xO|jD]A}t|dt||}|rJd|}n||}qWd|dS(Nts: s, t{t}(tkeystrepr(Rtstkeytt((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__repr__ s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt__len__scCst|jt|S(N(tevalRR (RR((s(/usr/lib64/python2.7/Demo/classes/Dbm.pyt __getitem__scCst||jt|s$ Rev.pyo000064400000005461152344456200006044 0ustar00 ^c@s<dZdddYZdZedkr8endS(s A class which presents the reverse of a sequence without duplicating it. From: "Steven D. Majewski" It works on mutable or inmutable sequences. >>> chars = list(Rev('Hello World!')) >>> print ''.join(chars) !dlroW olleH The .forw is so you can use anonymous sequences in __init__, and still keep a reference the forward sequence. ) If you give it a non-anonymous mutable sequence, the reverse sequence will track the updated values. ( but not reassignment! - another good reason to use anonymous values in creating the sequence to avoid confusion. Maybe it should be change to copy input sequence to break the connection completely ? ) >>> nnn = range(3) >>> rnn = Rev(nnn) >>> for n in rnn: print n ... 2 1 0 >>> for n in range(4, 6): nnn.append(n) # update nnn ... >>> for n in rnn: print n # prints reversed updated values ... 5 4 2 1 0 >>> nnn = nnn[1:-1] >>> nnn [1, 2, 4] >>> for n in rnn: print n # prints reversed values of old nnn ... 5 4 2 1 0 # >>> WH = Rev('Hello World!') >>> print WH.forw, WH.back Hello World! !dlroW olleH >>> nnn = Rev(range(1, 10)) >>> print nnn.forw [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print nnn.back [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> rrr = Rev(nnn) >>> rrr <1, 2, 3, 4, 5, 6, 7, 8, 9> tRevcBs,eZdZdZdZdZRS(cCs||_||_dS(N(tforwtback(tselftseq((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__init__?s cCs t|jS(N(tlenR(R((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__len__CscCs|j|d S(Ni(R(Rtj((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt __getitem__FscCs|j}t|tr'd}d}nHt|trEd}d}n*t|trcd}d}n d}d}g|jD]}t|^qy}|d |j||dS(Ns[]s, s()ts<>ii(Rt isinstancetlistttupletstrRtjoin(RRtwraptseptitemtoutstrs((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt__repr__Is    "(t__name__t __module__RRR R(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyR>s   cCs%ddl}ddl}|j|S(Ni(tdoctestRttestmod(RR((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt_testZst__main__N((t__doc__RRR(((s(/usr/lib64/python2.7/Demo/classes/Rev.pyt<s