Пример #1
0
def readpipe() -> str:
    """Read from a pipe"""
    while True:
        _input = ''
        _data = stdin.read(1)
        while _data:
            _input += _data
            _data = stdin.read(1)
        return str(_input)
Пример #2
0
def readpipe() -> str:
    """Read from pipe"""
    while True:
        _input = ''
        _character = stdin.read(1)
        while _character:
            _input += _character
            _character = stdin.read(1)
        return str(_input)
Пример #3
0
	def read(self):
		self.alive = True
		self.writer_thread.start()		
		ch = stdin.read(1)
		while ch != '#':
			self.sp.write(ch)
			ch = stdin.read(1)
		self.alive = False
		self.sp.write(' ')
		self.writer_thread.join()
Пример #4
0
    def alter(self, message, arguments):
        """
        Performs operations specified in the arguments to modify the message in
        whatever way.
        """

        message = message.copy()

        # Entity

        if arguments.entity:
            message["entity"] = arguments.entity
        if arguments.readEntity:
            message["entity"] = open(arguments.readEntity, "r").read()
        if arguments.entityStdin:
            message["entity"] = stdin.read()
        if arguments.appendEntity:
            message["entity"] += arguments.appendEntity
        if arguments.appendEntityStdin:
            message["entity"] += stdin.read()
        if arguments.appendEntityFile:
            message["entity"] += open(arguments.appendEntityFile, "r").read()

        # Top-line

        if arguments.version:
            message["version"] = arguments.version
        if arguments.method:
            message["method"] = arguments.method.upper()
        if arguments.path:
            message["path"] = arguments.path
        if arguments.status:
            message["status"] = arguments.status
        if arguments.reason:
            message["reason"] = arguments.reason.upper()

        # Headers

        for header in arguments.header:
            message["headers"] = setValuesByName(message["headers"], *header)
        if arguments.host:
            message["headers"] = setValuesByName(message["headers"], "Host", arguments.host)
        if arguments.auto: # obviously must come after entity
            message["headers"] = setValuesByName(
                message["headers"],
                "Content-length",
                str(len(message["entity"]))
        )

        return message 
Пример #5
0
	def getch():
		stdout.flush()
		fd=stdin.fileno()
		if isatty(fd):
			oldset=tcgetattr(fd)
			newset=oldset[:]
			try:
				newset[3]&=-11
				tcsetattr(fd, TCSANOW, newset)
				return ord(stdin.read(1))
			finally:tcsetattr(fd, TCSANOW, oldset)
		else:
			fd=stdin.read(1)
			return ord(fd) if fd else -1
Пример #6
0
def main():
    def getAdjMat(mat, n):
        for k in xrange(n - 1, -1, -1):
            for i in xrange(n - 1, -1, -1):
                for j in xrange(n - 1, -1, -1):
                    if i != j and j != k and i != k and mat[i][k] + mat[k][j] == mat[i][j]:
                        mat[i][j] = float('inf')
        for i in xrange(n):
            mat[i][i] = float('inf')
        for i in xrange(n):
            for j in xrange(n):
                if mat[i][j] == mat[j][i]:
                    mat[max(j, i)][min(i, j)] = float('inf')
        return mat

    dstream = imap(int, stdin.read().split())
    for _ in xrange(next(dstream)):
        n = next(dstream)
        mat = [[next(dstream) for _ in xrange(n)] for _ in xrange(n)]
        adjMat = getAdjMat(mat, n)
        for i in xrange(n):
            for j in xrange(n):
                if adjMat[i][j] != float('inf'):
                    print i + 1, j + 1
        print
def main():
    from sys import stdin, stdout
    from itertools import islice, izip
    tkns = iter(stdin.read().split())
    n,m = int(tkns.next()), int(tkns.next())
    graph = {str(i): [] for i in xrange(1,n+1)}
    for u,v in islice(izip(tkns,tkns),m):
        graph[u].append(v)
        graph[v].append(u)
    
    def dfs(adj, visited, color, u):
        visited.add(u)
        for v in adj[u]:
            if v not in visited:
                color[v] = not color[u]
                partitions[color[v]].add(v)
                dfs(graph, visited, color, v)

    visited = set()
    color = {}
    partitions = {True: set(), False: set()}
    for u in graph:
        if u not in visited:
            color[u] = True
            partitions[True].add(u)
            dfs(graph, visited, color, u)

    matchings = hopcroft_karp(graph, partitions[True], partitions[False], INF=999999, write=stdout.write)
Пример #8
0
    def _posix_shell(self, chan):
        oldtty = termios.tcgetattr(stdin)
        try:
            # tty.setraw(stdin.fileno())
            # tty.setcbreak(stdin.fileno())
            chan.settimeout(0.0)

            while True:
                r, w, e = select([chan, stdin], [], [])
                if chan in r:
                    try:
                        x = chan.recv(128)
                        if len(x) == 0:
                            print "\r\n*** EOF\r\n",
                            break
                        stdout.write(x)
                        stdout.flush()
                        # print len(x), repr(x)
                    except socket.timeout:
                        pass
                if stdin in r:
                    x = stdin.read(1)
                    if len(x) == 0:
                        break
                    chan.sendall(x)
        finally:
            termios.tcsetattr(stdin, termios.TCSADRAIN, oldtty)
Пример #9
0
def main():
    answers = ans

    def ansans(n):
        return answers[n - 1]

    print '\n'.join(map(ansans, map(int, stdin.read().split())))
Пример #10
0
def main():
    def all_lcs(a, b):
        def genlcs(r, c):
            if r == 0 or c == 0:
                lcss.append(''.join(reversed(lcs)))
                return
            if dp[r - 1][c - 1] == dp[r][c]:
                genlcs(r - 1, c - 1)
            if dp[r - 1][c - 1] + 1 == dp[r][c] and b[r - 1] == a[c - 1]:
                lcs.append(b[r - 1])
                genlcs(r - 1, c - 1)
                lcs.pop()
            if dp[r - 1][c] == dp[r][c]:
                genlcs(r - 1, c)
            if dp[r][c - 1] == dp[r][c]:
                genlcs(r, c - 1)

        dp = [[0]*(len(a) + 1) for _ in xrange(len(b) + 1)]
        for x in xrange(1, len(b) + 1):
            for y in xrange(1, len(a) + 1):
                dp[x][y] = max(
                    dp[x - 1][y - 1] + (b[x - 1] == a[y - 1]),
                    dp[x - 1][y],
                    dp[x][y - 1]
                )
        lcss = []
        lcs = []
        genlcs(len(b), len(a))
        return lcss
    dstream = iter(stdin.read().split())
    for _ in xrange(int(next(dstream))):
        for x, _ in groupby(sorted(all_lcs(next(dstream), next(dstream)))):
            print x
        print
