text
stringlengths
37
1.41M
#!/usr/bin/env python3 """ Typewriter Monkey problem for Google Code Jam 2015 Round 1C Link to problem description: https://code.google.com/codejam/contest/4244486/dashboard#s=p1 Author: Chris Nitsas (nitsas) Language: Python 3(.4) Date: May, 2015 Usage: python3 runme.py input_file """ import sys impo...
def execute_case(): num_row, num_col = [int(token) for token in raw_input().split()] table = [[int(cell) for cell in raw_input().split()] for i in range(num_row)] max_of_rows = [max(row) for row in table] max_of_cols = [max(col) for col in zip(*table)] for i in range(num_row): for j in range(num_col...
import os import time import decimal import functools #=============================================================================== # Generic helpers #=============================================================================== # TODO FOR 14 : rounding functions, graph manipulation, desert lion, AttrDict...
#!/usr/bin/python3 # Strategies: # 0. Sort both lists of block weights # Deceitful War: # 1. Walk through her own blocks from the lightest to the heaviest one # 2. If the block is lighter than the lightest one from Ken, Naomi will tell a weight slightly lower than Ken's biggest one. So Ken wins, but he loses his heavie...
#!/usr/bin/python from sys import stdin, stderr def solve(num_senators): parties = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' parties1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' assert parties == parties1 pair_list = [] for i, num in enumerate(num_senators): pair_list.append([num, parties[i]]) result = [] while True: if l...
#!/usr/bin/env python3 import sys import itertools def best_result(num_kids, bffs): kids = range(num_kids) best_so_far = 0 for circle_size in range(2, num_kids + 1): for combo in itertools.combinations(kids, circle_size): for perm in itertools.permutations(combo): if ...
class Parties: def __init__(self, parties): self.parties = parties self.count = 0 for i in xrange(len(self.parties)): self.count += self.parties[i] def find_largest(self): max_i = -1 max_val = -1 for i in xrange(len(self.parties)): if self.parties[i] > max_val: max_i = i max_val = self.par...
import sys def isPalindrome(n): return str(n)[::-1] == str(n) def palindromes(upperLength): palsByLength = [] palsByLength.append([]) # length 0 palsByLength.append(range(1, 10)) # length 1 (note that we skip 0) for length in range(len(palsByLength), upperLength + 1): prevPals = palsByLength[leng...
#!/usr/bin/env python def read(): row, col = map(int, raw_input().split()) board = [] for i in range(row): board.append(map(int, raw_input().split())) return board def work(board, cases): row, col = len(board), len(board[0]) cur = [[100 for j in range(col)] for i in range(col)] ...
# usage: (py3 a.py < a.in) > a.out import time, sys, inspect, math lineno = lambda: inspect.currentframe().f_back.f_back.f_lineno print = lambda *a, **k: __builtins__.print(str(lineno())+":", *a, file=sys.stderr, **k) map = lambda *a: list(__builtins__.map(*a)) #--------------------------------------------- """ is...
import math def betterRange(minimum, maximum): while minimum < maximum: yield minimum minimum += 1 def reverseNumber(n, partial=0): if n == 0: return partial return reverseNumber(n / 10, partial * 10 + n % 10) def isPalindrome (num): return num == reverseN...
import sys, string import time def readlist(): return [int(x) for x in sys.stdin.readline().strip().split(" ")] def readint(): return int(sys.stdin.readline()) def expand(seq, orig_seq): new = "" for ch in seq: if ch == "G": new += "G" * len(orig_seq) else: new += or...
import sys mul_dict = { '11':'1', 'i1':'i', 'j1':'j', 'k1':'k', '1i':'i', '1j':'j', '1k':'k', 'ii':'-1', 'ij':'k', 'ik':'-j', 'ji':'-k', 'jj':'-1', 'jk':'i', 'ki':'j', 'kj':'-i', 'kk':'-1', } def negate(val): if val[:1] == '-' : return val[-1:] else : return "-"+val def m...
import math import sys def print_ans(case_num,solution): print("Case #"+str(case_num)+":"), print_solution(solution) def print_solution(solution): """TO DO""" print solution def input_processor(filename): f=open(filename) data=f.read().split("\n") case_nums=int(data[0]) """Insert num...
#!/usr/bin/env python3 ################################################################################ def read_int(): return int(input()) def read_words(): return input().split() def parse(f): return [f(x) for x in read_words()] def read_ints(): return parse(int) def read_floats(): retur...
from sys import stdin from math import sqrt from math import ceil def palindrome(start, stop): if stop < 10: for i in xrange(int(ceil(sqrt(start))), int(sqrt(stop))+1): yield i*i else: for i in xrange(int(ceil(sqrt(start))), 10): yield i*i done = False i = 1 ...
import math fn = "sample.in" debug = False def primeDivisor(n): if n < 3: return 0 s = int(math.sqrt(n)) for i in range(2, s + 1): if n % i == 0: return i pass return 0 def process(N, J): print('Case #1:') for x in xrange(2 ** (N - 1) + 1, 2 ** N): ...
import sys alphabet = set("abcdefghijklmnopqrstuvwxyz") assert len(alphabet) == 26 vowels = set("aeiou") consonants = alphabet - vowels def hasNConsonants(s, n): for start in range(len(s)): substr = s[start:start+n] if len(substr) < n: continue hasEm = all( c in consonants for c in subs...
# Time to verify some jamcoins! :) import fileinput def convert_to_bitstring(value): """ Converts an integer to a base 2 bitstring. param: value, a positive value to convert to bitstring. """ #Oh boy does this feel sketchy. bin_string = bin(value) #this starts with 0b... converted...
cases = int(raw_input()) for case in range(1, cases + 1): answer = int(raw_input()) for i in range(1, 5): line = raw_input() if i == answer: valid = set(map(int, line.split())) answer = int(raw_input()) for i in range(1, 5): line = raw_input() if i == answer: ...
import sys def prework(argv): '''do something according to argv, return a message describing what have been done.''' return "nothing" def readline(fun) : return [fun(_) for _ in input().split()] def once(): '''to cope once''' r, c, N = [int(x) for x in input().split()] worst =...
#!/usr/bin/python """ Note this is assuming scores are all valid, of course """ def ispossible(points, best): if points < best + max(best - 2, 0) * 2: # Never possible for this score to have a best score >= "best" # because this is the lowest possible score needed for that. return -1 # Now check if it...
def oddForced(p): t = 0 f = 0 while (p % 3 == 0): p /= 3 t += 1 while (p % 5 == 0): p /= 5 f += 1 return [t, f] def evenForced(p): if p == 6: return [0, 3] if p == 5: return [1, 2] return [0, 0] def forced(p): odd = p even = 0 while (odd % 2 == 0): odd /= 2 even +...
def getDimList(X): return [(w, X-w+1) for w in range(1,(X+1)/2+1)] def WorstBlockWillCutBoardInHalf(X, R, C): # If the worst block will fit, you still need to see if it's going to cut the board in half in a bad way # The main example of this is the case where you use an S-shaped piece and you have a 2...
def checkCells(cell, N, M): for row in range(N): for column in range(M): possibility = True for j in range(M): if cell[row][j] > cell[row][column]: possibility = False break if possibility == True: continue possibility = True for i in range(N): if cell[i][column] > cell[row][colu...
#!/usr/bin/env python import sys from copy import deepcopy def draw(board): print_click = True for r in board: for c in r: if print_click: print_click = False print 'c', continue if c == 2: print '*', else: print '.', print def stats(board): lu...
#!/usr/bin/python import sys def find_last(letters): outw = letters.pop(0) for letter in letters: if letter >= outw[0]: outw = letter + outw else: outw += letter return outw with open(sys.argv[1], 'r') as f: cases = int(f.readline()) for case in range(cases...
#!/usr/bin/python from sys import stdin, stderr from math import sqrt from pprint import pprint def readiline(): return map(int, stdin.readline().strip().split() ) def small(x,y): ans = '' if x > 0: ans += 'WE' * abs(x) if x < 0: ans += 'EW' * abs(x) if y > 0: ans += 'SN' * abs(y) if y < 0: ans += 'NS...
#!/usr/bin/python def readline( f ): line = f.readline(); line = line[:-1] return line def read_integer( f ): line = readline( f ) return int( line ) def read_integer_list( f ): line = readline( f ) integers = line.split( " " ) for i in range( len( integers ) ): integers[i] = int( integers[i] ) return i...
import math ''' def miller_rabin(n): if n <=2: if n == 2: return True return False if n % 2 == 0: return False u = n - 1 # u is the exponent while u % 2 == 0: u /= 2 a16_list = [2,3,5,7,11,13,17,19,23] a25_list = [2,3,5,7,11,13,17,19,23,29,31,37,4...
from math import gcd from random import randint def st(n): t = n-1 s = 0 while t % 2 == 0: t = int(t/2) s += 1 return s,t def pseudoprime(n,s,t,b): if abs(pow(b,t,n)) == 1: return True for r in range(s): if abs(pow(b,2**r*t,n)) == -1: return True return False def n...
#python 2.7 import sys import math import string import time #https://stackoverflow.com/questions/2267362/convert-integer-to-a-string-in-a-given-numeric-base-in-python digs = string.digits + string.letters def int2base(x, base): if x < 0: sign = -1 elif x == 0: return digs[0] else: sign = 1 x *= sign digit...
# raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end. # This is all you need for most Google Code Jam problems. t = int(input()) # read a line with a single integer for i in range(1, t + 1): # read a list of integers, 2 in this case K, C ,S = [int(s) for s in input().split...
import heapq def gcd(*numbers): """Return the greatest common divisor of the given integers""" from fractions import gcd return reduce(gcd, numbers) def lcm(*numbers): """Return lowest common multiple.""" def lcm(a, b): return (a * b) // gcd(a, b) return reduce(lcm, nu...
def calc_ranges(base, complexity): r = [0] pr = 1 for x in xrange(complexity): pr *= base r.append(pr) return r # def get_position(ranges, check_stack): # pos = 0 # for i in check_stack: # pos += ranges[i-1]*(i-1) # return pos def get_position(ranges,count, check_stack): if count == 1: ...
import sys from itertools import * def concat_str(args): s = "" for arg in args: s += str(arg) return s def debug(*args): sys.stderr.write(concat_str(args) + "\n") def printf(*args): debug(*args) print concat_str(args) def int_input(): return map(int, raw_input().split(' ')) ##...
def colourRest(board, N, R, C): for i in range(2, R): for j in range(2, C): if N <= 0: return board[i][j] = '.' N -= 1 for t in range(1,int(input())+1): R, C, M = map(int,input().split()) N = R * C - M print('Case #{0}:'.format(t)) rotate = Fal...
# Python 3.2 from common import * def first_bigger(x, y, first): n = len(x) for i in range(first + 1, n): if x[i] == -1: x[i] = 0 if y[i] == -1: y[i] = 9 i = first while i >= 0: if x[i] != -1 and y[i] != -1 and x[i] > y[i]: for j in range(0...
#!/usr/bin/env python import sys case_num = 1 def printres(result): global case_num print "Case #%s: %s" % (case_num, result) case_num += 1 def readline(): return sys.stdin.readline().rstrip('\n') def splitline(f): return map(f, readline().split()) def calc(t1, t2, tree): x1, y1 = t1 x2,...
def scoreMulti(rows, columns, width): total = 0 while rows > 1: rows -= 1 target = columns while target > 1: total += 1 target -= width total += score(1, columns, width) return total def score(rows, columns, width): if width == 1: return rows ...
# Written in Python 3.3 import math import sys import random def bin2val(b,N): r = 0 for ii in b: r = N*r if (ii=='1'): r += 1 return r def convert2bin(N): a='' while (N>0): if (N%2 == 0): a='0'+a else: a='1'+...
import os import sys from sets import Set def main(): if len(sys.argv) != 2: print 'usage: a.py <input_file>' sys.exit(1) with open(sys.argv[1], 'r') as f, open('res', 'w') as out: [count] = map(int, f.readline().split()) for i in xrange(count): [N, J] = map(int, f...
#!/usr/bin/env python import sys T = int(sys.stdin.readline()) for case in range(1,T +1): row = int(sys.stdin.readline()) for i in range(1,5): line = sys.stdin.readline() if i == row: candidates = [int(x) for x in line.split(" ")] row2 = int(sys.stdin.readline()) for i in ...
from collections import Counter def get_num_keys_in_chest(chest, my_keys, key_used): num_keys = 0 if key_used in chest['keys']: num_keys = num_keys + 1 for k in chest['keys']: if k not in my_keys: num_keys = num_keys + 1 return num_keys num_test_cases = int(raw_input()) + 1 for i in xrange(...
sample = """ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv """ hint = """our language is impossible to understand there are twenty six factorial possibilities so it is okay if you want to just give up """ m = {"q":"z", "z":"q...
#!/usr/bin/python3 def is_fair(n): s = str(n) l = len(s) // 2 return s[:l]==s[:-l-1:-1] def bruteforce(N): """ Return all the palindromic square numbers below N """ n = 1 s = 1 res = [1] while s<N: s += 2*n + 1 n += 1 # Check if n and s are fair ...
#!/usr/bin/env python import sys import math testcases = int(input()) for testcase in range(testcases): print('Case #{}: '.format(testcase+1), end='') r, t = [int(x) for x in input().split()] r += 1 # r is the first big radius, t is mL of paint. lo = 0 hi = 10**20 while lo+1 < hi: n...
for case in range(1, int(input())+1): N = int(input()) if N == 0: result = "INSOMNIA" else: current = N digits = {1,2,3,4,5,6,7,8,9,0} while len(digits) > 0: analyze = current while analyze > 0: (analyze, last) = divmod(analyze, 10) if (last) in digits: digits.remove(last) ...
import time def isPrime(n): if n == 1: return False else: for i in range(2,n): if n%i==0: return False return True def factor(n): if isPrime(n)==False: for i in range(2,n): if n%i==0: ...
f=open("input") ff=open("output", "w") readint=lambda :int(f.readline()) readintarray=lambda :map(int, f.readline().split()) T=readint() def slow(r,t): s=n=0 while True: s += 2*(r+2*n) +1 if s<=t: n+=1 else: return n def isqrt(x): if x < 0: raise Val...
import fileinput import logging logging.basicConfig(level=logging.DEBUG) def find_answer(k, c, s): ''' Find the answer for this question ''' logging.debug('k = %d, c = %d, s = %d' % (k, c, s)) if c == 1: if s < k: return None elif k == 1: return [1] else: return range(1, k+1, 1) e...
#!/usr/bin/env python3 # coding=utf-8 """ Problem 2 for Google CodeJam 2014, Round 1B Author: A. Ayala killerrex@gmail.com """ import sys from itertools import product def naive(A, B, K): """ Brute force solution, counting """ t = 0 for a,b in product(range(A), range(B)): if a & b < K: ...
def problem(inPath, outDir = ""): def solve(inPath, processor, outDir = ""): from multiprocessing import Pool from os import path inf = open(inPath, 'rU') stem = path.basename(inPath) name, extension = path.splitext(stem) outName = name + ".out" outP...
#!/usr/bin/python import math import string import sys FREE = 'T' EMPTY = '.' def isWinningFour(arr, c): for x in arr: if x != c and x != FREE: return False return True def checkWin(board, c): for i in range(4): # Check i-th row and i-th column row = [ x for x in boar...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys testcase = input() for q in xrange(testcase): line = raw_input().split(' ') N = int(line[0]) M = int(line[1]) #print ( N , M ) board = [] myboard = [] ways = [] for n in xrange(N) : b = [] myb = [] line = raw_input().split(' ') for m in xran...
import math import sys def print_ans(case_num,solution): print("Case #"+str(case_num)+":"), print_solution(solution) def print_solution(solution): """TO DO""" print solution def input_processor(filename): f=open(filename) data=f.read().split("\n") case_nums=int(data[0]) """Insert num...
#!/usr/bin/env python2.7 -u import math def isPrime(n): if n <= 1: return False, -1 for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False, i return True, -1 print 'Case #1:' res_c = 0 for n in range(int('1'+'0'*14+'1',2),int('1'*16, 2) + 1): n_str...
import math def is_palindrome(x): s = str(x) for i in range(len(s)): if s[i] != s[len(s)-i-1]: return False return True T=int(raw_input()) # print "T",T for t in range(T): # print t A, B = raw_input().split(' ') A, B = int(A), int(B) # print A,B a = int(math.ceil(math.sqrt(A))) b = int(math.floor(mat...
FILENAME = "A-small-attempt0" INPUTFILE = FILENAME + ".in" OUTPUTFILE = FILENAME + ".out" LINE_PER_CASE = 1 inputfile = open(INPUTFILE, 'r') outputfile = open(OUTPUTFILE, 'w') NUMCASE = int(inputfile.readline()) class TestCase: def find_num_line(self): if LINE_PER_CASE: return LINE...
import sys def memoize(f): """ Memoization decorator for functions taking one or more arguments. """ class memodict(dict): def __init__(self, f): self.f = f def __call__(self, *args): return self[args] def __missing__(self, key): ret = self[key] = self...
"""Python2- and Python3-compatible. That's all.""" from time import clock from sys import argv #import math #import itertools #import numpy def read(f): return next(f).strip("\n") def read_singles(f): # returns chars of a word # or digits (as strings) of an int return list(read(f)) def read_i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- numbers = [-1] f = open('C-numbers.txt') for l in f: numbers.append(int(l)) f.close() def max_not_greater(p): s = 0 e = len(numbers) while True: h = (s + e) // 2 if numbers[h] <= p < numbers[h + 1]: return h elif numbers[h] > p: e = h elif p >= numbers[h +...
from functools import * import math def end(t): print('Case #' + str(t) + ': ', end='') def north(): print('SN', end='') def south(): print('NS', end='') def east(): print('WE', end='') def west(): print('EW', end='') testcases = int(input()) for tc in range(1, testcases + 1): x,y = [int(x) for x in inpu...
from Queue import Queue def isGoalState(state,X,Y): x = state[0][0] y = state[0][1] #print x,y if x == X and y == Y: #print state return True else: return False def getSuccessors(state): x = state[0][0] y = state[0][1] succ...
import math def isprime(number, base): i = 2 #print(number, i) while i*i <= int(number,base): #print(i*i) #if base == 8 and i == 32833: # print("8", i) if int(number,base) % i == 0: return i i += 1 return True def isprimeallbases(number): out...
from math import sqrt import primes def isPrime(n, base): val = 0 exponent = 1 for i in n[::-1]: val += i*exponent exponent *= base maxPrime = int(sqrt(val)) for p in primes.primeList: if p > maxPrime: break if val%p == 0: return False,p ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import sys def read_tests(instance_file): with open(instance_file) as f: n = int(f.next().strip('\n')) for _ in range(n): _, s_str = f.next().strip('\n').split(' ') s = [int(c) for c in s_str] yield s def solve_in...
#!/usr/bin/env python import sys input_file = open(sys.argv[1]) no_cases = int(input_file.next()) def solve(board, N, M): for y, row in enumerate(board): for x, col in enumerate(row): ok = True for nx in xrange(M): if board[y][nx] > col: ok = Fa...
# fair 2nd attemtp dynamic programming class palindrome(object): def __init__(self,a,n): self.a = a self.n = n def isrev(x,n): rev=0 a=x for k in range(0,n) : t=x%10 #if (t>3) : return 0 rev*=10 rev+=t x/=10 if rev==a: return 1 else: return 0 def check( a, ...
#0 mod 3 #0,0,0 (+0) #0,1,2 (s,+1) #1 mod 3 #0,0,1 (+1) #0,2,2 (s,+1) #2 mod 3 #0,0,2 (s,+2) #0,1,1 (+1) #Being suprising always increase the score for case in range(input()): print "Case #"+str(case+1)+":", inp=map(int,raw_input().split()) S=inp[1] p=inp[2] totals=inp[3:] passed=0 borde...
import sys import itertools import math import collections def area(r, i): return 2*i*i + 2*r*i - i def test(r, i, t): return area(r, i) <= t def find_num_circles(r, t): a = 1 while test(r, 2*a, t): a*=2 b = 2*a while a+1<b: half = math.ceil((a+b)/2.0) ...
def read_case(): return raw_input() def solve(case): result = case[0] for c in case[1:]: if c >= result[0]: result = c + result else: result = result + c return result T = int(raw_input()) for t in range(T): case = read_case() result = solve(case) pr...
#!/usr/bin/env python from __future__ import print_function import sys letters = "abcdefghijklmnopqrstuvwxyz" googlerese = ["ejp mysljylc kd kxveddknmc re jsicpdrysi", "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd", "de kr kd eoya kw aej tysr re ujdr lkgc jv"] english = ["our language is imp...
import sys def base_to_10(num, base): num_10 = 0 for i in range(len(num)): num_10 += num[len(num)-i-1] * (base ** i) return num_10 def find_divisor(num): if num % 2 == 0: return 2 for d in range(3, int(num ** 0.5) + 1, 2): if num % d == 0: return d return False def to_binary(k, n): b = [0] * n i = 0...
NUMBERS = ("ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE") def match(x, X): x = '0' * (len(X) - len(x)) + x for l1, l2 in zip(x, X): if l2 != '?' and l1 != l2: return False return True def replace(string, index, num): assert string[index] == '?' ...
import itertools def convex_hull(points): """Computes the convex hull of a set of 2D points. Input: an iterable sequence of (x, y) pairs representing the points. Output: a list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically smallest co...
import sys def d(*args): sys.stderr.write(', '.join(map(str, args)) + "\n") def printf(*args): print ''.join(map(str, args)) def int_input(): return map(int, raw_input().split(' ')) def float_input(): return map(float, raw_input().split(' ')) def solve(c, f, x): currentTime = 0 n = 0 wh...
from time import clock from sys import argv #import math #import itertools #import numpy def read(f): return next(f).strip("\n") def read_singles(f): # returns chars of a word # or digits (as strings) of an int return list(read(f)) def read_int(f, b=10): return int(read(f), b) def read_float(f):...
import sys ECHO_ON = True def writeline(output, line): if ECHO_ON: print(line) output.write(line + '\n') def getCharMatrix(input, R): matrix = [] for i in range(R): line = input.readline().strip() matrix.append(line) return matrix; def getIntMatrix(input): line = input.readline().strip(...
def simulate(farms): time = 0 rate = 2 while farms: time += c / rate rate += f farms -= 1 return time + x / rate for TC in range(1, int(raw_input())+1): c, f, x = map(float, raw_input().split()) fastest = x / 2 farms = 1 while True: time = ...
def check(n, path): #print "path to", n, ": ", path parents = classes[n-1] for parent in parents: if parent == -1: continue if parent in path: #print "FOUND", path return True else: path.append(parent) #print "adding", paren...
if __name__ == "__main__": known_words = [("ejp mysljylc kd kxveddknmc re jsicpdrysi", "our language is impossible to understand"), ("rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd","there are twenty six factorial possibilities"), ("de kr kd eoya kw aej tysr re ujdr lkgc jv","so ...
#!/usr/bin/env python import sys def read_test_case(f): # read board and following empty line board = [f.readline().strip() for i in range(4)] assert not f.readline().strip(), "Each test case is followed by an empty line." return board def analyze_quad(s): for player in ['X', 'O']: if s.count(player) ==...
import math def cost(c,f,x,i): res = x/(2+i*f) #print res for j in xrange(i): #print c/(2+j*f) res+= c/(2+j*f) return res cases = int(raw_input()) for count in xrange(cases): c,f,x = map(float,raw_input().split()) i = math.ceil(x/c - 2/f - 1) if i<0: i=0 #print...
#!/usr/bin/python def solve(): (c,f,x) = raw_input().split() c,f,x = float(c),float(f),float(x) rate = 2.0 time_spend = 0.0 while True: time_without = x/rate time_with = c/rate + x/(rate+f) if time_without <= time_with: return time_spend + time_without time_spend += c/rate rate += f ...
def primes(n): sieve = [True for i in range(int(n))] for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i] = [False for i in range(int((n-i*i-1)/(2*i))+1)] return [2] + [i for i in range(3,n,2) if sieve[i]] primeslist = primes(2**16) def tran(num, base): number = 0 n...
from math import sqrt def is_prime(val): if val == 1: return False if val % 2 == 0: return False for d in range(3, int(sqrt(val)) + 1, 2): if val % d == 0: return False return True def verify(val): #print(bin(val)[2:]) divisors = [] for base in range(2, 11): x...
import unittest,sys, re from collections import deque from decimal import * def getProblemAnswer(S): print S positionX = 0 positionY = 0 pogo = 0 goalX = int(S.split(' ')[0]) goalY = int(S.split(' ')[1]) path = '' direction = '' while(positionX != goalX or positionY != goalY): ...
from itertools import product from math import sqrt def smallest_divisor(n): for i in range(2, int(sqrt(n))+1): if n%i == 0: return i return -1 N = 16 J = 50 inner_len = N-2 results = {} for inside in product("01", repeat=inner_len): n = '1'+''.join(inside)+'1' divisors = [] ma...
#!/usr/bin/env python # -*- coding: utf-8 -*- def read(f): n = int(f.readline().strip()) for i in xrange(n): board = [list(f.readline().strip()) for j in xrange(4)] yield board # skip empty line f.readline() def get_lines(board): for row in board: yield row for ...
#!/usr/bin/env python # > import sys def work2(cols, rows, ship): count = 0 if cols == ship: return rows - 1 + cols elif ship == 1: return cols * rows elif cols > ship: per_row = cols / ship # print "cols %d / ship %d / per_row %d " % (cols, ship, per_row) coun...
#Henry Maltby #Code Jam 2016 def rank_file(lines): """ Determines which elements are missing from the table my inspecting parity. Because each row and each column is sorted, the missing row or column is precisely these missing elements, sorted. """ intset = set() for line in lines: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Problem B. Cookie Clicker Alpha Confused? Read the quick-start guide. Small input 8 points You may try multiple times, with penalties for wrong submissions. Large input 11 points You must solve the small input first. You have 8 minutes to solve 1 input file. (Judged af...
def dig(a): if not a: return 0 s = set() while a: s.add(a%10) a//=10 return s def f(a): if not a: return s = set() b = a while len(s) < 10: s |= dig(b) if len(s) == 10: return b b += a N = int(input()) for i in range(N): a = ...
import math palin_cache = {} def with_cache(fn): def wrapper(N): try: return palin_cache[N] except KeyError: r = fn(N) palin_cache[N] = r return r return wrapper @with_cache def get_palins(N): """ get palins for N digits """ if N == 1: ...
#!/usr/bin/python cache = {} def rotate(number): saved = str(number) number = str(number) if number in cache: return cache[number] rotations = set() for i in range(len(number)): number = number[1:] + number[0] rotations.add(int(number)) cache[saved] = frozenset(rotations) return rotations def rot...
# coding: utf-8 import sys def search(graph,flag,p): if flags[p]==True: return True flags[p] = True result = False for i in range(len(graph[p])): result |= search(graph,flag,graph[p][i]-1) return result if __name__=='__main__': T = int(sys.stdin.readline()) for tc in range(T): N = int(sys....
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created on Sat Apr 12 05:41:34 2014 # @author: Danilo J. S. Bellini """ Minesweeper Master """ import sys if sys.version_info.major >= 3: zip = lambda *args, **kwargs: list(zip(*args, **kwargs)) def minesweeper(R, C, M): if R > C: return ["".join(col) for col i...
import argparse from collections import defaultdict def solve(board): ''' Returns the solution ''' x_lens = defaultdict(lambda: (0,0,0,0)) o_lens = defaultdict(lambda: (0,0,0,0)) draw = True for y in range(4): for x in range(4): if board[y][x] == 'X': x_u...
''' Created on Apr 9, 2016 @author: fernandomendez Fractil problem ''' import argparse import sys import math def generate_powers (base, compexity): pows = dict() pows[0] = 1 for idx in range(compexity): pows[idx+1] = pows[idx]*base return pows def complete_powers (pows, compexity): base ...