Exemplo n.º 1
0
def to_iobes():
  current = ''
  next_ = ''
  lines = stdin.readlines()
  for ind, line in enumerate(lines):
    if line != '\n':
      splitted = line.strip().split(' ')

      current = splitted[-1][0]
      new_current = ''
      next_ = lines[ind+1].strip().split(' ')[-1]
      if len(next_) > 0:
        next_ = next_[0]

      if current == 'B' and next_ == 'O':
        new_current = 'S'
      elif current == 'B' and next_ == 'B':
        new_current = 'S'
      elif current == 'I' and next_ == 'O':
        new_current = 'E'
      elif current == 'I' and next_ == 'B':
        new_current = 'E'
      elif current == 'B' and next_ == '':
        new_current = 'S'
      elif current == 'I' and next_ == '':
        new_current = 'E'
      else:
        new_current = current[0]
      splitted[-1] = new_current + splitted[-1][1:]

      joined = ' '.join(splitted)
    else:
      joined = ''
    print(joined)
Exemplo n.º 2
0
def main():
    def bfs(initial, final):
        queue = deque([initial, None])
        count = 0
        while len(queue) > 1:
            node = queue.popleft()
            if node == final:
                break
            if node is None:
                count += 1
                queue.append(None)
                continue
            i, j = node
            for x, y in ((i - 1, j - 2),
                         (i - 2, j - 1),
                         (i - 2, j + 1),
                         (i - 1, j + 2),
                         (i + 1, j + 2),
                         (i + 2, j + 1),
                         (i + 2, j - 1),
                         (i + 1, j - 2)):
                if (0 <= x < 8) and (0 <= y < 8) and board[x][y]:
                    queue.append((x, y))
                    board[x][y] = False
        return count

    inp = stdin.readlines()
    for t in xrange(int(inp[0])):
        p1, p2 = inp[t + 1].split()
        board = [[True]*8 for _ in xrange(8)]
        print bfs(
            (ord(p1[0]) - ord('a'), int(p1[1]) - 1),
            (ord(p2[0]) - ord('a'), int(p2[1]) - 1))
Exemplo n.º 3
0
def task():
    n = int(stdin.readline())
    counter = 0
    tree = defaultdict(list)
    words = []
    pattern = ''

    for index, value in enumerate(stdin.readlines()):
        if index < n - 1:
            parent_string, word = value.split()
            words.append(word)
            tree[int(parent_string) - 2].append(index)
        elif index == n - 1:
            pattern = value.strip()

    length = len(pattern)
    search = [(0, child) for child in tree[-1]]

    pi = compute_prefix_function(pattern)

    append, pop = search.append, search.pop
    while search:
        matchLen, index = pop()
        for c in words[index]:
            matchLen = pi[matchLen][c]
            if matchLen == length:
                counter += 1
        for child in tree[index]:
            append((matchLen, child))

    print counter
Exemplo n.º 4
0
def main():
    p = ArgumentParser()
    p.add_argument("-s", dest="shell", action='store_true')
    p.add_argument("-n", "--no-raw", dest="accept_raw", action='store_false')
    args = p.parse_args()

    if args.shell:
        inputs = stdin.readlines()
        for i in inputs:
            try:
                cmd = handle_cmd(i, args.accept_raw)
            except Exception as e:
                dbg(e)
                raise
            if cmd:
                dbg("Executing %s" % cmd)
                c = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
                out, err = c.communicate()
                if c.returncode > 0:
                    call(["notify-send", "Error running: {}:\n{}".format(cmd,err)])
            else:
                dbg("Skipping unrecognized raw command '{}'".format(i))

    else:
        dmenu_path = Popen(["dmenu_path"], stdout=PIPE)
        # dmenu replacement, rofi
        # https://github.com/DaveDavenport/rofi
        dmenu = Popen(["rofi", "-dmenu"], stdin=dmenu_path.stdout, stdout=PIPE)
        #dmenu = Popen(["dmenu"], stdin=dmenu_path.stdout, stdout=PIPE)
        Popen([argv[0], "-s"], stdin=dmenu.stdout)
Exemplo n.º 5
0
def main():
    import argparse
    from sys import exit, stdin
    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--version', action='version', version="%%(prog)s %s (%s)" % (__version__, __author__))
    parser.add_argument('username', help="Your HE DNS username")
    parser.add_argument('password', help="Your HE DNS password")
    parser.add_argument('command', nargs=argparse.REMAINDER,
                        help="An optional command, if blank we drop into interactive mode")
    options = parser.parse_args()

    shell = HurricaneDNSShell(options.username, options.password)
    try:
        if not options.command:
            if stdin.isatty():
                shell.cmdloop()
            else:
                for line in stdin.readlines():
                    shell.onecmd(line)
        else:
            from pipes import quote
            shell.onecmd(" ".join(map(lambda x: quote(x), options.command)))
    except HurricaneDNS.HurricaneAuthenticationError as e:
        print '%s: HE sent an error (%s)' % (parser.prog, e)
        exit(1)
    except HurricaneDNS.HurricaneError as e:
        print '%s: %s' % (parser.prog, e)
