text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# Google CodeJam Assignment A
def robotsQualify(steps, script):
#location and target
robots = {'B' : [1], 'O' : [1]}
seconds = 0
#load targets
order = []
for robot, target in script:
robots[robot].append(target)
order.append(robot)
time = 0
whil... |
t = int(raw_input()) # read a line with a single integer
def isTidy(x):
while x > 0:
if x % 10 < x / 10 % 10:
return False
x /= 10
return True
for i in xrange(1, t + 1):
n = int(raw_input())
while not isTidy(n):
n -= 1
print "Case #{}: {}".format(i... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# google code jam - c.durr - 2014
# Tic-Tac-Toe-Tomek
# recherche. Mon idée: utiliser la recherche de chaine dans une autre.
def readInts(): return [int(i) for i in raw_input().split()]
def solve(G):
S = ""
for i in range(4):
S += G[i]+"|"
for j in ra... |
#!/usr/bin/python
import sys
def RF(numbers_str):
return [float(x) for x in numbers_str]
def Clicker(C,F,X):
s = 2.0
t = 0.0
while X/s > C/s + X/(s+F) :
t+= C/s
s+=F
t += X/s
return t
def main():
T = int(sys.stdin.readline().strip())
for i in range(T):
s = sys.stdin.readline()
numbers_str = s.spli... |
#!/usr/bin/env python
from __future__ import print_function
import sys
with open(sys.argv[1]) as f:
for case in range(1, int(f.readline().strip()) + 1):
cake = []
for line in range(int(f.readline().strip().split()[0])):
cake.append([l if l != '?' else '' for l in f.readline().strip()])
print('Case #%s:' % c... |
global flipcounter
def flip(line,start,k):
global flipcounter
for t in range(k):
if(line[start + t]) == '+':
line[start + t] = '-'
else:
line[start + t] = '+'
flipcounter= flipcounter +1
def myfunc(line,k):
global flipcounter
flipcount... |
def gcd(a,b):
if b==0:
return a
return gcd(b,a%b)
def lcm(a,b):
return a*b/gcd(a,b)
def lcm_l(l):
return reduce(lcm,l)
def find_best(otherfreq,L,H):
"""find a number in range L..H which divides every number in otherfreq"""
for x in range(L,H+1):
done=True
... |
#!/usr/bin/python
import sys
def readints(f):
return [int(s) for s in f.readline().split()]
def readint(f):
return int(f.readline())
def readmatrix(f, rows):
matrix = []
for i in xrange(rows):
matrix += [readints(f)]
return matrix
class memoized(object):
"""Decorato... |
## Question 1 Ovation
num_of_case = int(raw_input())
def do(data):
current = 0
addition = 0
for i in range(len(data)):
if i == 0:
current += data[i]
else:
if data[i] == 0:
continue
if current >= i:
current += data[i]
... |
import sys
import os.path
def main(lines):
it = iter(lines)
n_cases = int(next(it))
case = 0
for line in it:
case += 1
args = [int(x) for x in line.split()]
print "Case #%d:" % case
sol = solve(*args)
print sol,
if sol == "Impossible\n":
# ... |
# -*- coding: utf-8 -*-
"""
Google Code Jam 2009
Qualification B
Watersheds
"""
# --- constants ---
North = 4
West = 3
East = 2
South = 1
Sink = -1
Labels = "abcdefghijklmnopqrstuvwxyz"
tmplabels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# --- modules ---
import sys
# --- func ---
def cell_flow(map,h,w,H,W):
# get the cell ha... |
def pancakes(S, k, f, acc):
acc.append(S)
listS = list(S)
flips = f
min_flips = "IMPOSSIBLE"
if check_pancake(S):
return 0
for i in range(len(S)):
if S[i] == '-':
for j in range(k):
flip_t = flip_pancake(i - j, k, S)
if check_pancake(flip_t):
... |
#!/usr/bin/env python
from sys import argv
def bot_time(seq):
time = 0
total = 0
last_robot = None
pos = {'O' : 1, 'B': 1}
for robot,button in seq:
diff = button - pos[robot]
robot_changed = last_robot and last_robot != robot
# Update last robot color
last_robot = ... |
#!/usr/bin/env python
## File: Problem_A.py
## Author: Yunqi Zhang
## Email: yunqi@umich.edu
def get_content(file_path):
fp = open(file_path)
content = []
for line in fp:
content.append(line)
return content
def main():
content = get_content("QA_input.txt")
# Number of cases
number_of_cases = int(con... |
def generic_function(n):
val = int(n)
while val > 0:
newVal = check(val)
if newVal[0]:
return val
val = newVal[1]
return val
def check(i):
i = list(str(i))
loc = -1
for a, b in zip(i[:-1], i[1:]):
loc += 1
if int(a) > int... |
def readlines(fileName):
fh = open(fileName, "rb")
return [line for line in fh]
def ezprint(results, outputFile):
with open(outputFile, "wb") as fh:
for i, result in enumerate(results):
print >> fh, "Case #" + str(i+1) + ": " + result
def getnums(line):
return [int(num) f... |
#!/usr/bin/env python
infile = "A-small-attempt0.in"
ROWS_PER_TEST = 4
def make_guess(before, after):
before_row = before['rows'][before['answer']-1]
after_row = after['rows'][after['answer']-1]
intersect = list(set(before_row) & set(after_row))
if len(intersect) == 0:
return 'Volunteer cheated!'
elif ... |
import os
import sys
import itertools
def output_format(string_number,test_case):
output = "Case #%d:" % (test_case+1)
output += " %s" % str(string_number)
output +="\n"
return output
def to_digits(s):
return [int(d) for d in str(s)][::-1]
def to_str(l):
s = ""
for d in l:
s+= st... |
#!/bin/env python
# -*- coding: utf-8 -*-
'''Python for Google Code Jam 2008 Qualification Round, Saving The Universe
Problem
The urban legend goes that if you go to the Google homepage and search for
"Google", the universe will implode. We have a secret to share... It is true!
Please don't try it, or tell anyone. Al... |
def input():
filename="B-small-attempt1.in"
infile=open(filename,"r")
num_cases=int(infile.readline())
print num_cases,"cases"
count=0
cases=[]
for line in infile:
count+=1
case=[]
for i in line.split():
case.append(int(i))
cases.append(case)
... |
import os
def reader(file):
f_out = file[:-2] + "out"
if os.path.isfile(f_out):
with open(f_out, 'w') as f: # clear the output file
f.write('')
with open(file, 'r') as f:
T = int(f.readline())
for t in range(T):
line = f.readline()
s... |
#! /usr/bin/env python
T = int(raw_input())
t = 1
while t <= T:
a = int(raw_input())
i = 0
while i < a-1:
raw_input()
i += 1
r1 = set(raw_input().split(" "))
while i < 3:
raw_input()
i += 1
a = int(raw_input())
i = 0
while i < a-1:
raw_input()
... |
#!/usr/bin/env python
def int2bin(n, count=30):
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)])
def snap(n,k):
output=int2bin(k)
output=output[-n:]
#print output
for i in xrange(0,len(output)):
if output[i]=='0':
return 'OFF'
return 'ON... |
#!/usr/bin/env python
def print_solution((w, h), img):
for y in xrange(h):
for x in xrange(w):
c = img[y][x] == img[y+1][x] == img[y][x+1] == img[y+1][x+1] == '#'
if c:
img[y][x], img[y+1][x], img[y][x+1], img[y+1][x+1] = '/', '\\', '\\', '/'
f = lambda a: '... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
def solve(ans_1, board_1, ans_2, board_2):
# print ans_1
# print board_1
# print ans_2
# print board_2
row_1 = board_1[ans_1-1]
row_2 = board_2[ans_2-1]
set_row_1 = set(row_1)
set_row_2 = set(row_2)
intersection = set_row_1 & set_row_2
... |
def simplify(N):
for number in range(len(N)-1):
if int(N[-(number+1)]) < int(N[-(number+2)]):
nines = ""
for i in range(number+1):
nines += "9"
return simplify(N[:-(number+2)] + str(int(N[-(number+2)]) - 1) + nines)
return N
TestCases = int(i... |
#!/usr/bin/env python
from sys import stdin
class Responder:
def __init__(self):
self.answer_no = 1
def write(self, answer):
print "Case #{}: {}".format(self.answer_no, answer)
self.answer_no += 1
def get_max(portion):
return 0 if not portion else max(portion)
def column(lawn, col):... |
#!/usr/bin/env python
import collections
import itertools
import sys
def is_surprising(score):
for pair in itertools.combinations(score, 2):
if abs(pair[0] - pair[1]) > 1:
return True
return False
def number_of_surprising(scores):
return sum(1 for score in scores if is_surprising(scor... |
#!/usr/bin/env python3
count = int(input())
for x in range(1,count+1):
row_ind = int(input())
for i in range(1,5):
if i == row_ind:
row_1 = input().split()
else:
input()
row_ind = int(input())
for i in range(1,5):
if i == row_ind:
row_2 = inpu... |
# 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.
def rev(cakes,pan):
for i in range(1,pan+1):
if cakes[-i]=='+':
cakes[-i]='-'
else:
cakes[-i]='+'
return cakes
T = int(r... |
#!/usr/bin/python3
from sys import argv
def answer(c,f,x):
seconds = 0
cookieRate = 2
best = float('inf')
while True:
# Could finish at this time without buying more farms
couldFinish = seconds + x / cookieRate
if best > couldFinish:
best = couldFinish
else:... |
#!/usr/bin/env python
import sys
T = int(sys.stdin.readline())
def convert(lines, r, c):
try:
if lines[r][c] == '#' and lines[r][c+1] == '#' and lines[r+1][c] == '#' and lines[r+1][c+1] == '#':
lines[r][c] = '/'
lines[r][c+1] = '\\'
lines[r+1][c] = '\\'
lines[r+1][c+1] = '/'
return True
except Exc... |
def checkRight(lawnLst, i, j, height, width, dist):
#print 'width', width
#print 'dist', dist, 'j + dist', j + dist, 'width - 1', width - 1
if j + dist > width - 1:
#print 'Right true i', i, 'j', j, 'dist', dist
return True
elif lawnLst[i][j] >= lawnLst[i][j + dist]:
return checkRight(lawnLst, i, j, height, w... |
def listvalid(list):
if len(list) < 2:
return True
else:
return list[-1] < list[-2]
def solve(cases, inFile, outputFile):
for c in xrange(1, cases + 1):
outputFile.write("Case #" + str(c) + ": ")
farmcost, rateincr, goal = tuple(map(float, inFile.readline().split())... |
import sys
def magic(number):
return int(''.join(str(i) for i in number))
# 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.
nbrlines = int(input())
for k in range(nbrlines):
t = input()
data = [int(i) for i in t]
... |
encrypted = """
ejp mysljylc kd kxveddknmc re jsicpdrysi
rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd
de kr kd eoya kw aej tysr re ujdr lkgc jv
y qee
"""
plain = """
our language is impossible to understand
there are twenty six factorial possibilities
so it is okay if you want to just give up
a zoo
"""
alpha = set("abc... |
#coding:utf8
def main():
cases = int(raw_input())
for i in range(cases):
inp = raw_input().split(" ")
text = inp[0]
k = int(inp[1])
print "Case #" + str(i+1)+": " + str(algorithm(text,k))
def format(input):
lis = [a for a in input]
return lis
de... |
out1 = '''Case #1: our language is impossible to understand
Case #2: there are twenty six factorial possibilities
Case #3: so it is okay if you want to just give up'''
in1 = '''ejp mysljylc kd kxveddknmc re jsicpdrysi
rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd
de kr kd eoya kw aej tysr re ujdr lkgc jv'''
in... |
def is_tidy(number):
return sorted(number) == number
T = int(input())
for i in range(T):
N = input()
number = list(map(int, N))
N = int(N)
res = []
while not is_tidy(number):
number[-1] = 9
number[-2] -= 1
res.append(number[-1])
del number[-1]
number += res
print('Case #'... |
import math
import codejam
problems = (map(int, line.split()) for line in codejam.read())
def area(radius):
return math.pi * (radius ** 2)
def size_needed(current_radius):
return area(current_radius) - area(current_radius - 1)
def s(r):
return 2 * r + 1
def solve(r, t):
current_radius = r
n... |
#!/usr/bin/python
import sys, os, math
def print_usage():
print "Usage: fair_and_square.py <input file>"
def is_palindrome(num):
num_str = str(num)
for i in range(len(num_str)/2):
if num_str[i] != num_str[len(num_str) - 1 - i]:
return False
return True
def num_fair_and_square_in_range(start, end):... |
#!/usr/bin/env python
import sys
def main():
L, D, N = [int(v) for v in sys.stdin.readline().strip().split()]
words = [
sys.stdin.readline().strip() for i in range(D)
]
patterns = [
sys.stdin.readline().strip() for i in range(N)
]
test_case = 1
for pattern in patterns:
... |
from sys import stdin
input_it = iter(stdin)
T = int(input_it.next())
for t in range(T):
# interpret input
# N: number of strings
# strings: list of strings
N = int(input_it.next())
strings = []
for n in range(N):
strings.append(input_it.next().rstrip())
# characters: string o... |
fname = input ("Enter the name of input file(in quotes):") #Input the name of input file here
fin = open(fname, 'r')
fout = open('out.txt','w')
a=int(fin.readline()) #read no of test case
def move(i,f,t):
if i<f:
if i+t<f:
return i+t
else:
return f
else:
... |
def get_starting_tidy_substr_index(number_str):
index = 0
last_tidy_digit = int(number_str[index])
for index in range(1, len(number_str)):
if int(number_str[index]) >= last_tidy_digit:
last_tidy_digit = int(number_str[index])
else:
return index - 1
return index
... |
import sys
def ReadFile(filename):
file = open(filename)
n = int(file.readline())
for case in range(1,n+1):
board = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
for row in range(0,4):
newrow = file.readline()
for i in range(0,4):
board[row][i] ... |
#!/usr/bin/python
import sys
def numBits(num):
return bin(num).count("1")
# returns a string left padded with zeros
def convertToBinaryString(i, length):
return format(i, '0'+str(length) + 'b')
def toggleSwitches(inputOutlets, switches, constN, constL):
switches = convertToBinaryString(switches,constL)
switch... |
t = int(raw_input())
def checkTidy(x):
str_x = str(x)
for i in range(len(str_x) - 1):
if int(str_x[i]) > int(str_x[i + 1]):
return False
return True
def getTidy(n):
while n > 9:
if checkTidy(n):
return n
n = n - 1
return n
for i in range(t):
n = long(raw_input())
print("Case #" + str(... |
def work_out_time(orange_order, blue_order, button_order):
time = 0
orange_place = 1
blue_place = 1
while not button_order == []:
orange_push = False
# Check if orange is at place
if not orange_order == []:
if not orange_place == orange_order[0]:
if o... |
#!/usr/bin/env python
import os
import sys
import math
if len(sys.argv) < 2:
sys.exit(0)
fin = open(sys.argv[1], "rb")
lines = fin.readlines()
fin.close()
numtest = int(lines[0])
def CheckSqrt(num):
sq = math.sqrt(num)
if sq % 1 == 0:
return True
return False
def C... |
#!/usr/bin/python
# Constants definition
MINFLOAT = 1e-6
def isEqual(float_a, float_b):
if abs(float(float_a) - float(float_b)) < MINFLOAT: return True
else: return False
for case in xrange(input()):
company = []
changes = 0
for i in xrange(input()):
company.append(raw_input())
available = company[:]
f... |
#!/usr/bin/python
import sys
from math import sqrt
cache = {}
def is_possible(vines, cur_vine, cur_height, D, indent):
global cache
#print "cur",indent, cur_vine, cur_height
cur_d = vines[cur_vine][0]
if cur_d + cur_height >= D:
return True
if cur_vine in cache and cache[cur_vine] >= cur... |
from math import pi
def syrup(L):
m = 0
# we try every potential first pancake
for i in range(len(L)):
tmp = list(L)
surface = pi * tmp[i][0] * tmp[i][0] + 2 * pi * tmp[i][0] * tmp[i][1]
tmp.pop(i)
# we keep the best pancakes
LS = list(reversed(sorted(tmp, key=lam... |
import sys
def main(raw_data):
data = []
for line in raw_data:
data.append(line.strip())
recycled_dict = {}
checked_lengths = set()
T = data.pop(0)
for i in range(int(T)):
start, end = data.pop(0).split(' ')
#print start, end
if len(start) not i... |
def last_tidy_number(N):
s = str(N)
# list of characters in string
L = list(s)
numDigits = len(L)
i = 0
while i<numDigits-1 and L[i] <= L[i+1]:
i += 1
# if our index is at last digit
if i == numDigits-1:
return N
while i > 0 and L[i-1] == L[i]:
i -= 1
L[i] = chr(ord(L[i])-1)
for i in range(i+1, nu... |
# Lawnmower
# Conjecture: for every element suffices to test if we can "go all the way through" in one direction
import math
import sys
import itertools
with open(sys.argv[1], 'r') as f:
n = int(f.readline().strip())
for i in range(n):
l = f.readline().strip().split()
rows = int(l[0])
cols = int(l[1])
R = ... |
i = 0
t = 0
x = 0
def converting_numbers(my_list):
z = []
for word in my_list:
z.append(int(word))
return z
def comparing_numbers(a, b):
z = list(set(a).intersection(b))
if len(z) == 1:
return str(z[0])
elif len(z) > 1:
c = "Bad magician!"
return c... |
"""
Author: Greg Harfst (gharfst@gmail.com)
Date: 9/3/2009
Notes:
Problem
After years of study, scientists at Google Labs have discovered an
alien language transmitted from a faraway planet. The alien language
is very unique in that every word consists of exactly L lowercase
letters. Also, there are exactly D words... |
__author__ = 'jamesbutler'
def calculate_friends_needed(max_shyness, shyness_levels):
friends_needed = 0
audience_members_clapping = 0
for i in range(len(shyness_levels)):
if audience_members_clapping <= i:
difference = i - audience_members_clapping
friends_needed += differ... |
import sys
inp = sys.stdin.read().split("\n")
cases = int(inp.pop(0))
def best(rate, boost, goal, cost):
waitprice = goal/rate
buyprice = cost / rate
if waitprice < buyprice + goal / (rate+boost):
return waitprice
return buyprice + best(rate + boost, boost, goal, cost)
for case in range(case... |
#!/usr/bin/env python
# 2014 Matej Pavla
# This file is part of QaSys
import os, sys, getopt
import subprocess
if __name__ == '__main__': #if we run the program from command line
file = open('input.in')
string = file.readline()
total_number = int(string)
for i in range(0, total_number):
first_row_selected =... |
def solveboard(board):
complete = True
# do bfs and mark explored spots
# CHECK ROWS
i,j=0,0
for i in xrange(4):
#first row
letter = None
for j in xrange(4):
if board[i][j] == '.':
complete = False
if letter == None a... |
def people_standing(audience):
standing = 0
for shyness_level, number_of_people in enumerate(audience):
if shyness_level <= standing:
standing += int(number_of_people)
return standing
def add_friends(audience):
audience = list(audience)
audience[0] = str(int(audience[0]) + 1)
return "".join(audience)
N = i... |
# coding: utf8
import os, sys, re, string
class Robot:
def __init__(self, stack):
self.stack = stack
self.pos = 1
self.index = 0
self.size = len(stack)
self.time = 0
def is_end(self):
return self.index >= self.size
def target(self, v):
return self.index < self.size and self.stack[self.index][0] ==... |
#!/usr/bin/env python
import sys
def iterate_input():
t = int(sys.stdin.readline())
for i in range(t):
line = sys.stdin.readline().split(' ')
n, s, p = map(int, line[0:3])
total_points = map(int, line[3:3+n])
yield i+1, s, p, total_points
def all_combinations():
combinatio... |
import math
def ispalindrome(x):
if x[::-1] == x:
return True
else:
return False
def nextsquare(low,high):
squarenum = long(math.ceil(math.sqrt(low))**2)
yield long(squarenum)
lastodd = 1+(long(math.sqrt(squarenum))-1)*2
nextnum = long(squarenum)
lastodd+=2
while (nextnu... |
#!/usr/bin/env python
from collections import defaultdict
def has_opposed(opposed, elist, element):
return bool(set(elist) & opposed[element])
def invoke(combining, opposed, string):
element_list = []
#print '===', string
for element in string:
#print ''.join(element_list)
last_two ... |
def show(i, score, ret):
print "Case #%s: %s %s" % (i, score, len(ret))
for x, y, symbol in ret:
print "%s %s %s" % (symbol, x + 1, y + 1)
def show_board(board):
print
print "The board:"
for row in board:
print "".join(row)
print
def sol_small(board):
# show_board(board)... |
# Rob Record 2012
# Fair and Square
from math import sqrt, modf
def is_palindrome(to_eval):
return str(to_eval) == str(to_eval)[::-1]
def top_square(bottom, top):
while top >= bottom:
if modf(sqrt(top))[0] == 0:
return top
else:
top -= 1
def bottom_square(bottom,... |
def check_win(board,sym):
for i in xrange(4):
won=True
for j in xrange(4):
if board[i][j]!=sym and board[i][j]!='T':
won=False
break
if won:
return True
won=True
for j in xrange(4):
if board[j][i]!=sym and board[j][i]!='T':
won=False
break
... |
#!/usr/bin/python
import sys
from operator import itemgetter
def factorial( n ):
if n == 0:
return 1
else:
return n*factorial(n-1)
def nchoosek( n, k ):
#return factorial(n)/(factorial(k)*factorial(n-k))
answer = 1
for i in range(1,k+1):
answer *= (n - (k - i))
an... |
import sys
def find_primes(n):
"""Generate a list of the prime numbers [2, 3, ... m] where
m is the largest prime <= n."""
n = n + 1
sieve = range(n)
sieve[:2] = [0, 0]
for i in xrange(2, int(n**0.5)+1):
if sieve[i]:
for j in xrange(i**2, n, i):
sieve[j] = 0
... |
#!/usr/bin/env python
def process_file(file):
fsock = open(file)
text = fsock.read()
fsock.close()
lines = text.split('\n')
return lines
def process_lines(lines):
ans = []
first = True
numCases = int(lines[0])
lineIndex = 1
for caseIndex in range(numCases):
case = []
... |
import sys
f = open(sys.argv[1], 'r')
T = int(f.readline())
def isgood(x, numbers):
for n in numbers:
if x > n:
if x % n != 0:
return False
elif x < n:
if n % x != 0:
return False
return True
for t in xrange(T):
N, L, H = [int(x) for x in f.readline().strip().split(' ')]
... |
import math, code
fair_list = {}
def is_fair(i):
if i in fair_list:
return True
if(i%1 != 0):
return False
i = int(i)
string = str(i)
length = len(string)
for i in range(length/2):
if(string[i] != string[length-i-1]):
return False
fair_list[i] = 1
return True
def is_square(i):
return is_fair(math.... |
def get_case(case):
pancakes = case.split()[0]
flipper_size = int(case.split()[1])
min_flips = 0
for i in range(len(pancakes) - flipper_size + 1):
if pancakes[i] == '-':
pancakes = flip_stack(pancakes, flipper_size, i)
min_flips += 1
if pancakes.find('-') == -... |
class Robot(object):
def __init__(self):
self.pos = 1
def move(self, n, button):
for i in range(n):
if self.pos > button:
self.pos -= 1
if self.pos < button:
self.pos += 1
f = open('A-large.in')
of = open('A-large.out', 'w')
... |
def count(symbol,array):
cnt=0
for i in array:
if i==symbol:
cnt+=1
return cnt
def rowCheck(matrix):
winr="D"
for i in range(0,4):
row=[matrix[i][0],matrix[i][1],matrix[i][2],matrix[i][3]]
if count("X",row)+count("T",row)==4:
winr="X"
retu... |
# 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.
def alphabet_cake(matrix, R, C):
alphabet_dict = {} # alphabet: (row_low, row_high, column_low, column_high)
for i in xrange(R):
for j in xrange(C):
... |
def is_palindrome(num):
strnum = str(num)
numlen = len(strnum)
for i in xrange(numlen / 2):
if strnum[i] != strnum[numlen-1-i]:
return 0
return 1
n = input()
for i in xrange(n):
line = raw_input().split(' ')
min = int(line[0])
max = int(line[1])... |
#!/bin/env python3
import sys
import os
def doChallenge(_input_filename):
try:
with open(_input_filename, 'r') as f:
lines = f.read().split('\n')
except FileNotFoundError:
print("Input file '" + _input_filename + "' not found !")
sys.exit()
except PermissionError:
... |
def main():
num_cases = int(input())
for case_num in range(num_cases):
inp = input().split(' ')
num_rows = int(inp[0])
num_cols = int(inp[1])
grid = []
for row_num in range(num_rows):
grid.append(list(input()))
for row_num in range(num_r... |
import random
import math
import time
def check(circles):
for i in range(len(circles)):
for j in range(len(circles)):
if i!=j :
a = circles[i]
b = circles[j]
if math.sqrt((a[0]-b[0])**2 +(a[1]-b[1])**2) <= a[2]+b[2]:
return Fals... |
'''3-2-1-3'''
def solve(line):
count = 0
(N, suprise, par) = line.split(' ')[0:3]
scores = line.split(' ')[3:]
par = int(par)
suprise = int(suprise)
# print 'scores' + str(scores)
# print 'surpris' + str(suprise)
# print 'par' + str(par)
for s in scores:
if in... |
import heapq
def getMinMax(k):
if k%2 == 0:
return (k/2, (k/2) -1)
else:
return ((k-1)/2,(k-1)/2)
def bathroom(n,k):
myMax, myMin = getMinMax(n)
if k == 1:
return (myMax, myMin)
q = [myMax, myMin]
count = 0
while True:
curr = q.pop(0)
count += 1
#left
leftMax, leftMin = getMinMax(curr)
if coun... |
#!/usr/bin/env python
# google code jam 2015 -- standing ovation solution
#
# this will just print to stdout; should redirect into file for upload
def main():
"""Main function"""
import sys
with open(sys.argv[1]) as input_file:
cases = input_file.readline()
for x in range(int(cases)):
... |
# 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.
def ask1(n,m):
#print(n)
cnt=0
for i in range(0,len(n)):
#print(n)
if n[i]=="-" and i>len(n)-m:
return "IMPOSSIBLE"
elif n[i]=="-":
cnt+=1
fo... |
def calSpeed(totald, travelled, speed):
distance=float(totald-travelled)
time=distance/speed
newspeed=totald/time
return newspeed
def compareSpeed():
tests = input("")
#print tests
for test in range(tests):
totald, horses = [int(s) for s in raw_input().split(" ")]
minSpeed= 10000
for ... |
consec_cache = {}
def consec(N, F, T):
if N==0: return 1
elif N==1: return T-F-1
else:
global consec_cache
if not (N,F,T) in consec_cache:
s = 0
for k in xrange(F+1,T-1):
s += consec(N-1, k, T)
consec_cache[(N,F,T)] = s
return consec_cache[(N,F,T)]
# To N, starting with S
def calc(N,S):
if N==S:... |
def split_pattern(pattern):
while len(pattern)>0:
if pattern.startswith("("):
count = pattern.find(")")-1
yield pattern[1:1+count]
pattern = pattern[count+2:]
else:
yield pattern[0]
pattern = pattern[1:]
def does_pattern_match(pattern, wo... |
#python
#prima donna
#from decimal import *
infile="A-small-attempt0.in" #prima.in"#"B-large-practice.in"
#clears outfile.txt
outfileFlush=open("outfile.txt", "w")
outfileFlush.write("")
outfileFlush.close()
def writeout(answer,x):
#converts query from main loop (which is the answer list - ie place in list of items t... |
#!/usr/bin/python
import string, sys
height = 0
width = 0
map = []
result = []
next_char = ''
def map_get(p):
global map
return map[p[0]][p[1]]
def result_get(p):
global result
return result[p[0]][p[1]]
def mark(y, x):
global map, height, width, next_char, result
lowest_coord = (y,... |
import fileinput
def flip_with_flipper(S, k, index):
for i in xrange(k):
if S[index + i] == "-":
S[index + i] = "+"
else:
S[index + i] = "-"
def solve(k):
answer = ""
repeat_count = 1 # Used for counting how much back update I need in case of lower digit
... |
#-------------------------------------------------------------------------------
# Name: ??????1
# Purpose:
#
# Author: myegor
#
# Created: 07.05.2011
# Copyright: (c) myegor 2011
# Licence: <your licence>
#-------------------------------------------------------------------------------
#... |
class Basin(object):
def __init__(self,elevation):
self.parent = self
self.label = None
self.elevation = elevation
self.n = None
self.s = None
self.e = None
self.w = None
def __str__(self):
return self.getLabel()
def sink(self):
return ... |
"""Google codejam"""
def annie_speed(destination):
"""Annie's speed"""
start, speed = [int(x) for x in input().split()]
return destination/((destination - start)/speed)
def main():
"""Main Method"""
cases = int(input())
for case in range(1, cases+1):
destination, num_horses = tuple(int... |
##################################
## solve magic trick problem ##
## the logic is to find the ##
## intersection of the 2 rows ##
## if it returns 1 element ##
## then that is the solution ##
## if it returns more than 1 ##
## element then bad magician ##
## if it returns 0 element ##
## then user cheated ... |
#!/usr/bin/python
rawInput = raw_input()
L = int(rawInput.split(" ")[0])
D = int(rawInput.split(" ")[1])
N = int(rawInput.split(" ")[2])
dictionary = []
chkInput = []
finalResult = []
finalIndex = 0
inOrOut = 0
count = 0
for i in range(0,D):
dictionary.append(raw_input().split('\n')[0])
for i in range(0,N):
chkIn... |
def heightValid(board):
height = len(board)
width = len(board[0])
for i in range(height):
for j in range(width):
if not (highInRow(board, i, j) or highInCol(board, i, j)):
return False
return True
def highInRow(board, i, j):
height = board[i][j]
for w in rang... |
import sys
def solver(smax, s, count, add):
while len(s) > 0:
shyness = smax - len(s) + 1
diff = shyness - count
if diff > 0:
add += diff
count += diff
count += int(s[0])
s = s[1:]
return add
if __name__ == '__main__':
argvs = sys.argv
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.