Пример #11
0
def write_command(server, command):
    # write the command
    server.stdin.write('runcommand\n')
    writeblock(server, command)

    # receive the response
    while True:
        channel, val = readchannel(server)
        if channel == 'o':
            print val.rstrip()
        elif channel == 'e':
            print 'error: %s' % val.rstrip()
        elif channel == 'r':
            r = unpack(">l", val)[0]
            if r is not 0:
                print 'ERROR %s' % r
            break
        elif channel == 'L':
            print '(line read request)'
            writeblock(server, stdin.readline(val))
        elif channel == 'I':
            print '(block read request)'
            writeblock(server, stdin.read(val))
        else:
            print 'unexpected channel: %s %s' % (channel, val)
            if channel.isupper():  # required?
                break
Пример #12
0
def roy_and_code_streak():
	data = (line for line in stdin.read().splitlines())
	t = int(next(data))
	for z in xrange(t):
		n = int(next(data))
		submissions = []
		result = []
		for i in xrange(n):
			s,r = map(int,next(data).split())
			submissions.append(s)
			result.append(r)
		ranges_to_check = []
		i = 0
		while i < n:
			while i < n and result[i] == 0:
				i += 1
			if i >= n:
				break
			start = i
			while i < n and result[i] == 1:
				i += 1
			ranges_to_check.append([start,i])
		used = [0]*1000010
		each_range_max = [0]
		for i in ranges_to_check:
			cnt = 0
			for j in xrange(i[0],i[1]):
				if used[submissions[j]] != 1:
					used[submissions[j]] = 1
					cnt += 1
			each_range_max.append(cnt)
		print max(each_range_max)
Пример #13
0
def main():
    dstream = imap(float, stdin.read().split())
    try:
        for a, b, s, m, n in izip(dstream, dstream, dstream, dstream, dstream):
            print "%.2f %.2f" % (degrees(atan2(n*b, m*a)), sqrt((m*a / s)**2 + (n*b / s)**2))
    except ZeroDivisionError:
        pass
Пример #14
0
def main():
    nextitem = iter(stdin.read().split()).next
    n, m = int(nextitem()), int(nextitem())
    regs = [[] for _ in xrange(m)]
    for _ in xrange(n):
        sur, r, s = nextitem(), int(nextitem()), int(nextitem())
        regs[r - 1].append((s, sur))
    out = []
    for x in xrange(m):
        regs[x].sort(reverse=True)
        for i, (x, it) in izip((0, 1), groupby(regs[x], key=itemgetter(0))):
            if i == 0:
                items = list(it)
                k = len(items)
                if k > 2:
                    out.append('?')
                    break
                elif k == 2:
                    out.append(items[0][1] + ' ' + items[1][1])
                    break
                else:
                    out.append(items[0][1])
            else:
                items = list(it)
                k = len(items)
                if k > 1:
                    out[-1] = '?'
                    break
                else:
                    out[-1] += ' ' + items[0][1]
    print '\n'.join(out)
Пример #15
0
def main():
    fpp = [
        0, 3, 5, 11, 17, 2, 2, 5, 11, 19, 23, 23, 197, 307, 359, 521, 1553,
        2693, 3083, 419, 953, 5, 11, 13, 5, 7, 53, 107, 131, 103, 359, 419, 223,
        613, 541, 691, 151, 593, 1069, 1321, 1193, 3083, 311, 1619, 1543, 4813,
        5519, 23, 61, 151, 307, 359, 23, 197, 593, 827, 2789, 5443, 9311, 1427,
        1427, 5039, 13249, 4813, 13697, 6857, 19447, 4211, 4211, 38197, 12197,
        521, 1553, 1931, 853, 3083, 2693, 11353, 3083, 6857, 23789, 6007, 53881,
        60761, 51713, 111599, 72871, 100169, 244691, 134587, 248851, 288359,
        127081, 272141, 424243, 4127, 419, 5519, 12197, 49681, 10627, 36677,
        79349, 109037, 124181, 202987, 57559, 124181, 229727, 127081, 222863,
        373019, 170627, 364523]
    pp = [
        0, 2, 3, 5, 7, 11, 101, 131, 151, 181, 191,
        313, 353, 373, 383, 727, 757, 787, 797, 919, 929, 10301, 10501, 10601, 11311,
        11411, 12421, 12721, 12821, 13331, 13831, 13931, 14341, 14741, 15451, 15551,
        16061, 16361, 16561, 16661, 17471, 17971, 18181, 18481, 19391, 19891, 19991,
        30103, 30203, 30403, 30703, 30803, 31013, 31513, 32323, 32423, 33533, 34543,
        34843, 35053, 35153, 35353, 35753, 36263, 36563, 37273, 37573, 38083, 38183,
        38783, 39293, 70207, 70507, 70607, 71317, 71917, 72227, 72727, 73037, 73237,
        73637, 74047, 74747, 75557, 76367, 76667, 77377, 77477, 77977, 78487, 78787,
        78887, 79397, 79697, 79997, 90709, 91019, 93139, 93239, 93739, 94049, 94349,
        94649, 94849, 94949, 95959, 96269, 96469, 96769, 97379, 97579, 97879, 98389,
        98689]
    print '\n'.join(["%s %s" % (pp[n], fpp[n]) for n in map(int, stdin.read().split()[1:])])
Пример #16
0
def main(compiler):
    text = stdin.read().decode('utf8')
    parser = Parser(text, compiler)
    try:
        parser()
    except LexError as e:
        print >>stderr, e.pprint()