Exemplo n.º 6
0
def main():
    from sys import stdin
    try:
        range = xrange
    except NameError:
        pass
    inp = iter(stdin.readlines())
    z = inp.next()
    while z != '0':
        x = 1
        dp = [0]*(len(z) + 1)
        dp[0] = 1
        dp[1] = 1
        lenz = len(z)
        if z[0] == '0':
            print(0)
            z = inp.next()
            continue
        for x in range(1, lenz):
            dp[x + 1] = dp[x]
            if z[x] == '0' and not ('1' <= z[x - 1] <= '2'):
                dp[lenz] = 0
                break
            elif z[x] == '0':
                continue
            if '10' <= z[x - 1:x + 1] <= '26':
                if x < lenz - 1 and z[x + 1] != '0':
                    dp[x + 1] += dp[x - 1]
                elif x == lenz - 1:
                    dp[x + 1] += dp[x - 1]
        print(dp[lenz])
        z = inp.next()
Exemplo n.º 7
0
def main():
    def maxarea(arr, length):
        stack = []
        i = 0
        max_area = float('-inf')
        while i < length:
            if len(stack) == 0 or arr[stack[-1]] <= arr[i]:
                stack.append(i)
                i += 1
            else:
                top = stack.pop()
                if stack:
                    area_with_top = arr[top] * (i - stack[-1] - 1)
                else:
                    area_with_top = arr[top] * i
                max_area = max(max_area, area_with_top)
        while stack:
            top = stack.pop()
            if stack:
                area_with_top = arr[top] * (i - stack[-1] - 1)
            else:
                area_with_top = arr[top] * i
            max_area = max(max_area, area_with_top)


        return max_area

    inp = stdin.readlines()
    inp.pop()
    for x in inp:
        l = map(int, x.split())
        length = l.pop(0)
        print maxarea(l, length)
Exemplo n.º 8
0
def mst():
	lines = stdin.readlines()
	n = len(lines)
	
    #Prims
	tagged = [0]*n
	heaviest = 0
	edges = 0
	
	heap = getNode(lines,0)
	heapify(heap)
	tagged[0] = 1
	
	while edges < n-1:
		edge = heappop(heap)
		target = edge[1]
		if tagged[target]:
			continue
		
		tagged[target] = 1
		if heaviest < edge[0]:
			heaviest = edge[0]
			
		for e in getNode(lines,target):
			if not tagged[e[1]]:
				heappush(heap, e)
		edges += 1

	return heaviest
Exemplo n.º 9
0
def main():
    def maxpath(matrix, i, j):
        if i < 0 or i >= n or j < 0 or j >= m:
            return 0
        if memz[i][j]:
            return memz[i][j]
        # neighbour = (neigh_x, neigh_y)
        for neigh_x, neigh_y in zip(
                (i, i, i - 1, i + 1, i - 1, i - 1, i + 1, i + 1),
                (j - 1, j + 1, j, j, j - 1, j + 1, j - 1, j + 1)):
            if matrix[i][j] == matrix[neigh_x][neigh_y] - 1:
                memz[i][j] = max(memz[i][j], maxpath(matrix, neigh_x, neigh_y) + 1)

        return memz[i][j]

    inp = iter(stdin.readlines())
    n, m = map(int, inp.next().split())
    k = 1
    while n or m:
        mat = []
        memz = [[0]*52 for _ in xrange(52)]
        for x in xrange(n):
            mat.append(map(ord, list(inp.next())))
            mat[x].append(0)
            mat[x].append(0)
        mat.append([0] * (m + 2))
        ans = 0
        for x in xrange(n):
            for y in xrange(m):
                if mat[x][y] == 65:
                    ans = max(ans, maxpath(mat, x, y) + 1)
        print 'Case {}: {}'.format(k, ans)
        k += 1
        n, m = map(int, inp.next().split())
Exemplo n.º 10
0
def main():
    def extended_gcd(aa, bb):
        lastremainder, remainder = abs(aa), abs(bb)
        x, lastx, y, lasty = 0, 1, 1, 0
        while remainder:
            lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
            x, lastx = lastx - quotient * x, x
            y, lasty = lasty - quotient * y, y
        return lastremainder, 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

    inp = stdin.readlines()
    out = []
    for _ in xrange(int(inp[0])):
        n, p = map(int, inp[_ + 1].split())
        if n >= p:
            out.append("0")
            continue
        product = 1
        for x in xrange(p - 1, n, -1):
            product = (product * x) % p
        out.append(str(modinv(-1 * product, p)))

    print "\n".join(out)
Exemplo n.º 11
0
def main():
	try:
		in_file = open(argv[1], 'r')
		try:
			data = [s.replace('\n', '') for s in in_file.readlines()]
		finally:
			in_file.close()
	except IOError:
		print("Cant open file or read data")
		data = [s.replace('\n', '') for s in stdin.readlines()]

	alphabet = data[0].split()
	k = len(alphabet)
	max_n = int(data[1])

	result_strings = []

	for n in range(1, max_n + 1):
		result_strings += get_all_numbers(alphabet, k, n)

	new_alphabet = dict(zip( alphabet, map(chr, range(65, 91)) ))

	result_strings = [(s, in_new_alphabet(s, new_alphabet)) for s in result_strings]

	result_strings.sort(key = lambda x: x[1])

	try:
		out_file = open("lexv_out.txt", 'w')
		try:
			for s in result_strings:
				print(s[0], file = out_file)
		finally:
			out_file.close()
	except IOError:
		print("Cant write data")
