text
stringlengths
37
1.41M
text_file = open("B_input.txt", "r") out_file = open("out.txt", "w") out_file.write('') out_file.close() out_file = open("out.txt", "a") input_text = text_file.readlines() run_amount = int(input_text[0]) for x in range(1, run_amount+1): data = input_text[x].split(" ") number_of_googlers = data[0] ...
#!/usr/bin/python import sys import math def is_polindrom(s): s = str(s) for i in range(0, len(s) / 2): if s[i] != s[len(s) - i - 1]: return False return True def count_numbers(A, B): pnumber = math.sqrt(A) while not pnumber.is_integer(): pnumber = math.sqrt(A) A = A + 1 pnumber = int(p...
# -*- coding: utf-8 -*- # QR A. Oversized Pancake Flipper #INPUT = 'A-small-attempt0.in' #INPUT = 'qr_a-small.in' #OUTPUT = 'qr_a-small.out' INPUT = 'A-large.in' OUTPUT = 'qr_a-large.out' def result(caseno, msg): output = open(OUTPUT, 'a') output.write('Case #%d: %s\n' % (caseno, msg)) output.close() ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # 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. testCaseTotal = int(raw_input()) # read a line with a single integer for testCase in xrange(1, testCaseTotal + 1): D,...
t = int(raw_input()) # read a line with a single integer def round_down(num, divisor): return num - (num%divisor) for i in xrange(1, t + 1): N = int(raw_input()) r=N pow=1 while N > 0: if str(N)=="".join(sorted(str(N))): r=N; break divisor = 10**(pow-1) if N > divisor: N=round_down(N...
#import psyco import string order = [1,0,2,3,4,5,6,7,8,9] order = [str(i) for i in order] order = order + list(string.lowercase) def solve(alien_number): mapping = {} regular_number = [] i = 0 for digit in alien_number: if digit in mapping: regula...
INPUT = """ 3 4 O 2 B 1 B 2 O 4 3 O 5 O 8 B 100 2 B 2 B 1 """ OUTPUT = """ Case #1: 6 Case #2: 100 Case #3: 4 """ import itertools def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itertools.izip_longest(fillvalue=f...
from math import ceil, sqrt, floor def fair_and_square(n): str_n = str(n) str_n_sq = str(n * n) return str_n == str_n[::-1] and str_n_sq == str_n_sq[::-1] n = raw_input() for i in xrange(int(n)): interval = raw_input() interval = interval.split(" ") # print interval s = 0 for x in xran...
#!/usr/bin/env python import sys from math import * class Quaternion: def __init__(self,a,b): self.a=a self.b=b def __str__(self): aff='(' aff+=str(self.a.real)+')+(' aff+=str(self.a.imag)+')i+(' aff+=str(self.b.real)+')j+(' aff+=str(self.b.imag)+')k' return aff def __repr__(self): return s...
import math import sys def main(inputFilePath): """Main Function for Parsing the input File""" cases = [] try: inFile = open(inputFilePath, "r") try: inputNumber = int(inFile.readline()) for i in xrange(0,inputNumber): cases.append(inFile.readline().split()) inFile.close() ...
def snapout(): totalTest = int(input()) inpu = [] result =[] change = [] flipby = [] # input of values for i in range(totalTest): inpu.append(input()) x = inpu[i].split(" ") change.append(x[0]) flipby...
def requiredRounds(pancakes): maxPancakes = max(pancakes) if maxPancakes <= 3: return maxPancakes minAdditionalRounds = maxPancakes for k in range(1, maxPancakes/2+1): newPancakes = [pancake for pancake in pancakes if not pancake == maxPancakes] additionalRounds = len(pancakes) ...
def main(): filename = 'A-small-attempt1.in' magic_trick(filename) def magic_trick(infilename): f = open(infilename, 'r') num_tests = int(f.readline()) for i in range(0, num_tests): row1 = read_row_choice(f) array1 = read_array(f, 4) row2 = read_row_choice(f) arr...
def check_win(L): """ L is a list which contains either a row, column or diagonal """ valid = "XOT." counts = {} #print L for c in valid: counts[c] = 0 for i in L: counts[i] += 1 if counts["."] > 0: return "" for i in L: if (counts[i] == 3 and counts['T...
import math palindromes = {} palindromes[1] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] def generatePalindromesInInterval(start, end): startDigits = len(str(start)) endDigits = len(str(end)) palinList = [] for digits in range(startDigits, endDigits+1): if digits not in palin...
#!/usr/bin/python import sys import os def num_in_format(num): c = [int(d) for d in str(num)] clen = len(c) for i in range(clen-1): if c[i] > c[i+1]: return False return True def calculate_output(digit): if (digit < 10): return digit for i in range(digit, 9, -1): ...
import sys def even(l): remainder = sum(l)%2 if remainder == 1: return False else: return True def leastSigBit(l): l = [x%2 for x in l] return l def rightShift(l): l = [int(x/2) for x in l] return l def splitCandy(n, c): numCandies = int(n) candies = map(lambda x:...
import fileinput class TestCase(object): def __init__(self, num, dinerP): self.numberOfDiner = num self.dinerP = dinerP def sortPancakes(t): waitTime = 1 maxP = 0 for x in range (0, t.numberOfDiner): p = int(t.dinerP[x]) if (p > maxP): maxP = p minTime = maxP if minTime <= waitTim...
# encoding=utf8 """ Problem ======= Little John likes palindromes, and thinks them to be fair (which is a fancy word for nice). A palindrome is just an integer that reads the same backwards and forwards - so 6, 11 and 121 are all palindromes, while 10, 12, 223 and 2244 are not (even though 010=10, we don't consider le...
import numbers from re import split, compile import re from random import randint from string import ljust,rjust from sys import argv def run_file(): if len(argv)>1: filename = argv[1] else: filename = 'A-large.in' filename = 'A-small.in' f=file(filename) program =...
import fileinput def read_input(): # gets next line from the file specified as argument or stdin # useful to debug within PyCharm, because you can't redirect stdin :-( # first time, initialize a function attribute (it's like a static local function in C++) # that will keep state across invocations ...
def copy_row(grid, src, dest): for idx, char in enumerate(grid[src]): grid[dest][idx] = char def process_row(row): previous_letter = None unmatched_qm = 0 for idx, char in enumerate(row): if char == '?': if previous_letter is not None: row[idx] = previous_let...
#! /usr/bin/env python import sys class Cell : def __init__(self, alt) : self.alt = alt self.sink = None self.sources = [] self.basin = '' def __str__(self) : return self.basin def addSource(self, src) : if ( src.sink ) : src.sink.sources.remove(src) ...
#!/usr/bin/python import sys def read_tokens(f): for line in f: for t in line.split(): yield t words = [] tokenNumber = 0 caseNumber = 1 for token in read_tokens(sys.stdin): if (tokenNumber == 0): intL = int(token) elif (tokenNumber == 1): intD = int(token) ...
# coding: utf-8 import sys def test_horizontal(rows): # horizontal check is_possible = [] for row in rows: m = max(row) is_possible.append([m == h for h in row]) return is_possible def test_vertical(rows): # vertical check is_possible = [] for col in zip(*rows): m ...
cases = int(raw_input()) case = 1 def checkColumn(game, col, piece): return ((game[0][col] == piece or game[0][col] == "T") and (game[1][col] == piece or game[1][col] == "T") and (game[2][col] == piece or game[2][col] == "T") and (game[3][col] == piece or game[3][c...
def read_line(line): board_line = [] for ch in line: board_line.append(ch) return board_line def read_board(board_str): board = [] for line in board_str.splitlines(): board.append(read_line(line)) return board def get_char(target_char, actual_char): if target_char == actual_char: return target_char ...
def row_match(board, p): for row in board: if row == 4*p: return True return False def col_match(board, p): for i in range(4): if board[0][i]+board[1][i]+board[2][i]+board[3][i] == 4*p: return True return False def up_cross_match(board, p): for i in rang...
import sys filein, fileout = sys.argv[1:3] from math import log,floor primes_list = [2] def primes(): for p in primes_list: yield p k = p+1 while True: isprime = True for p in primes_list: if k % p == 0: isprime = False break if i...
#!/usr/bin/env python2 import math def check_palin(x): string = str(x) length = len(string) for y in xrange(0,length/2+1): if string[y] != string[length-y-1]: return False return True def check_square_palin(x): sqr = x*x return check_palin(sqr) count = int(raw_input()) for x in xrange(1,count...
# coding: utf8 # Problem # It's opening night at the opera, and your friend is the prima donna (the lead female singer). You will not be in the audience, but you want to make sure she receives a standing ovation -- with every audience member standing up and clapping their hands for her. # Initially, the entire audie...
cases = int(raw_input()) def readboard(): b = [raw_input(), raw_input(), raw_input(), raw_input()] try: raw_input() except: pass return b def cell_matches(player, value): assert player in 'XO' return value == player or value == 'T' def check_row(i, b): for player in 'XO': ...
def line_to_int(line): return int(line.rstrip()) def closest_pair(universe): W = len(universe) for i in range(W): if i == W-1: return None if universe[i][1] == "N" and universe[i+1][1] == "K": return i def closest_pair_inverse(universe): W = len(universe) for i in range(W): if i == ...
import math def palindrome(n): n=int(n) rev_n=int(str(n)[::-1]) if n==rev_n: return True else: return False def isSquare(n): tst =int(math.sqrt(n) + 0.5) return tst*tst == n a=[] f=open("input.txt","r") n = f.readline() line=f.readline...
""" Tidy numbers problem - find last number in range with ascending digits""" from sys import stdin def check_tidy(digit_string): if len(digit_string) < 2: return True, 0 for i in range(len(digit_string)-1, 0, -1): if digit_string[i] < digit_string[i-1]: return False, i-1 return...
import math import queue def get_side_area(r, h): return 2 * r * h def get_top_area(r): return r * r def answer(k, rhs): n = len(rhs) rhs.sort() max_area = 0 total_side_area = 0 q = queue.PriorityQueue() for i, (r, h) in zip(range(1, n + 1), rhs): i...
import sys import math f = open(sys.argv[1]) lines = f.readlines() f.close() lineNumber = 1 t = int(lines[0]) for tt in range(t): result = "YES" line = lines[lineNumber] lineNumber += 1 fields = line.split() #print(fields) (field1, field2) = fields numRows = int(field1) numCols = int(field2...
import sys def xor(x, y): return x ^ y def add(x, y): return x + y def get_max_candy(candy_values_str): max_candy = 0 candy_values = [int(value) for value in candy_values_str.split()] xor_sum = reduce(xor, candy_values) if xor_sum != 0: return "NO" # If the elements of the list ...
#!/usr/bin/env python input_1 = "ejp mysljylc kd kxveddknmc re jsicpdrysi" input_2 = "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd" input_3 = "de kr kd eoya kw aej tysr re ujdr lkgc jv" output_1 = "our language is impossible to understand" output_2 = "there are twenty six factorial possibilities" output_3 = "so it i...
# Google Code Jam 2015 def numstanding(peeps): return currently_standing(peeps, 0) def homies_required(peeps): numpeeps = sum(peeps) if numstanding(peeps) == numpeeps: return 0 possesize = 0 while True: possesize += 1 peeps[0] += 1 totalrequired = sum(peeps) standing = numstanding(peeps) if standi...
''' Created on 14 avr. 2012 @author: jerome ''' import sys, re def replaceChar(character): if character == 'a': return 'y' elif character == 'b': return 'h' elif character == 'c': return 'e' elif character == 'd': return 's' elif character == 'e': return 'o...
# fair and square def isrev(x): rev=0 n=x while x>0 : t=x%10 #if (t>3) : return 0 rev*=10 rev+=t x/=10 if rev==n: return 1 else: return 0 y=10**14 x=0 while x<y : if isrev(x)==1 and isrev(x*x)==1: print x,"=>",x*x x+=1
def isTidy(number): string_number = str(number) x = 1 for char in string_number: if int(char) >= x: x = int(char) else: return False return True T = int(input()) for i in range(T): #All test cases are covered number = int(input()) tidy = False while(not tidy): tidy = isTidy(number) ...
import sys def rotate(board): newBoard = [] num = len(board) for i in range(num): newBoard.append(range(num)) for i in range(num): for j in range(num): newBoard[i][j] = board[num - j - 1][i] return newBoard def drop(board): num = len(board) for i in range(num,-1,-1): for j in range(num): index = ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # AMiT Kumar | dtu.amit@gmail.com if __name__ == "__main__": testcases = int(raw_input()) def getresult(x, r, c): k = r*c if (k % x == 0): if (x == 4 and k == 8): return 'RICHARD' if (x > 2 and x != k) or (x ...
# 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 stable_neighbor(color_array): r_num = color_array[0] o_num = color_array[1] y_num = color_array[2] g_num = color_array[3] b_num = color_array[4] ...
x = int(raw_input()) for i in range(x): print "Case #" + str(i+1) + ":", number = raw_input() last = 0 newone = "" failingone = "" skipper = False for i in number: if skipper or (int(i) < last): skipper = True failingone += i else: newone += i last = int(i) if (not skippe...
def checkline(line): if (line[0]=='X' or line[0]=='T') and (line[1]=='X' or line[1]=='T') \ and (line[2]=='X' or line[2]=='T') and (line[3]=='X' or line[3]=='T'): return 'X won' if (line[0]=='O' or line[0]=='T') and (line[1]=='O' or line[1]=='T') \ and (line[2]=='O' or line[2]=='T') a...
def check_combine(combinations, e1, e2): for comb in combinations: match1 = comb.find(e1,0,2) match2 = comb.rfind(e2,0,2) if match1 != match2 and match1 != -1 and match2 != -1: return comb[-1] return '' def check_oppose(oppositions, magick, e2): for oppose in op...
#!/usr/bin/env python # -*- coding: utf-8 -*- FILE_NAME = 'A-small-attempt1' 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 = '' dic = { ' ': ' ', 'y': 'a', 'q': 'z', 'e': 'o', } sample_in = ...
import sys def start_standing_ovation(shyness_levels): count = 0 no_of_people_standing = 0 for i in range(0, len(shyness_levels)): if shyness_levels[i] != 0: if no_of_people_standing < i: # you need to add frnds here. count += i - no_of_people_standing ...
def rem(a, b): count = 0 score = 0 n = len(a) for x in a: if x < b[0]: count += 1 '''import pdb pdb.set_trace()''' if count == n: return 0 elif count==0: a = a[1:n] b = b[1:n] score = score + 1 + rem(a, b) else: a = a[count:...
#!/usr/bin/python import sys import math def readfile(file): """ input: T (number of test cases) A B """ tests = [] T = int(file.readline().strip()) for i in xrange(T): test = {} line = file.readline().strip() parts = line.split(" ") if len(parts) != 2: print "HORRIBLE ERROR IN TE...
#!/usr/bin/python3 from sys import argv def print_board(board): for i in range(4): for j in range(4): print(board[4 * i + j], end="") print() print() def winner(*line): """Return the winner of the game if the line is a win for a tic-tac-toe-tomek player. Return None if ...
#to check if num is tidy def isTidy(num): numS = str(num) lengthOfDigit = len(numS) #checking from left to right if 0 is less than 1 for i in range(0,lengthOfDigit-1): #is left digit is greater than right one number is not tidy if (numS[i]>numS[i+1]): return 0 return 1 #getting las...
with open("input") as f: content = f.readlines() case_count = 0 entry_count = None target_row = None row_count = 0 first_row = None second_row = None def check_rows(): global case_count,first_row,second_row case_count+=1 nk=list(set(first_row).intersection(second_row)) if len(nk)==1: print "Case #%s: %s"%(case...
from time import clock import sys import numpy as np # stderr isn't piped to a.out when we do (py3 a.py < a.in) > a.out print = lambda *s: sys.stderr.write(" ".join(str(m) for m in s)+"\n") #--------------------------------------------- """ for n = 2, we have to solve the formulas given in the problem statement ...
import sys import math import itertools def read_int(fp=sys.stdin): return int(fp.readline().strip()) def read_ints(fp=sys.stdin): return map(int, fp.readline().strip().split()) def palindrome(word): word = str(word) return word == word[::-1] def sqrt(number): return int(number ** 0.5) def pali...
def ovation(case,input): numclapping = int(input[0]) friends = 0 for index,value in enumerate(input[1:]): diff = (index+1) - numclapping if int(value) > 0 and diff > 0: friends += diff numclapping += diff numclapping += int(value) print "Case #"+str(case+1)+": "+ str(friends) with open("A-small-attempt...
#!/usr/bin/env python # vim: set fileencoding=utf-8 : """Problem Sean and Patrick are brothers who just got a nice bag of candy from their parents. Each piece of candy has some positive integer value, and the children want to divide the candy between them. First, Sean will split the candy into two piles, and choose on...
# 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): number = [int(s) for s in input()] adjust = 0 final = 0 same = 0 output = ""...
def maxSpeed(D, horses): bestTime=0 for horse in horses: arrivalTime=(D-horse[0])/horse[1] if arrivalTime > bestTime: bestTime=arrivalTime return D/bestTime def main(): t=int(input()) for number in range(1, t + 1): D, N = input().split(" ") ...
def digits(N): digitList = [] while N//10 != 0: digitList.append(N%10) N = N//10 digitList.append(N) return digitList # 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 wit...
# Max best result for non-surprising triplet is floor((total-1)/3 + 1) # Max best result for surprising triplet is floor((total-2)/3 + 2) # Cutoff total for non-suprising triplet is (p-1)*3+1 # Cutoff total for suprising triplet is (p-2)*3+2 # This doesn't work for very small p # non-s cutoff for p = 1 is 1 # non-s cut...
cases = int(raw_input()) debug = False winner = "RICHARD" # check if Richard can choose an onimo that doesn't fit in the grid def checkCheater(X, R, C): if X % 2 == 0: fixedX = X / 2 else: fixedX = (X / 2) + 1 if R < fixedX or C < fixedX: if debug: print "Cheatable grid" return True else: return False...
t = int(raw_input()) for i in xrange(1, t + 1): numbers = list(raw_input()) for ii in range(len(numbers) - 1, 0, -1): if numbers[ii] < numbers[ii - 1]: for j in range(ii, len(numbers)): numbers[j] = '9' numbers[ii - 1] = str(int(numbers[ii - 1]) - 1) result =...
#!/usr/bin/env python3 def flip(S, K, i): for j in range(K): if S[i+j] == '-': S[i+j] = '+' else: S[i+j] = '-' T = int(input()) for t in range(1,T+1): S, K = input().split() K = int(K) N = len(S) S = list(S) flips = 0 for i in range(N): if flips >=...
from typing import List from math import pi import itertools class Pancake: def __init__(self, radius, height): self.radius = radius self.height = height def surface(self): return pi * self.radius ** 2 def rim(self): return 2 * pi * self.radius * self.heig...
#!/usr/bin/python3 def check_combine(element_list, combinations, element): last = element_list[-1] if last == element: last_two = last + element.lower() else: last_two = last + element c = combinations.get(frozenset(last_two), None) if c: del(element_list[-1]) eleme...
#!/usr/bin/env python import sys def main(): n = int(sys.stdin.readline()) for i in range(1, n+1): line = sys.stdin.readline()[:-1] print 'Case #{0}: {1}'.format(i, dancing(line)) def dancing(line): split = line.split(" ") n = int(split[0]) surprises = int(split[1]) p = int(s...
#!/usr/bin/env python # -*- coding:utf-8 -*- ######################## # Google code jam # Problem A. Magic Trick # small input # @Author yangdf ######################## import re pattern = re.compile(r' +') def getInput(line): '''get float value from input str ''' line = line.strip() line = pattern.s...
import fileinput def replace_all(text, dic): for i, j in dic.iteritems(): print i+" to "+j text = text.replace(i, j) return text reps = {'a':'y', 'o':'k', 'z':'q', 'd':'s', 'k':'i', 'v':'p', 'j':'u', 's':'n', 'l':'g', 'g':'v', 'r':'t', 'x':'m', 'y':'a', 'b':'h', 'p':'r', 'e':'o', 'c':'e', 'f':...
#!/user/bin/env python """Google Code Jam 2017: Problem B. Ratatouille""" from __future__ import print_function from builtins import input def main(): T = int(input()) if T < 1 or T > 100: raise RuntimeError("T is not within the valid range") for i in range(T): N,P = map(int, input().split...
#!/usr/bin/env python3 import sys import re import heapq def read(): return sys.stdin.readline().strip() def add_person(occupancy, gap_heap): max_gap_size, gap_left = heapq.heappop(gap_heap) max_gap_size = -max_gap_size index = gap_left + (max_gap_size-1)//2 occupancy[index] = 1 new_gap1 = ...
NOMBRE = {'0': 0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9} def is_len_possible(num): tmp = str(num) l = len(tmp) res = "" for x in xrange(l-2, 0, -1): #print NOMBRE[tmp[l-1]], NOMBRE[tmp[x]], res if NOMBRE[tmp[l-1]] < NOMBRE[tmp[x]]: res += str(tmp[x]) else: return int(res...
from sys import stdin from math import sqrt, ceil, floor def is_palindrome(number): if len(str(number)) < 2: return True reversed = int(str(number)[::-1]) if reversed == number: return True return False f = open('C-small-attempt0.txt','w') stdin = open('C-small-attempt0.in', 'r') T = int(stdin.next().s...
# returns a list of all digits in N, in correct order def getDigList(N): digList = [] while(N > 0): digList.append(N % 10) N /= 10 digList.reverse() return digList # Loops through digList from left to right. If any consecutive elems # are in decreasing order, updates the list ...
#!/usr/bin/python3 def flip(cakes, n): cakes = list(cakes) for i in range(0, n): if cakes[i] == '-': cakes[i] = '+' else: cakes[i] = '-' return ''.join(cakes) def flipper(cakes, n): flips = 0 while len(cakes) > 0: if len(cakes) < n: retur...
#!/usr/bin/env python3 # coding=utf-8 import sys def solve(farm_cost, farm_rate, objective): time = 0.0 cookie_rate = 2.0 while objective/cookie_rate > (farm_cost/cookie_rate + objective/(cookie_rate+farm_rate)): time += farm_cost/cookie_rate cookie_rate += farm_rate #print('time:...
def all_happy(S): for p in S: if p == '-': return False return True def flip(S, l, r): for i in range(l, r + 1): if S[i] == '+': S = S[:i] + '-' + S[i + 1:] else: S = S[:i] + '+' + S[i + 1:] return S def count_flips(S, K): ...
#!/usr/bin/python class Arbol: def __init__(self, porcentaje, nombre, padre, izda=None, dcha=None): self.porcentaje = porcentaje self.nombre = nombre self.padre = padre self.izda = izda self.dcha = dcha def __str__(self): return str(self.datos) def __str_...
def compute_count(case): hops = int(case[0]) hop = 1 total_time = 0 pos = {'O':1, 'B':1} available_time = 0 consumed_time = {'robot':'O', 'time': 0} while hop<hops*2+1: time_taken = abs(int(case[hop+1]) - pos[case[hop]]) +1 #print "time_taken...
#global variable next = 0 tagged = 0 #returns (ln,cn) of the lesser neighbour of (l,c). (l, c) is returned if elt is sink def Less(l, c, map): #checks element out of boundries if c < 0 or c > len(map[0]) or l < 0 or l > len(map): return "OutOfBoundries" else: less = (l, c, map[l][c][0]...
# -*- coding: utf-8 -*- base_elements = ['Q', 'W', 'E', 'R', 'A', 'S', 'D', 'F'] nbase_elements = ['T', 'Y', 'U', 'I', 'O', 'P', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'] T = int(raw_input()) for t in xrange(1, T+1): line = raw_input().split(" ") C = int(line[0]) D = int(line[C+1]) N...
# 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 is_tidy_number(N): N = str(N) for i in xrange(len(N)-1): if N[i] > N[i+1]: return False return True T = int(raw_input())# ...
def checkAll(check): number = int(check) for i in range(number,0,-1): if checkTiny(i) == True: break return i def checkTiny(check): strTiny = str(check) listNum = [] for digit in strTiny: listNum.append(int(digit)) return all(x<=y for x,y in zip(listNum, listNum[1:])) t = int(input()) f =...
def isOn(n, k): rest = k + 1 pot = 2 ** n chunk = rest / pot rest -= chunk * pot while rest > 0: rest -= pot return not rest class Switch: on = 0 next = None def __init__(self, first, previous): self.first = first self.previous = previous def click(self...
import sys def read_arrangement(f): arr = [ f.readline(), f.readline(), f.readline(), f.readline() ] arr = [ line.strip().split() for line in arr ] return arr def read_possible_values(f): row = int(f.readline()) arr = read_arrangement(f) cards = set([ int (x) for x in arr[row - 1] ]) retur...
# raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end. # nb tests t = int(raw_input()) # read a line with a single integer for i in xrange(1, t + 1): N=raw_input() L=len(N) cd=0 tm=0 b=0 dead=False for k in range(L): if dead: ...
FILE_IN = "C-small-attempt0.in" FILE_OUT = "C-small-attempt0.out" NEWLINE = '\n' import math def is_palindrom(num): s = str(num) l = list(s) l.reverse() s1 = "".join(l) reversed_num = int(s1) return num == reversed_num if __name__ == '__main__': f = open(FILE_IN, "r") f_...
import sys name = "A-small" path = "" path2 = '/Users/daniel/Downloads/B-small-attempt0' sys.stdin = open(path2 +'.in') sys.stdout = open(path2 + ".out", "w") testCases = int(input()) def check_non_decreasing(num): num = str(num) prev_d = num[0] for d in range(1, len(num)): if int(num[d]) >= i...
#!/usr/bin/env python import sys f=sys.stdin def base10toN(num,n): """Change a to a base-n number. Up to base-36 is supported without special notation.""" num_rep={10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f', 16:'g', 17:'h', 18:'i',...
def robot(units,ham): avg = (sum(ham)+units)/len(ham) nobs = [] while max(ham) > avg: bop = [] for i in ham: if i > avg: nobs.append(i) else: bop.append(i) ham = bop if len(ham) > 0: avg = (sum(ha...
def read_ints(): return map(int, raw_input().split()) def read_str(): return raw_input() def row_ok(L, n, m): return all([L[n][i] <= L[n][m] for i in range(len(L[n]))]) def col_ok(L, n, m): return all([L[i][m] <= L[n][m] for i in range(len(L))]) def lawn(): N, M = read_ints() L=[] for n ...
#!/usr/bin/env python3 """Problem 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...
from heapq import * 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 for t in xrange(1, t + 1): n, k = [int(s) for s in raw_input().split(" ")] #...
def tokenizer(stream): for line in stream: for token in line.split(): yield token filename = 'C-small-attempt1.in' def main(): with open(filename, 'r') as file_stream: tokenized = tokenizer(file_stream) T = int(next(tokenized)) for case in range(T): N = ...
cases = [int(input()) for _ in range(input())] for index, case in enumerate(cases): max_tidy = 0 for num in range(case + 1): if "".join(sorted(str(num))) == str(num): max_tidy = num print("Case #{}: {}".format(index + 1, max_tidy))
#!/usr/bin/python C=int(raw_input()) for case in range(C): row=raw_input().split() pushs=int(row[0]) o=[] b=[] s=[] for push in range(pushs): robot=row[push*2+1] button=int(row[push*2+2]) s.append([robot,button]) if robot=='B': b.append(button) else: o.append(button) o.append(1) b.append(1...
import math class Problem: def __init__(self) : self.data = {"X": 0, "R": 0, "C": 0} self.X = 0 self.X = 0 def readProblem(input): problem = Problem() line = input.readline().split() problem.data["X"] = int(line[0]); problem.data["R"] = int(line[1]); probl...