text
stringlengths
37
1.41M
def get_maximum(l, f): items = [] last = -1 for item in l: if item is not None: test = f(item) if test > last: #New maximum according to comparison function last = test items = [item] elif test == last:...
__author__ = 'Roberto' import math def finish(index, solution): print solution file_out.write("Case #{0}: {1}\n".format(index+1, solution)) debug_out.write("{0}\n".format( solution)) def is_bishop_collision(bishop_a, bishops): for bishop in bishops: if (bishop_a[0] + bishop_a[1...
def isRecycled(int1, int2): str1 = str(int1) str2 = str(int2) if len(str1) != len(str2): return False for i in range(len(str1)): part1 = str1[:i] part2 = str1[i:] total = part2 + part1 if total == str2: return True return False a_...
from math import sqrt def checkPalineDrome(x): if len(x) == 1: return True else: for i in range(0,int(len(x)/2)): if x[i] != x[len(x)-i-1]: return False return True f = open('input.txt','r') w = open('output.txt', 'w') testcase = int(f.readline()) for a in range (0, testcase): AB = ...
from queue import PriorityQueue def eat(l): i = 0 while i < len(l): l[i] -= 1 if l[i] <= 0: l[i] = 0 i += 1 while len(l) > 1 and l[-1] == 0: l = l[:-1] return tuple(l) def lift(l): res = [] need_zero = True i = l.index(max(l)) diners_plate = ...
from sys import stdin, stdout def check_row(grid, row): for h in grid[row]: if h != 1: return False return True def check_col(grid, col): for i in range(len(grid)): if grid[i][col] != 1: return False return True def solve(grid): for i in range(len(grid)): ...
import math liste_palindrome = set() liste_non_palindrome = set() liste_carre = set() liste_non_carre = set() def is_palindrome(a): if len(str(a)) == 1: return True if a in liste_palindrome: return True if a in liste_non_palindrome: return False A = str(a) fo...
import sys def readline(): return sys.stdin.readline().strip() def mark(p, r, c, R, C): p[r][c] = '/' if r < (R - 1) and p[r + 1][c] == '#': p[r + 1][c] = '\\' else: return False if c < (C - 1) and p[r][c+1] == '#': p[r][c + 1] = '\\' else: return False if p...
number = raw_input() def parseInput(example): stripped_example = example.strip() l = stripped_example.split(" ") return(int(l[0]), int(l[1])) def printMap(m, R, C): for row in m: print(''.join(row)) def solve(m, R, C): for r in xrange(R): current = '?' for c in xrange(C): if m[r][c] != '?': if cur...
import time debug = False def checkreduceboard(board): while board: if debug: print '---' for row in board: print row nextpass = False boardmin = min(min(board[i]) for i in range(len(board))) for rc in range(len(board)): ...
def solve(Nstr): res = '' numToDecrement = -1 # invalid value for i in range(len(Nstr) - 1): # loop from 0 to len(Nstr) - 2 if (Nstr[i+1] < Nstr[i]): # next digit less than previous digit numToDecrement = Nstr[i] break; if numToDecrement == -1: # string is already arrange in non descendin...
#!/usr/bin/env python def find_note(l, h, notes): for t in range(l, h+1): if check_note(t, notes): return t return 'NO' def check_note(n, notes): for note in notes: if note % n != 0 and n % note != 0: return False return True def main(): case...
#!/opt/local/bin/python3.1 import sys def count_intersect(ropes): print(ropes) res = 0 ropes.sort() for rope in ropes: for other in ropes: if rope[0] < other[0] and rope[1] > other[1]: res += 1 return res def main(argv=None): if not argv: argv = sys....
import sys class flipPancake(): leftCounter = 0 rightCounter = 0 flipperSize = 0 stringArray = [] def startProcessing(self,caseNumber): self.leftCounter = 0 self.rightCounter = len(self.stringArray) - 1 if self.flipperSize == len(self.stringArray): if '-' in self.stringArray and '+' in self.stringArray...
#!/usr/bin/env python import sys import numpy as np def check(raw_board): board = np.zeros((4,4), dtype=int); Tx = 0; Ty = 0 empty_cell = False for i,line in enumerate(raw_board): for j,ch in enumerate(line): if ch == "X": board[i,j] = -1; elif ch == "O"...
#!/usr/bin/env python def sign(x): if x>0: return 1 return 0 def sure(p): def a(x): if x>3*p - 3: return 1 return 0 return a def candi(p): def a(x): if (x == 3*p - 3) or (x == 3*p -4 ): return 1 return 0 return a if __name__...
from math import sqrt, floor, ceil def is_square(num): root = sqrt(num) return root == int(root) def is_palindrome(num): return num == int((str(num))[::-1]) num_cases = int(raw_input()) for case in range(1, num_cases+1): count = 0 limits = (raw_input()).split(" ") A = int(limits[0]) B ...
#!/usr/bin/python # Filename: Problem A. Speaking in Tongues.py #file = "Problem A. Speaking in Tongues" #file = "Problem A. Speaking in Tongues small" #file = "Problem A. Speaking in Tongues large" file = "A-small-attempt0" #debug = True debug = False inputExamp0 = "ejp mysljylc kd kxveddknmc re jsicpdry...
#!/usr/bin/env python import sys import math def is_fair(num): if not is_pal(num): return False sqr = is_square(num) if sqr is not False: if is_pal(sqr): return True return False def is_square(num): if num == 2: return 2 # Stupid edge cases root = math.sqrt(num) if int(root + 0....
def solve(N, mine, others): """ solve the problem """ mine.sort(reverse=True) others.sort(reverse=True) count1 = 0 mine_index = 0 others_index = 0 while mine_index < N and others_index < N: if mine[mine_index] > others[others_index]: count1 += 1 mi...
class Toilet: def last_optimal(self, case): num_stalls = int(case[0]) num_people = int(case[1]) if num_stalls == num_people: return '0 0' num_left = 0 num_right = 0 stall_blocks = [] stall_blocks.append(num_stalls) while num_people > ...
import math def fair_squares(start, end): ret = [] a = int(math.ceil(math.sqrt(float(start)))) b = int(math.floor(math.sqrt(float(end)))) for n in range(a, b + 1): if is_palindrome(n) and is_palindrome(n * n): ret.append(n) return len(ret) def is_palindrome(n): s = str(n...
case = int(raw_input()) for t in range(1,case+1): x = raw_input().split() can = False if(0 < int(x[2]) < 100 or int(x[2]) == int(x[1])): for i in range(int(x[0])+1): for j in range(max(1,i),int(x[0])+1): if(float(i)*100/float(j) == int(x[1])): ...
# ___ ______________________________________________ ___ # #|_/*| |*\_|# #|_/*| Google Code Jam - "Hello World" |*\_|# #|_/*| 10.04.2015 - the end |*\_|# #|_/*| Qualification |*\_|# #|_/*|___________________...
q_mul_table = { '1': {'1': '1', 'i': 'i', 'j': 'j', 'k': 'k'}, 'i': {'1': 'i', 'i':'-1', 'j': 'k', 'k':'-j'}, 'j': {'1': 'j', 'i':'-k', 'j':'-1', 'k': 'i'}, 'k': {'1': 'k', 'i': 'j', 'j':'-i' ,'k':'-1'} } # doesn't work if q1 or q2 starts with '--' or greater # hopefully, algoryths doesn't supp...
#!/usr/bin/python import sys import math def factorial( n ): if n == 0: return 1 else: return n*factorial(n-1) def nchoosek( n, k ): #return factorial(n)/(factorial(k)*factorial(n-k)) answer = 1 for i in range(1,k+1): answer *= (n - (k - i)) answer /= i return...
def solve(T): arg = raw_input() c,f,x = [float(i) for i in arg.split(' ')] t = 0.0 speed = 2.0 while True: t += c / speed time_no_buy = (x - c) / speed time_buy = x / (speed + f) if time_no_buy < time_buy: t += time_no_buy break else: speed += f print 'Case #{T}: {pr}'.forma...
class Quaternion: type = '1' sgn = 1 def __init__(self, t, s): self.type = t self.sgn = s def __str__(self): if self.sgn == -1: return '-' + self.type else: return self.type def eval_q(a, b): if a.type == '1': return Quaternion(b.typ...
def digits_are_ascending(num): nstr = str(num) return all(int(x) <= int(y) for x, y in zip(nstr, nstr[1:])) t = int(input()) for i in range(1, t + 1): line = input() n = int(line) while not digits_are_ascending(n): n -= 1 #digits = str(line)[::-1] #pairs = [[int(x) for x in digits[...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on Apr 13, 2012 @author: daniel We have come up with the best possible language here at Google, called Googlerese. To translate text into Googlerese, we take any message and replace each English letter with another English letter. This mapping is one-...
# Usage: python search.py <input_file> [<output_file>] # If "output_file" isn't specified, the program simply write it to console. import sys input_file = open(sys.argv[1]) output_text = "" num_tests = int( input_file.readline() ) for i in range(num_tests): switches = 0 num_engines = int( input_file.readlin...
# coding=utf-8 from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from math import ceil, floor def horse(distance, pos_speeds): finish_times = [(distance - pos) / speed for pos, speed in pos_speeds] our_speed = d...
class Palindrome: def __init__(self, n): if int(n) < n: n = int(n) + 1 self.n = list(str(int(n))) if not self.is_palindrome(): self.correct() def is_palindrome(self): for i in range(len(self.n) / 2): if self.n[i] != self.n[-1-i]: return False ...
# # Google Code Jam 2014 # # Author: Tim van Deurzen <tim.vandeurzen@gmail.com> # import sys def parseInput(fileName): """ Parse the input following the format described on the code jam web page. """ with open(fileName, 'r') as fp: dataRead = fp.readlines() data = [x.strip() for x in data...
def check_case(board, dimx, dimy): if dimx == 1 or dimy == 1: return "YES" ymaxes = [(max([line[x]for line in board])) for x in range(dimx)] y = 0 for line in board: xmax = max(line) x = 0 for char in line: if char < xmax and char < ymaxes[x]: ...
#!/usr/bin/python import sys, string def flip(pancakes, index, flipper_size): for i in range(flipper_size): pancakes[index + i] = '+' if pancakes[index + i] == '-' else '-' def solve(pancakes, flipper_size, case_number): count = 0 index = 0 while True: if len(pancakes) - index < flip...
import sys n = int(raw_input()) def is_tidy(numstr): prev = numstr[0] ret = True for i in xrange(1,len(numstr)): if int(numstr[i]) < int(prev): ret = False break prev = numstr[i] return ret for i in xrange(1,n+1): t = int(raw_input()) ans = 0 for j...
import math def next_palindrome(n): if n < 9: return n + 1 if n == 9: return 11 s = str(n) m = len(s) if m & 1: r = m - 1 else: r = m t = r/2 front = s[:t] back = front[::-1] if int(back) > int(s[-t:]): if m & 1: return int(s[:...
def run(): test_case_count = int(raw_input()) # read a line with a single integer for case in range(1, test_case_count + 1): kilometers, horse_count = [int(x.strip()) for x in raw_input().split(" ")] horses = [] for horse in range(horse_count): horses.append(int(x.strip()) for x in raw_input().s...
def find_flipped(sequence, m): count=0 sequence=[i for i in sequence] for i in range(len(sequence)): if sequence[i]=='-': count+=1 if i+m>len(sequence): return 'IMPOSSIBLE' for j in range(m): if sequence[i+j]=='-': ...
#!/usr/bin/env python def findTidy(N): if N // 10 == 0: return N number = 0 power = 0 countRepeated = 0 while(N // 10 > 0): if N % 10 < (N // 10) % 10: number = number + (9 * (10 ** power)) for i in range(power-1, -1, -1): number = number + ...
def run_case(input): """ Return string you want outputted. input is a file you can read from """ _, shyness = read_strs(input, 2) total_standing = 0 total_needed = 0 for i in range(len(shyness) - 1): to_stand = int(shyness[i]) total_standing += to_stand need_to_add ...
from sys import argv f = open(argv[1], 'r') games = f.read() games = games.split('\n') number_of_tests = int(games[0]) i = 1 j = 1 while i < (10 * number_of_tests): row1 = int(games[i]) nums_in_row1 = [int(num) for num in games[i + row1].split()] row2 = int(games[i+5]) nums_in_row2 = [int(num) for num in games...
#! /usr/bin/env python import sys import math def is_square_of_palindrome(num): sq = math.sqrt(num) return sq == int(sq) and is_palindrome(int(sq)) def is_palindrome(num): w = str(num) return w == w[::-1] def process_input(): sets = int(sys.stdin.readline()) for s in range(sets): nums = sys.stdin.readli...
t = int(raw_input()) for i in range(1, t + 1): num = int(raw_input()) tidy = False #while not tidy #for num, num-1, -1... #loop through string of number #if previous # > current or completed parse, stop loop num +=1 while not tidy: num -=1 prev = 0 tidy = True for digit in str(num): if prev <= dig...
#!/usr/bin/python import math from sys import argv def sqrtest(n): root = math.sqrt(n) r = str(root)[::-1] if r[1] == '.': return True return False def palindrome(foo): t = str(foo) if t[::-1] == t: return True return False fin = open(argv[1]) flag = True numcount = 0 casecount = 1 for line in fin: if fl...
#!/usr/bin/python2 import sys ''' class Auxiliar: def __init__(self): self.a = 0 self.b = 0 def func(self): self.a = b c = Auxliar() ''' def func(): for path in recursives: len_path = len(path) if paths[1]: if len(paths[1][0]) < len_path: ...
#!/usr/bin/env python Mapping = ['?'] * 256; def Convert(fromTxt, toTxt): global Mapping for a, b in zip(fromTxt, toTxt): p = ord(a) c = ord(b) if Mapping[c] == '?': Mapping[c] = a elif Mapping[c] == a: pass else: print "Conflito: '%c...
""" Written by blackk100 for Google Code Jam 2017 Qualifications 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 ...
#!/usr/bin/python import sys WHITE = 0 BLACK = 1 class Node: def __init__(self, neighbours): self.color = WHITE self.neighbours = neighbours def DFS(node, graph): if graph[node].color == WHITE: result = True for i, n in enumerate(graph[node].neighbours): result = result and DFS(n, graph) graph[node...
import sys def flip(pan_array, flip_size, position): for i in xrange(flip_size): #print "index: " + str(i) #print "position: " + str(position) old_val = pan_array[position + i] new_val = "+" if old_val == "-" else "-" #print "old val: " + str(old_val) #print "new val...
#!/usr/bin/env python3 import itertools import sys def main(): input_file = sys.argv[1] solve(input_file) def solve(input_file): with open(input_file) as f_in: t = int(next(f_in)) for case in range(t): k, l, s = tuple(int(num) for num in next(f_in).split()) keyboa...
def worth(curr, prod, coss, incr, goaa): return (((coss-curr)/(prod) + goaa/(prod+incr)) < (goaa-curr)/(prod)) def optimal(cost, increase, goal): current = 0.0 production = 2.0 time = 0.0 for i in range(100000): if(worth(current, production, cost, increase, goal)): time+=(cost-current)/(production) curre...
line_count = int(raw_input()) def isAscending(number): number_str = str(number) return ''.join(sorted(number_str)) == number_str def maximumAscendingNumber(number): if isAscending(number): return number else: return maximumAscendingNumber(number-1) for i in range(line_count): targ...
t = input() for T in xrange(1,t+1): print "Case #"+str(T)+":", ans = 0 inp = raw_input().split() x = list(inp[0]) k = int(inp[1]) l = len(x) for i in xrange(0,(l-k)+1): if(x[i]=='-'): ans += 1 for j in xrange(k): if(x[i+j]=='-'): ...
#!/usr/bin/env python import sys # globals result = [] # get test count test_count = int(raw_input()) if test_count>100 or test_count<1: print "Test Count input out of bounds. Should be between 1 and 100 only" sys.exit() # compute for result def check_for_the_number(rows): Number = [] fo...
class memoized(object): '''Decorator. Caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated). ''' def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: ...
#!/usr/bin/env python import sys search = "welcome to code jam" def main(): n = int(sys.stdin.readline().strip()) for i in range(n): test = sys.stdin.readline().strip() #print "TEST: " + test print "Case #%d: %04d" % (i+1, countSubsequences(test)) def countSubsequences(sequence): positions = [] for letter ...
#!/usr/bin/env python2.7 # 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 isPossible(N, l): for color in l: if color > N/2: return False return True def solve(N, R, O, Y, G, B, V): ...
def is_tidy(num): s = list(str(num)) t = list(sorted(s)) return s == t T = int(raw_input()) for t in range(1, T + 1): N = int(raw_input()) for j in range(N, 0, -1): if is_tidy(j): print 'Case #%d: %d' % (t, j) break
import sys from pprint import pprint def get_num_input(): num = sys.stdin.readline() try: num = int(num) except ValueError: print("Error : first line of input is not an int") exit() return num def line_to_item(line): if line[-1] == '\n': return line[:-1] #remove trailing '\n' else: re...
def findBiggestTidy(N): Nlist = list(str(N)) #print Nlist for i in xrange(1,len(Nlist)): if Nlist[-i]<Nlist[-i-1]: for j in xrange(1,i+1): Nlist[-j]='9' Nlist[-i-1]=str(int(Nlist[-i-1])-1) #print Nlist return int("".join(Nlist)) ...
def isTidy(num): digits = list(str(num)) for i in range(len(digits)-1): if digits[i+1] < digits[i]: return False; return True def previousTidy(N): while N >= 0: if isTidy(N): return N N -= 1 return 0 cases = int(raw_input()) #print "processing", case...
__author__ = 'banarasitippa' import sys def dijk_reduce ( twochars): dijk_lookup = {'ii': '-i', 'ij': 'k', 'ik': '-j', 'ji': '-k', 'jj': '-j', 'jk': 'i', 'ki': '-j', 'kj': '-i', 'ki': 'j' } if twochars[0] == '1' and twochars[1] == '1': res = '1...
import sys class Plane(object): def __init__(self, height, width, grid): self.height = height self.width = width self.grid = grid def at(self, x, y): if (x < 0 or x >= self.width or y < 0 or y >= self.height): return None else: re...
from sys import argv def extract_input( filename ): try: print "Your first variable is:", filename file = open(filename, 'a+') out_file = open('out', 'a+') no_of_input = int(file.readline()) index = 1 for lines in file.readlines(): line = lines.split('...
def addSpecial(process): """apply special minute to process""" return (process[0] + 1, process[1]) def pancakeReduce(*processes): """Summarize an arbitrary number of processes to the best process that can be made from them Process can be described by how many special minutes and regular minutes are n...
from math import pi from queue import PriorityQueue import itertools from math import pi from queue import PriorityQueue import itertools def choose_best(combos): total_for_best_combo = 0 for combo in combos: largest_radius = 0 total_edges = 0 for cake in combo: ...
#!/usr/bin/python # Tic-Tac-Toe-Tomec import sys import os from itertools import chain def _get_cases(raw): """Takes a raw list of strings/lines and turn into cases. """ raw[0] = int(raw[0]) step = len(raw[1:])/raw[0] cases = [] for i in range(1,len(raw),step): c = raw[i:i+step] ...
#! /usr/bin/python import sys # Return a set representing the cards # in the specified row. Row is indexed by 1 def read_row_cards(fh, row): row_set = set() for i in range(1, 5): row_cards = f.readline().split() if i == row: row_set = set(row_cards) return row_set # # Main # i...
#!/usr/bin/env python import fileinput def isTidy(n): """ Is n a tidy numbers? A tidy number is a number that, when written in base 10 with no leading zeros, has its digits sorted in non-decreasing order. I'm going to implement this as, from right-to-left, digits are non-increasing. """ ...
#!/usr/bin/env python3 def main(): #"The first line of the input gives the number of test cases, T." t = int(input()) for i in range(t): "Each line describes a test case with a single integer N, the last number counted by Tatiana." ans = solve(int(input())) print("...
arr=[] def revert(arr,index,s,flip): for i in range(index,index+flip): if(arr[i]=='-'): arr[i]='+' else: arr[i]='-' def comp(arr,k,size): for i in range(k,size): if(arr[i]=='-'): return False return True; def main(): t=raw_input() for nu...
#!/usr/bin/python from __future__ import with_statement import sys def solve_problem(input_file): with open(input_file, 'r') as rf: count=int(rf.readline()) #print count for idx in range(0, count): #print idx line = rf.readline().strip('\n') #print line numbers = {} actual = 0 for c in l...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Uses https://github.com/rkistner/contest-algorithms from __future__ import print_function import sys # from Set import Set def debug(*args): print(*args, file=sys.stderr) fin = sys.stdin T = int(fin.readline()) for case in range(1, T + 1): s, ks = fin.readline...
#!/usr/bin/env python3 from heapq import heappush, heappop def solve_testcase(testcase_number): C, F, X = [float(i) for i in input().split()] objective = X farm_cost = C farm_bonus = F time = 0 speed = 2 heap = [] heappush(heap, (time, speed, 0)) while True: time, speed,...
#!/usr/bin/env python dictionary = {'a': 'y', ' ': ' ', 'c': 'f', 'b': 'n', 'e': 'c', 'd': 'i', 'g': 'l', 'f': 'w', 'i': 'k', 'h': 'b', 'k': 'o', 'j': 'u', 'm': 'x', 'l': 'm', 'o': 'e', 'n': 's', 'q': 'z', 'p': 'v', 's': 'd', 'r': 'p', 'u': 'j', 't': 'r', 'w': 't', 'v': 'g', 'y': 'a', 'x': 'h', 'z': 'q'} inverted_dic=...
#!/usr/bin/env python import collections import sys class Attempt(object): __slots__ = ['state', 'step'] def __init__(self, state, step): self.state = state self.step = step def __eq__(self, other): return self.state == other.state def __hash__(self, other): r...
from math import sqrt, ceil, floor def check_palindrome(num): num = str(num) return num == num[::-1] def palindrome(sm,bg): count = 0 for i in range(sm,bg+1): if check_palindrome(i) and check_palindrome(i*i): count +=1 return count f = open('C-small-attempt0.in', ...
import sys class Move: def __init__(self, bot, position, preceding_move): self.done = False self.bot = bot self.position = position self.preceding_move = preceding_move class Bot: def __init__(self, bot, position, moves): self.bot = bot self.position...
import sys def print_board(board, N) : # Write board print for jj in xrange(0, N, 1): for kk in xrange(0, N, 1): print board[jj][kk], print def rotate_board(board, N) : new_board = [] for ii in xrange(0, N, 1) : row = [] for jj in xrange(N ...
# NextNumber # # To run this on an input file called sample.in, use the following # command line: # # python base.py sample.in # # The output will appear on the console. I used Python 2.5.2. import sys if len( sys.argv ) < 2: print "Please provide input file." exit(1) fp = open( sys.argv[1], 'r...
import math def solve(A, B): count = 0 a = int(math.ceil(math.sqrt(A))) b = int(math.floor(math.sqrt(B))) for x in range(a, b+1): if is_palindrome(x) and is_palindrome(x*x): count = count + 1 return count def is_palindrome(x): return str(x) == str(x)[::-1] File = open("C-small-attempt0.in", "r") f = [] fo...
#!/usr/bin/python2.6 import re class Robot(): def __init__(self, symbol): self.symbol = symbol self.position = 1 self.instructions = [] def queue(self, instruction): self.instructions.append(instruction) def move(self): if len(self.instructions) == 0: ret...
def is_tidy(x): largo = len(x) midlargo = int(largo/2) if(largo==0 or largo==1): return True try: if(x[midlargo]>=x[midlargo-1] and x[midlargo]<=x[midlargo+1] ): return is_tidy(x[:midlargo]) and is_tidy(x[midlargo:]) except IndexError: if(x[midlargo]>=x[midlargo...
import math def isFairSquare(n): if isPalindrome(n): if math.sqrt(n).is_integer(): if isPalindrome(int(math.sqrt(n))): return True return False def isPalindrome(n): forward = str(n) backward = forward[::-1] if forward == backward: return True else: return False f = open('C-small-attempt1.in', '...
class Horse: def __init__(self, position, speed): self.position = position self.speed = speed def time_to_destination(self, destination): return max([ 0, (destination - self.position) / self.speed ]) class HorseProblem: def __init__(self, destinat...
def tidy_checker(arg): if 0 < arg < 10: return arg elif arg <= 0: return "Number should not be less than 1" else: lst = [int(i) for i in str(arg)] if sorted(lst) == lst: return arg else: for length in range(len(lst)-1): if lst[l...
#!/bin/python import sys input_filename, = sys.argv[1:] input = open(input_filename) assert input_filename.endswith('.in'), input_filename output = open(input_filename[:-3]+'.out', 'w') def is_tidy(s): last = '0' for c in s: if c<last: return False last = c return True assert i...
from __future__ import print_function import sys sys.stdin = open("A.in") sys.stdout = open("A.out", "w") N = int(raw_input()) for test in range(N): field = [ raw_input() for i in range(4) ] #print(field) def row(field, x, letter): return all( i in (letter,'T') for i in field[x] ) def col(fi...
def build_mapping(samples): mapping = [' ']*(ord('z')-ord('a')+1) for (o,t) in samples: for i in range(len(o)): if t[i] == ' ': continue mapping[ord(t[i]) - ord('a')] = o[i] print mapping for i in range(len(mapping)): print "%s -> %s" % (chr(ord('...
#!/usr/bin/env python2.7 # Standard libs import sys # Constants USAGE = "python %s INPUT_FILE" % (sys.argv[0]) def main(argv): if len(argv) != 2: raise Exception("Invalid arguments! Usage: %s" % (USAGE)) input_filename = argv[1] with open(input_filename, "r") as input_file: # Read in th...
#!/usr/bin/python3 def main(): t=int(input()) for k in range(t): n=int(input()) check(n,k) def check(n,k): if (n<=100): generate(n,k) else: generate1(n,k) def generate(N,t): ...
#!/usr/bin/env python import fractions def solve(line): N, PD, PG = map(int, line.strip().split()) if (PG == 100 and PD != 100) or (PG == 0 and PD != 0): return "Broken" today = fractions.Fraction(PD,100) # find the win fraction if today.denominator > N: return "Broken" print N, "\t", PD, PG, "\t\t", to...
def cost(c,f,r,x): return def timeit(c,f,x): farms = 0 investment = 0 r = 2.0 ans = cost = x/(r+f*farms) # keep investing as long as it reduces the time to reach x while ans >= cost: # consider the cost of building one more farm investment += c/(r+f*farms) # build ...
# snapper # read input file fIn = open("input.txt") # get count count = int(fIn.readline()) # read each line for i in range(count): line = fIn.readline().split(' ') N = int(line[0]) K = int(line[1]) # make snapper chain snappers = [False for j in range(N)] for j in range(K): # the f...
#!/usr/bin/env python # -*- coding: utf8 -*- __author__ = "renaud blanch <rndblnch at gmail dot com>" __copyright__ = "Copyright © 2010 - Renaud Blanch" __licence__ = "GPLv3 [http://www.gnu.org/licenses/gpl.html]" import sys next_line = sys.stdin.next """ Number Game [http://code.google.com/codejam/contest/das...
class Case: def __init__(self, config): self.config = config def solve(self, logic): return logic(self.config) class Problem: def __init__(self, config, parser, writer): self.case_counter = 0 self.config = config self.parser = parser self.writer = writer self.case_logic = None se...
import os, sys, math def isPalindrome(num): n = num rev = 0 while num > 0: dig = num % 10 rev = rev * 10 + dig num = num / 10 if n == rev: return 1 return 0 # Babylonian Algorithm for determining sqrt, to avoid floating point nonsense def isSquare(num): if num == 0: return False if...
# Oversized pancake. def oversizePancake(tc): case_num = 0 while (tc != 0): pancake_string, K = raw_input().split() #print pancake_string, K count = 0 for x in xrange(len(pancake_string) - int(K) + 1): if pancake_string[x] == '-': count += 1 for i in xrange(x, x+int(K)): if pancake...