Пример #17
0
def main():
    nextint = iter(map(int, stdin.read().split())).next
    # next = iter(stdin.read().split()).next
    nk, q = nextint(), nextint()
    temp = 0
    Qu = [(nextint(), nextint() + 1, nextint()) for _ in xrange(q)]
    ends = []
    temps = {}
    for k, it in groupby(sorted(Qu), key=itemgetter(0)):
        while ends and ends[0][0] <= k:
            e = heappop(ends)
            temp -= e[1]
            temps[e[0]] = temp
        for _, y, i in it:
            temp += i
            heappush(ends, (y, i))
        temps[k] = temp
    while ends:
        e = heappop(ends)
        temp -= e[1]
        temps[e[0]] = temp
    assert temp == 0
    tot = 0
    xxx = sorted(temps.items())
    for (x1, y1), (x2, y2) in zip(xxx, xxx[1:]):
        if y1 >= nk:
            tot += x2 - x1
    print tot
Пример #18
0
def main():
    parser = OptionParser()
    parser.set_defaults(flavor='TEXT', translate=True, copy=False,
                        list_=False, verbose=False)
    parser.add_option("-c", "--copy", dest="copy", action="store_true",
                      help="copy stdin to clipboard [default: paste clipboard"
                           " to stdout]")
    parser.add_option("-l", "--list", dest="list_", action="store_true",
                      help="list currently available flavors with data sizes")
    parser.add_option("-x", "--notrans", dest="translate",
                      action="store_false",
                      help="don't translate CR to LF on output")
    parser.add_option("-f", "--flavor", dest="flavor", action="store",
                      help="specify flavor [default: TEXT]")
    parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                      help="complain if scrap flavor not found [default:"
                           " treat as empty]")
    
    options, args = parser.parse_args()
    if options.list_:
        for flavor in list_flavors():
            print "'%s' %9d" % flavor
    elif options.copy:
        copy(stdin.read(), options.flavor)
    else:
        text = paste(options.flavor, options.verbose)
        if options.translate:
            text = text.replace('\r', '\n')
        stdout.write(text)
Пример #19
0
def main():
    nextitem = iter(stdin.read().split()).next
    for _ in xrange(int(nextitem())):
        image = int(nextitem().replace('w', '1').replace('b', '0'), 2)
        n = int(nextitem())
        filters = [
            int(nextitem().replace('-', '0').replace('+', '1'), 2) \
                for _ in xrange(n)]
        # print '\n'.join(bin(x)[2:].zfill(10).replace('0', '-').replace('1', '+') for x in filters)
        flags = [1 << x for x in xrange(11)]
        for x in xrange(9, -1, -1):
            filters.sort(reverse=True)
            for y in xrange(n):
                if filters[y] & flags[x] and filters[y] < flags[x + 1]:
                    # print bin(filters[y])[2:].zfill(10).replace('0', '-').replace('1', '+')
                    for z in xrange(n):
                        if z != y and filters[z] & flags[x]:
                            filters[z] ^= filters[y]
                    break
        # print '\n'.join(bin(x)[2:].zfill(10).replace('0', '-').replace('1', '+') for x in filters)
        nums = filter(None, filters)
        if image == 0:
            print pow(2, n - len(nums), 1000000007)
            return
        for x in xrange(1, len(nums) + 1):
            for com in combinations(nums, x):
                if xorsum(com) == image:
                    print pow(2, n - len(nums), 1000000007)
                    break
            else:
                continue
            break
        else:
            print 0
Пример #20
0
    def _windows_shell(self, chan):
        import threading

        stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")

        def writeall(sock):
            while True:
                data = sock.recv(256)
                if not data:
                    stdout.write("\r\n*** EOF ***\r\n\r\n")
                    stdout.flush()
                    break
                stdout.write(data)
                stdout.flush()

        writer = threading.Thread(target=writeall, args=(chan,))
        writer.start()

        try:
            while True:
                d = stdin.read(1)
                if not d:
                    break
                chan.send(d)
        except EOFError:
            # user hit ^Z or F6
            pass
Пример #21
0
def main():

    nThreads = 8
    ths = []
    for i in range(nThreads):
        t = threading.Thread(target=work)
        t.setDaemon(True)
        ths.append(t)

    data = stdin.read()
    r = re.compile("[ \t]*[1-9][0-9]*\. .*")
    ref = data.rfind("References")
    print data[:ref]
    allRefs = re.findall(r, data[ref:])
    for ans in allRefs:
        ans = ans.split()
        q.put(ans)
    map(lambda x: x.start(), ths)
    map(lambda x: x.join(), ths)
    if allRefs:
        print "References:"

    d = {}
    while True:
        try:
            ans = rq.get(block=False)
        except Queue.Empty:
            break
        else:
            d[ans[0]] = ans[1]
    for ans in allRefs:
        ans = ans.split()
        print ans[0], d[ans[0]]
Пример #22
0
	def test_periodic_orders(self):
		'''
		We generate a periodic order which will be executed 10 times.
		Hit enter when at least 3 answers arrived
		'''
		order = {'orderid': None, # the Client class will care about this!
				  'identifier1':self.localip,
				  'identifier2':self.remoteip,
				  'type':'periodic',
				  'parameters' : {'interval': '3', 'lifetime': '30'},
				  'dataitem':'RTT'}
		
		
		def callback(result):
			print("callback function: %s" % result)
			self.assertEquals(result['identifier1'], self.localip)
			self.assertEquals(result['identifier2'], self.remoteip)
			self.count +=1
			print("%d outstanding answers" % (3-self.count))
		
		#for the lulz: skip one oderderid
		self.assertEquals(self.c.getOrderId(), '0')
		
		ret = self.c.commit_order(order, callback)
		#orderid is now '1', return code should be 0 (no error)
		self.assertEquals(ret, ('1',0))
		
		orderid = ret[0]
		
		print("press any key ....")
		ch = stdin.read(1)
		
		self.assertTrue(self.count >= 3)
		
		self.assertEqual(self.c.cancel_order(self.c.getId(), orderid), 0)
Пример #23
0
	def test_make_7_orders(self):
		'''make 7 oneshot orders'''
		order = {'orderid': None, # the Client class will care about this!
				  'identifier1':self.localip,
				  'identifier2':self.remoteip,
				  'type':'oneshot',
				  'dataitem':'RTT'}
		
		
		def callback(result):
			print("callback function: %s" % result)
			self.assertEquals(result['identifier1'], self.localip)
			self.assertEquals(result['identifier2'], self.remoteip)
			self.count +=1
			print("%d outstanding answers" % (7-self.count))
		
		self.assertEquals(self.c.commit_order(order, callback), ('0',0))
		sleep(1)
		self.assertEquals(self.c.commit_order(order, callback), ('1',0))
		self.assertEquals(self.c.commit_order(order, callback), ('2',0))
		self.assertEquals(self.c.commit_order(order, callback), ('3',0))
		self.assertEquals(self.c.commit_order(order, callback), ('4',0))
		
		#skip one oderderid
		self.assertEquals(self.c.getOrderId(), '5')
		
		self.assertEquals(self.c.commit_order(order, callback), ('6',0))
		self.assertEquals(self.c.commit_order(order, callback), ('7',0))
		
		print("press any key ....")
		ch = stdin.read(1)
		
		self.assertEquals(self.count, 7)
