text stringlengths 37 1.41M |
|---|
#!/usr/bin/python
#-----------------------------------------------------
# check the input number is tidy by comparing each
# digit to it predecessor and making sure its larger
def isTidy(string):
number_of_digits = len(string)
last_digit = -1
for digit in string:
digit_int = int(digit)
i... |
# 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 c in range(1, t + 1):
n, m = input().split(" ") # read a list of integers, 2 in this case
k = int(m)
possible... |
#!/usr/bin/env python
#import numpy as np
import sys, os
import math
import itertools
class Robot(object):
pos = 1
def __init__(self, color, iterable):
self.it = itertools.ifilter(lambda x: x[0] == color, iterable)
self.color = color
try:
self.next_pos = self.it.next()[1]
except StopIteration:
self.n... |
import math
import sys
def read_cases(f):
f.readline()
tmp = read_case(f)
while tmp:
yield tmp
tmp = read_case(f)
def read_case(f):
params = f.readline()
if not params:
return None
return [int(x) for x in params.strip().split()]
def palindrome(x):
strx = str(x)
... |
#!/usr/bin/python3
import sys
fileName = sys.argv[1]
print(fileName)
inputFile = open(fileName, 'r')
lines = inputFile.readlines()
inputFile.close()
def isTidyNum(n):
numStr = str(n)
for i in range(0, len(numStr)-1):
if numStr[i] > numStr[i+1]:
return False
return True
skip = True
cou... |
#!/usr/bin/env python
import sys
import math
def recycle(x, B):
num_digits = int(math.log(x, 10))+1
num = x
result = set([])
for i in range(num_digits-1):
num = (num // 10) + ((num % 10) * (10**(num_digits-1)))
if num > x and num <= B:
result.add(num)
return len(result)
... |
def test_sort_small(data):
while ''.join(sorted(str(data))) != str(data):
data -= 1
return data
def test_sort_large(data):
res = [0]
err = False
for val in list(str(data)):
val = int(val)
if err is False and val >= res[-1]:
res.append(val)
elif err:
... |
import sys
def is_non_descending(number):
digits = []
if number < 10:
return True
while (number != 0):
digits.append(number % 10)
number /= 10
digits.reverse()
# print digits
for i in xrange(len(digits)):
for j in xrange(i, len(digits)):
# print "COM... |
import sys
def possible_numbers(field, choice, prev_numbers=[]):
if prev_numbers:
return list(filter(lambda x: x in prev_numbers, field[choice]))
else:
return field[choice]
if __name__ == '__main__':
f = open(sys.argv[1], 'r')
cases = int(f.readline())
for i in range(c... |
#!/usr/bin/env python
def isCircle(a, b):
a = str(a)
b = str(b)
for i in range(1, len(a)):
j = len(a) - i
if a[:i] == b[-i:] and a[-j:] == b[:j]:
return True
return False
n = int(raw_input())
for i in range(0, n):
(a, b) = [int(j) for j in raw_input().split()]
count = 0
for j in range(a, b):
for k in ... |
height_min = 1
height_max = 100
def main():
numCases = input()
for case in xrange(1, numCases+1):
rows, cols = input_line(int)
this, currMin, currMax = get_case(rows)
while min(min(this)) == currMin and currMin < currMax:
validrows = list(find_rows(this, currMin, rows))
validcols = list(fi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Usage: python run.py < A-small-practice.in > result.txt
def solve(c,f,x):
nf = 0
tinvest = 0
while (True):
tx = x / (2 + nf * f)
t = tinvest + tx;
#print("Nf=%i, Time Invested=%.5f, Time To X With Farms=%.5f, Total=%.5f" % (nf, tinvest, tx, t))... |
import fileinput
from queue import Queue
def flip(S):
def opposite(e):
if e == '+':
return '-'
else:
return '+'
return ''.join([opposite(s) for s in S ])
def neighbours(S, K):
n = []
for i in range(len(S) - K + 1):
n.append(S[:i] + flip(S[i: i + K]) +... |
def is_palindrome(n, partial=0):
if n == 0:
return partial
return is_palindrome(n / 10, partial * 10 + n % 10)
def is_fair_and_square(apositiveint):
if apositiveint ==1 or apositiveint==0:
return True
x = apositiveint // 2
seen = set([x])
while x * x != apositiveint:
x ... |
from math import *
from collections import Counter
from time import time
import itertools as it
''' gcd INT A, INT B --> INT C : C is the greatest common divisor of A and B '''
def gcd(a,b): return a if b==0 else gcd(b, a%b)
''' lcm INT A, INT B --> INT C : C is the lowest common multiple of A and B '''
def lcm(a,b)... |
#!/usr/bin/env python2
# by Santiago Saavedra
from math import sqrt, floor, ceil
def is_palindrome(x):
if type(x) is not int:
if ceil(x) != floor(x):
return False
x = int(x)
s = str(x)
for i in xrange(len(s) / 2 + 1):
if s[i] != s[-(i + 1)]:
return False
... |
def get_raw():
choice = int(raw_input()) - 1
chosen = []
for i in range(4):
raw = raw_input()
if i == choice:
chosen = set([int(v) for v in raw.split()])
return chosen
if __name__ == '__main__':
nb_cases = int(raw_input())
for case in xrange(nb_cases):
firs... |
import random
expansion_dictionary = dict()
expansion_dictionary[1] = (0,0,[]) # min, max, to_extend
def dynamic_calculate_left_right(bathroom_stalls,kth_person, verbose=False):
to_expand = [bathroom_stalls]
for personhelping in range(kth_person):
if verbose and personhelping % 1000 == 1:
... |
def flip(part):
for i in range(len(part)):
if part[i]=="+":
part[i]="-"
elif part[i]=="-":
part[i]="+"
return(part)
def main(n, m):
number_flips = 0
for i in range(len(n)):
if n[i]== '-' and i + m <= len(n):
part = flip(n[i: i+m])
... |
import sys
isprint = False
#isprint = True
def comment(t):
if(isprint): print t
if __name__ == '__main__':
data = open(sys.argv[1])
n_case = int(data.readline().strip())
for n in xrange(1,n_case+1):
q_array = data.readline().strip().split()
orders = []
for i in xrange(1,len(q_array),2):
o... |
'''
Created on Apr 12, 2013
@author: hou
'''
import sys
import re
def read_board(infile):
board = []
for i in xrange(4):
board.append(infile.readline().strip())
infile.readline() # skip the empty line
return board
def check_board(board, O_WIN, X_WIN):
winner_r, empty_cell... |
def get_tidy(n):
number = n
while True:
digits = [int(digit) for digit in str(number)]
all_good = True
for index in range(len(digits) - 1):
if digits[index] > digits[index + 1]:
digits[index] -= 1
for sub_index in range(index + 1, len(digits)):... |
import sys
import math
def solve(instream):
farm_price, farm_prod, target = [float(x) for x in instream.readline().strip().split(" ")]
speed = 2.0
time = 0.0
while True:
next_farm_time = farm_price / speed
if target / (speed + farm_prod) + next_farm_time > target / spee... |
import sys
# 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(raw_input()) # read a line with a single integer
ints = []
for i in xrange(1, t + 1):
#n = raw_input() # read a list of integers, 2 in this ca... |
import os
import math
PALENDROMES = {}
def is_palendrome(value):
if value in PALENDROMES:
return PALENDROMES[value]
valstr = str(value)
ret = valstr == valstr[::-1]
PALENDROMES[value] = ret
return ret
def count(lower, upper):
min = int(math.ceil(math.sqrt(lower)))
max = math.sqrt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
FILE_NAME = 'C-small-attempt0'
IN_FILE = FILE_NAME + '.in'
OUT_FILE = FILE_NAME + '.out'
f = open(IN_FILE, 'r')
src = f.read().split('\n')
f.close()
case_num = int(src.pop(0))
case_count = 0
result = ''
def recycle (num):
result = set()
line = str(num)
for i in range... |
import sys
import re
test_splitter = re.compile(r"[a-z]|\([a-z]+\)")
class Trie(object):
def __init__(self, letter = ""):
self.letter = letter
self.next = {}
self.word = False
def add_word(self, word):
if len(word) == 0:
self.word = True
retu... |
from itertools import groupby
def sub_unit(digits):
if digits[0] > 1:
return "%s%s" % (digits[0]-1, "".join("9" for x in range(len(digits)-1)))
else:
return "".join("9" for x in range(len(digits)-1))
T = int(raw_input())
for case in range(T):
N = raw_input()
digits = [int(i) for i in... |
# A certain bathroom has N + 2 stalls in a single row; the stalls on the left and right ends are permanently occupied by the bathroom guards. The other N stalls are for users.
#
# Whenever someone enters the bathroom, they try to choose a stall that is as far from other people as possible.
# To avoid confusion, they... |
import sys
import math
file = open(sys.argv[1])
T = int(file.readline())
#T=int(input())
for X in range(1,T+1):
line = file.readline()
number1= int(line.split(" ")[0])
number2= int(line.split(" ")[1])
sqrt1 = int(math.ceil(math.sqrt(number1)))
sqrt2 = int(math.floor(math.sqrt(number2)))
count = 0
f... |
import sys
file = open(sys.argv[1], "r")
numberoftests = int(file.readline())
case = 1
def printCase(case, money):
print "Case #%d: %d" % (case, money)
def runRollercoaster(runs, size, groups):
money = 0
for run in range(runs):
riding = []
while groups:
if groups[0] + sum(ridi... |
palindrome=lambda x: int(str(x)[::-1])
is_palindrome= lambda x: str(x)==str(x)[::-1]
square=lambda x: int((x**.5))**2
sqrt=lambda x: int(x**.5)
is_square=lambda x: square(x)==x
fair_and_square=lambda x: is_square(x) and is_palindrome(x) and is_palindrome(sqrt(x))
for case in xrange(int(raw_input())):
a,b=map(int,raw... |
import sys
fname = sys.argv[1]
f = open(fname)
tline = f.readline().strip()
t = int(tline)
def optimal(armin, motes):
if not motes:
return 0
else:
if motes[0] < armin:
# print "ok"
return optimal(armin + motes[0], motes[1:])
elif armin < 2:
return 1 ... |
import sys
#Given a number, construct a triple of scores
#that is as unsurprising as possible.
def unsurprise(number):
average = number/3
if (number % 3 == 0):
return [average,average,average]
else:
b = average+1
c = number - average - b
return [average,b,c]
#Given a triple of scores, return... |
#!/bin/python
def getRobot (letter):
# 0 for blue, 1 for orange
if letter == "B": return 0
else: return 1
def norm (x):
return x / abs(x)
class Move (object):
def __init__ (self, robot, button):
self.robot = robot
self.button = button
self.nextMove = None
s... |
from string import *
import math
def read_words(filename):
'''
converts a file to a list
'''
words = []
for line in filename:
words.append(line.strip())
return words
filename = open("lotto.txt", 'r')
numcases = int(filename.readline())
for case in range(numcases):
numarra... |
def answer(case, ans):
print("Case #{0}: {1}".format(case, ans))
FAIL = "RICHARD"
WIN = "GABRIEL"
"""
1: 1
2: 1
3: 2
4: 5
5: 12
"""
def solve(size, x, y):
if size == 1:
return WIN
if (x * y) % size != 0:
return FAIL
elif size == 2:
if (x * y) % 2 == 0:
... |
#! /usr/bin/python
import re
import string
def readinp():
global dict1
global p
global case
f = open("inpfile","r")
firstline = f.readline().strip("\n")
wordlen = int(firstline.split()[0])
totalWords = int(firstline.split()[1])
numofTests = int(firstline.split()[2])
dict1 = []
j = 0
while (j < totalWords... |
def count_recycled(a, b):
n = a
m = a+1
count = 0
digits = len(str(n))
for i in range(n, b+1):
for j in range(i+1, b+1):
for k in range(1, digits):
if str(j)[k:] + str(j)[:k] == str(i):
count = count + 1
contin... |
#!/usr/bin/env python
#encoding: latin1
ent = "A-small-attempt0.in"
sal = "output.out"
entrada = open(ent, 'r')
salida = open(sal, 'w')
def imprime(case, texto):
"""Recibe numero de case y texto que puede ser numero.
Graba en salida."""
salida.write("Case #"+str(case)+": "+str(texto)+"\n")
def crear_dic():
dic ... |
#! /usr/bin/env python2
# -*- coding: utf-8 -*-
import sys
def parse_input(filename):
"""
Parse the input according to the following format:
The first line of the input gives the number of test cases, T. T lines
follow. Each line contains three space-separated real-valued numbers: C, F
and X, whose meanings are... |
import math
def get_max_tidy(n):
ns = str(n)
if(len(ns)==1 or is_tidy(n)):
return n
else:
for i in xrange(n-1,9,-1):
if(is_tidy(i)):
return i
def is_tidy(num):
s = str(num);
for i in range(len(s)-1):
if s[i]> s[i+1]:
retu... |
#!/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... |
#!/usr/bin/env python3
# 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 nothing on the other side (the "blank side").
#
# You are the head cook on duty. The pancakes are cooked in a single row over a
# hot ... |
#! /usr/bin/env python
def read_grass(height, width):
return [map(int, raw_input().replace(' ', '')) for i in range(height)]
def can_cut(height, width, grass):
if height == 1 or width == 1:
return True
for x, y in [(x, y) for x in range(height) for y in range(width)]:
if not okay(x, y, hei... |
def divisible(x):
if x < 10:
return (x == 3 or x == 6 or x == 9 or x == 0)
return divisible(sum(map(int, str(x))))
def check(a, b, c):
xa, ya = a
xb, yb = b
xc, yc = c
if divisible(xa+xb+xc) and divisible(ya+yb+yc):
return 1
return 0
def run_case():
coords = set()
... |
def is_tidy(n):
s = str(n)
if len(s) == 1:
return True
for i in range(1, len(s)):
if int(s[i]) < int(s[i-1]):
return False
return True
T = int(input())
for c in range(T):
N = int(input())
answer = ""
while not is_tidy(N):
S = list(str(N))
S[-1] = "9"
answer = ans... |
#!/usr/bin/python2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("inp")
args = parser.parse_args()
def palindrome(x):
return str(x) == str(x)[::-1]
def num_fairnsquare(a, b):
i = 0
num = 0
while True:
i += 1
if i*i >= a:
if i*i > b:
... |
if __name__ == "__main__":
T = int(raw_input())
for testcase in xrange(T):
line = raw_input().split()[1]
total = 0 #running sum
friends = 0 #how many friends we have to add
for i,v in enumerate(line):
if total < int(i):
#not enough, add difference as f... |
__author__ = 'alessandro.pavesi'
in_file = open("C:\\Users\\alessandro.pavesi\\Downloads\\B-small-attempt1.in", 'r')
out_file = open("C:\\Users\\alessandro.pavesi\\Downloads\\GCJQ1.in", 'w')
t = next(in_file)
def isInAlphabeticalOrder(word):
return word==''.join(sorted(word))
cont_case = 1
for i in r... |
import os
from copy import copy
from collections import Counter, defaultdict
PROB_NAME = 'treasure'
INPUT_TYPE = 'small2'
class Chest(object):
def __init__(self, index, lock, keys):
self.index = index
self.keys = keys
self.lock = lock
self.open = False
def open_c... |
import sys
BLUE = '#'
RED1 = '/'
RED2 = '\\'
def int_input():
return int(raw_input())
def list_str_input():
return raw_input().split()
def list_int_input():
return map(int, list_str_input())
def list_char_input():
return list(raw_input())
def table_int_input(h):
return [list_int_input() for i ... |
#!/usr/bin/python
import sys
import os
def flip_chars(line):
for i in range(len(line)):
if line[i] == '+':
line [i] = '-'
elif line[i] == '-':
line[i] = '+'
return line
def calculate_min_flips(line, flipper_len):
flips = 0
plus_str = "".join('+' for i in range(... |
#!/usr/bin/python
in_file = "tongues.in"
out_file = "tongues.out"
def get_letter(let):
if let == 'a':
return 'y'
elif let == 'b':
return 'h'
elif let == 'c':
return 'e'
elif let == 'd':
return 's'
elif let == 'e':
return 'o'
elif let == 'f':
retu... |
from Queue import PriorityQueue
f = open("3.in")
num_test = int(f.readline())
for iter_test in xrange(num_test):
n, k = map(int, f.readline().split())
h = PriorityQueue()
h.put(-n)
for i in xrange(k):
a = -h.get()
x = (a - 1) / 2
y = a - 1 - x
h.put(-x)
h.put(-... |
# -*- coding: utf-8 -*-
import sys
def intersect(a, b):
if ( (a[0]>b[0]) and (a[1]<b[1]) ) or ( (a[0]<b[0]) and (a[1]>b[1]) ):
return 1
return 0
getline=sys.stdin.readline;
T=int(getline());
print >> sys.stderr, 'T={0}'.format(T)
for idx in range(T):
print >> sys.stderr, '=======================... |
def compute(cake):
R, C = len(cake), len(cake[0])
rows = [i for i in range(R) if set(cake[i]) != set(["?"])]
# first fill the non-empty lines
for i in rows:
cols = [j for j in range(C) if cake[i][j] != "?"] + [C]
for j in range(cols[0]):
cake[i][j] =... |
def is_tidy(num):
lst = []
num_str = str(num)
prev = 1
for ch in num_str:
digit = int(ch)
if digit >= prev:
prev = digit
continue
return False
return True
def read_file():
file = open('input.file', 'r')
lines = file.readlines()
lines = lis... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import math
def debug(*args):
print(*args, file=sys.stderr)
fin = sys.stdin
T = int(fin.readline())
for case in range(1, T + 1):
N = int(fin.readline()) # 1st volunteer row
s1 = None
for i in range(1, 5):
numbers = set(map(int, fin.re... |
import Queue
class Key(object):
def __init__(self, start,end):
self.start = start
self.end = end
self.length = end-start+1
def __cmp__(self,other):
if self.length > other.length:
return -1
elif self.length < other.length:
return 1
elif self... |
def count_friend():
people = input().split(' ')[1]
friend = 0
unshy_people = int(people[0])
shyness = 1
people = people[1:]
while (people):
while (people and unshy_people < shyness):
friend += 1
unshy_people += 1
unshy_people += int(people[0])
... |
import collections
def main():
for testcase in range(1, int(input()) + 1):
print(f"Case #{testcase}: {solve()}")
def fill_row(row):
c = len(row)
if row == ['?']*c:
return row
first_char = None
curr_char = None
for i in range(c):
if row[i] != '?':
curr_char =... |
import sys
import math
def check_palindrome(v):
s = str(v)
rp = len(s)/2
lp = rp if len(s) % 2 else rp - 1
while lp >= 0:
if s[lp] != s[rp]:
return False
else:
lp -= 1
rp += 1
else:
return True
def fair_and_square(A, B):
count = 0... |
import string
# abrir arquivo e ler suas linhas
arquivo = open("entrada.txt", "r")
linhas = arquivo.readlines();
arquivo.close()
# inicializar variáveis necessárias
quantidade_casos = int(linhas[0].split()[0])
caso_atual = 1
resultado = []
elementos_base = ["Q", "W", "E", "R", "A", "S", "D", "F"]
elemen... |
from sys import argv
def standing_ovation_num(digits):
extras = 0
count = 0
for i, d in enumerate(digits):
count += d
while(count <= i):
count += 1
extras += 1
return extras
if __name__ == '__main__':
filename = argv[1]
with open(filename, "r... |
# 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
F = open("result.in", 'w')
for i in range(1, t + 1):
pencakes, num = [s for s in input().split(" ")] # read a list ... |
import copy
def tryCutField(Field):
emptyField=[]
emptyField=copy.deepcopy(Field)
highest=0
different_values=[]
#Tomo el mas alto de la lista Field y corto todo en emptyField
for i in range(0,len(Field)):
for j in range(0,len(Field[i])):
#Si no esta el valor en mi ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Apr 13, 2012
@author: daniel
Problem
You're watching a show where Googlers (employees of Google) dance, and then each
dancer is given a triplet of scores by three judges. Each triplet of scores
consists of three integer scores from 0 to 10 inc... |
# programing language python3
# problem: Dancing With the Googlers
def topScore(x):
ns = 0 #non surprising highest score
s = 0 #surprising highest score
n = x % 3
if n == 2:
ns = (x +1)//3
s = (x -2 )//3 + 2
elif n == 1:
ns = (x -1)//3 +1
s = (x - ... |
#!/usr/bin/python2.7
from decimal import Decimal
from collections import Counter
class FileIO(object):
"""
Utility to interact with input/output files.
"""
def __init__(self, input_filename='input.txt', output_filename='output.txt'):
"""
set the input and output file names.
... |
def column(array, i):
return [row[i] for row in array]
def find_first_letter(row):
for item in row:
if item != "?":
return item
return "?"
def assign_cake(r, c, grid):
for row in range(r):
letter = find_first_letter(grid[row])
for col in range(c):
if gr... |
#!/usr/bin/env python3
def flip(S,K):
if len(S)<K:
return False
if len(S)==K:
return flip_front(S,K)
nfront = 0
nback = 0
for i in range(K):
if S[i] == '-':
nfront = nfront+1
if S[-1-i] == '-':
nback = nback+1
if nback > nfront:
return flip_back(S,K)
else:
return f... |
#! /usr/local/bin/python3.5
import sys
import copy
def sol_print(value):
sol_print.line_number += 1
print("Case #%d: %s" % (sol_print.line_number, value))
sol_print.line_number = 0
HAPPY = "+"
BLANK = "-"
T = int(input())
def flip_line(line, K, pos):
for i in range(K):
if line[pos + i] == ... |
def is_tidy(num):
num = str(num)
last = "0"
for n in num:
if int(n) < int(last):
return False
last = n
return True
t = int(input())
for case in range(1, t + 1):
n = int(input())
if is_tidy(n):
print("Case #%d: %s" % (case, n))
else:
tidy_num = 0
for i in range(1, len(str(n))):
... |
#!/usr/bin/env python
import sys
import math
def is_palindrome(n):
s = str(n)
length = len(s)
for i in xrange(0, int(length/2.0)):
if not s[i] == s[length-1-i]:
return False
return True
f = open(sys.argv[1])
cases = int(f.readline())
for case in xrange(0, cases):
r = f.read... |
#!/usr/bin/python3
import re, sys, math
def main():
with open(sys.argv[1]) as file:
count = -1
case = 0
for line in file.readlines():
line = line.rstrip("\n")
count += 1
if count == 0:
cases = int(line)
else:
va... |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
def test_snapper(n, k):
snapper_mask = (1 << n) - 1
all_snappers = k #the snappers follow binary rules, just counter
return ( ((~all_snappers)&snapper_mask) == 0 )
if __name__ == "__main__":
import sys
infile = "A-large.in"
case_number = ... |
class MyString:
def __init__ (self, string, parent):
self.string = string
self.parent = parent
self.f = 0
self.g = 0
self.h = 0
def __eq__ (self, other):
if (self.string == other.string):
return True
else:
return False
def heurist... |
# -*- coding: utf-8 -*-
import sys
import os
import math
from decimal import Decimal
import itertools
input_text_path = __file__.replace('.py', '.txt')
fd = os.open(input_text_path, os.O_RDONLY)
os.dup2(fd, sys.stdin.fileno())
T = int(input())
f = open('submit.txt', 'w')
for t in range(T):
print()
print('テス... |
#!/usr/bin/env python
class Group(object):
def __init__(self, size):
self.size = size
self.i = 0
self.next = None
self.last_visit = 0
self.next_head = None
self.last_total = 0
self.last_ride = 0
def __str__(self):
return "(%s, %s)" % (self.i, sel... |
#!/usr/bin/python
import os, sys
def change_color(tile, r, c):
ir = len(tile)
ic = len(tile[0])
if r+1 >= ir or c+1 >= ic:
return False
if tile[r][c] != '#' or tile[r][c+1] != '#' or tile[r+1][c] != '#' or tile[r+1][c+1] != '#':
return False
tile[r][c] = '/'
tile[r][... |
"""
Alien numbers
"""
class Solution:
def __init__(self,gps):
self.GPS=gps
def result(self):
ret=0
gps=self.GPS
ss,tt=[],[]
for s,n,t in gps:
if n==1:
ss.append(s);tt.append(t)
else:
for k in range(n)... |
#-------------------------------------------------------------------------------
# Name: Google Code Jam 2015 - Qualifiers - B Infinite House of Pancakes
#
# Author: Ashish Nitin Patil
#
# Created: 11-04-2015
# Copyright: (c) Ashish Nitin Patil 2015
# Licence: New BSD License
#------------... |
#!/usr/bin/env python
# Been a while since I've done any Python
words = []
def group(s):
sep = False
ret = []
for c in s:
if c == '(':
sep = True
ret.append("")
elif c == ')':
sep = False
elif sep:
ret[-1] = "%s%c" % (ret[-1], c)
... |
import sys
import math
sqrt = math.sqrt
def find_gcd(a, b):
if (a < b):
a, b = b, a
while b != 0:
a, b = b, a%b
return a
def find_lcd(x,y):
global gcd
lcd=(x*y)/gcd
return lcd
def factors(n):
fact=[1,n]
check=2
rootn=sqrt(n)
while che... |
from math import sqrt
def read(filename):
input = open(filename, 'r')
lines = []
for line in input:
lines.append(line.rstrip('\n')) # strip out the newline characters
return lines
def get_range(s):
nums = list(map(int, s.split(' ')))
return range(nums[0], nums[1] + 1)
def is_palindrom... |
__author__ = 'Via'
# file_in = open('example_input.txt', 'r')
# file_in = open('A-small-attempt0.in', 'r')
file_in = open('A-large.in', 'r')
file_out = open('output.txt', 'a')
line_idx = 0
def solve(problem):
stand_up = 0
invited = 0
for sh_lvl in range(len(problem)):
invite = sh_l... |
import sys
class Snapper:
pass
def snap(snappers):
# toggle all powered snappers
for i in range(0, len(snappers)):
if snappers[i].powered:
snappers[i].on = not snappers[i].on
# determine which snappers are powered now
for i in range(1, len(snappers)):
snappers[i].powered = snappers[i - 1]... |
## Determines the smallest number of flips required to flip str into a string of "+" using a flipper of size k, output IMPOSSIBLE otherwise
def flip(str, k):
str = list(str)
n = len(str)
count = 0
for i in range(n-k+1):
if str[i] == "-":
for j in range(i,i+k):
## Flip the substring of size k starti... |
from math import sqrt, ceil
# bases = []
def is_palindrome(num):
return str(num) == "".join(reversed(str(num)))
# def build_bases(a,b):
# for i in range(a,b+1):
# if is_palindrome(i) and is_palindrome(i**2):
# bases.append(i)
bases = [1, 2, 3, 11, 22, 101, 111, 121, 202, 212, 1001, 1111,... |
#!/usr/bin/python
import fileinput
#import time
line_number = 0
#f = 'sample_input.txt'
#f = 'C-small-attempt0.in'
f = 'C-large-1.in'
def int_sqrt(x):
if x < 0:
raise ValueError('square root not defined for negative numbers')
n = int(x)
if n == 0:
return 0
a, b = divmod(n.bit_length(), 2)
x = 2**(a+b)
whil... |
import sys
import string
def check_base(current, base) :
if (len(current) < 2) :
return current
postfix = current[-2] + current[-1]
if postfix in base :
replacement = base[postfix]
answer = current[0:-2] + replacement
return answer
else :
return current
def che... |
minus = {}
minus['1'] = 'm'
minus['i'] = 'n'
minus['j'] = 'o'
minus['k'] = 'p'
minus['m'] = '1'
minus['n'] = 'i'
minus['o'] = 'j'
minus['p'] = 'k'
def computeProd(a, b):
if a == '1':
return b
elif a == 'i':
if b =='1':
return 'i'
elif b == 'i':
return minus['1']
elif b == 'j':
ret... |
class IO (object):
def __init__ (self, mode='test'):
self.mode = mode
if self.mode != 'debug':
self.f_out = open ('output.txt', 'w')
f_in = open ('input.txt', 'r')
self.lines = [line.strip () for line in f_in.readlines ()]
f_in.close ()
... |
def cutPancakeLine(pancakeLine):
while len(pancakeLine) != 0 and pancakeLine[0] == '+':
pancakeLine = pancakeLine[1:]
return pancakeLine
def reversePancakeLine(pancakeLine, number):
tmpNumber = 0
newPancakeLine = ""
while tmpNumber < number:
newPancakeLine += '-' if pancakeLine[tmpNumber] == '+' el... |
import math
fname=raw_input("input filename:")
data=open(fname,"r+")
text=data.readlines()
data.close()
nos=int(text[0])
nos=nos
tn=1
def is_square(integer):
root = math.sqrt(integer)
if int(root + 0.5) ** 2 == integer:
return True
else:
return False
def reve(num):
r=0
while(num>0... |
#!/usr/bin/python
import sys
def flip(pan, K):
moves = 0
s = 0
e = len(pan)
#print "** ", pan, e,s, e-s, K
if (e-s) < K:
for o in range(0,e):
if pan[o] == '-':
return -1
return 0
e -= K -1
for o in range(s, e):
if pan[o] == '-':... |
#lawnmower
# standard functions
#File input
file2test="B-small-attempt0.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 that add up to credit)
... |
def solve():
times = 0
speed = 2
C, F, X = map(float, raw_input().split())
res = X / 2;
while True:
times += C / speed;
speed += F;
if(res < times + X / speed):
break
res = times + X / speed;
return res
if __name__ == "__main__":
tn = int(raw_input())
for cn in range(tn):
print... |
import sys
import re
def read_spaced_line(file):
line = file.readline()
#print("Read: '%s'\n"%line,file=sys.stderr)
return re.split('\s+', line.strip())
import contextlib
@contextlib.contextmanager
def yield_none():
yield None
@contextlib.contextmanager
def _open_argv_file(argnum, mode=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.