text stringlengths 37 1.41M |
|---|
def number_flipping(S, K):
"""
Given a string S of + and - and a size K of the pancake flipper, determine how many flips are necessary
to flip all the pancakes to the + side
:param S: a string of + or -
:param K: size of the humongous pancake flipper
:return: either an int containing th... |
import math
def read_int():
return int(raw_input());
def read_cfx():
return ([float(x) for x in raw_input().split()]);
def stop_buying_at(target, cost, base_rate, additional_rate):
#target is the targeted number of cookies, X in the problem
#cost is the cost of a cookie farm, C in the problem
#base_rate is t... |
tn=int(input())
for tt in range(tn):
print("Case #%d: "%(tt+1),end='')
a,b = (int(i) for i in input().split('/'))
if b%a==0:
b/=a
a=1
ans=1
test=1
chk=True
while test<b:
test<<=1
if test==b:
while a*2<b:
ans+=1
a*=2
else:ans="impossible"
print(ans) |
#!/usr/bin/env python
from queue import PriorityQueue
class Horse():
def __init__(self, endurance, speed, city):
self.endurance = endurance
self.speed = speed
self.city = city
def __lt__(self, other):
return self.endurance > other.endurance or self.speed > other.speed
def nex... |
import pdb
quaternion_multiplication = {
'ii': '-1', 'ij': 'k' , 'ik': '-j',
'ji': '-k', 'jj': '-1', 'jk': 'i' ,
'ki': 'j' , 'kj': '-i', 'kk': '-1',
}
def getInput(path):
f = open(path)
lines = f.readlines()
f.close()
return lines
def get_solution():
if validate(0, ['i', 'j', 'k']) i... |
import sys
from math import sqrt
# Stores previously determined results with key of n and value of True/False.
result_cache = {}
def is_perfect_square(n):
"""Returns whether or not the specified int is a perfect square."""
return int(sqrt(n) + 0.5) ** 2 == n
def is_fair_and_square(n):
"""
Returns ... |
import sys
from typing import List
#T: number of test cases
#N: the last number tatiana counted
def int_to_digit_list(n: int) -> List[int]:
return [int(d) for d in str(n)]
def is_tidy(n: int):
digit_list = int_to_digit_list(n)
return is_tidy_digit_list(digit_list)
def is_tidy_digit_list(dig... |
class Time:
def __init__(self, s, t=None):
self.hour = 0
self.minute = 0
self.turnaroundTime = t
self.parse(s)
if t:
self.minute += t
if self.minute >= 60:
self.hour += self.minute / 60
self.minute = self.minu... |
#!/usr/bin/env python
import sys
def count_recycle_pair(Min , Max):
length = len(Min)
if length < 2:
return 0
count = 0
Dict = {}
i_min = int(Min)
i_max = int(Max)
for i_now in range(i_min, i_max):
if i_now in Dict:
continue
Dict[i_now] = 1
s_now = str(i_now)
s_pair = s_now
local_count = 0
... |
def debug(msg):
#print(msg)
pass
def tidy_number(digits):
debug("digits is {0}".format(digits))
last = len(digits) - 1
for i in range(last, 0, -1):
if digits[i - 1] > digits[i]:
debug("fixing number {0}".format(digits))
digits[i - 1] = digits[i - 1] - 1
... |
def main():
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
num_cases = int(input())
for case in range(num_cases):
last_num = input()
chars = list(last_num)
num = ''
for i in range(len(chars))[::-1]:
if i != 0 and chars[i] < chars[i - 1]:
... |
#-------------------------------------------------------------------------------
# Name: Fair and Square
# Purpose:
#
# Author: udonko
#
# Created: 14/04/2013
# Copyright: (c) udonko 2013
# Licence: <your licence>
#--------------------------------------------------------------------------... |
import sys
import string
import os
import array
def BumpUpBigOne(numString, currentIndex):
#currentIndex is the one we are replacing
#Find the next smallest digit greater than the one we are replacing
#Get that index
digitToReplace = int(numString[currentIndex])
replacerIndex = currentInd... |
#! /bin/env python3
#! -*- coding: utf-8 -*-
ifn = 'A-small-attempt0.in'
def get_chosen_row(input):
answer = int(input.readline())
# jump to chosen row
for _ in range(1, answer):
input.readline() # skip row
row = [int(x) for x in input.readline().split(' ')]
# jump to second chosen row
for _ in range(answer, ... |
# 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
for i in xrange(1, t+1):
S, N = [s for s in raw_input().split(" ")] # read a list of integers, 2 in this cas... |
from string import ascii_lowercase, maketrans
case = 1
# worked out by hand ;)
table = maketrans (ascii_lowercase, 'yhesocvxduiglbkrztnwjpfmaq')
with open('small.txt') as f:
lines = f.readlines()[1:]
for line in lines:
print "Case #%d: %s" % (case, line.strip().translate (table))
case += 1 |
import sys
def calc(line):
line = line.strip().split()
c = float(line[0])
f = float(line[1])
x = float(line[2])
rate = 2.0
curr_time = 0.0
next_time = 0.0
total_time = 0.0
#print x/rate
while curr_time >= next_time:
curr_time = x / rate
next_time = (x / (rate +... |
#!/usr/bin/env python2
import sys
import math
class Test:
pass
class Result:
pass
def parseInput(path):
ret = []
testFile = open(path)
inputSize = int(testFile.readline())
for i in range(inputSize):
text = testFile.readline().split()
test = Test()
googlerCount = int(t... |
#! /usr/bin/env python
import pprint
import sys
def count_possibilities(language, test_string):
letter_count = 0
return_count = 0
if test_string[letter_count] == '(':
paren_string = ""
letter_count += 1
while test_string[letter_count] != ')':
paren_string += test_stri... |
import sys
class Input(object):
def __init__(self, c, f, x):
# cookie farm cost
self.cost = c
# cookies per second per farm
self.farmIncome = f
# win with this many cookies
self.goal = x
self.baseIncome = 2
def run(self):
elapsed = 0.0
num_farms = 0
prev_seconds = elapsed + self.secondsToWin(num... |
#!/usr/bin/env python
import sys
import re
file = open(sys.argv[1])
def next_line():
return file.readline()[:-1]
class Tree:
pass
def parse_tree(num_lines):
entire_tree = ''
for i in range(num_lines):
entire_tree = entire_tree + next_line()
remake = ''
for s in entire_tree.spli... |
import re
class Trie:
end_node = {}
"""
A Trie is like a dictionary in that it maps keys to values. However,
because of the way keys are stored, it allows look up based on the
longest prefix that matches.
"""
def __init__(self):
self.root = {}
def add(self, key)... |
import math
def is_palindrome(string):
l = len(string)
if l == 1:
return True
if l % 2 == 0:
return string[:l/2] == string[l/2:][::-1]
return string[:l/2] == string[(l/2)+1:][::-1]
# Gets the number of square and palindrome numbers between a and b
def nbrs(a, b):
count = 0
for i in range(int(a), int(b)+... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Problem C. Fair and Square
# https://code.google.com/codejam/contest/2270488/dashboard#s=p2
#
import sys
import math
import itertools
class Palindromes(list):
PALINDROMES_FILE = 'palindromes.txt'
def __init__(self):
import os
if not os.path.is... |
#!/usr/bin/env python
# Google Code Jam 2008 Qualifcations, Task C
# Solution by Sebastian Hagen
# language: Python 2.5
# This program reads input from stdin and writes output to stdout.
import math
from math import sin,cos,asin,acos,pi
def p_ring(R, t, f):
safe_r = (R-t-f)
if (R == 0):
return 0
return... |
# -*- coding: utf-8 -*-
import sys
# 一行読む
def ReadL():
return sys.stdin.readline()[0:-1]
# 一行読んでINTにする
def ReadLInt():
return int(ReadL())
# スペースで区切って一行読む
def ReadLSplit():
return ReadL().split(' ')
# さらにINT型にする
def ReadLSplitInt():
return [int(x) for x in ReadLSplit()]
# 回答を出力する
def PrintA(q,out):
print 'Ca... |
def flip(s):
flipD = {'-':'+','+':'-'}
return [flipD[x] for x in s]
def pancake(s, k):
s = [str(d) for d in s]
flips = 0
for i in range(len(s)-k+1):
if s[i] == '-':
s[i:i+k] = flip(s[i:i+k])
flips += 1
if s.count('-') == 0:
return flips
else:
return "IMPOSSIBLE"
def main():
t = int(raw_input())
fo... |
import os, math
def isPali(n):
n = str(n)
if n == n[::-1]:
return True
else:
return False
if __name__ == '__main__':
file = open('IN', 'r')
dati = file.read().split('\n')
L = int(dati[0])
dati = dati[1:-1]
#print dati
prati = []
for count in range(L):
results = 0
lati = dati[0... |
#!/usr/bin/env python
class Tree(object):
def __init__(self, subtree):
self.weight = float(subtree[0])
if len(subtree) == 1:
self.feature = None
self.left = None
self.right = None
return
self.feature = subtree[1]
count = 1
p... |
def find_min_num_of_swaps(pancakes, K):
'''
:param pancackes: (list of strings) + is happy, - is blank pancake
:param K: (int) - how much consecutive elements should we swap
:return: minimum # of swaps, if no solutions (str) "IMPOSSIBLE"
'''
# Conver el-ts in list to Boolean
res = 0... |
# Google Dictionary
GoogDict = {'\n':'\n', 'z':'q', ' ': ' ', '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', 'q': 'z', 'p': 'r', 's': 'n', 'r': 't', 'u': 'j', 't': 'w', 'w': 'f', 'v': 'p', 'y': 'a', 'x': 'm'}
"""
T... |
#!/usr/bin/env python3
import sys
def main():
if len(sys.argv) < 2 or len(sys.argv) > 3:
print('Usage: {0} IN_FILE [OUT_FILE]'.format(sys.argv[0]))
return
in_file = open(sys.argv[1])
out_file = open(sys.argv[1]+'.txt' if len(sys.argv) == 2 else sys.argv[2], mode='w')
cases = int(next... |
#!/usr/bin/env python3
def invite_standing(people):
accumulate = 0
friend_invites = 0
for shyness, audience in enumerate(people):
shortage = max(0, shyness - accumulate)
accumulate += audience + shortage
friend_invites += shortage
return friend_invites
for case in range(int(in... |
#!/usr/bin/python
import sys,os
from operator import itemgetter
def solve(lawn):
"""Returns a string result to one lawn of a problem
Possible output: {"YES","NO"}"""
# for each row find minimum
# make sure that in mimimums column minimum is maximum
# else fail
for y, row in enumerate(lawn):
... |
#!/usr/bin/env python
import os
#get list of all recycled numbers of a given number
def getRecycleNumbers(num, B, uniquRecyclePairs):
lstNums = []
for i in range(1, len(num)):
rear = num[i:]
front = num[0:i]
recycleNum = (rear + front)
#check vali... |
import sys
num = int(sys.stdin.readline());
lines = [s.strip() for s in sys.stdin.readlines()]
board = []
def orMap2_Columns(board, fun):
for x in range(0,4):
atLeastOne = False
for y in range(0,4):
if not fun(board[y][x]):
atLeastOne = True
break
if not atLeastOne: return True
return False
def ... |
""" Google Code Jam - Qualification
Part B Solution
Author: Marc Katzef
"""
def solution(in_file):
"""Uses the data in in_file to generate an answer as a single string to be written to file"""
out_list = []
test_cases = int(in_file.readline().strip())
for i in range(test_... |
def read_int(f):
return int(f.readline().strip())
def read_ints(f):
return [int(w) for w in f.readline().strip().split()]
def read_floats(f):
return [float(w) for w in f.readline().strip().split()]
from sys import argv
in_f = open(argv[1])
T = read_int(in_f)
for i_t in range(1, T+1):
C, F,... |
from string import ascii_lowercase
googlerese_map = ('y', 'h', 'e', 's', 'o', 'c', 'v', 'x', 'd', 'u', 'i', 'g', 'l',
'b', 'k', 'r', 'z', 't', 'n', 'w', 'j', 'p', 'f', 'm', 'a', 'q',)
def main():
with open('input.txt', 'r') as input, open('output.txt', 'w') as output:
T = input.readline(... |
#!/usr/bin/env python
cases = input()
case=0
while case < cases :
case+=1;
row1_index = input()
row1 = []
row2 = []
count = 0;
number = -1;
for i in xrange(1,5):
if i == row1_index:
row1 = map(int,raw_input().split(" "))
else:
dev_null=raw_input()
row2_index = input()
for i in xrange(1,5):
if i == ... |
#! /usr/bin/python
# usage :: ./snapper.py <file>
from sys import argv
def light_check(N,K):
# with x or y snaps the light will turn on
x= 2**N - 1
if K == x: return 'ON'
elif K > x:
y= x
r= 1
while y <= K:
y= x + (x+1)*r
if K == y: return 'ON'
... |
#!/usr/bin/env python
import re
import sys
class Memoize:
def __init__(self,function):
self._cache = {}
self._callable = function
def __call__(self, *args, **kwds):
cache = self._cache
key = self._getKey(*args,**kwds)
try: return cache[key]
except K... |
def dancing(scores, p, simlar):
number_above_p = 0
for score in scores:
score = int(score)
mod_score = score % 3
if (mod_score == 1):
if ((((score - 1) / 3) + 1) >= p):
number_above_p += 1
if (mod_score == 0):
if ((score / 3) >= p):
number_above_p += 1
else:
... |
import sys
def main():
with open(sys.argv[1]) as f:
N = int(f.readline())
#print N
for i, line in enumerate(f):
smax, audience = line.split()
smax = int(smax)
paid_applauders = start_applause(smax, audience)
print "Case #%d: %d" % (i+1, paid_a... |
import sys
from queue import PriorityQueue
def bathroom(N,K):
q = PriorityQueue()
q.put(-N)
for i in range(K):
x = -q.get()
x -=1
mi = x//2
ma = mi + (x%2)
#print ("%d %d (%d,%d)" % (i+1, x, ma, mi))
q.put(-ma)
q.put(-mi)
return ... |
#!/usr/bin/python2
from __future__ import print_function
def apply_f(s, l):
for elem in l:
r = elem.apply(s)
if r != None:
return r
return None
with open("input.txt") as f:
lines = f.readlines()
lines.pop(0)
n_line = 0
for line in lines:
n_line += 1
... |
import sys
def solve(board):
'''
Read a game board and return the current result.
Return value will be one of:
"X won" (the game is over, and X won)
"O won" (the game is over, and O won)
"Draw" (the game is over, and it ended in a draw)
"Game has not completed" ... |
#!/usr/bin/python
def result(R, C, tiles):
for i in range(0, R):
for j in range(0, C):
if tiles[i][j] == '#':
# print i, j
if j+1 >= C or i+1 >= R:
return 'Impossible'
if tiles[i+1][j] != '#' or tiles[i][j+1] != '#' or tiles[i+... |
import string
class GraphNode(object):
def __init__(self, x_pos, y_pos):
self.x_pos = x_pos
self.y_pos = y_pos
self.flows_to = None
self.flows_from = []
self.label = None
def set_flows_to(self, other):
assert self.flows_to != other
self.f... |
#!/usr/bin/env python
import sys
def read_data():
input = sys.stdin.read()
lines = input.split("\n")
n_times = int(lines[0])
lines = lines[1:]
stripped_lines = []
for line in lines:
sl = line.strip()
if sl != "":
stripped_lines.append(sl)
assert(n_times == len(s... |
#!/usr/bin/env python
import sys
import argparse
class InputCase: # Calling this "TestCase" will make PyCharm think it's a Python unittest
pass
def process_command_line(argv):
parser = argparse.ArgumentParser()
parser.add_argument("filename", type=argparse.FileType('r'),
help="In... |
#decoder
a1 = "ejp mysljylc kd kxveddknmc re jsicpdrysi"
b1 = "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"
c1 = "de kr kd eoya kw aej tysr re ujdr lkgc jv"
a2 = "our language is impossible to understand"
b2 = "there are twenty six factorial possibilities"
c2 = "so it is okay if you want to just give up"
... |
import os
# Classe Gestion de fichier
class Fichier:
def __init__(self,path):
self.path = path
self.fichier = None
def open(self,option):
try:
self.fichier = open(self.path,option)
except:
print("Error File doesn't exist !!!")
def close(self):
self.fichier.close()
def read(se... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def makeArray(board):
result = []
result.append(board[0])
result.append(board[1])
result.append(board[2])
result.append(board[3])
result.append([board[0][0], board[1][0], board[2][0], board[3][0]])
result.append([board[0][1], board... |
#!/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 impossible(row, col, t, R, C):
if t[row... |
'''
Problem
Tatiana likes to keep things tidy. Her toys are sorted from smallest to largest, her pencils are sorted from shortest to longest and her computers from oldest to newest. One day, when practicing her counting skills, she noticed that some integers, when written in base 10 with no leading zeroes, have the... |
def getv(n, a, row, col):
return a[row * n + col]
def setv(n, a, row, col, v):
a[row * n + col] = v
def setv_safe(n, a, row, col, v):
if row < 0 or col < 0: return
if row >= n or col >= n: return
setv(n, a, row, col, v)
def set_bishop_disallowed_in_row(n, a, row, col, row_to_set):
diff = abs(... |
import sys
def best_possible(total):
for i in range(10, -1, -1):
if i == 0:
sum_list = [0]
else:
sum_list = [
i * 3,
(i * 2) + (i - 1),
i + ((i - 1) * 2)
]
if total in sum_list:
return i
def b... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import math
import fractions
f_input = open(sys.argv[1])
problems = int(f_input.readline().rstrip())
for probnum in xrange(1, problems+1):
P, Q = map(int, f_input.readline().rstrip().split("/"))
gcd = fractions.gcd(P, Q)
P, Q = P/gcd, Q/gcd
... |
def readFile(fname):
"""
The first line of the input gives the number of test cases, T.
T test cases follow.
Each consists of one line with a string S and an integer K.
S represents the row of pancakes:
each of its characters is either
+ (which represents a... |
def pancakes(S, T):
res = 0
for i in range(len(S) - T + 1):
if S[i] is '-':
res += 1
for j in range(T):
if S[i+j] is '-':
S[i+j] = '+'
else:
S[i+j] = '-'
if '-' in S:
return 'IMPOSSIBLE... |
file_out = open("output.txt","w")
def findTidy(val):
if val < 10:
return val
#print "checking for " + str(val)
for num in range (val, 0 , -1):
#print "looping for " + str(num)
#arr = [int(d) for d in str(num)]
if (checkSorted(num) == True):
#print "found.."
return num
def checkSorted(val):
#pr... |
import os
import math
def is_palindrome(num):
x = str(num)
x_letters = [c for c in x]
res = (x_letters == x_letters[::-1])
return res
def main():
f = open("C-small-attempt4.in","r")
doc = f.read().split('\n')
num_test_cases = int(doc[0])
numa = []
numb = []
... |
def read_input():
line = input()
# print(line)
length = len(line)
# print(length)
value = int(line)
# print(value)
digits = [0]*length
for i in range(0, length):
digits[i] = (value // (10**i)) % 10
# print(digits)
for i in range(0, length):
if i==length-1:
... |
def finding_max_space(a):
'''
Finding maximum space where the next prson will occupy
'''
l=len(a)
i_start=0
i_end=l-1
i=0
maximum=0
while(i<l):
i_temp_start=i
temp=0
while(i<=l-1 and a[i]!="o"):
temp+=1
i+=1
if(te... |
def solve(config):
config, k = config.split()
k = int(k)
config = list(config)
ii = 0
cnt = 0
while ii <= len(config) - k:
if config[ii] == '+':
ii += 1
else:
for jj in range(ii, ii + k):
if config[jj] == '-':
config[jj... |
import sys
def check_board(board):
# Check the rows
for row in board:
s = sum(row)
if s == 4 or s == 13:
return "X won"
elif s == -4 or s == 7:
return "O won"
# Check the columns
for idx in xrange(0, 4):
column = [row[idx] for row in board]
s = sum(column)
if s == 4 or s == 13:
... |
import sys
from collections import defaultdict
class Robot:
def __init__(self, buttons):
self.moves = buttons
self.pos = 1
def move(self, canPush):
if self.moves:
if self.pos < self.moves[0]:
self.pos += 1
elif self.pos > self.moves[0]:
... |
def flip(pancake_str, flipper_size):
"""
Input : string that is sequence of face sign of pancake, and size of flipper
Output : minum number of flip or impossible.
"""
if len(pancake_str)<flipper_size:
return 'IMPOSSIBLE'
pancake=[]
for item in pancake_str:
pancake.append(item)
count=0
for item in range... |
def gettable():
example = [("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 it is okay if you w... |
def maquina():
file_name = "input.txt"
objecto_archivo = open(file_name, 'r')
count_case = int(objecto_archivo.readline()[:-1])
for number_case in range(0, count_case):
frase = "Case #"+str(number_case +1)+": "
values = objecto_archivo.readline()[:-1]
A,B,K = values.split(" ")
count_result = count_of_resu... |
#!/usr/bin/env python
def parse_pattern(pattern):
p_list = []
flag = False
for i in pattern:
if i == '(':
flag = True
tmp = []
elif i == ')':
flag = False
p_list.append(tmp)
else:
if flag == False:
p_list.ap... |
#!/usr/bin/python3
from common import *
# square root of i, rounded down
def int_sqrt(i):
if i <= 1:
return i
# Easier version:
# low = 0
# high = i + 1
# Faster version:
log4 = 0
power4 = 1
while power4 < i:
log4 += 1
power4 *= 4
high = (2 ** log4) + 1
... |
def main():
number_of_inputs = int(input())
for currentInput in range(1, number_of_inputs + 1):
searching = True
current_number = input()
current_number_list = [int(digit) for digit in current_number]
while searching:
if sorted(current_number_list) == current_numbe... |
def getUntidyDigit(n):
prevDigit = ''
for i, digit in enumerate(str(n)):
if prevDigit > digit: return len(str(n)) - i -1
prevDigit = digit
return -1
def getPreviousTydyNumber(n):
while True:
digit = getUntidyDigit(n)
if digit < 0: return n
n = FastGo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def eat(pancakess):
if pancakess[0] < 3:
return pancakess[0]
top = pancakess[0]
# print pancakess
# route 1
pancakes1 = list(pancakess)
tmp = 3 if top == 9 else top / 2
pancakes1[0] = tmp
pancakes1.append(top - tmp)
pan... |
def testmid(mid, r, t):
if(mid * (2 * r + 1) + 2 * mid * (mid - 1) <= t):
return True
return False
def bsearch(lo, hi, r, t):
while hi - lo > 1:
mid = (lo + hi) / 2
if(testmid(mid, r, t)):
lo = mid
else:
hi = mid - 1
if(testmid... |
import sys
from math import sqrt, ceil, floor
class Prob3(object):
def __init__(self, limita, limitb):
# new limits
self.limita, self.limitb = int(ceil(sqrt(limita))), int(floor(sqrt(limitb)))
self.output = 0
def solve(self):
for x in range(self.limita, self.limitb + 1):
... |
#!/usr/bin/python
import sys,re
if len(sys.argv) != 2:
print "usage: " + sys.argv[0] + " infile"
sys.exit()
infile = sys.argv[1]
def E(n):
if n < 2: return 0
return n
def countNumInWrongPlace(l):
c = 0
for i in range(0, len(l)):
if i+1 != int(l[i]): c = c +1
return c
def f(l):
return E(countNu... |
import sys
import os
def main():
s = ''.join(sys.stdin.readlines()).split()
os.close(0)
T = int(s[0])
s = s[1:]
for i in range(T):
N = int(s[0])
K = int(s[1])
s = s[2:]
board = []
for j in range(N):
board += [[]]
... |
def d2b(n):
bStr = ''
#if n < 0: raise ValueError, "must be a positive integer"
if n == 0: return '0'
while n > 0:
bStr = str(n % 2) + bStr
n = n >> 1
return bStr
def input() :
t = int( raw_input())
for i in xrange(0,t) :
val = raw_input()
inp = val.split()
n = int(inp[0])
k = int(inp... |
f = [
"ejp mysljylc kd kxveddknmc re jsicpdrysi",
"rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd",
"de kr kd eoya kw aej tysr re ujdr lkgc jv"
]
t = [
"our language is impossible to understand",
"there are twenty six factorial possibilities",
"so it is okay if you want to just give up"
]
mp = {'y':'a','e':'o','q':'z'}... |
# Let's count 0 separately
#
# 1 digit: 9 1, ..., 9
# 2 digits: 9 *1, ..., 99
# 3 digits: 90 *?1, ..., 9?9
# 4 digits: 90 1001, ..., 9999
# 5 digits: 900 10001, ..., 99999
from math import sqrt
def ints(l):
return [int(w.strip()) for w in l.strip().split()]
def nd... |
def getDigits(number):
###returns an array with the digits of the number from last to first###
digits = []
while(number!=0):
rem = number%10
digits.append(rem)
number = number/10
return digits
def isTidy(ls):
###checks if the sorted array is equal to the number array###
if sorted(ls, reverse = True) == ls:... |
# 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.
import math
f = open("C-large.in",'r')
g = open("Answer.txt", 'w')
def calcuate_priority(i, j):
if (i-j)%2 == 0:
return (i+j-1)/2, ((j-i)/2 - 1,(j-... |
__author__ = 'alestainer'
def check_if_tidy(number):
for i in range(len(number) - 1):
if (number[i] > number[i+1]):
return False
return True
def solution(number):
if (check_if_tidy(str(number))):
return number
else:
return solution(number / 10 - 1) * 10 + 9
t = int... |
# 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.
fo = open("q2input.txt", "r")
t = int(fo.readline())
for i in xrange(1, t + 1):
nums = fo.readline().split(" ") # read a list of integers, 2 in this case
... |
import math
def base_surface(p):
r, h = p
return math.pi * r**2 + 2 * math.pi * r * h
def circumference(p):
r, h = p
return 2 * math.pi * r * h
"""
def calculate_surface_area(l, k):
l.sort(key = lambda x: best_surface(*x))
p_r, p_h = l.pop()
surface_area = math.pi * p_r**2 + 2 * math.pi *... |
#! /usr/bin/env python2.7
import sys
def is_tidy( vals ):
i = len(vals)-1
while i > 0:
if vals[i-1] > vals[i]:
return False
i -= 1
return True
def is_untidy( num ):
num.reverse()
if is_tidy( num ):
num.reverse()
return True
else:
num.reverse()
return False
#decrement numb... |
def is_pancakes_happy(pancakes, flip_size):
temp_bool_list = []
for p in pancakes:
temp_bool_list.append(p == "+")
counter = 0
for i in range(len(temp_bool_list) - flip_size + 1):
if not temp_bool_list[i]:
for j in range(flip_size):
temp_bool_list[i + j] = no... |
class Elements(object):
def __init__(self):
self.clearElements()
self.opposedPairs = [] # [("A", "B"), ...]
self.mixPairs = [] # [(("A", "B"), "C"), ...]
def clearElements(self):
self.elements = [] # ["A", "B", ...]
self.counts = {} # {"A": 0,... |
import string
def is_blank(x):
if isinstance(x, list):
return all(v == "?" for v in x)
if isinstance(x, str):
return x == "?"
print "bad x!", x
def extend_list(lst):
ret = lst[:]
if is_blank(lst):
return lst
val = [v for v in lst if not is_blank(v)][0]
for i in ran... |
def BathroomStall(N,K):
curA = {N:1}
toFill = K
curPower = 0
while True:
curLayer = pow(2,curPower)
if curLayer < toFill:
nextA = {}
for space in curA:
if space % 2 == 0:
lv = (space//2)-1
mv = space//2
if lv not in nextA:
nextA[lv] = 0
if mv not in nextA:
... |
#!/usr/bin/env python
import sys
import logging
log = logging.getLogger(__name__)
logging.basicConfig()
class Impossible(Exception):
pass
def print_result(result, i):
sys.stdout.write("Case #%s: %s\n" % (i, result))
def readline():
return sys.stdin.readline().rstrip('\n')
def splitline(fn=str):
... |
# -*- coding: utf-8 -*-
def mow(board, i, sens, high) : # → list [ list [ int ] ] = mowed board
"""
i = indice de la colonne/rangée à tondre
sens = 0 pour horizontal
1 pour vertical
high = hauteur de tondure (oui oui, tondure)
"""
def isOK(board,H,L):
maxRangee = []
maxColonne ... |
#!/usr/bin/python2
import sys
class ElementList:
def __init__(self):
self._elems = []
def __str__(self):
return str(self._elems).replace('\'', '')
def add(self, e):
self._elems.append(e)
def length(self):
return len(self._elems)
def combine(self, triplet):
... |
#! /usr/bin/env python
import sys
def is_palindrome(s):
y = s[::-1]
if (y == s):
return True
else:
return False
def is_square(apositiveint):
if apositiveint == 1:
return (True, 1)
x = apositiveint // 2
seen = set([x])
while x * x != apositiveint:
x = (x + (apositiveint // x)) // 2
if x in seen: retur... |
def read_file():
input_file = open("B-small-attempt0.in")
x = input_file.readline()
y = input_file.read()
d = y.split("\n")
num_tests = int(x)
test_cases = list()
'''
for i in d:
if i is not "":
test_cases.append(int(i))
'''
test_cases = d
tes... |
from __future__ import division
from sys import stdin
def is_square(apositiveint):
if apositiveint == 1:
return 1
x = apositiveint // 2
seen = set([x])
while x * x != apositiveint:
x = (x + (apositiveint // x)) // 2
if x in seen:
return False
seen.add(x)
... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Yixuan Zhao <johnsonqrr (at) gmail.com>
# f = open('A-large-practice.in','r')
# import sys
# sys.stdin = f
T = int(raw_input())
def flip(pancake, start, flipper_size):
for index in range(start, start + flipper_size):
if pancake[index] == '+':
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.