text
stringlengths
37
1.41M
def check_rows(board): draw = True for line in board: if line[0] in 'XT' and line[1] in 'XT' and line[2] in 'XT' and line[3] in 'XT': return 'X' if line[0] in 'OT' and line[1] in 'OT' and line[2] in 'OT' and line[3] in 'OT': return 'O' if '.' in line: ...
#!/usr/bin/python import sys,os from math import sqrt, ceil, floor def solve(min, max): """Returns a number[int] of fair and square palindromes between min and max""" num_fair_n_square = 0 sqrt_min = int(ceil(sqrt(min))) sqrt_max = int(floor(sqrt(max))) # for each palindrome between min and sqrt_m...
#returns string: minimum # flips (if possible) # n: pancake sequence (+/-), size of flipper def solve(input): pancakes = input.split()[0] pancakes_list = list(pancakes) size = int(input.split()[1]) result = 0 for i in range(0, (len(pancakes)-(size-1))): if pancakes_list[i] == "-": #flip ...
import math def is_palindrome(n): s = str(n) l_2 = int(len(s)/2) if l_2==0: return True for i in xrange(l_2): if s[i]!=s[-i-1]: return False return True tcases = int(raw_input()) for d in xrange(tcases): bounds = map(int,raw_input().split()) cnt = 0 for n in xrange(1,int(math.ceil(math.sqrt(bounds[1...
def checkBoard(): for i in range(N): for j in range(M): valid = checkSquare(i,j) if not valid: return False return True def checkSquare(i,j): value = board[i][j] rowgood = True colgood = True # Check row for k in range(M): if board[i][k] > value: rowgood = False break...
fin = open('in', 'r') fout = open('out', 'w') numberOfCases = int(fin.readline()) def findChosenRow(): answer = int(fin.readline()) for rowNum in range (1,5): row = fin.readline() if rowNum == answer: cosenRow = row.split() cosenRow = [int(string) for str...
def find_game_state(array): not_completed_possible = False for line in array: player = "" for i, letter in enumerate(line): print "linea ", line if letter == ".": not_completed_possible = True break if letter == "T": ...
infile = raw_input("File: ") lines = open(infile, 'r').readlines() output = open(infile[:-3]+"_solution"+infile[-3:], "w") T = lines.pop(0) counter = 1 for line in lines: numbers = line.split() N = int(numbers.pop(0)) #number of numbers S = int(numbers.pop(0)) #number of surprises p = int(numbers.pop(0)) #number ...
''' @author: Shawn McClelland ''' ### Enter filename for input and output filename = 'A-test' filename = 'A-small-attempt2' filename = 'A-large' file_in = open('%s.in' % filename) #### Get first line of file as number of cases number_cases = int(file_in.readline()) #### Get lists of data for each C...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Google Code Jam 2017. Qualification Round Problem A. Oversized Pancake Flipper * Problem Last year, the Infinite House of Pancakes introduced a new kind of pancake. It has a happy face made of chocolate chips on one side (the "happy side"), and noth...
import math import heapq def topsize(r, h): return math.pi * r * r def ringsize(r, h): return 2 * math.pi * r * h def maximize(pancakes, k, minimum): pq = [] rt, ht = pancakes[minimum] total = topsize(rt, ht) + ringsize(rt, ht) # print "Total for {}: {}".format(minimum, total) for t in...
import sys inpath = sys.argv[1] outpath = sys.argv[2] multiplication = {'1': {'1': '1', 'i': 'i' , 'j': 'j' , 'k': 'k'}, 'i': {'1': 'i', 'i': '-1', 'j': 'k' , 'k': '-j'}, 'j': {'1': 'j', 'i': '-k', 'j': '-1', 'k': 'i'}, 'k': {'1': 'k', 'i': 'j' , 'j': '-i', 'k': '-1'}} def multiply(s1, s2): "...
def flip(p): if p == '+': return '-' return '+' def num_flips(s, k): flips = 0 for i in range(len(s)-k+1): if s[i] == '-': flips += 1 for j in range(i, i+k): s[j] = flip(s[j]) for i in range(k-1): if s[i-k+1] == '-': return 'IMPOSSIBLE' ...
#Author: Parker Olson #Date: 4/13/2012 def main(): number = int(input()) string = input(); trans = translate(string, number); print(trans); def translate(s, n): trans = "" i = 0 count = 1; transStr = [] while i < len(s): u = 0 char = s[i] ...
#!/usr/bin/env python # -*- coding:utf-8 -*- # def readint(): return int(raw_input()) def readfloat(): return float(raw_input()) def readarray(N, foo): res = [] for _ in xrange(N): res.append(foo()) return res def readlinearray(foo): return map(foo, raw_input().split()) #######...
import functools def choosePile(vals): exorVals = functools.reduce(lambda x,y: x^y, vals) if (exorVals != 0 or len(vals)<2): #not possible if odd number of 1s in any column return 'NO' #otherwise give back a candy minVal = min(vals) sumVals = sum(vals) #print (vals) ...
def getInput(path): f = open(path) lines = f.readlines() f.close() return lines def print_ouput(): lines = getInput("./input.txt") no_cases = int(lines[0].strip()) case = 1 while (case<=no_cases): i=(case-1)*10 + 1 answer1 = int(lines[i].strip()) layout1 = [lines[i+1].split(),...
def tiy(num): num1= list(str(num)) num2 = ''.join(sorted(str(num))) if len(num1)==1 or num2 == str(num): return num else: for i in range(len(num1)): comps = int(num1[i]) # print(num1) if i == 0 or nummax <= comps: nummax = comps pos = i elif nummax > comps: for i2 in range(i,len(num1)...
import sys from math import log if (len(sys.argv) != 2): print "Require 1 input file as argument" exit(1) inputFile = open(sys.argv[1]) outputFile = open("output.txt", 'w') N = int(inputFile.readline()) def numDigits(n): return int(round(log(n)/log(10)+0.5)) def toInt(lst): sum = 0 for i in range(len(ls...
#!/usr/bin/env python import math import sys def isPalindrome(n): numString = str(n) length = len(numString) for i in range(length/2): if (numString[i] != numString[-(i+1)]): return False return True fin = open(sys.argv[1], 'r') fout = open(sys.argv[2], 'w') lines = fin.readlines(...
#!/usr/bin/python def mkdir_count(existent, to_create): existent = [tuple(x.split('/')[1:]) for x in existent] to_create = [tuple(x.split('/')[1:]) for x in to_create] q = 0 for full_path in to_create: current_path = () for item in full_path: current_path += (item,) ...
from sys import argv def search(left, m): #print m, left if m <= 3: return m tmp = [] for i in range(m+1): tmp.append(left[i]) tmpm = m #print 'path1' for i in range(1, m): tmp[i] = tmp[i+1] tmp[m] = 0 ans1 = 1+search(tmp, m-1) ans = ans1 tmp = [] for i in range(m+1): tmp.append(left[i]) m = tmpm...
#!/usr/bin/env python import sys file = open(sys.argv[1]) next(file) # Ignore the line because this is python lineno = 1 for line in file: line = line.strip() people, shyness = line.split() # Cast them all to INTs people = int(people) + 1 shyness = map(int, list(shyness)) friends_to_bring = ...
def checkHappy(pancake): if "-" in pancake: return False return True def flipPancake(side): if (side == "-"): return "+" if (side == "+"): return "-" with open('A-large.in') as f: t = int(f.readline()) # read a line with a single integer case = 0 for line in f: case+=1 numFlip = 0 pancakeStr, flip...
#!/usr/bin/env python import sys def cross_wire(A, B): if A[0] < B[0] and A[1] > B[1]: return True if A[0] > B[0] and A[1] < B[1]: return True return False def main(): num = int(sys.stdin.readline().strip()) for i in range(num): wire_num = int(sys.stdin.readline().strip())...
total_test_case = int(raw_input()) for test_case in range(1, total_test_case+1) : s, k = raw_input().split(' ') k = int(k) left = 0 l = len(s) count = 0 impossible = False while left < l : while left < l and s[left] != '-' : left += 1 if left == l : break if left + k > l : impossible = True ...
#! /usr/local/Cellar/python3/3.6.1/bin/python3 nb_tests = int(input()) for t in range(nb_tests): pancakesstr, kstr = input().split() pancakes = list(pancakesstr) k = int(kstr) y = 0 impossible = False for i in range(len(pancakes)): if pancakes[i] == "+": continue y += 1 if i + k > len(pancakes): ...
import sys n = int(input()) def findtidy(num, digit, index): a = int(str(num)[index]) b = int(str(num)[index-1]) while(a < b and a >= 0): a -= 1 num -= 10**digit if digit > 0: num += (10**digit - 1) - num % (10 ** digit) return num def findall(num): l = len(s...
#!/usr/bin/python import sys BOOL_STR_MAP = {True: "YES", False: "NO"} def format_test_case(i, n): return "Case #%i: %s" % (i+1, BOOL_STR_MAP[n]) def get_ints(line): return map(lambda x: int(x), line.strip().split(' ')) def load_lawn(stdin, N, M): lawn = [] for i in xrange(N): lawn.append(g...
# N by N square of cells to place models in # +, x are worth 1 # o is worth 2 # if two models are in same row or column, one must be + # IOW every row/column may have at most one non-+ model # if two models are in same diagonal, one must be x # IOW every diagonal may have at most one non-x model # number of model p...
#!/usr/bin/python # this script is compatible with python 3.4 for N in range(int(input())): max_shyness, audience = input().split() audience = [int(c) for c in audience] added = 0 total = 0 for i in range(len(audience)): # i is shyness level if total < i: # if people with shyness level i won't stand up # ...
T = int(raw_input()) # given a matrix, compute winning percentage # not considering the ignore element def wp(A,team,ignore): wins, losses = 0, 0 resultline = A[team] for team in range(len(resultline)): if team == ignore or resultline[team] == '.': continue if resultline[team] == '1': wins += 1 if ...
from math import log2 from math import floor def read_one(stream, type_to_read=int): return type_to_read(stream.readline().strip()) def read_several(stream, type_to_read=int): return [type_to_read(x) for x in stream.readline().strip().split()] def next(N): if N % 2 == 0: return N//2, N//2 - 1 ...
import fileinput def check_for_tidy(number): tidy = all([int(number[i]) <= int(number[i + 1]) for i in range(len(number) - 1)]) return tidy def make_int(number): return int(number.replace("0","")) def find_last_tidy(number): if check_for_tidy(number): return make_int(number) for i in ran...
#!/usr/bin/env python import sys import string data = open(sys.argv[1],"r").readlines() n = int(data[0]) data = data[1:] def build_solve(): text ="ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv" solv ="our language is impossible ...
input =""" ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv """ output = """ our language is impossible to understand there are twenty six factorial possibilities so it is okay if you want to just give up """ D = {} for x, y in zip(list(in...
#!/usr/bin/env python import math import sys def is_palindrome(a): return str(a) == ''.join(reversed(str(a))) def solve_problem(min_num, max_num): count = 0 for i in xrange(min_num, max_num + 1): if is_palindrome(i): sqrt = math.sqrt(i) if int(sqrt) == sqrt and is_palindr...
INPUT = "numbers.in" OUTPUT = "numbers.out" def check_range(digits, start, stop): for i in range(start, stop): if digits[i] < digits[i + 1]: return False return True def replace_range(digits, value, start, stop): for i in range(start, stop+1): digits[i] = value def solve(N): digits = list(str(N)) digits ...
def contain(matriz, char): for r in matriz: if char in r: return True return False def print_mat(matriz): for r in matriz: print(''.join(r)) def change_direita(matriz, char, r, c): lim = len(matriz[0]) - 1 while c<lim and matriz[r][c+1] == '?': c += 1 ...
#! /usr/bin/python import sys import math def isPalindrome(n): numstr = "%d" % n numstrlen = len(numstr) for idx in range((numstrlen/2)+1): if numstr[idx] != numstr[numstrlen-idx-1]: #print "%d is not palindrome" % n return False #print "%d is palindrome" % n return...
def solve(s): return ''.join(map(inverse.get,s)) examples = \ [ ('a zoo', 'y qee') , ('our language is impossible to understand', 'ejp mysljylc kd kxveddknmc re jsicpdrysi') , ('there are twenty six factorial possibilities', 'rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd') , ('so it is okay if you want to j...
import sys import math def half_floor_as_int(x): return int(math.floor(float(x) / 2)) def half_ceil_as_int(x): return int(math.ceil(float(x) / 2)) def pancake_calc(pancakes, count): m = max(pancakes) if m < 1: return count count += 1 candidates = [pancake_calc(map(lambda x: x - 1...
#!/usr/bin/env python def omit_colon(s): ss = s[0].split(':') s[0] = int(ss[0])*60 + int(ss[1]) ss = s[1].split(':') s[1] = int(ss[0])*60 + int(ss[1]) return s testcases = int(raw_input()) t = 1 while t <= testcases: turn_around_time = int(raw_input()) str = raw_input() ...
#!/usr/bin/env python def main(argv): # Parsing our file assert(len(argv) == 2) fname = argv[1] lines = None with open(fname) as fd: lines = fd.readlines() if not lines: return lines = lines[1:] lines = [line.split() for line in lines if len(line.strip())] for testid...
def getint(): return int(raw_input()) def getlist(): return [float(x) for x in raw_input().split()] def fun(c, f, x, r): a = x/r rc = False if c < x: a1 = c/r a2 = x/(r+f) if (a1+a2) < a: a = a1 rc = True return a, rc de...
#------------------------------------------------------------------------------- # Name: module3 # Purpose: # # Author: kiit # # Created: 10/04/2014 # Copyright: (c) kiit 2014 # Licence: <your licence> #------------------------------------------------------------------------------- def l...
#!/usr/bin/env python # encoding: utf-8 """ SquareTiles.py Created by Graham Dennis on 2011-05-22. Copyright (c) 2011 __MyCompanyName__. All rights reserved. """ import sys def solve(R, C, picture): for r in xrange(R): for c in xrange(C): if picture[r][c] != '#': continue if r == ...
t = int(raw_input()) # read a line with a single integer def is_tidy(num): # checks if the number is tidy istidy = True num_string = str(num) for n in range(0, len(num_string)-1): if int(num_string[n]) > int(num_string[n+1]): istidy = False return istidy for i in xrange(1, t...
import copy import math max_height = 100 def readLineOfInts(fin): return [int(x) for x in fin.readline().strip().split()] def importData(filename): fin = open(filename) cases = int(fin.readline().strip()) lawns = [] for c in range(cases): lawns.append(readLineOfInts(fin)) return lawn...
#!/usr/bin/python3 from sys import argv def process(C, F, X): old_wait_to_farm = 0 if X > C or C <= X/2: per_second = 2 old_wait_time = X / per_second while True: wait_to_farm = C / per_second + old_wait_to_farm per_second += F next_wait_time = X / pe...
# by Enrique Gonzalez (Enriikke) # enjoy! import math # Setup the files here. in_file = '../../../Downloads/C-small-attempt0.in' out_file = 'solution.out' try: in_file = open(in_file, 'r') out_file = open(out_file, 'w') except IOError as e: print e.errno print e.strerror # Quick util function to pri...
import sys def main(): file_name = sys.argv[1] input_file = open(file_name, 'r') output_file = open('output.out', 'w') T = int(input_file.readline()) for i in range(T): if i != 0: temp = input_file.readline() xwon = False owon = False draw = False row_board = [input_file.readline().strip(...
def getAB(string): list = string.split() return (int(list[0]), int(list[1])) def calculateRecycled(string): A,B = getAB(string) pairs = {} for num in range(A,B+1): original = str(num) for digits in range(1,len(original)): newNum = (original[-digits:]+original[:len(original)-digits]) intNum...
def solve(pancakes,spatula): flipcounter = 0 for i in range(len(pancakes)-spatula+1): if not pancakes[i]: pancakes = flip(pancakes,i,i+spatula) flipcounter += 1 if correct(pancakes): return flipcounter else: return -1 def correct(pancakes): for p in pancakes: if not p: return...
def checkOneGame(C,F,X): currentTime = 0. currentRate = 2.0 mini = X/2. while ((currentTime+(C/currentRate)+X/(currentRate+F)) < mini): mini = currentTime+(C/currentRate) + X/(currentRate+F) currentTime = currentTime+(C/currentRate) currentRate += F return str(mini) if __name__ ==...
def prod(a,b): if a=='1': return b elif a=='-1': return '-'+b elif a=='i': if b=='i': return '-1' elif b=='j': return 'k' elif b=='k': return '-j' elif a=='j': if b=='i': return '-k' elif b=='j': return '-1' elif b=='k': return 'i' elif a=='k': if b=='i': return 'j' elif b=...
# This is a standard python library import heapq def parseString(raw, w): count = 0 for elem in raw: if count != 0: w.write('Case #' + str(count) + ': ') temp = list(map(int, elem.split())) w.write(' '.join(map(str, findSeats(temp))) + '\n') count += 1 def findSeats(temp): seats = temp[0] people = t...
import sys from math import sqrt, floor def is_square(n): return sqrt(n).is_integer() def is_palindrome(n): s = str(int(n)) return s == s[::-1] def is_fair_and_square(n): return is_palindrome(n) and is_square(n) and is_palindrome(sqrt(n)) f = open(sys.argv[1]) o = open("out", 'w') cases = int(f.readline()) ...
#!/usr/bin/env python import sys class NameN(object): def __init__(self, name, n): self.name = name self.n = int(n) self.substrings = self.get_substrings() self.match_count = self.get_match_count() def get_match_count(self): count = 0 for element in self.substri...
class TicTacToeTomek(object): def __init__(self, board, players): self.board = board self.both = 'T' self.empty = '.' self.players = players def set_player(self, player): self.player = player def checkwin(self): ''' Checks if the player has won...
test_cases = int(raw_input()) for i in range(test_cases): get_input = raw_input().split(" ") pancakes = list(get_input[0]) k = int(get_input[1]) left_point = 0 count = 0 while left_point <= len(pancakes)-k: if pancakes[left_point] == "+": left_point += 1 else: ...
def read_strings (prompt = ''): return raw_input(prompt).split() def read_ints (prompt = ''): value = map(int, read_strings(prompt)) return value def read_int (prompt = ''): try: value = read_ints(prompt)[0] except: value = None return value def rec_cut (Pi): newPi = [] Pi = Pi max_value = max(Pi) if ...
from sys import argv def flip(c): if c == '+': return '-' else: return '+' def solve(line): pancakes = list(line.split(' ')[0]) width = int(line.split(' ')[1]) flips = 0 for i in range(len(pancakes) - width + 1): if pancakes[i] == '-': pancakes[i:i+width] = [flip(c) for c in pancakes[i:i+...
# -*- coding: utf-8 -*- __author__ = "Sommily" input = """4 132 1000 7 111111111111111110 """ def read_input(): f = open("/Users/Sommily/Downloads/B-small-attempt0.in", 'r') lines = f.readlines() f.close() input = "".join(lines) return input def check(number): number_str = str(number) l...
#!/usr/bin/env python import argparse def get_arguments(): parser = argparse.ArgumentParser() parser.add_argument("--input","-i", help="input file") parser.add_argument("--output","-o") args = parser.parse_args() return args def tidy_num(num): if len(num) == 1: return num nums = lis...
def checkTidy(numLst): lastDigit = 0 for digit in numLst: if digit < lastDigit: return False lastDigit = digit return True def makeList(num): numStr = str(num) numLst = [] for digit in numStr: numLst.append(int(digit)) return numLst def ...
import sys class Point(object): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "(%d, %d)" % (self.x, self.y) def main(file): n_cases = int(file.readline().strip()) for i in range(n_cases): trees = [] n, a, b, c, d, x_0, y_0, m = [int(...
#!/usr/bin/env python #-*- coding: UTF-8 -*- import sys def solve(a, b): intersection = list(set(a) & set(b)) equals = len(intersection) if equals == 0: return 'Volunteer cheated!' elif equals == 1: return str(intersection[0]) return 'Bad magician!' def main(): cas...
def ContainsNonQuestionMarkCharacters(row): for c in row: if c != '?': return True return False def FirstNonQuestionMarkCharacter(row): for c in row: if c != '?': return c def FirstRowWithANonQuestionMarkCharacter(rows): for row in rows: if ...
#! /usr/bin/env python2 # -*- coding: utf-8 -*- import sys def parse_input(filename): """ Parse the input according to the following format #Test cases #Answer to the first arrangement #First Arrangement 4x4 #Answer to the second arrangement #Second Arrangement 4x4 The input may of course have several test ...
def main(): row = input() for i in xrange(1, 5): r = raw_input().split() if i == row: selected1 = r row = input() for i in xrange(1, 5): r = raw_input().split() if i == row: selected2 = r results = set(selected1) & set(selected2) if len(results) == 0: re...
import sys class Trick: def __init__(self): self.has_multiple = False self.has_solution = False self.row1 = [] self.row2 = [] self.solution = 0 def get_row(fin, row_num): for i in range(4): temp = fin.readline() if i == row_num: ...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Finding "fair and square" numbers... Instead of using a naive approach, I directly searched for a more scalable way to find the number of fair and square numbers in a specified interval. Outputing the first fair and square numbers along with their square root shows t...
#!/usr/bin/env python import math T = int(raw_input()) #number of real tests for t in range(1,T+1): A,B = raw_input().split() #read a test case, splot out the needed numbers A = int(A) B = int(B) myxi = B + 1 #to abort the next loop if no squares found ...
#!/usr/bin/env python # coding=utf-8 from __future__ import print_function from sys import stdin, stdout def compute_min(n, p): if n == 0: return 0 if n == 1: return p-1 if 2**n == p: return 2**n - 1 if p <= 2**(n-1): return 0 else: return 2 * compute_min(n-1, p - 2*...
#!/usr/bin/env python2.7 from sys import stdin def reprGrid(g): return '\n'.join([' '.join(map(str, row)) for row in g]) def reprGridMask(g, cells): g = [row[:] for row in g] for (i,j) in cells: g[i][j] = '*' return reprGrid(g) def raiseTest(I, J, g): ''' >>> g=[[2, 1, 2, 1, 2], [1, 1, 1, 1, 1], [2, 1, 2, 1, ...
import sys args = sys.argv if len(args) < 2: print 'small or large?' exit() inp = args[1] out = open(inp + '_OUT', 'w') def float_row(): return map(float, raw_input().split()) # No change before this def solve(): C, F, X = float_row() r = 2.0 T = 0 while X > 0: t1 = X/r ...
#!/usr/bin/env python import copy # # Support Functions # # Determines the maximum value on a list def maxAlongLine( line ): result = line[ 0 ] count = len( line ) for i in range( 1, count ): if line[ i ] > result: result = line[ i ] return result # Places on a single list the values of...
import math def is_square(integer): root = math.sqrt(integer) if int(root) ** 2 == integer: return root else: return False def is_palindrome(number): number = str(number) return number == number[::-1] test_list = [] tmin,tmax = 1000L,0L with open('input.txt','r') as i...
def read_file(): #f = open('C:/Users/Avinash/Desktop/Google codejam 2017/pycharmworks/input2', 'r') # C:\Users\Avinash\Desktop\Google codejam 2017\pycharmworks\AA-small-practice.in f = open('C:/Users/Avinash/Desktop/Google codejam 2017/pycharmworks/B-small-attempt2.in', 'r') # f = open('C:/Users/Avi...
#!/usr/bin/python import math import sys testCase = 1 with open(sys.argv[1]) as f: f.readline() for line in f: AB = line.split(' ') A=int(AB[0]) B=math.sqrt(int(AB[1])) i=1 no=0 while i <= B: i_reversed = int(str(i)[::-1]) if i == i_reversed: s = i**2 if s >= A: s_reversed = int(str(s...
from math import sqrt from math import pow def solve(P,K,L,fr): #print "solve",P,K,L,fr; fr.sort(); fr.reverse(); rez=0; press=1; cnt=0; for key in fr: if (press>P): rez=-1; break; rez+=key*press; cnt+=1; if (cnt % ...
#!/usr/bin/env python # coding: utf-8 d = {'a': 'y', 'c': 'e', 'b': 'h', 'e': 'o', 'd': 's', 'g': 'v', 'f': 'c', 'i': 'd', 'h': 'x', 'k': 'i', 'j': 'u', 'm': 'l', 'l': 'g', 'o': 'k', 'n': 'b', 'p': 'r', 's': 'n', 'r': 't', 'u': 'j', 't': 'w', 'w': 'f', 'v': 'p', 'y': 'a', 'x': 'm', 'q': 'z', 'z': 'q', ' ': ' '} def d...
import math def is_palindrome(number): numstr = str(number) return numstr == numstr[::-1] cases = int(raw_input()) for case in xrange(cases): A, B = map(int, raw_input().split()) count = 0 for number in xrange(int(math.ceil(math.sqrt(A))), int(math.sqrt(B))+1): if not is_palindrome(number...
# /usr/bin/env python # -*- coding: utf8 -*- IMP = "IMPOSSIBLE" HAPPY = "+" BLANK = "-" def convert_row_to_int(row): return [1 if p == HAPPY else -1 for p in row] def convert_int_to_row(int_row): return "".join([HAPPY if p == 1 else BLANK for p in int_row]) class PancakeRow: __slot...
def function1(nstalls, npeople): stalls = [nstalls] # if npeople == nstalls or npeople == nstalls - 1: if npeople == nstalls: return [0, 0] else: while npeople > 0: stalls.sort() npeople -= 1 if stalls[-1] % 2 == 1: temp1 = (stalls[-1] ...
import sys import itertools def reducestring(instring): retstring = str() retstring += instring[0] count = 1 while count <= len(instring) - 1: if instring[count-1] != instring[count]: retstring += instring[count] count += 1 return retstring ##def reducetoma...
#!/usr/bin/env python from collections import deque def solve_test(num_runs, coaster_length, num_groups, groups): #print groups money_made = 0 # Do one run for i in range(num_runs): #print "Run: %s" % i # Reset for this run space_left = coaster_length stop = False ...
from sys import stdin #import math def find_next(list, color): try: return [y[0] for y in list].index(color) except: return -1 def move(current, goal): if current > goal: return -1 elif current < goal: return 1 else: return 0 f = open('outputA.txt', 'w') case = 1 firstLine...
INPUT_FILE = "test_input.in" class Found(Exception): pass def generate(case_file): n_cases = int(case_file.readline()) boards = [] for n_boards in range(n_cases): board = [] for i in range(4): tmp_line = [] tmp_line = list(case_file.readline().strip()) board.append(tmp_l...
from sys import stdin def main(): firstline = stdin.readline().split() length = int(firstline[0]) numberOfWords = int(firstline[1]) testCases = int(firstline[2]) words = [] testWords = [] for i in xrange(0,numberOfWords): words.append(stdin.readline().strip()) for i in xra...
import math T = int(input()) def findGaps(bathroom): gaps = [] occupied = [] for i in range(0,len(bathroom)): if bathroom[i]==0: occupied.append(i) for i in range(len(occupied)-1): gaps.append([occupied[i]+1, occupied[i+1]-1]) return gaps def findStall(bathroom): ga...
#!/usr/bin/env python import argparse def is_tidy(n): n = str(n) for i in range(1, len(n)): if int(n[i]) < int(n[i-1]): return False return True def next_tidy(n): if is_tidy(n): return n n = list(str(n)) for i in reversed(range(1, len(n))): if int(n[i]) < ...
import string T = input() def isPalindrome(word): for i in xrange(len(word)): if word[i] != word[len(word)-i-1]: return False return True def isPerfectFairSquare(x): ans = 0 if x >= 0: while ans*ans < x: ans = ans + 1 if ans*ans != x: # this if statement was nested inside the while...
#Pancake Flipping def to_list(string): l = [] for i in string: if i == "+": l.append(True) elif i == "-": l.append(False) return l def main(): t = int(input()) cases = [] for c in range(t): temp = input() pancakes = [] ...
#!/usr/bin/env python3 """ Tidy Numbers problem for Google Code Jam 2017 Qualification Round Link to problem description: https://code.google.com/codejam/contest/3264486/dashboard#s=p1 Author: Chris Nitsas (nitsas) Language: Python 3(.5) Date: April, 2017 Usage: python3 runme.py input_file """ import s...
#!/usr/bin/python #-*- coding: utf-8 -*- ''' Template for Google Code Jam ''' import sys def main(): ''' main ''' case_num = int(sys.stdin.readline()) for i in range(1, case_num+1): line = sys.stdin.readline().rstrip() args = line.split(' ') row = int(args[0]) col = int(ar...
# -*- coding: utf-8 -*- """ Created on Sat Apr 8 14:16:47 2017 @author: Sebastian """ def swap(i,K,line): if i + K > len(line): print("Wrong arguments") line = list(line) for j in range(i,i+K): if line[j] == '-': line[j] = '+' elif line[j] == '+': ...
def last_tidy(N): while N >= 1: if is_tidy(N): return N N -= 1 return None def is_tidy(x): digits = str(x) last_number = None for n in digits: if last_number is None: last_number = n elif n >= last_number: last_nu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 8 11:20:24 2017 @author: rcuriel Problem B. Tidy Numbers """ def finding_Tidy(n): TidyNumber = -1 nAux = int(n) isTidy = True for i in range(nAux,0,-1): nx = str(i) for j in range(len(nx)-1): if (nx[j] ...