text stringlengths 37 1.41M |
|---|
# -- separate project --BASE FILE for comp-----------
def readint(): return int(f.readline())
def readarray(): return [int(x) for x in f.readline()[:-1].split()]
def fun():
R=readint(); v=[]
for i in xrange(1,5):
if i==R: v=readarray()
else: readarray()
R1=readint(); v1=[]
for i in xrange(1,5):
if i==R1: v1... |
from math import pi
def compare(x,y):
return y[1]*y[0] - x[1]*x[0]
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K:
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def _... |
#!/usr/bin/env python
def readRow(row):
P = {}
for x in range(1,5):
if row == x:
P = map(int, raw_input().split())
else:
raw_input()
return P
N = int(raw_input())
for t in range(N):
A1 = int(raw_input())
P = readRow(A1)
A2 = int(raw_input())
Q = read... |
# Rahul Butani
# April 8th, 2017
# Takes a character; either '-' or '+'
# Returns the other character
def flip(pancake):
return '-' if pancake is '+' else '+'
# Takes a string of '-'s and '+'s of length S followed by K (space separated)
# Returns the number of flips required or IMPOSSIBLE as a string
def p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==============================================================================
from __future__ import unicode_literals
def print_solution(i, solution):
"""Print the solution string."""
print('Case #{}: {}'.format(i, solution))
# ====================... |
#!/usr/bin/env python3
def first_bad_digit(n_list):
for idx, (a, b) in enumerate(zip(n_list, n_list[1:])):
if a > b:
return idx + 1
return -1
num_cases = int(input())
for case in range(1, num_cases+1):
n_list = list(input())
fbd = first_bad_digit(n_list)
while fbd != -1:
... |
#!/usr/bin/python3
from sys import argv
class walk:
def __init__(self, l, w):
self.l, self.w = l, w
def __lt__(self, other):
return self.w < other.w
infile = open(argv[1])
cases = int(infile.readline())
for i in range(cases):
x, s, r, t, n = map(int, infile.readline().split())
w, e = ... |
#!/usr/bin/env python
#TEST = """3
#1
#3
#4
#1 2 1 2
#1
#4"""
#input = iter(open("B-small-attempt1.in")).__next__
def eat(layout):
return [p-1 for p in layout if p>1]
memo = {}
def best(layout):
# fastest time you can get p pancakes eaten...
# divide the largest or wait?
layout = tuple(sorted(layou... |
def getTimeToDest(d, k, s):
return (d - k) / float(s)
def getSpeedToDest(d, t):
return d / float(t)
if __name__ == '__main__':
noTestCases = int(raw_input())
for testCaseNo in range(1, noTestCases + 1):
d, n = map(int, raw_input().strip().split(' '))
maxTimeToDest = 0
for hi in range(n):
k, ... |
#!usr/bin/env python
"""
Input
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 pancake that is initially happy side up) or - (which r... |
""" Output a file.
For each test case, output one line containing "Case #x: y",
where x is the test case number (starting from 1)
and y is the minimum number of friends you must invite.
Call as
python a.py input
in Terminal
"""
import sys
firstArgument = sys.argv[1]
def output(fileName = firstArgument):
try:
... |
def solve(r, c, grid):
for i in range(1,r):
for j in range(c):
if grid[i][j] is '?':
grid[i][j] = grid[i-1][j]
for i in range(r-1)[::-1]:
for j in range(c):
if grid[i][j] is '?':
grid[i][j] = grid[i+1][j]
for i in range(r):
for j in range(1,c):
if grid[i][j] is '?':
grid[i][j] = grid[i][j-... |
def time(rate, target): return target / rate
def r(cost, ad, tg):
t = 0
rate = 2.0
while time(rate, tg) > time(rate, cost) + time(rate + ad, tg):
t += time(rate, cost)
rate += ad
t += time(rate, tg)
return t
n = int(raw_input())
for z in range(n):
q = map(float, raw_input().split(" "))
print "Case #%d: %... |
def foo(S, K):
# print(S)
if len(S) == K and all([ch=='+' for ch in S]):
return 0
if len(S) < K:
return "IMPOSSIBLE"
if S[0] == '+':
return foo(S[1:], K)
if S[0] == '-':
for x in range(K):
S[x] = '+' if S[x]=='-' else '-'
r = foo(S, K)
if... |
import sys
def solve( filename ):
file = open( filename, 'r' )
tests = int( file.readline() )
for i in range(tests):
[height, width ] = [int(x) for x in file.readline().split()]
board = []
for row in range(height):
board.append( file.readline().strip() )
possible... |
#!/usr/bin/python
import sys
import math
# brute force method
with open(sys.argv[1]) as infile:
cases = int(infile.readline().strip())
for case in range(cases):
values = infile.readline().split()
count = 0
for x in range(int(values[0]), int(values[1])+1):
# if x is a palind... |
import os, copy
class memoized(object):
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self,... |
def _get_breaking_point(digits):
for i in xrange(len(digits) - 1):
if digits[i] > digits[i + 1]:
return i
return len(digits) - 1
def _get_reducing_point(digits):
ret = 0
for i in xrange(1, len(digits)):
if digits[i] != digits[i - 1]:
ret = i
return ret
def... |
#!/usr/bin/python2.6
# Standard libs
import math
import sys
NUM_JUDGES = 3
def get_max_number_of_scores_above_threshold(num_googlers,
num_surprising_scores,
score_threshold,
total_sc... |
#!/usr/bin/python
import sys
class Map:
def __init__(self,H,W):
self.altitudes = []
self.table = []
self.H = H
self.W = W
def __str__(self):
return '\n'.join([' '.join(row) for row in self.table])
def add_row(self,row):
""" must add as we read them in"... |
#!/usr/bin/python
import sys
from math import sqrt, floor
DBG = False
def log(s):
if DBG:
print s
def p(s):
sys.stdout.write(s)
def is_palindrom(a):
s = str(a)
l = len(s)
if l == 1:
return True
m = l / 2
i = 0
while i < m:
if s[i] != s[l-i-1]:
return False
i += 1
return True
def solve(A, B):
... |
import string
import sys
def check(rows, r,c):
try:
return (rows[r][c+1] =="#")and(rows[r+1][c] =="#")and(rows[r+1][c+1] =="#")
except IndexError:
return False
f =open(sys.argv[1],"r")
T =int(f.readline())
for i in range (T):
inp = f.readline().split()
R = int(inp[0])
C = int(in... |
a=int(input())
for i in range(a):
b=int(input())
while(True):
s=str(b)
s=list(s)
sorted_list=sorted(s)
if(s==sorted_list):
break
else:
b-=1
print("Case #%d: %d" % (i+1,b))
|
#!/usr/bin/python
import sys
def Dec2Bin(num):
binaryNum = ''
if 0 == num: return '0'
while num > 0:
binaryNum += str(num % 2)
num = num >> 1
return binaryNum
def main():
numOfCases = input()
for currentCase in range(1, numOfCases + 1):
''' We input the whole line and ... |
class cooperative():
def __init__(self,q):
self.total = int(q[0])
self.q = q[1:]
self.O=1
self.B=1
self.O_blocked = False
self.B_blocked = False
self.seconds=0
i=0
while (i<self.total):
self.q[2*i+1]=int(self.q[2*i+1])
... |
def is_tidy(number):
numbers = [int(num) for num in str(number)]
correct = True
last = numbers[0]
for num in numbers[1:]:
if last > num:
correct = False
last = num
return correct
def load_tests():
tests = []
with open('tidy_numbers_input.txt') as data... |
#!/usr/bin/python3
import re
#import matplotlib.pyplot as plt
import sys
import itertools
import math
import logging
from functools import partial
import argparse
# CodeJam I/O helpers adapted from royf
# A single word (minus whitespace)
def read_word(f):
return next(f).strip()
# A single int (given base)
def r... |
from sys import stdin
def is_palindrome(n):
forward = str(n)
backward = [c for c in forward]
backward.reverse()
backward = ''.join(backward)
return forward == backward
cases = int(stdin.readline())
for case in range(1, cases+1):
(A, B) = [int(n) for n in stdin.readline().split()]
f... |
import operator
def analyse(n,r,o,y,g,b,v):
letters = "ROYGBV"
valids = [(2,3,4),(3,4,5),(4,5,0),(5,0,1),(0,1,2),(1,2,3),(0,1,2,3,4,5)]
origN = n
origNumbers = [r,o,y,g,b,v]
numbers = [r,o,y,g,b,v]
#print("")
#print(numbers)
if y + g + b < r or g + b + v < o or b + v + r < y or v + r + o < g or r + o + y < ... |
'''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 their d... |
#!/usr/bin/python
#
# Google Code Jam
#
#
import sys
import os
debug=False
def checkwin(board,i,j,idiff,jdiff):
global k
for x in xrange(0, k):
ii = i+(idiff*x)
jj = j+(jdiff*x)
if ii < 0 or ii >= len(board): return False
if jj < 0 or jj >= len(board): return False
if board[i+(idiff*x)][j+(jdiff*x)] != b... |
#!/usr/bin/env python2
import logging
import math
logging.basicConfig(filename='debug.log',level=logging.DEBUG)
log = logging.getLogger("default")
results = { }
def calculate(num_stalls, num_people):
cached = results.get((num_stalls, num_people))
if cached:
return cached
if num_people == 1:
... |
def sol_print(value):
sol_print.line_number += 1
print "Case #%d: %s"%(sol_print.line_number, value)
def is_tidy(number):
max_idx = len(number) - 1
for idx, value in enumerate(number):
if idx < max_idx:
if int(number[idx]) > int(number[idx + 1]):
return False
re... |
#!/usr/bin/env python
import sys
import operator
from math import sqrt, floor, ceil
from collections import Counter
class InputFile:
def __init__(self, fd):
self.fd = fd
def readInt(self):
return int(self.fd.readline())
def readIntegers(self):
return tuple([int(x) for x in self.fd.readline().split()])
def r... |
from sys import stderr, stdout
how_many_cache = dict()
text = ""
pattern = "welcome to code jam"
# How many times the given pattern occurs in the given text?
def how_many(start_text, start_pattern):
global how_many_cache
global text
global pattern
#print >> stderr, "how_many(%s (%d), %s (%d))" % (tex... |
import logging
import Queue as Q
import math
import pprint
logging.basicConfig(filename='log.txt', level=logging.DEBUG)
def compute(N,K,pancakes):
# bottom_cake = -1
# bottom_cake_surface = -1
# for i in xrange(N):
# r,h = pancakes[i]
# this_cake_surface = math.pi*r**2+2*math.pi*r*h
#... |
#!/usr/bin/python
f=open("alien.txt");
line=f.readline();
values=line.split();
L=int(values[0]);
D=int(values[1]);
N=int(values[2]);
words=[]
for i in range(0,D):
words.append(f.readline()[:L]);
index=0;
for i in range(0,N):
index+=1;
p=f.readline();
patterns=[];
group=0;
for c in p[:-1]:
if c=='(' and g... |
#!/usr/bin/python
import re
import sys
line = raw_input()
(L, D, N) = line.split(' ', 3)
L, D, N = int(L), int(D), int(N)
words = []
patterns = []
for i in range(0, D):
line = raw_input()
words.append(line)
for i in range(0, N):
line = raw_input()
patterns.append(line.replace('(', '[').replace(')', ']'))
#print ... |
#!/usr/bin/env python3.2
"""
Swinging Wild problem
for Google Code Jam 2012
Round 2
Link to problem description:
http://code.google.com/codejam/contest/1842485/dashboard#s=p0
author:
Christos Nitsas
(chrisn654)
language:
Python 3.2.1
date:
May, 2012
usage:
$ python3.2 runme.py sample.in
or
$ runme.py sample.in
(w... |
#!/usr/bin/python
#coding:utf8
"""
#patricks sum is xor?
def add(a,b):
return a ^ b
assert add(12L,5L) == 9
assert add(5, 4) == 1
assert add(7, 9) == 14
assert add(50, 10) == 56
"""
from operator import xor, add
def partition(A):
if reduce(xor, A):
return "NO"
menor = min(A) #O(n)
A.remove(men... |
#v2.0
import os
#Reads file whose name is specified by the argument "infilename" in the current working directory, and returns a value T, the first line in the file, and a two dimensional array, where X is the line number and Y is the values on that line, seperated by spaces.
def read_infile(infilename,splitSpaces):
f... |
#!/usr/bin/python
import sys
def patcalc(pile):
""" patrick calculation of how much a pile of candies is worth"""
if len(pile) == 1: # just one candy
return(pile[0])
elif len(pile) > 1: # more than 1
return(patsum(pile[0],patcalc(pile[1:]))) # recurse
def patsum(a,b):
abin = bin(a)
bbin = bin(... |
#coding:utf8
def insert(queue, a,n):
for item in queue:
if item[0] == a:
item[1]+=n
return
queue.append([a,n])
#TODO
#gör så att alla consecutive likadana, addas i samma lista, då vinner du
#det finns bara två tal i taget!!!!!!! tänk på det
def main():
te... |
import math
import Queue
def occupyStall(n, p):
# if n == 1:
# return n, p + 1, n, n - 1
if n % 2 == 0:
n = n / 2
return n, p + 1, n, n - 1
else:
n = n - 1
return n, p + 1, n / 2, n / 2
f_in = open("C-small-1-attempt1.in", "r")
f_out = open("bathroom_stalls_output", "w")
numTests = int(f_in.readline())
f... |
import sys
from math import sqrt, ceil
file = sys.argv[1]
text = open(file)
lines = text.readlines()
cases = lines.pop(0);
fair_squares = []
def is_palindrome(n):
n = str(n)
if len(n) == 1 or len(n)==0:
return True
if n[0] == n[-1]:
return is_palindrome(n[1:-1])
return False
for i in range(1, ceil(sqrt(1... |
# input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Google Code Jam problems.
t = int(input()) # read a line with a single integer
for i in range(1, t + 1):
pancake_list, pancaker = input().split(" ") # read a list of integers, 2 in this case
... |
import sys
import math
file = sys.stdin
def ispalindrome(n):
s = str(n)
k = len(s)
for i in range(0,k/2):
if s[i] != s[k-1-i]:
return 0
return 1
def countfairandsquare(A,B):
count = 0
n = int(math.sqrt(A))
bound = int(math.sqrt(B))
while n*n < A:
n += 1
while n <= bound:
if ispalindrome(n) and ispa... |
# -*- coding: utf8 -*-
import os
import sys
import math
def isPalindrome(num):
candy = str(num);
maxIdx = len(candy);
if(1 == num or 2 == num):
return True;
idx = 0;
while(idx < maxIdx):
#print("idx : %d / len(candy) : %d" % (idx, len(candy)));
if(candy[idx] != candy[len(candy) - idx - 1])... |
# Daniel Balle 2017
#
# Bathrooms Stalls
# https://code.google.com/codejam/contest/3264486/dashboard#s=p2
# use this with inverted inputs lol
import heapq
def pee(stalls):
# find the best stall
section = -heapq.heappop(stalls) - 1 # minus one since we now poop
half = section / 2
if half > 0 : heapq.h... |
def solve(cipher):
cipher = cipher.split(' ')
num_standing, str_index, s_max, zeros = 0, 0, int(cipher[0]), 0
cipher = cipher[1]
while (str_index < len(cipher)):
if (str_index > num_standing + zeros):
zeros += 1
num_standing += int(cipher[str_index])
str_index += 1
return zeros
if __name__ == "__main__"... |
from fractions import Fraction
T = int(raw_input())
for t in range(T):
print "Case #{0}:".format(t+1),
c, f, x = [float(i) for i in raw_input().split()]
tm = 0.0
cf = 0.0
while True:
# no farm: wait tm+x/(2+cf*f)
# farm: wait tm+c/(2+cf*f), buy, wait x/(2+(cf+1)*f)
... |
#!/usr/bin/python3
def get_possible_cards():
row = int(input())
result = None
for i in range(4):
cards = set(map(int, input().split()))
if i + 1 == row:
result = cards
return result
for test_case in range(int(input())):
print('Case #{}: '.format(test_case + 1), end='')... |
import sys
def d(*args):
sys.stderr.write(', '.join(map(str, args)) + "\n")
def printf(*args):
print(''.join(map(str, args)))
def int_input():
return list(map(int, input().split(' ')))
def solve(n, s):
nb = s[0]
toadd = 0
for i in range(1, n+1):
if nb < i:
toadd += (i-nb)... |
#!/usr/bin/python
import os, sys, math
def solve(case):
possibles = set(case[0]['board'][case[0]['guess']])
possibles = list(possibles.intersection(set(case[1]['board'][case[1]['guess']])))
if len(possibles) == 1:
return possibles[0]
if len(possibles) == 0:
return "Volunteer cheated!"
... |
input_file = open("A-large.in")
output_file = open("standing_ovation.txt", "w")
Testcases = int(input_file.readline()[:-1])
def calc_shyness(string):
'''
To seperate the 2 parts of a line and return as a list
'''
for letter in range(len(string)):
if string[letter] == ' ':
... |
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 circle(r, t):
num = 0
amount_used = 0
r += 1
while amount_used <= t:
area = (2 * r - 1)
amount_used +... |
def is_tidy(string):
num_list = list(map(int,string))
sorted_list = list(num_list)
sorted_list.sort()
return num_list == sorted_list
def find_last_tidy(num):
while num > 0:
if is_tidy(str(num)):
return num
num -= 1
def find_last_tidy_fast(num):
if is_tidy(str(num)):
return num
digits = ... |
#!/usr/bin/env python
# Indicates the winner of a tic-tac-toe-tomek game based on the given game board
# Input:
# board - a 4-element list of strings representing a 4x4 board
# - each string has 4 characters and represents the pieces on a row
# of the game board
# - each character of a... |
# 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 heapq
def solve_slow(n, k):
q = []
heapq.heappush(q, -n)
for __ in range(k):
n = -heapq.heappop(q)
heapq.heappush(q, -(n // 2))
h... |
# 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 tidy(x):
tidy = True
while x>0:
tidy = (x//10)%10 <= x%10
x = x//10
if not(tidy):
return tidy
return t... |
import sys
import math
f_in = open(sys.argv[1], 'r')
T = int(f_in.readline())
r = open(sys.argv[2], 'w')
def is_palindrome(s):
reverse = s[::-1]
if s == reverse:
return True
else:
return False
def solve(low,high):
count = 0
for i in range(low,high+1):
if (is_palindrome(str(i))):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def solve(user_input):
users = user_input.split()[1]
current_users = 0
needed_users = 0
for i in range(0, len(users)):
if int(users[i]) != 0:
if i <= current_users:
current_users += int(users[i])
else:
... |
import sys
def possible_design(lawn, n, m):
possible = [[False for i in range(m)] for j in range(n)]
for i in range(n):
line = lawn[i]
highest = max(line)
for j in range(m):
if line[j] == highest:
possible[i][j] = True
for j in range(m):
line = [... |
#! /usr/bin/env python
input = open("/Users/benzax/code_jam/input.txt",'r')
s = input.readline()
arr = s.split(" ")
L = int(arr[0])
D = int(arr[1])
N = int(arr[2])
words = []
for i in xrange(0,D):
words.append((input.readline())[:-1])
output = open("/Users/benzax/code_jam/output.txt",'w')
def match(word, lette... |
import sys
def main():
if(len(sys.argv) < 2):
print("Not enough arguments. Exiting.")
exit()
file = open(sys.argv[1], 'r')
totalCases = int(file.readline().strip())
testCases = 0
line = file.readline().strip()
while(line != ""):
pancakes, flipper = line.split(" ")
... |
def readint(): return int(raw_input())
def readints(): return [ int(x) for x in raw_input().split() ]
nt = readint()
for i in range(nt):
ns, nf = tuple(readints())
sw = (1 << ns)-1
if (sw & nf) == sw :
a = "ON"
else:
a = "OFF"
print "Case #%d: %s" % (i+1, a)
|
# -*- coding:utf-8 -*-
import sys,os
def ReadInt():
line = sys.stdin.readline().rstrip("\n").split()
return map(int,line)
def IsLight(n,k):
if k == 0:
return False
elif k == ((2**N) - 1):
return True
else:
return False
T = ReadInt()[0]
for i in xrange(1,T+1):
N,K = ReadInt()
# if N == 1:
... |
#!/usr/bin/python
import sys;
import string;
import math;
if len(sys.argv) != 2:
print 'Usage: fair-and-square.py <input file>'
exit()
try:
f = open(sys.argv[1], 'r')
except:
print "Could not open the file: " + sys.argv[1]
exit()
def is_int(num):
if (num == math.floor(num)):
return True;
def is_palindrome(n... |
def opposite(c):
if c == '+': return '-'
else: return '+'
def count_flips(S, k):
S_chars = []
for c in S:
S_chars.append(c)
num_flips = 0
remaining_len = len(S)
index = 0
while True:
# keep scanning until you find a -
for i in xrange(remaining_len):
if S_chars[index] == ... |
#!/usr/bin/python
from sys import argv
def main():
f = file(argv[1])
n = int(f.readline())
for i in range(n):
board = []
for r in range(4):
board.append(list(f.readline()[:-1]))
Xboard = replace_board(board, 'T', 'X')
Oboard = replace_board(board, 'T', 'O')
... |
import string, sys
mapping = dict((a, b) for a, b in zip(
"""ejp mysljylc kd kxveddknmc re jsicpdrysirbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcdde kr kd eoya kw aej tysr re ujdr lkgc jvqeez""",
"""our language is impossible to understandthere are twenty six factorial possibilitiesso it is okay if you want to ju... |
#! /usr/bin/env python
import pprint
import sys
import string
next_letter = 0
def scan_cells(basin_map, row, col):
if basin_map[row][col]['basin'] != None:
return basin_map[row][col]['basin']
flow_cell = None
lowest_altitude = basin_map[row][col]['height']
# test where water flows down
#... |
#!/usr/bin/python
"""
Dancing With the Googlers problem solution
(GCJ 2012, Qualification Round)
Author: a5kin
"""
import sys, math
# open input file
if len(sys.argv) == 2 and sys.argv[1] != '--help':
in_file = open(sys.argv[1])
else:
print "Usage: dancing_with_the_googlers.py <input file>"
sys.exit(0)
... |
#!/usr/bin/env python
"""
recycled_numbers.py
a script for the Google code jam 2012 Qulification Round Problem C
USAGE: python recycled_numbers.py filename.in filename.out
"""
import sys
RECYCLED = {}
def go(inputfile):
result = []
num_of_problems = int(inputfile.readline())
for case in range(1,nu... |
from codejam import *
def doboard(board):
R = len(board)
C = len(board[0])
for rr in range(R-1):
while True:
try:
cc = board[rr].index('#')
except ValueError:
break
if cc == C-1 or board[rr][cc+1] != '#': return "Impossible"
... |
#!/usr/bin/env python2.7
from sys import argv
if len(argv) != 2:
print 'no file'
else:
inputfile = open(argv[1], 'r')
outputfile = open('result', 'w')
n = inputfile.readline().split('\n', 1)
n = int(n[0]) # convertir chaine
print n, ':nombre de tours'
for i in range(0, n):
line... |
def flip(ch):
if ch == '+':
return '-'
else:
return '+'
def main():
t = int(input()) # read a line with a single integer
for case in range(1, t + 1):
print("Case #{}: ".format(case), end="")
count = 0
impossible = False
s, k = input().split(" ") # rea... |
case_nr = int(input())
for i in range(case_nr):
text, number = input().split()
txt = list(text)
nr = int(number)
cnt = 0
if "-" in txt:
for idx in range(len(txt[:len(txt)-nr+1])):
if txt[idx] == "-":
for x in range(nr):
if txt[idx+x]=="-":
txt[idx+x]="+"
else:
txt[idx+... |
from sys import stdin
def _other(x, y):
return [u for u in ('i', 'j', 'k') if u not in (x, y)][0]
def _mult(x, y):
if x == 1:
return (1, y)
elif y == 1:
return (1, x)
elif x == y:
return (-1, 1)
else:
sign = 1 if (ord(y) - ord('i')) % 3 == (ord(x) - ord('i') + 1) % ... |
#!/usr/bin/pypy
def read_line():
s = raw_input()
while s == "":
s = raw_input()
return s
def read_int():
return int(read_line())
def read_ints():
return tuple(int(s) for s in read_line().split())
def solve():
N, X = read_ints()
S = read_ints()
S = tuple(sorted(S))
assert... |
import math
def get_result_from_stall_bank(num_stalls):
half = (num_stalls - 1) / 2
return [math.ceil(half), math.floor(half)]
def solve(left, right):
if left is None:
# print("Using right side")
return right
elif right is None:
# print("Using left side")
return left
... |
__author__ = 'Drazen'
import math
from fractions import Fraction
def solve(frac):
result = math.log(frac.denominator,2)
temp = 1.0
counter = 0
if math.floor(result) != result:
return 'impossible'
while temp > frac:
counter += 1
temp /= 2.0
return str(cou... |
import math
import sys
def get_map():
file_read = open("1_map.txt", 'r')
lines = file_read.readlines()
g_word = [] ; e_word = [] ; lang_map = {}
for k in range(3):
g_word.append(str(lines[2*k]))
e_word.append(str(lines[(2*k)+1]))
for j in range(len(g_word[k])):
val = e_word[k][j] ; key = ... |
#! /usr/bin/env python
import sys
import string
filename = sys.argv[1]
file = open(filename, 'r')
lines = file.readlines()
S = int(lines.pop(0)) #pop off how many lines there are
file.close()
# E - T English - Translation
# a - y
# b - n
# c - f
# d - i
# e - c
# f - w
# g - l
# h - b
# i - k
#... |
def is_tiny(number):
for i in range(len(number) - 1):
if (number[i] > number[i + 1]):
return False
return True
def make_tiny(number):
for i in range(len(number) - 1):
if (number[i] > number[i + 1]):
for j in range(len(number) - i - 1):
# print("# i:... |
testcases=input()
def is_not_sorted(l):
for i in range(len(l)-1):
if(l[i]<=l[i+1]):
pass
else:
return True
return False
def update(l):
for i in range(len(l)-1):
if (l[i]>l[i+1]):
p=int(l[i])
p=p-1
c=len(l)-i
... |
num = int(input())
def get_tidy_number(num):
while num:
number = str(num)
if "".join(sorted(number)) == number:
return number
num -= 1
for i in range(num):
val = int(input())
print("Case #" + str(i+1) + ": " + get_tidy_number(val)) |
#!/usr/bin/env py3k
"""
Problem
Geologists sometimes divide an area of land into different regions based on where rainfall flows down to. These regions are called drainage basins.
Given an elevation map (a 2-dimensional array of altitudes), label the map such that locations in the same drainage basin have the same la... |
def process(f):
cost, extraRate, goal = [float(x) for x in f.readline().split(' ')]
rate = 2
projectedTime = goal / rate
overhead = 0
# We want to compare time at current rate vs. time when we buy
while True:
timeIfBought = overhead + cost / rate + goal / (extraRate + rate)
if timeIfBought >= projectedTime:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import time
def getValue(inputFile,dataType="string"):
line=""
value=0
while len(line) < 1:
line=inputFile.readline()
if dataType=="string":
value=line.split()[0]
elif dataType=="integer":
value=int(line.split()[0])
elif dataType=="float":
... |
'''
Created on Apr 12, 2014
@author: learning-python
'''
def get_choices (row_zero_index, grid):
return {int(number) for number in grid[row_zero_index].split(" ")}
if __name__ == '__main__':
test = open("test_input", "r")
lines = [line.strip() for line in test]
num_tests = int(lines[0]... |
#!/usr/bin/python3
import sys
input_file = sys.argv[-1]
file = open(input_file, 'r')
twerk = file.readlines()
num_test_cases = int(twerk[0])
cursor = 1
case = 1
cursor_final = (num_test_cases * 10) - 9
while cursor <= cursor_final:
first_row_index = int(twerk[cursor])
second_row_index = int(twerk[cursor+5])
... |
def googl(fin):
#dic = {}
o = 0
compa = {'y':'a','n':'b','f':'c','i':'d','c':'e','w':'f','l':'g','b':'h','k':'i','u':'j','o':'k','m':'l','x':'m','s':'n','e':'o','v':'p','z':'q','p':'r','d':'s','r':'t','j':'u','g':'v','t':'w','h':'x','a':'y','q':'z'}
a = ""
c = 1
while fin!='':
#print c
#print fin
... |
import itertools
def joinTuple(A):
ans = ''
for each in A:
ans += str(each)
return ans
def getAll(str, times):
return [p for p in itertools.product(list(str), repeat = times)]
def search(pattern, text):
shift = computeShifts(pattern)
startPos = 0
matchLen = 0
ans = 0
for c in text:
... |
cases = int(raw_input())
for case in xrange(cases):
board = []
winner = ''
complete = True
for r in xrange(4):
row_in = raw_input()
if '.' in row_in:
complete = False
board.append(list(row_in))
raw_input() # Take empty line following case
# Check horizonta... |
import math
def distance(N, K):
"""
returns min(Ls, Rs), max(Ls, Rs)
"""
if N == 1:
return 0, 0
if K == 1:
return (N-1)//2, N//2
lv = int(math.log(K, 2)) # how many levels we'll go down this "binary tree split"
# note that if K == 2**N-1, we'll technically complete the last level,
# bu... |
problemName = "A-large (2)"
#problemName = "test"
class multiQueue(object):
def __init__(self):
self.que = []
def push(self, station, people):
self.que.append((station, people))
def pop(self, stationOff, people,costFunc):
Runningcost = 0
while p... |
numcases = int(input())
for numcase in range(numcases):
inputs = list(map(float, input().split(' ')))
farmcost, farmcookierate, goal = inputs[0], inputs[1], inputs[2]
cookierate = 2
cookies = 0
seconds = 0
while cookies < goal:
#print(seconds, cookies, cookierate)
ti... |
__author__ = 'giagulei'
import sys
def parse_input(filename):
with open(filename, 'r') as f:
T = int(f.readline())
tests = f.readlines()
counter = 1
for l in tests:
testcase = l.split()
pancakes = testcase[0]
K = int(testcase[1])
# s... |
#!/usr/bin/env python
def read_input():
num_test_cases = input()
test_cases = []
for i in range(0, num_test_cases):
first_answer = input()
first_arrangement = [map(int, raw_input().split()) for j in range(0, 4)]
second_answer = input()
second_arrangement = [map(int,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.