Пример #24
0
def main():
    dstream = imap(int, stdin.read().split())
    mod = 1000000007
    for case in xrange(1, next(dstream) + 1):
        m, l = next(dstream), next(dstream)
        print "Case %s: %s" % (case,
            ((((pow(m, l + 1, mod) - 1) % mod)*(pow(m - 1, mod - 2, mod))) % mod) if m != 1 else l + 1)
Пример #25
0
def main():
    nextint = map(int, stdin.read().split()).__next__
    n, m = nextint(), nextint()
    graph = [defaultdict(int) for _ in range(n)]
    for _ in range(m):
        graph[nextint() - 1][nextint() - 1] += 1
    print(" ".join(map(str, topological_sort(graph))))
Пример #26
0
def main():
    out = bytearray()
    try:
        dstream = imap(int, stdin.read().split())
        for _ in xrange(1000000000):
            n = next(dstream)
            arr = [(0, next(dstream)) for _ in xrange(n)]
            dp = [[(float('inf'), float('inf'))]*x for x in xrange(1, len(arr))]
            dp.append(arr)
            for x in xrange(n - 2, -1, -1):
                for y in xrange(x + 1):
                    lo, hi = y, y + n - x
                    for lhi in xrange(lo + 1, hi):
                        dp[n - (hi - lo)][lo] = min(
                            dp[n - (hi - lo)][lo],

                            (
                                dp[n - (lhi - lo)][lo][0] +
                                dp[n - (hi - lhi)][lhi][0] +
                                (
                                    dp[n - (lhi - lo)][lo][1] *
                                    dp[n - (hi - lhi)][lhi][1]),

                                (
                                    dp[n - (lhi - lo)][lo][1] +
                                    dp[n - (hi - lhi)][lhi][1]) % 100
                            )
                        )
            out.extend(bytes(dp[0][0][0]))
            out.append('\n')
    except StopIteration:
        print out
Пример #27
0
def main():
    def extended_gcd(aa, bb):
        lastr, remainder = abs(aa), abs(bb)
        x, lastx, y, lasty = 0, 1, 1, 0
        while remainder:
            lastr, (quotient, remainder) = remainder, divmod(lastr, remainder)
            x, lastx = lastx - quotient * x, x
            y, lasty = lasty - quotient * y, y
        return lastr, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)

    def modinv(a, m):
        g, x, _ = extended_gcd(a, m)
        if g != 1:
            raise ValueError
        return x % m

    dstream = map(int, stdin.read().split())
    dstream.pop()
    dstream.pop()
    dstream = iter(dstream)
    out = []
    m = 1000000007
    for n, l in zip(dstream, dstream):
        out.append(str((n*(pow(n, l, m) - 1)*modinv(n - 1, m)) % m))
    print '\n'.join(out)
Пример #28
0
def main():
    fibs = [
        1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584,
        4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811,
        514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352,
        24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
        701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049,
        12586269025, 20365011074, 32951280099, 53316291173, 86267571272,
        139583862445, 225851433717, 365435296162, 591286729879, 956722026041,
        1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723,
        17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994,
        190392490709135, 308061521170129, 498454011879264, 806515533049393, 1304969544928657]

    def nbin(n):
        if n == 0:
            return '0'
        num = bytearray()
        for x in xrange(bisect(fibs, n - 1), -1, -1):
            if fibs[x] <= n:
                num.append('1')
                n -= fibs[x]
            else:
                num.append('0')
        return str(num).lstrip('0')

    dstream = map(int, stdin.read().split())
    print '\n'.join([nbin(dstream[x]) for x in xrange(1, dstream[0] + 1)])
Пример #29
0
	def test_some_datasets(self):
		'''query the datasets defined im commands'''
		commands = ['CPU_CORE_COUNT', 'CPU_SPEED', 'CPU_TYPE']
		for i in commands:
			self.assertTrue(i in self.c.list_available_dataitems())

		self.commands = commands
		
		def callback(result):
			print("test_some_datasets callback function: %s" % result)
			self.assertEquals(result['identifier1'], self.localip)
			self.assertEquals(result['identifier2'], self.remoteip)
			found = False
			for i in self.commands:
				if i in result:
					self.commands.remove(i)
					found = True
			if not found:
				print("unknown field in result %s" % result)
				self.assertTrue(False)
			
		for i in commands:
			#invalid orderird fixed in Client
			order = {'orderid': 'invalid', 'identifier1':self.localip,
					'identifier2':self.remoteip, 'type':'oneshot',
					'dataitem':i}
			self.c.commit_order(order, callback)
		
		print("press any key ....")
		ch = stdin.read(1)
		
		self.assertEquals(self.commands, [])
Пример #30
0
def main():
	# Read the file in through standard input
	f = stdin.read()
	
	
	# Use regex to find text
	n = re.findall(r'[a-zA-Z0-9]{3,}', f)
	
	
	wordList = []

	# Read in each line of the file and print out the words that are found
	for line in n:
		
		# If words found, save to a string var and print them
		if line:
			words = str.split(line)
			for word in words:
				if not word.isdigit() and not word=="" and not word==" ":
					for char in badchars:
						if char in word:
							break
					else:
						wordList.append(word)

	for i in range(len(wordList)-1):
		print wordList[i] + ',' + wordList[i+1] + '\t' + '1'
Пример #31
0
from sys import stdin

Segment = namedtuple('Segment', 'start end')

def sortcrit(list):
    return list.end

def compute_optimal_points(segments, output):
    n1 = len(segments)
    if n1 == 0:
        return output
    else:
        temp = segments[:]
        for j in range(1, n1):
            if segments[-j].start <= segments[0].end: # check from right
                del(temp[-j + n1]) # delete from left
        segments = temp[:]
        output.append(segments[0].end)
        del(segments[0])
        return compute_optimal_points(segments, output)