Exemplo n.º 12
0
def main():
    def max_score(p, Ag, Bg):
        apq = pqueue(zip(Ag, Ag, [2]*len(Ag)))
        bpq = pqueue(zip([0]*len(Bg), Bg, [1]*len(Bg)))
        tasks = 0

        while True:
            d = apq.pop()
            if d[0] >= p:
                break
            apq.push((d[0] + d[1]*d[2], d[1], d[2] + 1))
            w = bpq.pop()
            if max(w[0], d[0]) + w[1]*w[2] < p:
                tasks += 1
                bpq.push((max(w[0], d[0]) + w[1]*w[2], w[1], w[2] + 1))

        return tasks

    inp = stdin.readlines()
    for T in xrange(int(inp[0])):
        p = int(inp[4*T + 1])
        # n, m = map(int, inp[4*T + 2])
        Ag = map(int, inp[4*T + 3].split())
        Bg = map(int, inp[4*T + 4].split())
        print max_score(p, Ag, Bg)
Exemplo n.º 13
0
def main():
    def sieve(n):
        numbers = [True]*n
        primes = []
        for x in range(2, n):
            if numbers[x]:
                primes.append(x)
                for y in range(2*x, n, x):
                    numbers[y] = False
        return primes

    primes = sieve(1001)
    stdin.readline()
    for n in map(int, stdin.readlines()):
        mc = float('-inf')
        for x in primes:
            if n == 1 or x >= n:
                break
            c = 0
            while n % x == 0:
                c += 1
                n /= x
            mc = max(c, mc)
        if n != 1:
            mc = max(1, mc)

        print(mc)
def main():
	from sys import stdin, stdout

	# stdin = open("input.txt", "r")

	inp = stdin.readlines()

	n = int(inp[0])

	versePattern = iter(map(int, inp[1].split()))

	ans = True

	for line in inp[2:]:
		vowelCnt = 0

		for x in line:
			if x in "aeiouy":
				vowelCnt += 1
	
		if vowelCnt != next(versePattern):
			ans = False
			break

	stdout.write("YES\n" if ans else "NO\n")
Exemplo n.º 15
0
def main():
    def steps(a, b, c):
        queue = deque([(0, 0), (-1, -1)])
        visited = set()
        count = 0
        while len(queue) > 1:
            x, y = queue.popleft()
            if x == -1 == y:
                count += 1
                queue.append((-1, -1))
                continue
            if x == c or y == c:
                return count
            if (x, y) in visited:
                continue
            visited.add((x, y))
            for p in [
                    (0, y), (x, 0), (a, y), (x, b),
                    (x - min(x, b - y), y + min(x, b - y)),
                    (x + min(y, a - x), y - min(y, a - x))]:
                if p not in visited and p != (x, y):
                    queue.append(p)
        return -1

    dstream = map(int, stdin.readlines())
    for t in xrange(dstream[0]):
        a, b, c = dstream[3*t + 1], dstream[3*t + 2], dstream[3*t + 3]
        print steps(a, b, c)
Exemplo n.º 16
0
def dfs():
    from sys import stdin
    import gc
    gc.disable()
    r = stdin.readline
    r()
    r()
    rot = int(r())
    goal = int(r())
    s = str.split
    linjer = map(s, stdin.readlines())
    keys = []
    a = keys.append
    for linje in linjer:
        a(linje.pop(0))

    if int(goal) == rot:
        return 0

    dybde = 1

    i = keys.index
    k = keys.remove
    l = linjer.remove
    while 1:
        for key in keys:
            if key != str(goal):
                if str(goal) in set(linjer[i(key)]):
                    goal = key
                    if int(goal) == rot:
                        return dybde
                    dybde += 1
                    l(linjer[i(key)])
                    k(key)
                    break
Exemplo n.º 17
0
def main():
    lines = stdin.readlines()
    lines = [line.strip().split() for line in lines]
    true_pos = 0
    true_neg = 0
    false_pos = 0
    false_neg = 0
    for line in lines:
        pred = line[0]
        real = line[1]
        if real in POSITIVES and pred in POSITIVES:
            true_pos += 1
        elif real in POSITIVES and pred in NEGATIVES:
            true_neg += 1
        elif real in NEGATIVES and pred in POSITIVES:
            false_pos += 1
        elif real in NEGATIVES and pred in NEGATIVES:
            false_neg += 1
    
    soundness = float(true_pos)/(true_pos + true_neg)
    print "%f\tpercent of actual follow-backs predicted." % soundness*100
    completeness = float(true_pos)/(true_pos + false_pos)
    print "%f\tpercent of predicted follow-backs were correct." % completeness*100
    accuracy = float(true_pos + false_neg)/(true_pos + false_pos + true_neg + false_neg)
    print "%f\tpercent of all predictions were accurate." % accuracy*100
