def pretty_print(self, indent): s = operator.repeat(" ", indent) + self.name + "\n" indent = indent + 2 for d in self.dependents: s += operator.repeat(" ", indent) + d.name + "\n" for d in self.dependents: s += d.pretty_print(indent) + "\n" # trim the last newline off return s[:-1]
def pretty_print(self, indent): s = operator.repeat(' ', indent) + self.name + "\n" indent = indent + 2 for d in self.dependents: s += operator.repeat(' ', indent) + d.name + "\n" for d in self.dependents: s += d.pretty_print(indent) + "\n" #trim the last newline off return s[:-1]
def XbeInfo(FileName): # Modified by me. Original by chunk_1970 - http://forum.kodi.tv/showthread.php?tid=24666&pid=125356#pid125356 try : XbeDta = {} if os.path.isfile(FileName) and FileName.endswith('.xbe') : xbe = open(FileName,'rb') ## Get XbeId Data ## xbe.seek(0x104) tLoadAddr = xbe.read(4) xbe.seek(0x118) tCertLoc = xbe.read(4) LoadAddr = struct.unpack('L',tLoadAddr) CertLoc = struct.unpack('L',tCertLoc) CertBase = CertLoc[0] - LoadAddr[0] CertBase += 8 IdStart = xbe.seek(CertBase) tIdData = xbe.read(4) IdData = struct.unpack('L',tIdData) ## Get Xbe Title ## XbeTitle = '' for dta in struct.unpack(operator.repeat('H',40),xbe.read(0x0050)): try : if dta != 00: XbeTitle += str(unichr(dta)) except : pass XbeDta = str(XbeTitle) #XbeDta['Title'] = str(XbeTitle) #XbeDta['Id'] = str(hex(IdData[0])[2:-1]).lower().rjust(8,'0') #XbeDta['Path'] = str(FileName) xbe.close() return XbeDta except : xbe.close() return {}
def XbeInfo(FileName): try: XbeDta = {} if os.path.isfile(FileName) and FileName.endswith(".xbe"): xbe = open(FileName, "rb") ## Get XbeId Data ## xbe.seek(0x104) tLoadAddr = xbe.read(4) xbe.seek(0x118) tCertLoc = xbe.read(4) LoadAddr = struct.unpack("L", tLoadAddr) CertLoc = struct.unpack("L", tCertLoc) CertBase = CertLoc[0] - LoadAddr[0] CertBase += 8 IdStart = xbe.seek(CertBase) tIdData = xbe.read(4) IdData = struct.unpack("L", tIdData) ## Get Xbe Title ## XbeTitle = "" for dta in struct.unpack(operator.repeat("H", 40), xbe.read(0x0050)): try: if dta != 00: XbeTitle += str(unichr(dta)) except: pass XbeDta["Title"] = str(XbeTitle) XbeDta["Id"] = str(hex(IdData[0])[2:-1]).lower().rjust(8, "0") XbeDta["Path"] = str(FileName) xbe.close() return XbeDta except: xbe.close() return {}
def test_repeat(self): a = range(3) self.failUnless(operator.repeat(a, 2) == a + a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == []) a = (1, 2, 3) self.failUnless(operator.repeat(a, 2) == a + a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == ()) a = '123' self.failUnless(operator.repeat(a, 2) == a + a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == '')
def test_repeat(self): a = range(3) self.failUnless(operator.repeat(a, 2) == a + a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == []) a = (1, 2, 3) self.failUnless(operator.repeat(a, 2) == a + a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == ()) a = "123" self.failUnless(operator.repeat(a, 2) == a + a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == "")
def test_repeat(self): a = range(3) self.failUnlessRaises(TypeError, operator.repeat) self.failUnlessRaises(TypeError, operator.repeat, a, None) self.failUnless(operator.repeat(a, 2) == a + a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == []) a = (1, 2, 3) self.failUnless(operator.repeat(a, 2) == a + a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == ()) a = '123' self.failUnless(operator.repeat(a, 2) == a + a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == '')
def test_repeat(self): a = range(3) self.failUnlessRaises(TypeError, operator.repeat) self.failUnlessRaises(TypeError, operator.repeat, a, None) self.failUnless(operator.repeat(a, 2) == a+a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == []) a = (1, 2, 3) self.failUnless(operator.repeat(a, 2) == a+a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == ()) a = '123' self.failUnless(operator.repeat(a, 2) == a+a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == '')
def _canon(numstr, size): """ @param numstr: the string representation of an integer which will be canonicalized @param size: the size in 8-bit bytes (octets) that numbers of this kind should have; This number should almost always be EGTPConstants.SIZE_OF_UNIQS or EGTPConstants.SIZE_OF_MODULAR_VALUES @return: the canonical version of `numstr' for numbers of its type @precondition: `numstr' must be a string.: type(numstr) == types.StringType: "numstr: %s :: %s" % (humanreadable.hr(numstr), `type(numstr)`) @precondition: `numstr', not counting leading zeroes, is not too large.: len(strip_leading_zeroes(numstr)) <= size: "numstr: %s" % humanreadable.hr(numstr) """ assert type(numstr) == types.StringType, "precondition: `numstr' must be a string." + " -- " + "numstr: %s :: %s" % (humanreadable.hr(numstr), `type(numstr)`) assert len(strip_leading_zeroes(numstr)) <= size, "precondition: `numstr', not counting leading zeroes, is not too large." + " -- " + "numstr: %s" % humanreadable.hr(numstr) if len(numstr) >= size: return numstr[len(numstr) - size:] return operator.repeat('\000', size - len(numstr)) + numstr
def XbeInfo(FileName): try : XbeDta = {} if os.path.isfile(FileName) and FileName.endswith('.xbe'): xbe = open(FileName,'rb') ## Get XbeId Data ## xbe.seek(0x104) tLoadAddr = xbe.read(4) xbe.seek(0x118) tCertLoc = xbe.read(4) LoadAddr = struct.unpack('L',tLoadAddr) CertLoc = struct.unpack('L',tCertLoc) CertBase = CertLoc[0] - LoadAddr[0] IdStart = xbe.seek(CertBase + 8) tIdData = xbe.read(4) IdData = struct.unpack('L',tIdData) ## Get Xbe Title ## XbeTitle = '' for dta in struct.unpack(operator.repeat('H',40),xbe.read(0x0050)): try : if dta != 00 : XbeTitle += str(unichr(dta)) except : pass RegionStart = xbe.seek(CertBase + 0xA0) tRegionData = xbe.read(4) Region = struct.unpack('L',tRegionData)[0] XbeDta['Title'] = str(XbeTitle) XbeDta['Id'] = str(hex(IdData[0])[2:]).lower().rjust(8,'0') XbeDta['Path'] = str(FileName) XbeDta['Region'] = Region xbe.close() return XbeDta except : xbe.close() return {}
def test_error_message_module_function(self): import operator # use repeat because it's defined at applevel exc = raises(TypeError, lambda : operator.repeat(1, 2, 3)) # does not contain the warning about missing self assert exc.value.message == "repeat() takes exactly 2 arguments (3 given)"
print(" x ** y ", (2).__pow__(3)) x = True y = False print('x and y is',x and y) print('x or y is',x or y) print('not x is',not x) print(" sequence operator ") print(" + ", "Hello" + "World") print(" concat ", op.concat("Hello", "World")) print(" __add__ ", "Hello".__add__("World")) print(" * ", "Hello" * 3) print(" __mul__ ", "Hello".__mul__(3)) print(" repeat ", op.repeat("Hello", 3)) print(" is ", "abc" is "abc") print(" is_", op.is_("abc","abc")) print(" is not ", "abc" is not "abcd") print(" is_", op.is_not("abc","abcd")) print(" in ", "a" in "abc") print(" __contains__", "abc".__contains__('a')) print(" contains", op.contains("abc",'a')) print(" in ", "a" not in "abc") print(" __contains__", not("abc".__contains__('a'))) print(" contains", op.not_(op.contains("abc",'a')))
def test_error_message_module_function(self): import operator # use repeat because it's defined at applevel exc = raises(TypeError, lambda: operator.repeat(1, 2, 3)) # does not contain the warning # 'Did you forget 'self' in the function definition?' assert 'self' not in str(exc.value)
# -*- coding:utf-8 -*- # Example 1-62. 使用 operator 模块 import operator sequence = 1, 2, 4 print "add", "=>", reduce(operator.add, sequence) print "sub", "=>", reduce(operator.sub, sequence) print "mul", "=>", reduce(operator.mul, sequence) print "concat", "=>", operator.concat("spam", "egg") print "repeat", "=>", operator.repeat("spam", 5) print "getitem", "=>", operator.getitem(sequence, 2) print "indexOf", "=>", operator.indexOf(sequence, 2) print "sequenceIncludes", "=>", operator.sequenceIncludes(sequence, 3)
print "16 << 1 = operator.lshift(16, 1) = ", operator.lshift(16, 1) # 乘法運算 print "2 * 8 = operator.mul(2, 8) = ", operator.mul(2, 8) # 負數運算 print "-10 = operator.neg(10) = ", operator.neg(10) # 否定運算 print "not 0 = operator.not_(0) = ", operator.not_(0) # 右移運算 print "16 >> 1 = operator.rshift(16, 1) = ", operator.rshift(16, 1) # 連續型態值乘法運算(tuple或list) print "'-' * 10 = operator.repeat('-', 10) = ", operator.repeat('-', 10) # 以切片指派值 seq = [1, 2, 3] seq[2:3] = [4] print "seq[2:3] = [4] = operator.setslice(seq,2,3,[4]) = ", seq # 以切片刪除值 operator.delslice(seq, 1, 2) print "del seq[1:2] = operator.delslice(seq,1,2) = ", seq # 取得切片值 print "seq[1:2] = operator.getslice(seq,1,2) = ", operator.getslice(seq, 1, 2) # 餘數運算 print "10 % 3 = operator.mod(10, 3) = ", operator.mod(10, 3)
f = open('link.txt', 'w') f.write(endre) f.close() print("""estágio concluido iniciando o redirecionamento dos endereços""") linkss = (commands.getoutput("cut -d \\' -f 2 link.txt")) f = open('link2.txt', 'w') f.write(linkss) f.close() print('verificando o número de linhas') linhas = int(commands.getoutput("cat link2.txt | wc -l")) print('criando as colunas') rep1 = operator.repeat('<address><a href="\n', linhas) f = open('col1', 'w') f.write(rep1) f.close() print('coluna 1 concluida') rep2 = operator.repeat('"><span style="font-family: serif;">\n', linhas) f = open('col2', 'w') f.write(rep2) f.close() print('coluna 2 concluida') rep3 = operator.repeat('</span></a></address>\n', linhas) f = open('col3', 'w') f.write(rep3) f.close()
def test_repeat(self): a = range(3) self.assertRaises(TypeError, operator.repeat) self.assertRaises(TypeError, operator.repeat, a, None) self.assertTrue(operator.repeat(a, 2) == a+a) self.assertTrue(operator.repeat(a, 1) == a) self.assertTrue(operator.repeat(a, 0) == []) a = (1, 2, 3) self.assertTrue(operator.repeat(a, 2) == a+a) self.assertTrue(operator.repeat(a, 1) == a) self.assertTrue(operator.repeat(a, 0) == ()) a = '123' self.assertTrue(operator.repeat(a, 2) == a+a) self.assertTrue(operator.repeat(a, 1) == a) self.assertTrue(operator.repeat(a, 0) == '') a = Seq1([4, 5, 6]) self.assertTrue(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) self.assertTrue(operator.repeat(a, 1) == [4, 5, 6]) self.assertTrue(operator.repeat(a, 0) == []) a = Seq2([4, 5, 6]) self.assertTrue(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) self.assertTrue(operator.repeat(a, 1) == [4, 5, 6]) self.assertTrue(operator.repeat(a, 0) == []) self.assertRaises(TypeError, operator.repeat, 6, 7)
import operator sequence = 1, 2, 4 print ("add", "=>", reduce(operator.add, sequence), "sub", "=>", reduce(operator.sub, sequence),"\n", "mul", "=>", reduce(operator.mul, sequence),"\n", "concat", "=>", operator.concat("spam", "egg"),"\n", "repeat", "=>", operator.repeat("spam", 5),"\n", "getitem", "=>", operator.getitem(sequence, 2),"\n", "indexOf", "=>", operator.indexOf(sequence, 2),"\n", "sequenceIncludes", "=>", operator.sequenceIncludes(sequence, 3))
f.write(endre) f.close() print("""estágio concluido iniciando o redirecionamento dos endereços""") linkss = (commands.getoutput("cut -d \\' -f 2 link.txt")) f = open('link2.txt', 'w') f.write(linkss) f.close() print('verificando o número de linhas') linhas = int(commands.getoutput("cat link2.txt | wc -l")) print ('criando as colunas') rep1 = operator.repeat('<address><a href="\n', linhas) f = open('col1', 'w') f.write(rep1) f.close() print ('coluna 1 concluida') rep2 = operator.repeat('"><span style="font-family: serif;">\n', linhas) f = open('col2', 'w') f.write(rep2) f.close() print('coluna 2 concluida') rep3 = operator.repeat ('</span></a></address>\n', linhas) f = open('col3', 'w') f.write(rep3) f.close()
a = [1,2,3,4,5] print operator.getslice(a,0,2) #设定字典的值 同 a[b]=c a = {0:"zero",1:"one",2:"two"} operator.setitem(a,3,"three") print a #设定序列的片段 同 a[b:c]=d a = [1,2,3,4,5] operator.setslice(a,1,2,["two"]) print a #序列翻倍 同序列的 *= a = [1,2,3] print operator.repeat(a,5) print operator.irepeat(a,5) #判断值相等 同 = print operator.eq(1,"1") print operator.eq("a","a") #判断值不等 同 != print operator.ne(1,"1") print operator.ne("a","a") #判断地址相等 同 is print operator.is_(1,"1") print operator.eq("a","a") #判断地址不相等 同 is not
def test_repeat(self): a = list(range(3)) self.failUnlessRaises(TypeError, operator.repeat) self.failUnlessRaises(TypeError, operator.repeat, a, None) self.failUnless(operator.repeat(a, 2) == a+a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == []) a = (1, 2, 3) self.failUnless(operator.repeat(a, 2) == a+a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == ()) a = '123' self.failUnless(operator.repeat(a, 2) == a+a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == '') a = Seq1([4, 5, 6]) self.failUnless(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) self.failUnless(operator.repeat(a, 1) == [4, 5, 6]) self.failUnless(operator.repeat(a, 0) == []) a = Seq2([4, 5, 6]) self.failUnless(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) self.failUnless(operator.repeat(a, 1) == [4, 5, 6]) self.failUnless(operator.repeat(a, 0) == []) self.failUnlessRaises(TypeError, operator.repeat, 6, 7)
from operator import repeat def problem_fifteen(): """ ans = 1 for i in xrange(21, 41): ans *= i for i in xrange(1, 21): ans /= i print ans """ pass # http://projecteuler.net/thread=15 - solution by roxtar l = repeat([repeat([0], 21)], 21) for i in range(21): l[20][i] = 1 l[i][20] = 1 for i in range(19, -1, -1): for j in range(19, -1, -1): l[i][j] = l[i + 1][j] + l[i][j + 1] print l[0][0] problem_fifteen() # 137846528820
def getBinaryData(self): #Make the Short Stream self.shortStream = "" tmp = self.ssectors.keys() tmp.sort() max_sid = tmp.pop() for sid in range(max_sid + 1): if self.ssectors.has_key(sid): self.shortStream += struct.pack( str(self.ShortSectorSize) + "s", self.ssectors[sid]) else: self.shortStream += struct.pack( str(self.ShortSectorSize) + "s", operator.repeat("\x00", self.ShortSectorSize)) #Add Stream and Write Short Stream SID in the Root Entry SIDShortStream = self.addStream(self.shortStream, 1, 0) #Make SSAT Stream self.ssatStream = "" tmp = self.ssat.keys() tmp.sort() max_ssat = tmp.pop() for sid in range(max_ssat + 1): if self.ssat.has_key(sid): self.ssatStream += struct.pack("<l", self.ssat[sid]) else: self.ssatStream += struct.pack("<l", -1) TotalSSAT = int( math.ceil(float(len(self.ssatStream)) / float(self.SectorSize))) SIDssatStream = self.addStream(self.ssatStream, 1) #Make the Directory Stream self.directoryStream = "" for did in self.directory: self.directoryStream += self.directory[did].getBinaryData() SIDDirectory = self.addStream(self.directoryStream, 1) #Calc SAT Sectors Usage (check if I need a MSAT extention) TotalSAT = int( math.ceil(float(len(self.sat) * 4) / float(self.SectorSize))) initMSAT = "" if TotalSAT > 109: # Use extra sectors to extend the SAT # TODO! print "argh... TODO! - satStream.len=%u - SectorSize=%u - TotalSAT=%u" % ( int(len(self.sat) * 4), int(self.SectorSize), int( self.TotalSAT)) sys.exit(255) else: #Make MSAT and Reserve space on SAT for SAT sectors SATChain = [] SIDsatStream = -1 for part in range(TotalSAT): sat_sid = self.getUnusedSector() if SIDsatStream < 0: SIDsatStream = sat_sid self.sat[sat_sid] = -3 # mark sector as "used by SAT" initMSAT += struct.pack("<l", sat_sid) SATChain.append(sat_sid) #Fill MSAT for x in range(0, 436 - len(initMSAT), 4): initMSAT += struct.pack("<l", -1) # mark as free #Make SAT Stream self.satStream = "" tmp = self.sat.keys() tmp.sort() max_sat = tmp.pop() for sid in range(max_sat + 1): if self.sat.has_key(sid): self.satStream += struct.pack("<l", self.sat[sid]) else: self.satStream += struct.pack("<l", -1) #Write SAT Sectors part = 0 for sid in SATChain: self.sectors[sid] = self.satStream[part * self.SectorSize:(part + 1) * self.SectorSize] part += 1 #Recalc Header self.oleheader.setTotalSectorsSAT(TotalSAT) self.oleheader.setSIDfirstRootDirectory(SIDDirectory) self.oleheader.setSIDfirstShortSectorAllocTable(SIDssatStream) self.oleheader.setTotalSectorsSSAT(TotalSSAT) self.oleheader.setinitialMSAT(initMSAT) #Sectors allSectors = "" tmp = self.sectors.keys() tmp.sort() max_sectors = tmp.pop() for sid in range(max_sectors + 1): if self.sectors.has_key(sid): allSectors += struct.pack( str(self.SectorSize) + "s", self.sectors[sid]) else: allSectors += struct.pack( str(self.SectorSize) + "s", operator.repeat("\x00", self.SectorSize)) #Write all together return self.oleheader.getBinaryData() + allSectors
import operator
获取元素或属性: attrgetter: itemgetter: 判断对象类型: isMappingType: isNumberType: isSequenceType: """ import operator a = [1, 2, 3] b = ['a', 'b', 'c'] print operator.concat(a,b) print operator.repeat(b, 3) print operator.contains(a, 2) print operator.contains(b, 'hhhhhh') print operator.countOf(operator.repeat(b, 4), 'a') print operator.countOf(a, 8) print operator.indexOf(a, 2) # output # [1, 2, 3, 'a', 'b', 'c'] # ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'] # True # False # 4 # 0 # 1 c = [1, 'a', None, 10.01, {'key':'value'}]
import operator sequence = 1,2,4 print "add","==>", reduce(operator.add, sequence) print "sub","==>", reduce(operator.sub, sequence) print "mul","==>", reduce(operator.mul, sequence) print "concat","==>", operator.concat("spam", "egg") print "repeat","==>", operator.repeat("spam", 5) print "reduce lambda" , "==>" ,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) print "getitem","==>",operator.getitem(sequence, 2) print "indexOf","==>",operator.indexOf(sequence, 4) print "sequenceIncludes","==>", operator.sequenceIncludes(sequence, 3)
def test_repeat(self): class Seq1: def __init__(self, lst): self.lst = lst def __len__(self): return len(self.lst) def __getitem__(self, i): return self.lst[i] def __add__(self, other): return self.lst + other.lst def __mul__(self, other): return self.lst * other def __rmul__(self, other): return other * self.lst class Seq2(object): def __init__(self, lst): self.lst = lst def __len__(self): return len(self.lst) def __getitem__(self, i): return self.lst[i] def __add__(self, other): return self.lst + other.lst def __mul__(self, other): return self.lst * other def __rmul__(self, other): return other * self.lst import operator a = range(3) raises(TypeError, operator.repeat) raises(TypeError, operator.repeat, a, None) assert operator.repeat(a, 2) == a + a assert operator.repeat(a, 1) == a assert operator.repeat(a, 0) == [] a = (1, 2, 3) assert operator.repeat(a, 2) == a + a assert operator.repeat(a, 1) == a assert operator.repeat(a, 0) == () a = '123' assert operator.repeat(a, 2) == a + a assert operator.repeat(a, 1) == a assert operator.repeat(a, 0) == '' a = Seq1([4, 5, 6]) assert operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6] assert operator.repeat(a, 1) == [4, 5, 6] assert operator.repeat(a, 0) == [] a = Seq2([4, 5, 6]) assert operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6] assert operator.repeat(a, 1) == [4, 5, 6] assert operator.repeat(a, 0) == [] raises(TypeError, operator.repeat, 6, 7)
def test_repeat(self): a = range(3) self.failUnlessRaises(TypeError, operator.repeat) self.failUnlessRaises(TypeError, operator.repeat, a, None) self.failUnless(operator.repeat(a, 2) == a+a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == []) a = (1, 2, 3) self.failUnless(operator.repeat(a, 2) == a+a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == ()) a = '123' self.failUnless(operator.repeat(a, 2) == a+a) self.failUnless(operator.repeat(a, 1) == a) self.failUnless(operator.repeat(a, 0) == '') a = Seq1([4, 5, 6]) self.failUnless(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) self.failUnless(operator.repeat(a, 1) == [4, 5, 6]) self.failUnless(operator.repeat(a, 0) == []) a = Seq2([4, 5, 6]) self.failUnless(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) self.failUnless(operator.repeat(a, 1) == [4, 5, 6]) self.failUnless(operator.repeat(a, 0) == []) if not test_support.is_jython: # Jython repeat is mul self.failUnlessRaises(TypeError, operator.repeat, 6, 7)
def test_repeat(self): a = range(3) self.assertRaises(TypeError, operator.repeat) self.assertRaises(TypeError, operator.repeat, a, None) self.assertTrue(operator.repeat(a, 2) == a + a) self.assertTrue(operator.repeat(a, 1) == a) self.assertTrue(operator.repeat(a, 0) == []) a = (1, 2, 3) self.assertTrue(operator.repeat(a, 2) == a + a) self.assertTrue(operator.repeat(a, 1) == a) self.assertTrue(operator.repeat(a, 0) == ()) a = '123' self.assertTrue(operator.repeat(a, 2) == a + a) self.assertTrue(operator.repeat(a, 1) == a) self.assertTrue(operator.repeat(a, 0) == '') a = Seq1([4, 5, 6]) self.assertTrue(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) self.assertTrue(operator.repeat(a, 1) == [4, 5, 6]) self.assertTrue(operator.repeat(a, 0) == []) a = Seq2([4, 5, 6]) self.assertTrue(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6]) self.assertTrue(operator.repeat(a, 1) == [4, 5, 6]) self.assertTrue(operator.repeat(a, 0) == []) self.assertRaises(TypeError, operator.repeat, 6, 7)
def repeat(a, b): return operator.repeat(a, b)
def test_repeat(self): class Seq1: def __init__(self, lst): self.lst = lst def __len__(self): return len(self.lst) def __getitem__(self, i): return self.lst[i] def __add__(self, other): return self.lst + other.lst def __mul__(self, other): return self.lst * other def __rmul__(self, other): return other * self.lst class Seq2(object): def __init__(self, lst): self.lst = lst def __len__(self): return len(self.lst) def __getitem__(self, i): return self.lst[i] def __add__(self, other): return self.lst + other.lst def __mul__(self, other): return self.lst * other def __rmul__(self, other): return other * self.lst import operator a = range(3) raises(TypeError, operator.repeat) raises(TypeError, operator.repeat, a, None) assert operator.repeat(a, 2) == a+a assert operator.repeat(a, 1) == a assert operator.repeat(a, 0) == [] a = (1, 2, 3) assert operator.repeat(a, 2) == a+a assert operator.repeat(a, 1) == a assert operator.repeat(a, 0) == () a = '123' assert operator.repeat(a, 2) == a+a assert operator.repeat(a, 1) == a assert operator.repeat(a, 0) == '' a = Seq1([4, 5, 6]) assert operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6] assert operator.repeat(a, 1) == [4, 5, 6] assert operator.repeat(a, 0) == [] a = Seq2([4, 5, 6]) assert operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6] assert operator.repeat(a, 1) == [4, 5, 6] assert operator.repeat(a, 0) == [] raises(TypeError, operator.repeat, 6, 7)
a = [1, 2, 3, 4, 5] print operator.getslice(a, 0, 2) #设定字典的值 同 a[b]=c a = {0: "zero", 1: "one", 2: "two"} operator.setitem(a, 3, "three") print a #设定序列的片段 同 a[b:c]=d a = [1, 2, 3, 4, 5] operator.setslice(a, 1, 2, ["two"]) print a #序列翻倍 同序列的 *= a = [1, 2, 3] print operator.repeat(a, 5) print operator.irepeat(a, 5) #判断值相等 同 = print operator.eq(1, "1") print operator.eq("a", "a") #判断值不等 同 != print operator.ne(1, "1") print operator.ne("a", "a") #判断地址相等 同 is print operator.is_(1, "1") print operator.eq("a", "a") #判断地址不相等 同 is not
def overload_mul_rep(*args): if hasattr(type(args[0]),'__iter__') and isinstance(args[1],int): return op.repeat(*args) else: return op.mul(*args)