if __name__ == '__main__':
n, *data = map(int, stdin.read().split())
    input_segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))
    input_segments.sort(key=sortcrit)
    assert n == len(input_segments)
    output_points = compute_optimal_points(input_segments, [])
    print(len(output_points))
    print(*output_points)

# May 8, 2020
# Program 5: Timelock
# Python 2
#----------------------------------------------------------------------------------------
from sys import stdin
from datetime import datetime
import pytz
from hashlib import md5

DEBUG = False
USE_MANUAL = False
ON_SERVER = False
INTERVAL = 60
if USE_MANUAL:
    MANUAL_DATETIME = "2017 03 23 18 02 06"
epoch  = stdin.read()

# calculate seconds elapsed from epoch to current system time
systemtime = datetime.now()
local_time = pytz.timezone("America/Chicago")
if USE_MANUAL:
    current_naive = datetime.strptime(MANUAL_DATETIME, "%Y %m %d %H %M %S")
else:
    current_naive = systemtime
epoch_naive = datetime.strptime(epoch, "%Y %m %d %H %M %S")
current_local = local_time.localize(current_naive, is_dst=None)
epoch_local = local_time.localize(epoch_naive, is_dst=None)
current_utc = current_local.astimezone(pytz.utc)
epoch_utc = epoch_local.astimezone(pytz.utc)

difference = (current_utc - epoch_utc).total_seconds()
Пример #33
0
from sys import stdin

# the decoding function
def decode(binary, n):
    text = ""
    i = 0
    while (i < len(binary)):
        # convert to bytes
        byte = binary[i:i+n]
        # translate bytes
        byte = int(byte, 2)
        # add the decoded characters to the text string
        # check for the backspace, remove the last character if it is
        if byte == 8:
            text = text[:-1]
        else:
            text += chr(byte)
        i += n

    return text

# reading binary from input
binary = stdin.read().rstrip("\n")

# determining if 7- or 8-bit
if (len(binary)  % 7 == 0):
    text = decode(binary, 7)
    print(text)
if (len(binary)  % 8 == 0):
    text = decode(binary, 8)
    print(text)
Пример #34
0
from sys import stdin

cadena = stdin.read().splitlines()


for linea in cadena:
    contador = 0
    cadenaplit = linea.split()

    string = str()


    for letra in linea:

        if letra.isalpha():
            string += letra

        else:
            string += " "


    for cualquier in string.split():

        contador += 1

    print(contador)
Пример #35
0
n = input()
try:
    n = int(n)
    a = [[int(e) for e in input().split()] for w in range(n)]
except:
    from sys import stdin
    n += '\n' + stdin.read()
    a = [[int(e) for e in w.split()] for w in n.split('\n')]
    n = len(a)
from functools import total_ordering
# @total_ordering
# class cmp:
# 	def __init__(s,q):
# 		s.x,s.y=q
# 		s.a=s.x**2+s.y**2
# 	def __lt__(s,o):
# 		return [s.a,-s.y,s.x]<[o.a,-o.y,o.x]
# 	def __eq__(s,o):
# 		return s<=o and s>=o
a = [[[s[1]**2 + s[0]**2, s[0], s[1]], s] for s in a]
a.sort()
a = [w[1] for w in a]
for w in a:
    print(*w)
Пример #36
0
#!/usr/bin/env python3

# SPDX-FileCopyrightText: 2021 Gleb Smirnov <*****@*****.**>
#
# SPDX-License-Identifier: GPL-3.0-or-later

from sys import stdin, stdout
from hashlib import sha256

stdout.write(sha256(stdin.read().encode()).hexdigest())
Пример #37
0
    def keyboard_poll(self):
        """Check for keyboard inputs and if any exist send an interupt"""

        if select([stdin], [], [], 0) == ([stdin], [], []):
            self.ram[last_key] = ord(stdin.read(1))
            self.registers[interrupt_status] |= 1 << 1
Пример #38
0
# https://www.acmicpc.net/problem/5554

from sys import stdin