Exemplo n.º 18
0
def main():
    lines = stdin.readlines()
    longest = max([len(t.rstrip()) for t in lines])

    for line in lines:
        left = len(line.rstrip()) - len(line.strip())
        print((line.strip()+(" "*left)).rjust(longest, " "))
Exemplo n.º 19
0
	def read_input(self):
		print "Enter your statements(s) and then question(s). Terminate by pressing (Control + D) :"
		for line in stdin.readlines():
			self.lines.append( ((self.pattern.sub(' ',line)).strip()) )
			#self.lines.append(line)
		#print self.lines
		return self.lines
Exemplo n.º 20
0
def main():
    from sys import stdin

    try:
        range = xrange
    except NameError:
        pass
    inp = iter(stdin.readlines())

    for x in range(int(inp.next())):
        # code...
        inp.next()
        a, plus, b, equ, c = inp.next().split()
        try:
            a = int(a)
        except ValueError:
            b = int(b)
            c = int(c)
            a = c-b
            print('{} {} {} {} {}'.format(a, plus, b, equ, c))
            continue
        try:
            b = int(b)
        except ValueError:
            c = int(c)
            b = c - a
            print('{} {} {} {} {}'.format(a, plus, b, equ, c))
            continue
        try:
            c = int(c)
        except ValueError:
            c = a + b
            print('{} {} {} {} {}'.format(a, plus, b, equ, c))
            continue
Exemplo n.º 21
0
def main():
    """ Reads input from stdin, prints answer to stdout, and returns. """
    # Parse input
    lines = ''.join(stdin.readlines()).split('\n')
    splits = ( a.split(' ') for a in lines[1:] )    # generator
    parsed = [ (a[0], int(a[1])) for a in splits ]

    # Build lists 
    positive, negative = [], []
    for p in parsed:
        if p[1] > 0:
            positive.append(p)
        else:
            negative.append(p)

    # Find smaller list
    (smaller, larger) = (positive, negative) if len(positive) < len(negative) else (negative, positive)

    # Permute the smaller list
    for combo in combinations(smaller):
        calories = sum( a[1] for a in combo )
        for pcombo in combinations( [l for l in larger if abs(l[1]) < abs(calories)] ): # ignore elements with calorie count too big
            if sum( b[1] for b in pcombo ) + calories == 0:
                for ele in sorted( a[0] for a in combo+pcombo ):
                    print ele
                return 

    # No solution found
    print 'no solution'
Exemplo n.º 22
0
def main():
    inp = stdin.readlines()
    out = []
    for _ in range(int(inp[0])):
        a, b = inp[_ + 1].split()
        out.append(str(int(a[::-1]) + int(b[::-1]))[::-1].lstrip('0'))
    print('\n'.join(out))
Exemplo n.º 23
0
def get_input():
  """
    Returns a list of every number from stdin
  """
  from sys import stdin
  result = stdin.readlines()
  del result[0]
  return map(int, result)
Exemplo n.º 24
0
def main():
    n, k = map(int, stdin.readline().split())
    d = 0
    array = map(int, stdin.readlines())

    for i in range(len(array)):
        if array[i] % k == 0:
            d += 1
    print d
Exemplo n.º 25
0
def get_input():
  """
    Returns a tuple containing 2 elements:
    - A int containing amount test cases
    - A list of all test cases containing 3 integers: money, price, discount
  """
  from sys import stdin
  raw = [line.strip() for line in stdin.readlines()]
  return int(raw[0]), [map(int, line.split()) for line in raw[1:]]
Exemplo n.º 26
0
def main():
  from sys import stdin, stdout
  n, k = map(int, stdin.readline().split())
  d = 0

  for t in stdin.readlines():
    if int(t) % k == 0: d += 1

  stdout.write(str(d) + "\n")
Exemplo n.º 27
0
def main():
    def ans(h, n, k):
        a = float('inf')
        for x in xrange(n - k + 1):
            a = min(a, h[x + k - 1] - h[x])
        return a
    from sys import stdin
    inp = stdin.readlines()
    for _ in xrange(int(inp[0])):
        print ans(sorted(map(int, inp[2*_ + 2].split())), *map(int, inp[2*_ + 1].split()))