time = sum(map(int, stdin.read().split()))
print(time // 60, time % 60, sep='\n')
Пример #39
0
        all_points.append((PointType.Start, x))

    for x in ends:
        all_points.append((PointType.End, x))

    for (i, x) in enumerate(points):
        all_points.append((PointType.Point, x, i))

    all_points.sort(key=lambda x: (x[1], x[0]))

    counts = [0] * len(points)
    count = 0
    for x in all_points:
        if x[0] == PointType.Start:
            count += 1
        elif x[0] == PointType.End:
            count -= 1
        else:
            counts[x[2]] = count
    return counts


if __name__ == '__main__':
    data = list(map(int, stdin.read().split()))
    n, m = data[0], data[1]
    input_starts, input_ends = data[2:2 * n + 2:2], data[3:2 * n + 2:2]
    input_points = data[2 * n + 2:]

    output_count = points_cover(input_starts, input_ends, input_points)
    print(*output_count)
Пример #40
0
###################################################
# By: Cole Edwards
# Date: 5.6.2020
# Python 2.7.17
###################################################
from sys import stdin, stdout

#get key from a file in the directory
with open('binary.txt', 'r') as file:
    temp = file.read()
#create the bytearray
key = bytearray(temp)

#get the text that will be XOR'd with the key
temp = stdin.read().rstrip("\n")
#create the bytearray
text = bytearray(temp)

#XOR the key and text
i = 0
msg = bytearray()
while (i < len(key)):
    msg.append(key[i] ^ text[i])
    i += 1

#output the msg
stdout.write(msg)
Пример #41
0
    def perform_operation(x: int, y: int, right_clicked: bool) -> int:
        nonlocal current_revealed, ever_revealed, ever_rest_cells, ever_rest_mines, flagged, stack, operation_pointer, recent_input, opration_to_perform, stack_append
        if debug_mode:
            nonlocal output_debug
        current_number = field[x][y]
        right_clicked ^= flag_mode
        if current_revealed[x][y]:  # revealed
            if right_clicked:
                if current_number == 0:  #command-0r (push 0)
                    stack_append(0)
                    return 20
                else:  # number > 0
                    flagged_count = 0
                    not_revealed_count = 0
                    not_revealed_0_list = []
                    not_revealed_list = []
                    contain_mine = False
                    for i in range(max(0, x - 1), min(height, x + 2)):
                        for j in range(max(0, y - 1), min(width, y + 2)):
                            if flagged[i][j]:
                                flagged_count += 1
                            elif not current_revealed[i][j]:
                                not_revealed_count += 1
                                i_j = (i, j)
                                i_j_command = field[i][j]
                                if i_j_command == 9:
                                    contain_mine = True
                                elif i_j_command > 0:
                                    not_revealed_list.append(i_j)
                                else:
                                    not_revealed_0_list.append(i_j)
                    if not_revealed_count > 0 and flagged_count == current_number:
                        if contain_mine:  #command-9r (reset game & stack)
                            stack_clear()
                            current_revealed = [[False] * width
                                                for _ in range_height]
                            flagged = [[False] * width for _ in range_height]
                            return 29
                        else:  #command-xp (push sum of revealed numbers)
                            reveal_sum = 0
                            for cell in not_revealed_list:
                                c_x, c_y = cell
                                reveal(c_x, c_y, False)
                                reveal_sum += field[c_x][
                                    c_y]  # must precede 0s.
                            for cell in not_revealed_0_list:
                                reveal_sum += open_recursively(cell, True)
                            stack_append(reveal_sum)
                            return 9
                    elif current_number == 1:  #command-1r (top == 0 ? 1 : 0)
                        if len(stack) > 0:
                            stack_append(1 if stack_pop() == 0 else 0)
                            return 21
                    elif current_number == 2:  #command-2r (roll top p1 items p0 times)
                        if len(stack) > 1:
                            roll_depth = stack[-2]
                            if abs(roll_depth) + 1 < len(stack):
                                roll_time = stack_pop()
                                stack_pop()
                                if roll_depth > 0:
                                    roll_time_mod = roll_time % roll_depth
                                    insert_index = len(stack) - roll_depth
                                    roll_items = stack[-roll_time_mod:]
                                    del stack[-roll_time_mod:]
                                    stack[
                                        insert_index:insert_index] = roll_items
                                elif roll_depth < 0:
                                    roll_time_mod = roll_time % -roll_depth
                                    insert_index = -roll_depth - roll_time_mod
                                    roll_items = stack[:roll_time_mod]
                                    del stack[:roll_time_mod]
                                    stack[
                                        insert_index:insert_index] = roll_items
                                return 22
                    elif current_number == 3:  #command-3r (input as integer)
                        if input_from_stdin:
                            recent_input += stdin.read()
                        read_match = re.fullmatch(int_re, recent_input)
                        if read_match != None:
                            stack_append(int(read_match[1]))
                            recent_input = read_match[2]
                            return 23
                    elif current_number == 4:  #command-4r (input as char)
                        if input_from_stdin:
                            recent_input += stdin.read()
                        if len(recent_input) > 0:
                            c, recent_input = recent_input[0], recent_input[1:]
                            stack_append(ord(c))
                            return 24
                    elif current_number == 5:  #command-5r (output top as integer)
                        if len(stack) > 0:
                            p = stack_pop()
                            print(p, end='', flush=True)
                            if debug_mode:
                                output_debug += str(p)
                            return 25
                    elif current_number == 6:  #command-6r (output top as char)
                        if len(stack) > 0:
                            p = stack[-1]
                            if p > -1 and p < 0x110000:
                                c = chr(stack_pop())
                                print(c, end='', flush=True)
                                if debug_mode:
                                    output_debug += c
                                return 26
                    elif current_number == 7:  #command-7r (skip p operations)
                        if len(stack) > 0:
                            operation_pointer = (
                                operation_pointer +
                                stack_pop()) % operations_length
                            return 27
                    elif current_number == 8:  #command-8r (perform right click(p1, p0))
                        if len(stack) > 1:
                            opration_to_perform = (stack_pop() % height,
                                                   stack_pop() % width, True
                                                   )  # inverted.
                            return 28
            else:  # left-clicked revealed
                if current_number == 0:  #command-0l (pop)
                    if len(stack) > 0:
                        stack_pop()
                        return 10
                elif current_number == 1:  #command-1l (p > 0 ? 1 : 0)
                    if len(stack) > 0:
                        stack_append(1 if stack_pop() > 0 else 0)
                        return 11
                elif current_number == 2:  #command-2l (duplicate top)
                    if len(stack) > 0:
                        stack_append(stack[-1])
                        return 12
                elif current_number == 3:  #command-3l (p1 + p0)
                    if len(stack) > 1:
                        stack_append(stack_pop() + stack_pop())
                        return 13
                elif current_number == 4:  #command-4l (p1 - p0)
                    if len(stack) > 1:
                        stack_append(-stack_pop() + stack_pop())
                        return 14
                elif current_number == 5:  #command-5l (p1 * p0)
                    if len(stack) > 1:
                        stack_append(stack_pop() * stack_pop())
                        return 15
                elif current_number == 6:  #command-6l (p1 / p0)
                    if len(stack) > 1 and stack[-1] != 0:
                        p0, p1 = stack_pop(), stack_pop()
                        stack_append(p1 // p0)
                        return 16
                elif current_number == 7:  #command-7l (p1 % p0)
                    if len(stack) > 1 and stack[-1] != 0:
                        p0, p1 = stack_pop(), stack_pop()
                        stack_append(p1 % p0)
                        return 17
                elif current_number == 8:  #command-8l (perform left click(p1, p0))
                    if len(stack) > 1:
                        opration_to_perform = (stack_pop() % height,
                                               stack_pop() % width, False
                                               )  # inverted.
                        return 18
        else:  # not revealed
            if right_clicked:  #command-f (swap top 2 items)
                flagged[x][y] = not flagged[x][y]
                if len(stack) > 1:
                    stack[-1], stack[-2] = stack[-2], stack[-1]
                    return 30
            elif flagged[x][y]:  # left-clicked flagged
                return 31
            else:  # left-clicked not flagged
                if current_number == 0:  #command-0n (push the number of revealed(>=1))
                    reveal_count = open_recursively((x, y), False)
                    stack_append(reveal_count)
                    return 0
                elif current_number == 9:  #command-9l (reset game)
                    reveal(x, y, True)
                    current_revealed = [[False] * width for _ in range_height]
                    flagged = [[False] * width for _ in range_height]
                    return 19
                else:  #command-1n-8n (push number)
                    reveal(x, y, False)
                    stack_append(current_number)
                    return current_number

        return -1
Пример #42
0
def main():
    lines = stdin.read().splitlines()  #Use ctrl+d to finish read process
    for curr_Line in lines:
        print(curr_Line)

    return
# python3

from itertools import product
from sys import stdin
import itertools


def partition3(A):
    assert 1 <= len(A) <= 20
    assert all(1 <= v <= 30 for v in A)

    for c in itertools.product(range(3), repeat=len(A)):
        sums = [None] * 3
        for i in range(3):
            sums[i] = sum(A[k] for k in range(len(A)) if c[k] == i)

        if sums[0] == sums[1] and sums[1] == sums[2]:
            return 1

    return 0


if __name__ == '__main__':
    input_n, *input_values = list(map(int, stdin.read().split()))
    assert input_n == len(input_values)
    print(partition3(input_values))
Пример #44
0
'''
程序31】
题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续
   判断第二个字母。
1.程序分析:用情况语句比较好,如果第一个字母一样,则判断用情况语句或if语句判断第二个字母。
2.程序源代码:
'''
from sys import stdin
letter = stdin.read(1)
stdin.flush()
while letter != 'Y':
    if letter == 'S':
        print 'please input second letter'
        letter = stdin.read(1)
        stdin.flush()
        if letter == 'a':
            print 'Saturday'
        elif letter == 'u':
            print 'Sunday'
        else:
            print 'data error'
            break
    elif letter == 'F':
        print 'Friday'
        break
    elif letter == 'M':
        print 'Monday'
        #break
    elif letter == 'T':
        print 'please input second letter'
        letter = stdin.read(1)
Пример #45
0
                        format=logformat,
                        filename=join(DEPLOY, 'handler.log'),
                        style='{')
    ch = logging.StreamHandler()
    ch.setFormatter(logging.Formatter(logformat, style='{'))
    logging.getLogger().addHandler(ch)

    myself = socket.gethostname()
    manual_input = None

    if len(argv) >= 2 and argv[1] in FakeExec.faked:
        # mock some executables
        print(FakeExec.run(' '.join(argv[1:])))
    elif len(argv) == 2 and argv[1].lower() == 'test':
        # run some unittests
        argv.pop(-1)
        TEST = True
        requests.post = TestRequests.post
        unittest.main(verbosity=2)
    elif len(argv) >= 3:
        # allow to launch manually inside consul docker
        event = argv[1]
        payload = b64encode(' '.join(argv[2:]).encode('utf-8')).decode('utf-8')
        manual_input = json.dumps([{
            'ID': str(uuid1()), 'Name': event,
            'Payload': payload, 'Version': 1, 'LTime': 1}])
        handle(manual_input, myself)
    else:
        # run what's given by consul watch
        handle(stdin.read(), myself)
Пример #46
0
from sys import stdin

print(sum({'(': 1, ')': -1}[v] for v in stdin.read()))
Пример #47
0
#All Wehrmacht models
LIST_OF_ROTORS = ['I', 'II', 'III', 'IV', 'V']
#Kriegsmarine M3 & M4
#LIST_OF_ROTORS = ['I','II','III', 'IV', 'V', 'VI', 'VII', 'VIII']

#X is not in use, to make your life easier
ALPHABET = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', 'Z'
]

#there are more reflectors, but this will be bad enough for you to deal with.
LIST_OF_REFLECTORS = ['B', 'C']

message = stdin.read().rstrip("\n")

#splugs = ['LO', 'KI', 'JU', 'HY', 'GT', 'FR', 'DE', 'SW', 'QA']
srotors = ['I', 'IV', 'V']
grotors = ['II', 'III']
sreflectors = ['B', 'C']
srings = ['W', 'H']

temp = []
trotors = []
trings = []
talph = []

for srotor in srotors:
    temp = [srotor, grotors[0], grotors[1]]
    #trotors.append(temp)
Пример #48
0
                letter = letter.lower()
            plaintext += letter
            #print "index = " + str(index) + " = " +letter
        #Invalid characters just get appended
        else:
            plaintext += letter

        #only progress the key counter if we found a valid character
        if (valid):
            keyCounter += 1

    return plaintext


try:

    'implement error catching'
    mode = argv[1]
    key = argv[2]

    text = stdin.read().rstrip("\n")

    if (mode == "-e"):
        ciphertext = encrypt(text, key)
        print ciphertext
    elif (mode == "-d"):
        plaintext = decypt(text, key)
        print plaintext
except:
    print "To use this utility use the syntax: '<Program Name> -(options) <Key>' \n options are -e or -d for encrpyt and decrypt respectivly"
Пример #49
0
#     return None


def make_match(df):
    df = get_cluster(df)
    matches = break_clusters(df)
    #matches = break_df(df)
    return matches


def make_df(data_in):
    data = loads(data_in)
    df = pd.DataFrame(data).T
    return df


def main(data_in):
    df = make_df(data_in)
    matches = make_match(df)
    return matches


data_in = stdin.read()

output = main(data_in)

stdout.write(output)

# Can be tested with this command
# pipenv run python3 dotPy/matchmaking.py < integration/src/matchmaking_test.json
    return txt


# MAIN
file = open(DICTIONARY_FILE, "r")
pKeys = file.read().rstrip("\n").split("\n")
file.close()

dictionary = []
for word in pKeys:
    dictionary.append(word.lower())

# filter potential keys
pKeys = filterKeys(pKeys)

cipherTxt = stdin.read().rstrip("\n")
cipherTxt = "\n".join(cipherTxt.split("\n"))

# changes the bounds of the follwoing for loop depending
# on if the keys should be processed forwards or backwards
if FORWARD == True:
    start = 0
    end = len(pKeys)
    step = 1
else:
    start = len(pKeys) - 1
    end = -1
    step = -1