Exemplo n.º 28
0
def main():
    inp = stdin.readlines()
    for _ in xrange(int(inp[0])):
        x, y = map(int, inp[_ + 1].split())
        if x == y:
            print((x // 2) * 4 + (x % 2))
        elif x > 1 and y == x - 2:
            print((y // 2) * 4 + (y % 2) + 2)
        else:
            print('No Number')
Exemplo n.º 29
0
def get_input():
  """
    Returns a list of integers with all test cases
  """
  from sys import stdin
  raw = [line.strip() for line in stdin.readlines()]
  assert 1 <= int(raw[0]) <= 10
  for i in map(int, raw[1:]):
    assert 2 <= i <= 10**7
  return map(int, raw[1:])
Exemplo n.º 30
0
def main():
    inp = stdin.readlines()
    for _ in xrange(int(inp[0])):
        n, k = map(int, inp[2*_ + 1].split())
        a = map(int, inp[2*_ + 2].split())
        for x in xrange(1, k):
            a[x] += 2*a[x - 1]

        for x in xrange(1, k):
            pass
Exemplo n.º 31
0
from sys import stdin

print('\n'.join(str((int(w) + 399) // 400) for w in stdin.readlines()[1:]))
Exemplo n.º 32
0
from sys import stdin
import re
from statistics import mode
progs = [re.split(r' -> |, ', line.strip()) for line in stdin.readlines()]
children = {
    re.sub(r'\([0-9]+\)', '', line[0]).strip(): line[1:]
    for line in progs
}
weights = {
    re.sub(r'\([0-9]+\)', '', line[0]).strip():
    int(re.search(r'([0-9]+)', line[0]).group(0))
    for line in progs
}
partials = {}


def sum_weights(s):
    partials[s] = weights[s] + sum(
        sum_weights(t) if t not in partials else partials[t]
        for t in children[s])
    return partials[s]


for prog in children:
    sum_weights(prog)
unbal = lambda s: not all(partials[ch] == partials[children[s][0]]
                          for ch in children[s])
nodes = lambda n: 1 + sum(nodes(c) for c in children[n])
root = [prog for prog in children if nodes(prog) == len(children)][0]
final = root
while any(unbal(child) for child in
Exemplo n.º 33
0
from sys import stdin

difference = {}
difference[1] = 1
difference[2] = 0
difference[3] = 1
numbers = set()

minimum = 9999999999999999999
maximum = -1

for jolt in [line.rstrip() for line in stdin.readlines()]:
    if jolt == '':
        break

    jolt_number = int(jolt)
    minimum = min(minimum, jolt_number)
    maximum = max(maximum, jolt_number)
    numbers.add(jolt_number)

memoized = {}

# sort of part 1, messed it up trying to write part 2
# def recurse(minimum, maximum, current, numbers, difference, difference_value):
#     if current not in numbers:
#         return False
#     elif current == maximum:
#         return True

#     for i in [1, 2, 3]:
#         if recurse(minimum, maximum, current + i, numbers, difference, i):
Exemplo n.º 34
0
from sys import stdin

for line in stdin.readlines():
    tokens = line.split()
    name = []
    bpm = []
    for token in tokens:
        try:
            bpm.append(float(token))
        except:
            name.append(token)
    print('{0} {1}'.format(sum(bpm) / len(bpm), ' '.join(name)))
Exemplo n.º 35
0
    prob = prob * weight
    if len(subtrees) > 0:
        if feature in features:
            prob = probability(subtrees[0], name, features, prob)
        else:
            prob = probability(subtrees[1], name, features, prob)
    return str(D(prob).quantize(D('1.0000000')))


def probabilities(tree, animals):
    tree = make_tree(tree)
    probabilities = []
    for animal in animals.split('\n'):
        if animal.strip() != '':
            animal = animal.strip().split(' ')
            name = animal.pop(0)
            probabilities.append(probability(tree, name, animal[1:], D(1)))
    return '\n'.join(probabilities)


lines = stdin.readlines()
nocases = int(lines.pop(0))
lenfirstcase = lines.pop(0)

sections = split('\n[0-9]+\n', ''.join(lines))
cases = zip(*[iter(sections)] * 2)  # tree: animals

caseno = 1
for tup in cases:
    print('Case #%s:\n%s' % (caseno, probabilities(tup[0], tup[1])))
    caseno += 1
Exemplo n.º 36
0
def get_input():
    from sys import stdin
    input = stdin.readlines()
    return input[0], deque(input[1:])
Exemplo n.º 37
0
#!/usr/bin/python3
#
# Copyright (C) 2019 Trevor Last

from sys import stdin


def manhattan(x1, y1, x2, y2):
    return abs(x1 - x2) + abs(y1 - y2)


DELTA = {'U': (0, 1), 'D': (0, -1), 'L': (-1, 0), 'R': (1, 0)}

paths = [wire.split(',') for wire in stdin.readlines()]

overlaps = []

grid = dict()
idx = 0
for path in paths:
    x, y = 0, 0
    for line in path:
        dx = DELTA[line[0]][0] * int(line[1:])
        dy = DELTA[line[0]][1] * int(line[1:])

        for i in range(abs(dx) + 1):
            for j in range(abs(dy) + 1):
                pt = (x + i * DELTA[line[0]][0]), y + (j * DELTA[line[0]][1])
                try:
                    if grid[pt] != idx and pt != (0, 0):
                        overlaps.append(pt)
Exemplo n.º 38
0
def main():
    test_cases = parse_input(stdin.readlines())
    output = get_output(test_cases)
    write_output(output, 'output-recycle.out')
Exemplo n.º 39
0
    for i in range(1, N):
        for j in range(1, M):
            dp[i][j] = max((dp[i - 1][j], dp[i][j - 1]))
            if aseq[i] == bseq[j]:
                dp[i][j] = max((dp[i][j], dp[i - 1][j - 1] + 1))

    # track lcs
    lcs = ''
    i, j = N - 1, M - 1
    while True:
        if dp[i][j] == 0:
            break
        if aseq[i] == bseq[j]:
            lcs = aseq[i] + lcs
            i -= 1
            j -= 1
        else:
            if dp[i][j - 1] >= dp[i - 1][j]:
                j -= 1
            else:
                i -= 1

    return len(lcs), lcs


for a in solution(*[row.strip() for row in stdin.readlines()]):
    print(a)
"""
ACAYKP
CAPCA
"""
    "legal_address",
    "kpp",
    "bank_name",
    "kor_schet",
    "orgn_date",
    "bik",
    "boss_fio",
    "phone",
    "inn",
    "orgn",
    "orgn_emitter",
    "email",
    "bill_numb")

j = []
lines = grouper(4, stdin.readlines())
for s, i in zip(lines, count(1)):
    s = [i.strip() for i in s]
    entity = order_dict(ENTITY_ORDER, {
        "model": "tsj.servicecompany",
        "pk": i,
        "fields": {
            "workgraph": "Ежедневно 10:00-24:00",
            "kpp": "12345654321",
            "bank_name": "12343543",
            "kor_schet": "2342342343",
            "orgn_date": "2014-10-10",
            "bik": "3424234324",
            "boss_fio": "\u0419\u0446\u0443\u043a \u0415\u043d\u0433 \u0418\u0447\u0435\u0448\u0443\u0442\u0441\u044f",
            "phone": "777771",
            "inn": "123123213123213",
        cnd = get_candidate(x, y)
        if not cnd:  # no possible number means past selection is wrong
            return False
        for shift in range(9):
            if cnd & (1 << shift):  # if the number is markable
                mark(x, y, shift + 1)
                if solve(que_idx + 1):
                    return True
                unmark(x, y, shift + 1)
        return False  # all candidate gone through but no matching means worng past

    solve(0)
    return board


board = [[int(c) for c in row.strip()] for row in stdin.readlines()]
for row in solution(board):
    print(''.join([str(i) for i in row]))

# board = '''103000509
# 002109400
# 000704000
# 300502006
# 060000050
# 700803004
# 000401000
# 009205800
# 804000107'''
# board = [[int(c) for c in row.strip()] for row in board.splitlines()]
# for row in solution(board):
#     print(' '.join([str(i) for i in row]))
Exemplo n.º 42
0
from sys import stdin

m = {}
s = [x.strip() for x in stdin.readlines()]
s = s[1:]
s = "".join(s)
for i in range(len(s) - 3):
    t = s[i:i + 4]
    if t in m:
        m[t] += 1
    else:
        m[t] = 1
ans = []
for a in "ACGT":
    for b in "ACGT":
        for c in "ACGT":
            for d in "ACGT":
                e = "".join([a, b, c, d])
                if e in m:
                    ans.append(m[e])
                else:
                    ans.append(0)
print(" ".join(str(x) for x in ans))
Exemplo n.º 43
0
    # If normalized_names_require_pep503 is True we require the pep503
    # normalized name, if it is False we provide the legacy normalized name
    normalized_names_require_pep503 = args.normalized_names_format == "pep503"

    # If normalized_names_provide_pep503/legacy is True we provide the
    #   pep503/legacy normalized name, if it is False we don't
    normalized_names_provide_pep503 = \
        args.normalized_names_format == "pep503" or args.normalized_names_provide_both
    normalized_names_provide_legacy = \
        args.normalized_names_format == "legacy-dots" or args.normalized_names_provide_both

    # At least one type of normalization must be provided
    assert normalized_names_provide_pep503 or normalized_names_provide_legacy

    for f in (args.files or stdin.readlines()):
        f = f.strip()
        lower = f.lower()
        name = 'python(abi)'
        # add dependency based on path, versioned if within versioned python directory
        if py_abi and (lower.endswith('.py') or lower.endswith('.pyc')
                       or lower.endswith('.pyo')):
            if name not in py_deps:
                py_deps[name] = []
            purelib = get_python_lib(standard_lib=0,
                                     plat_specific=0).split(version[:3])[0]
            platlib = get_python_lib(standard_lib=0,
                                     plat_specific=1).split(version[:3])[0]
            for lib in (purelib, platlib):
                if lib in f:
                    spec = ('==', f.split(lib)[1].split(sep)[0])
Exemplo n.º 44
0
 def bufferize(self):
     self.idx = 0
     self.data = [line for line in stdin.readlines()]
Exemplo n.º 45
0
from sys import stdin

data = stdin.readlines()

for no, case in enumerate(data[1:], 1):
    C, J = case.split()

    CC, JJ = '', ''
    best = (10**20, str(10**20), str(10**20))

    def getBest(best, C, J):
        #print(best, C, J)
        cval, jval = int(C), int(J)
        val = (abs(cval - jval), C, J)
        if (best > val): return val
        return best

    for i, (c, j) in enumerate(zip(C, J), 1):
        if c == '?' and j == '?':
            best = getBest(best, CC + '0' + C[i:].replace('?', '9'),
                           JJ + '1' + J[i:].replace('?', '0'))
            best = getBest(best, CC + '1' + C[i:].replace('?', '0'),
                           JJ + '0' + J[i:].replace('?', '9'))
            CC += '0'
            JJ += '0'
        elif c == '?':
            if j > '0':
                best = getBest(best,
                               CC + str(int(j) - 1) + C[i:].replace('?', '9'),
                               JJ + j + J[i:].replace('?', '0'))
            if j < '9':
Exemplo n.º 46
0
#!/usr/bin/python
# coding: utf-8
from sys import stdin, stdout

t = int(raw_input())
list = stdin.readlines()
for i in list:
    last = int(i) - 1
    num = last / 3
    tot = (num * (6 + (num - 1) * 3)) / 2
    num = last / 5
    tot += (num * (10 + (num - 1) * 5)) / 2
    num = last / 15
    tot -= (num * (30 + (num - 1) * 15)) / 2
    stdout.write(str(tot) + "\n")
'''

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below N.

Input Format
First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N.

Output Format
For each test case, print an integer that denotes the sum of all the multiples of 3 or 5 below N.

Constraints
1<=T<=10^5
1<=N<=10^9
Exemplo n.º 47
0
from sys import stdin
from itertools import product


def solution(seq1, seq2):
    dp = [[0] * (len(seq2) + 1) for _ in range(len(seq1) + 1)]
    for a, b in product(range(1, len(seq1) + 1), range(1, len(seq2) + 1)):
        if seq1[a - 1] == seq2[b - 1]:
            dp[a][b] = dp[a - 1][b - 1] + 1
        else:
            dp[a][b] = max([dp[a][b - 1], dp[a - 1][b]])
    return dp[-1][-1]


print(solution(*[row.strip() for row in stdin.readlines()]))
"""
AAA
BBAB
"""
"""
aaa
bbbaaaa
"""
"""
bbbaaaa
aaa
"""
Exemplo n.º 48
0
from sys import stdin
from copy import deepcopy
rules = {
    tuple(r[:r.find(' ')].split('/')): r[r.find('=> ') + 3:].strip().split('/')
    for r in [line.strip() for line in stdin.readlines()]
}
for rule in list(rules.keys()):
    r = deepcopy(rule)
    for _ in range(4):
        rules[tuple(v[::-1] for v in r)] = rules[rule]
        r = tuple(''.join(v) for v in zip(*r[::-1]))
        rules[r] = rules[rule]
img = [".#.", "..#", "###"]
for _ in range(5):
    enhanced = []
    div = 2 if len(img[0]) % 2 == 0 else 3
    for x in range(len(img[0]) // div):
        for y in range(len(img) // div):
            p = []
            for yi in range(y * div, (y * div) + div):
                sub = ''
                for xi in range(x * div, (x * div) + div):
                    sub += img[yi][xi]
                p.append(sub)
            p = tuple(p)
            for i, row in enumerate(rules[p]):
                if y * len(rules[p]) + i >= len(enhanced):
                    enhanced.append('')
                enhanced[y * len(rules[p]) + i] += row
    img = enhanced
print(sum(s.count('#') for s in img))
def read_doc():
    from sys import stdin
    return stdin.readlines()
Exemplo n.º 50
0
def read_data():
    return [[int(x) for x in line.split()] for line in stdin.readlines()]
Exemplo n.º 51
0
from sys import stdin

cards = stdin.readlines()[0][:-1]

ts = 0
cs = 0
gs = 0

for a in cards:
    if a == "T":
        ts += 1
    elif a == "C":
        cs += 1
    elif a == "G":
        gs += 1
print(ts**2 + cs**2 + gs**2 + min(ts, cs, gs) * 7)
Exemplo n.º 52
0
#!/usr/bin/env python3

from sys import stdin, stdout
from Bio import Phylo

clades = list(
    Phylo.BaseTree.Clade(name=name) for name in stdin.readline().split())
splits = list(list(int(c) for c in line.strip()) for line in stdin.readlines())


def find_cols_to_unify(splits):
    for split in splits:
        if 2 == sum(split):
            return tuple(i for i, x in enumerate(split) if x == 1)
        elif len(split) - 2 == sum(split):
            return tuple(i for i, x in enumerate(split) if x == 0)
    raise Exception('no cols to unify!', splits)


def print_splits(splits):
    for split in splits:
        print(split)


def print_clades(clades):
    for clade in clades:
        tree = Phylo.BaseTree.Tree.from_clade(clade)
        Phylo.write(tree, stdout, 'newick', plain=True)


while 0 < len(splits):
Exemplo n.º 53
0
from sys import stdin
input = stdin.readline
MIS = lambda: map(int, input().rstrip().split())
MIRS = lambda: map(int, stdin.readlines())

n, m = MIS()
arr = list(MIS())

range_sum = [0] * len(arr)
range_sum[0] = arr[0]
for i in range(1, n):
    range_sum[i] = range_sum[i - 1] + arr[i]

for _ in range(m):
    u, v = MIS()
    u -= 1
    v -= 1
    print(range_sum[v] - range_sum[u - 1] if u - 1 >= 0 else range_sum[v])
Exemplo n.º 54
0
#
#n = stdin.readline()
#[f(int(x)) for x in stdin.readlines()]

# lets optimize this process
# read new value,
# if array doesn't contains copy array to bigger array
#   compute factorial from end of last array to new value
# print factorial 'dynamic programming'
#a = [1]*2
#l = len(a)
#n = stdin.readline()
#for i in stdin.readlines():
#    j = int(i)+1
#    if l < j:
#        a += [0]*(j-l)
#        for k in range(l,j):
#            a[k] = a[k-1]*k
#            l = j
#    s = str(a[j-1])
#    print(s[len(s)-1])

# cheat solution
d = {'0': 1, '1': 1, '2': 2, '3': 6, '4': 4}
n = stdin.readline()
for i in stdin.readlines():
    i = i.rstrip()
    if i in d:
        print(d[i])
    else:
        print(0)
Exemplo n.º 55
0
# Basic Input
# Input: Read a line of input input from STDIN
# Output: string
input_str = input()

# Input: space seperated list of numbers
# Output: an iterable map object of integers
input_list = map(int, input().split())

# Basic Output
# outputs data to STDOUT
# this adds a newline character at the end
print(output_data)

# Input/Output using sys
from sys import stdin, stdout

# Input: a line of input from STDIN
# Output: string
input_str = stdin.readlines()

# Output to STDOUT
# no newline character is added
stdout.write(output_data)
Exemplo n.º 56
0
	h = height(trees)
	current = zeroPos()
	hits = 0
	while(current[1] < len(trees)):
		print(f"{current}: {position(trees, current)}")
		hits += 1 if position(trees, current) else 0
		current = move(current, slope)
	return hits

def parse(line: str) -> List[bool]:
	return [t == '#' for t in line.replace('\n','')]

def part1(trees):
	return part(trees, (3,1))

trees = [parse(l) for l in stdin.readlines()]
slope1 = part(trees, (1,1))
print(slope1)
print("*"*7)
slope2 = part(trees, (3,1))
print(slope2)
print("*"*7)
slope3 = part(trees, (5,1))
print(slope3)
print("*"*7)
slope4 = part(trees, (7,1))
print(slope4)
print("*"*7)
slope5 = part(trees, (1,2))
print(slope5)
print("-"*7)
Exemplo n.º 57
0
            if len(passed) >= L and all(
                (passed[-(i + 1)] == next_seg - 1 for i in range(L))):
                passed.append(road.popleft())
                continue

            # going low
            if len(road) >= L and all(
                (road[i] == last_seg - 1 for i in range(L))):
                for _ in range(L):
                    passed.append(
                        -road.popleft())  # negate to mark bridge built
                continue

            # else, can't build bridge
            break
        else:  # if all road is moved to passed, mark good path
            path_count += 1

    return path_count


N, L = None, None
board = []
for i, row in enumerate(stdin.readlines()):
    if i == 0:
        N, L = (int(c) for c in row.strip().split(' '))
    else:
        board.append([int(c) for c in row.strip().split(' ')])

print(solution(N, L, board))
Exemplo n.º 58
0
from collections import deque
from sys import stdin

index = 0
case = 1
myString = stdin.readlines()

while index < len(myString):
    myCase = myString[index].strip('\n').split()
    myPopulation = int(myCase[0])
    myIteration = int(myCase[1])
    myDeque = deque()

    if myPopulation == 0 and myIteration == 0:
        break

    for num in range(min(myPopulation, 1000)):
        myDeque.append(num + 1)

    print(f'Case {case}:')

    #print(myCase)
    mySeries = myString[index + 1:index + 1 + myIteration]

    for i in mySeries:
        myPatient = i.strip('\n').split()
        #print(caso)
        if len(myPatient) > 1:
            # Lógica para E
            myDeque.appendleft(int(myPatient[1]))
            #myDeque.remove(int(myPatient[1]))
Exemplo n.º 59
0
from collections import deque
from sys import stdin

lines = deque(line.strip() for line in stdin.readlines())


def nextline():
    return lines.popleft()


def types(cast):
    return tuple(int(x) for x in nextline().split())


def ints():
    return types(int)


def strs():
    return nextline().split()


def ishappy(ch):
    return ch == '+'


def main():
    # lines will now contain all of the input's lines in a list
    T = int(nextline())
    for testCase in range(1, T + 1):
        pancakes, K = strs()
Exemplo n.º 60
0
#!/usr/bin/env python3
from sys import stdin


def solve(data):
    mount = [[val[0], int(val[1])] for val in data[1:]]
    sorted_mount = sorted(mount, key=lambda x: x[1], reverse=True)
    print(sorted_mount[1][0])


if __name__ == "__main__":
    # 1行
    # data = list(map(int, stdin.readline().rstrip().split(" ")))
    # data = list(map(str, stdin.readline().rstrip().split(" ")))
    # 複数行
    raw_data = [val.rstrip() for val in stdin.readlines()]
    # data = [list(map(int, val.split(' '))) for val in raw_data]
    data = [list(map(str, val.split(' '))) for val in raw_data]
    solve(data)