# iterating through keys to find the most correct deciphered text
for k in range(start, end, step):
Пример #51
0
def main():
    import argparse
    from sys import stdin
    from collections import OrderedDict

    parser = argparse.ArgumentParser(
        prog=__package__, description='Configuration manager in your pocket')
    parser.add_argument('config_file',
                        action='store',
                        nargs='*',
                        help="file/s to load config from")
    parser.add_argument('--handler',
                        action='store',
                        default='json',
                        help="set default handler")
    parser.add_argument('-e',
                        '--export',
                        action='store',
                        default='json',
                        help="set format to export to")
    parser.add_argument('-k',
                        '--key',
                        action='store',
                        help="set config key to get value of")
    args, ukargs = parser.parse_known_args()

    config = Kaptan()
    config_files = args.config_file + ukargs

    if not config_files:
        parser.print_help()
        parser.exit(1)

    def get_handlers():
        for f in config_files:
            s = f.split(':')
            if len(s) != 2:
                s += [None]
            yield tuple(s)

    config_handlers = OrderedDict(list(get_handlers()))

    for config_file, handler in config_handlers.items():
        is_stdin = config_file == '-'
        if is_stdin:
            handler = handler or args.handler
        else:
            ext = handler or os.path.splitext(config_file)[1][1:]
            handler = HANDLER_EXT.get(ext, args.handler)
        _config = Kaptan(handler=handler)
        if is_stdin:
            _config.import_config(stdin.read())
        else:
            with open(config_file) as f:
                _config.import_config(f.read())
        config.configuration_data.update(_config.configuration_data)

    if args.key:
        print(config.get(args.key))
    else:
        print(config.export(args.export))

    parser.exit(0)
Пример #52
0
from sys import stdin
import math
lines = stdin.read().splitlines()

factorial = {}

factorial[0] = 1
factorial[1] = 1

divisors = {}


def d(n):
    if (divisors.get(n)):
        return d[n]

    cont = 0
    lim = math.ceil(math.sqrt(n))
    for i in range(1, lim):
        if n % i == 0:
            cont += 1

            if i != lim:
                cont += 1
    divisors[n] = cont
    return cont


def facti(n):
    if factorial.get(n):
        return factorial[n]
Пример #53
0
# https://www.acmicpc.net/problem/1181

from sys import stdin, stdout

stdout.write('\n'.join(tp[1] for tp in sorted(
    (len(s), s) for s in set(stdin.read().splitlines()[1:]))) + '\n')
Пример #54
0
from sys import stdin
for n in map(int, stdin.read().split()):
    dp = [0 for x in range(1002)]

    dp[0] = 1
    dp[1] = 1
    for i in range(2, n + 1):
        dp[i] = (dp[i - 1] + dp[i - 2] * 2)

    print(dp[n])
Пример #55
0
            if st1:
                st1.pop()

    print(''.join(st1) + ''.join(reversed(st2)))


sol()
```

> 

* 모범답안

  ```python
  from sys import stdin
  l = stdin.read().rstrip().split("\n")
  txt_l = list(l[0])
  txt_r = []
  l = l[2:]
  
  for o in l:
      if o[0] == "P":
          txt_l.append(o[2])
      elif o=="L" and txt_l:
              txt_r.append(txt_l.pop())
      elif o=="D" and txt_r:
              txt_l.append(txt_r.pop())
      elif o=="B" and txt_l:
              txt_l.pop()
  
  print("".join(txt_l)+"".join(txt_r[::-1]))
Пример #56
0

def match(rule, msg):
    if rule == 0:  # we rely on 0: 8 11 to bypass rules 8 and 11
        l, r = length(42), length(31)
        for i in range(l, len(msg), l):
            # potential bug: 8 and 11 must have 1+ element, not just 0+
            if (len(msg)-i)%r==0 and i//l>(len(msg)-i)//r and \
             all(match(42,msg[j:j+l]) for j in range(0,i,l)) and \
             all(match(31,msg[j:j+r]) for j in range(i,len(msg),r)):
                matches[(0, msg)] = True
                return matches[(0, msg)]
    if length(rule) != len(msg):
        return False
    if (rule, msg) in matches:
        return matches[(rule, msg)]
    if rule not in rules:
        return False
    for seq in rules[rule]:
        assert len(seq) <= 2
        l = length(seq[0])
        if match(seq[0], msg[:l]) and (len(seq) == 1
                                       or match(seq[1], msg[l:])):
            matches[(rule, msg)] = True
            return True
    matches[(rule, msg)] = False
    return False


print(sum(match(0, m) for m in stdin.read().split()))
Пример #57
0
def main():
    f = stdin.read()
    res = parse(f)
    pprint(res)
Пример #58
0
from sys import stdin
from operator import mul
stdin.readline()


c = [1, 1] + [reduce(mul, xrange(2, x+1)) for x in xrange(2, 24)]
c.extend([c[-1]*reduce(mul, xrange(24, x+1)) for x in range(24, 48)])
c.extend([c[-1]*reduce(mul, xrange(48, x+1)) for x in range(48, 71)])

def fac(n):
    if n < 70:
        return c[n]
    else:
        return n*fac(n-1)
    
print '\n'.join(map(str, map(fac, map(int, stdin.read(-1).split()))))






def f(n):
    if n <= 1:
        return 1
    else:
        return f(n-1) * n

d = map(fac, map(int, stdin.read(-1).split()))
print len(d)
print d
Пример #59
0
                    temp_lst.append(self.lst[row][item] + other.lst[row][item])
                new_lst.append(temp_lst)
            return Matrix(new_lst)

    def __mul__(self, other):
        new_lst = []
        for row in range(self.size()[0]):
            temp_lst = []
            for item in range(self.size()[1]):
                temp_lst.append(self.lst[row][item] * other)
            new_lst.append(temp_lst)
        return Matrix(new_lst)

    __rmul__ = __mul__

    def transpose(self):
        temp_list = []
        for c in range(self.size()[1]):
            temp_list.append([])
            for r in range(self.size()[0]):
                temp_list[c].append(self.lst[r][c])
        self.lst = temp_list
        return self

    @staticmethod
    def transposed(x):
        return Matrix([list(i) for i in zip(*copy.deepcopy(x.lst))])


exec(stdin.read())
Пример #60
0
         print('>>> a')
         print(a)
         print('>>> b')
         print(b)
         print('>>> patch')
         print(patch)
         print('>>> mayb')
         print(mayb)
         print('Try again...')
 elif cmd == 'diff':
     assert len(argv) > 2, "A file should be provided."
     with open(argv[2]) as f:
         txta = f.read()
     if len(argv) < 3:
         from sys import stdin
         txtb = stdin.read()
     else:
         with open(argv[3]) as f:
             txtb = f.read()
     print(create_patch(txta, txtb), end='')
 elif cmd == 'patch':
     assert len(argv) > 2, "A patch should be provided."
     with open(argv[2]) as f:
         patch = f.read()
     if len(argv) < 3:
         from sys import stdin
         txta = stdin.read()
     else:
         with open(argv[3]) as f:
             txta = f.read()
     print(apply_patch(txta, patch), end='')