text
stringlengths
37
1.41M
import sys def canbesurprising(total): return total%3 != 1 def bestscore(total, surprise): if total%3 == 0: if surprise and total >= 2: return total/3 + 1 else: return total/3 elif total%3 == 1: return total/3 + 1 else: if surprise: r...
import sys def flip_pancake(state): return '-' if state == '+' else '+' # Flip count pancakes starting at index def flip(pancakes, index, count): if index + count > len(pancakes) or index < 0: raise ValueError("Flipping invalid pancakes. Index %d, Count %d" % (index, count)) for i in xrange(inde...
''' Created on 13/04/2013 @author: shb ''' import sys import numpy as np def check_lawn(lawn, N, M): for i in range(N): for j in range(M): if not all(lawn[i, :] <= lawn[i, j]) and not all(lawn[:, j] <= lawn[i, j]): return False return True if __name__ == '__main__': n = int(sys.s...
one = "ejp mysljylc kd kxveddknmc re jsicpdrysi" onet = "our language is impossible to understand" two = "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd" twot = "there are twenty six factorial possibilities" three = "de kr kd eoya kw aej tysr re ujdr lkgc jv" threet = "so it is okay if you want to just give up" translat...
#!/bin/python import sys #sys.stdin = file("sample.in") def readint(): return int(raw_input()) def readints(): return [ int(x) for x in raw_input().split() ] def solve(R, C, tmap): for r in range(R): for c in range(C): if tmap[r][c] == "#": if r == R-1 or c == C-1: ...
import math from math import sqrt def is_palendrome_bool(num): return is_palendrome(num) == num def is_palendrome(n, partial=0): if n == 0: return partial return is_palendrome(n / 10, partial * 10 + n % 10) def print_fair_and_squares_for_range(case, bot, top, o): bot_range = int(math.sqrt(bot)) ...
import re import math def is_palindrome(number): string = str(number) for i in range(len(string) / 2): if string[i] != string[len(string) - i - 1]: #print str(number) + " isn't a palindrome bc %s != %s" % (string[i],string[len(string) - i - 1]) return False return T...
def getArray(number): result=[] while(number!=0): result.append(number%10) number=number//10 return result def getValue(arr): mul=1 result=0 for i in arr: result+=i*mul mul*=10 return result def checkTidy(arr): for i in range(0,len(arr)-1): if(a...
def compute(case): hops = int(case[0]) hop = 1 total_time = 0 pos = {'O':1, 'B':1} available_time = 0 consumed = {'robot':'O', 'time': 0} while hop<hops*2+1: time = abs(int(case[hop+1]) - pos[case[hop]]) +1 actual_time = time ...
def main(): nCases = int(input()) for case in range(1, nCases + 1): farmCost, boost, target = [float(n) for n in input().split()] bestTime = target / 2 origTime = bestTime if farmCost > target: print('Case #{}: {}'.format(case, bestTime)) continue ...
# go from right to left setting numbers to 9 and decrementing the next number import math def set_nines(n): value = 0 for i in range(0, n+1): value += pow(10, i)*9 return value def solve(n): value = 0 for i in range(0, int(math.log(n,10)+1)): a = n % 10 ...
r = 0 tot = 0 def binary(start, end): if(start==end): return start mid = (start+end+1)/2 v = 2*mid*mid + 2*mid*(r-1) + mid if(v>tot): return binary(start,mid-1) return binary(mid,end) t = int(raw_input()) for i in range(1,t+1): r,tot = raw_input().split(' ') r=int(r) tot=int(tot) print 'Ca...
# -*- coding: utf-8 -*- """ Created on Sat Apr 8 10:57:49 2017 @author: JPGallagher """ def is_tidy(number): str_number = str(number) for digit in range(1,len(str_number)): if int(str_number[digit-1]) > int(str_number[digit]): return False return True def largest_tidy_n(n...
import os HAPPY_SIDE = "+" BLANK_SIDE = "-" NO_SOLUTION = "IMPOSSIBLE" def print_case(case_number, number_of_flips): if number_of_flips < 0: number_of_flips = NO_SOLUTION print("Case #" + str(case_number) + ": " + str(number_of_flips)) input_file = open("tests/A-large.in", "r") number...
def solve(): c,f,x = [float(x) for x in raw_input().split()] rate = 2.0 currentTime = 0 time = x/rate solution = False while not solution: totalTime = currentTime + c/rate + x/(rate+f) if totalTime > time: print time solution = True else : ...
#!/usr/bin/python import sys import time DEBUG = False def main(): T = int(sys.stdin.readline()) for i in range(1, T + 1): test_data = read_test_data() if DEBUG: start_time = time.time() print "Case #{} INPUT: {}".format(i, test_data) print "Case #{}: {}"...
#!/usr/bin/env python import sys def solve(db): line = sys.stdin.readline().strip() if line == '': line = sys.stdin.readline().strip() a, b = line.split(' ') return db.count_between(a, b) class DB: def __init__(self): import sqlite3 self.conn = sqlite3.connect('fairsq.db') self.c = self.conn.cursor() ...
def process(numbers): if (len(numbers) == 1): return else: for i in range(len(numbers) - 1): if (numbers[i] > numbers[i+1]): numbers[i] = numbers[i] - 1 for j in range(i+1, len(numbers)): numbers[j] = 9 break def check(numbers): for i in range(len(numbers) - 1): ...
import sys class Board(object): def __init__(self, case, rows): self.case = case self.rows = rows def get_score(self): x_has_won = self.has_score('X') o_has_won = self.has_score('O') if x_has_won and o_has_won: return 'Draw' if x_has_wo...
#!/user/bin/env python """Google Code Jam 2017: Problem C. Bathroom Stalls""" 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,K = map(int, input().s...
import math import check_pali def palindrome_and_sqrt(a,b): mylist = [] newlist = [] for i in range(a,b): part1 = list(str(i)) part2 = list(str(i)) part2.reverse() if part1[0:] == part2[0:]: mylist.append(i) for j in mylist: root = math.sqrt(j) if int(root + 0.5) ** 2 == j: newlist.append(in...
def is_possible(x, r, c): if x == 1: return False elif r * c % x != 0: return True elif x == 3: return r == 1 or c == 1 elif x == 4: return r < 3 or c < 3 return False for t in range(input()): print "Case #%s:" % str(t + 1), x, r, c = map(int, raw_input().sp...
import sys, os puzzles = list() FILENAME = 'D-large.in' def solveOptimal(puzzle): naomi, ken = puzzle naomi = sorted(naomi) ken = sorted(ken) naomiScore = 0 while len(naomi) > 0: chosenNaomi = naomi.pop(0) chosenKen = 0. for block in ken: if bloc...
testcase = int(raw_input()) result =[] def compare (set1, set2): set1 = set1.split(' ') set2 = set2.split(' ') if sorted(set1)==sorted(set2): return 'Bad magician!' elif len(list(set(set1) & set(set2))) ==0: return 'Volunteer cheated!' else: return list(set(set1) & ...
def count_flip_time(faces, k): count = 0 for idx in range(len(faces)): face = faces[idx] if face == "+": continue # can not flip anymore if idx + k > len(faces): return -1 # flip K pancakes starting from the first blank one count += 1 ...
import sys def problem_instances(filename): f = open(filename) num_instances = int(f.readline()) for i in range(num_instances): rows, cols = map(int, f.readline().split()) lines = [] for r in range(rows): lines.append(map(int, f.readline().split())) yield lines ...
# this works for small case: def rings(r,t): ans = 0 while True: nextRing = (r+1)**2 - r**2 #print ans, t, r, nextRing if nextRing > t: break t -= nextRing ans += 1 r += 2 return ans """ paint used is sum of (x+1...
import sys def is_tidy(number): div = 1 pos = 10 prev = sys.maxint while div <= number: digit = (number % pos) / div if digit > prev: return False prev = digit div *= 10 pos *= 10 return True def last_tidy(n): while n >= 1: if is_ti...
#!/usr/bin/env python # coding=utf-8 # Last modified: <2012-04-14 11:21:34 Saturday by richard> # @version 0.1 # @author : Richard Wong # Email: chao787@gmail.com import sys _input = """ y qee ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc...
import fileinput pastFirstLine = False caseNum = 0 def is_tidy(num): nums = list(str(num)) i = 0 currentMax = 0 while i < len(nums): currentNum = int(nums[i]) if currentNum >= currentMax: currentMax = currentNum else: return False i += 1 retu...
def ocurr(phrase,text): if len(phrase)==1: return text.count(phrase[0]) res=0 for i in range(len(text)-len(phrase)): if phrase[0]==text[i]: res+=ocurr(phrase[1:],text[i:]) return res #print ocurr('welcome to code jam',"""So you've registered. We sent you a welcoming email, to welcome you to code jam. But it's po...
#!/usr/bin/env python from math import * from sys import * # N is a string def findtidy(N): num = list(N) for i in range(len(num)-1): if num[i] > num[i+1]: for j in range(i,-1,-1): if (num[j] > num[j+1]): num[j] = str(int(num[j])-1) pi...
testNum = int(input()) testCount =0 def flip(pancakes, index, flipper): counter = index while counter < (index+flipper): if pancakes[counter] == "-": pancakes[counter] = "+" else: pancakes[counter] = "-" counter +=1 while testCount < testNum: line = input() li...
# 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. from collections import deque def checknondecreasing(s): for i in range(len(s)-1): if s[i] > s[i+1]: return False return True def fill(s,c): ...
from collections import Counter def check_vertical(board, i, player): for j in [0, 1, 2, 3]: if board[i][j] == player: continue if board[i][j] == 'T': continue return None return player + ' won' def check_horizontal(board, i, player): for j in [0, 1, 2, 3]: if boar...
#!/usr/bin/env python # Google Code Jam 2011 # Round 1C # Jeremy Chin <rekless@gmail.com> # A. Square Tiles import math import sys # Simple stupid method f = open(sys.argv[1]) def fill(graph, width): if '#' not in graph: return graph idx = graph.index('#') x = idx % width x1 = x + 1 y = idx / width y1 =...
def count_line(paint_data): paintamt = paint_data[1] whiteradius = paint_data[0] p = paintamt c = 0 r = whiteradius paint = 0 x = 1 while (x!=0): paint = paint + (((r+1)**2) - (r**2)) if (paint <= paintamt): c = c+1 r = r+2 else: break return c def readfile(): output = ...
#!/usr/bin/env python """ Developed by Jormar Arellano <jormar.arellano@gmail.com> Google Code Jam 2017 Problem TODO - TODO Notes: """ import sys import math import operator import collections class _: def __repr__(self): return self.__str__() def __str__(self): return "" pass # c...
import math def interpret(p, s, scores): adjustedScores=[] #sUsed=0 tally=0 for x in scores: if(x/3==math.floor(x/3)): adjustedScores.append([x/3, x/3, x/3]) elif(x/3-math.floor(x/3)>=.5): adjustedScores.append([math.ceil(x/3), math.ceil(x/3), math.floor(x/3)]) elif(x/3-math.floor(x/3)<.5): adjusted...
''' Created on 8 apr 2017 @author: algestam ''' def all_ok(plates): for c in plates: if c == '-': return False return True def solve(plates, size): plates = list(plates) flips = 0 if all_ok(plates): return 0 max_flips = 1 + (len(plates) - size) for i in range(m...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Apr 7 21:15:08 2017 @author: shuzheng """ #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Apr 7 20:54:02 2017 @author: shuzheng """ def findallneg(S, K): #remove the last one that inside K mostright side S_n = list(S) ...
import sys import string if len(sys.argv) < 2: print "Usage: $(basename $0): input" exit() input = sys.argv[1] f = open(input) T = f.readline() T = int(T) if T < 1 or T > 50: print "T is out of range" exit() N_max = 2000000 def n_digits(n): if n == 0: return 1 digits = 0 while n...
def toggle(cake,i,flip): k=0; while(i+k < len(cake) and k != flip): flipper(cake,i+k) k+=1; if(k==flip): return True; else: return False; def flipper(cake,i): if(cake[i]=="+"): cake[i] = "-" else: cake[i] = "+" t=int(input()) for v in range(t): cake,flip = input().split(" ") flip= int(flip) ...
import sys args = sys.argv if len(args) < 2: print 'small or large?' exit() inp = args[1] out = open(inp + '_OUT', 'w') # No change before this def check_win(s, player): if s.count(player) == 4: return True if s.count(player) == 3 and s.find('T') >= 0: return True return False ...
#!/usr/bin/env python import itertools import array import math import sys import fractions import copy # Print the result def print_result(res): if res == -1: return "NO" else: return str(res) # Check if the problem has no solution def has_solution(l): res = 0 for e in l: re...
#!/usr/bin/env python2.7 # Standard libs import math import sys # Constants USAGE = "python %s INPUT_FILE" % (sys.argv[0]) PRECOMPUTED_UPPER_BOUND = 10**14 def main(argv): if len(argv) != 2: raise Exception("Invalid arguments! Usage: %s" % (USAGE)) input_filename = argv[1] # Pre-compute all fai...
def is_tidy(number): string = str(number) for i in range(len(string)): if i == 0: #SKIP x = 1 else: if int(string[i]) < int(string[i-1]): return False return True def last_tidy(number): tidy_number = int(number) while ...
__author__ = 'faet' import math def checkit(first, second): count = 0 squares = [1,4,9,121,484,10201,12321,14641,40804,44944,1002001,1234321,4008004] for n in squares: if n in range(first, second+1): count += 1 return count ins = open( "sqr.txt" ) count = ins.readline() game = ...
# Hopcroft-Karp bipartite max-cardinality matching and max independent set # David Eppstein, UC Irvine, 27 Apr 2002 def bipartiteMatch(graph): '''Find maximum cardinality matching of a bipartite graph (U,V,E). The input format is a dictionary mapping members of U to a list of their neighbors in V. The output is a ...
def leftmost(pan): for i in range(len(pan)): if pan[i] == '-': return i return 'none' infile = open('A-large.in','r') t = infile.readline() outfile = open('q1outlarge.txt','w') line = str(infile.readline().strip()) count = 1 minflips = 100 def determine(line): global minfli...
def line2intlist(line): list = line.split() numbers = [ int(x) for x in list ] return numbers def processLawn(lawnSize, lawn): rowCount = lawnSize[0] colCount = lawnSize[1] lawnCellVisiblity = [] for y in xrange(0, rowCount): lawnCellVisiblity.append([]) for x in xrange(0, colCount...
def read_words(filename): ''' converts a file to a list ''' words = [] for line in filename: words.append(line.split()) return words filename = open("test2.txt", "r") T= int(filename.readline()) total = read_words(filename) for i in range(len(total)): count = 0 first =...
def flip(array): substringarray = [] for stri in array: if stri == '-': substringarray.append('+') else: substringarray.append('-') return substringarray with open('small.in', 'r') as f: lines = f.readlines() row = 0 for line in lines[1:]: pancakes = [] ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import sys def is_tidy(n): """ Check if an integer is ``tidy`` """ return sorted(n) == list(n) def down(i): """ cycling number """ return i-1 if i else 9 def main(): """ Do the job. """ t = int(sys.stdin.readline()) for...
import itertools # return binary numbers with up to j 1s def binary_list_upto(num_digits, j): binary_list = [] for k in range(1, j + 1): binary_list.extend([2 ** (num_digits - 1) + sum([2 ** a for a in comb]) for comb in list(itertools.combinations(range(0, num_digits - 1), ...
import math def int_to_list(a): l = [] while a >= 10: l.append(a % 10) a /= 10 else: l.append(a) return l def is_reverse(x): x = int_to_list(x) y = list(x) y.reverse() if x == y: return True else: return False def main(): test_cnt = int...
def is_tidy(n): number = [int(d) for d in str(n)] for i in xrange(len(number) - 1): if number[i + 1] < number[i]: return False return True cases = int(raw_input()) for case in xrange(1, cases + 1): n = int(raw_input()) while not is_tidy(n): n = n - 1 print "Case #%d: %...
import sys def is_palindrome(num): return num == num[::-1] # (kind of) babylonian method - see wikipedia def is_square(num): x = num // 2 check = set([x]) while x * x != num: x = (x + (num // x)) // 2 if x in check: return False check.add(x) return True # newto...
def solve(C, F, X): """ solve the problem """ seconds = 0.0 rate = 2.0 buildings = 0 while True: seconds += C / rate remains = X - C # s1: dont buy new building strategy1 = remains / rate # s2: buy new building strategy2 = ( remains + C ) / ( rate...
#!/usr/bin/env python import sys import itertools import math def open_input(file): try: f = open(file, "r") return f except: print "can not open ", file sys.exit(1) palindromes = {} def is_palindrome(num): if num in palindromes: return True s = str(num) r...
#! /usr/bin/python import sys def solve(nb_assoc, assoc, nb_opposite, opposite, nb_elmt, elmt): # print elmt, assoc, opposite elmt_list = [] opp_present = nb_opposite * [-1] for e in elmt: # print "*", elmt_list, opp_present elmt_list += e combined = False if len(elmt_list) >= 2: elmt_ch...
import sys in_file = sys.argv[1] f = open(in_file, 'r') input_array,output_array = [],[] for line in f: input_array += [line.rstrip()] input_array = input_array[1::] def is_permutation(s1,s2): if s1 == s2: return False #should never happen st = s1[1:] + s1[0] while not st == s1 and not st == s2: ...
# -*- coding: utf-8 -*- """ Created on Fri Apr 7 20:04:20 2017 @author: willedwa """ def solve(N): #print('Starting number: ' + str(N)) c = [] for digit in N: c.append (int(digit)) for i in range(len(c)-1): #print('len(c)-i: ' + str(len(c)-i)) #print('c[last]: ' ...
#!/usr/bin/env python def get_cases(): f = open("A-small-attempt5.in", "r") data = f.readlines() f.close() case = [] cases = [] for line in data[1:]: if line != '\n': case.append(line.strip()) else: cases.append(case) case = [] return ca...
#!/usr/bin/env python import sys def attempt(moz): for y in range(len(moz)): for x in range(len(moz[0])): if moz[y][x] == '#': result = place_red(x, y, moz) if result is False: return False else: moz =...
def calc(c, f, x): # I wish I knew more calculus best = x / 2.0 cand = c / 2.0 + x / (f + 2.0) i = 1 while cand < best: best = cand k = (i*f + 2.0) cand = cand - x / k + c / k + x / (k+f) i += 1 return best if __name__ == '__main__': import sys if len(sys.argv) > 1 and sys.argv[1] == 't...
#!/usr/bin/env python3 import sys examples = [ ('y qee', 'a zoo', ), ('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 ...
t=int(raw_input()) for j in range(1,t+1): n=int(raw_input()) a=[] for i in range(n+1): ascending = int("".join(sorted(str(i)))) if ascending<=n+1: a.append(ascending) print "case #"+str(j)+":",max(a)
def main(): """ docstring for main """ exit_values = [] N = int(raw_input()) for case in range(1,N+1): matrix = [] rang = raw_input() rang = rang.split() N = int(rang[0]) M = int(rang[1]) for r in range(0,N): row = raw_input() ...
def flipPancake(pancake): if pancake == '+': pancake = '-' else: pancake = '+' return pancake def flipRight(row, index, n): for i in range(index, index+n): row[i] = flipPancake(row[i]) return row def solvePancake(row, k): flips = 0 for i in range(0, len(row)-k+...
#!/usr/bin/env python # -*- coding: utf-8 -*- from itertools import izip_longest def grouper(n, iterable, fillvalue=None): ''' Copied from python doc: http://docs.python.org/library/itertools.html grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx grouper(2, 'O 2 B 1 B 2 0 4'.split()) -> ('O', '2'),...
################################################################# ### https://code.google.com/codejam/contest/2270488/dashboard ### ################################################################# cases = int(raw_input()) for z in xrange(cases): sol = [] #adding rows to solution set for y in xran...
#!/usr/bin/python # 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 fileinput t = int(input()) #print("numLines = %d" % (t)) caseNum = 1 for line in fileinput.input(): if caseNum > t: break; strin...
class Snapper: """ Google Codejam problem 1: Snappers are power intermediaries that control current. Snappers may be ON or OFF, and may only change state when powered. Snappers keep track of their connections, and connections must support the function call is_on() """ def __ini...
import math def gcd(a, b): b, a = sorted([a,b]) while b > 0: a, b = b, a % b return a def x(a, b): c = gcd(a, b) a, b = a//c, b//c # simplify ex = math.log(b, 2) if ex != int(ex): # pow2 return False ex = int(ex) i = 0 while a > 1: i += 1 a = a >> 1 return ex-i def main(...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from numpy import array, rot90 import re X = re.compile("[TX][TX][TX][TX]") O = re.compile("[TO][TO][TO][TO]") def columns(lines): a = ''.join([line[x] for x in range(4) for idx, line in enumerate(lines)]) return a[0:4], a[4:8], a[8:12], a[12:16] def diagon...
#!/usr/bin/python def main(): #handle input #input format #C number of strings #[C] string containing three letters, two base followed by non base #[D] string containing two characters... two base characters that are opposed #[N] series of base elements you are to invoke, left to right. #T // T testcases #C ...
#!/usr/bin/python f = open("B-small.in") def time_in_mins( t ): dd,mm = t.split(':') return 60*int(dd) + int(mm) def get_time_list(num_trains): i = 0 time_list = [] for i in range(0,num_trains): start,end = f.readline().strip(nl).split(' ') start = time_in_mins(start) end = time_in_mins(end) time_list.a...
#!/usr/bin/env python3 import argparse import itertools parser = argparse.ArgumentParser(description="google code jam practice all your base") parser.add_argument("inputfile", type=str, help="input file") args = parser.parse_args() outfile = open(args.inputfile + ".out", "w") vowels = "aeiou" def read_input(): f...
def main(): cases = int(input()) for i in range(cases): num = int(input()) highest = check(num) out = "Case #" + repr(i+1) + ": " + repr(highest) print(out) def check(num): for i in range(int(num), 0, -1): if check_tidy(i): break return i def che...
mapping = {'a' : 'y' , 'o' : 'e' , 'z' : 'q', ' ': ' '} inv_mapping = {} def encode(str) : result = '' for c in str: result += mapping[c] return result def decode(str) : result = '' for c in str: result += inv_mapping[c] return result def create_mapping(code, te...
def x_win(elements): for i in range(4): win = True for j in range(4): if (elements[j][i] == 'X' or elements[j][i] == 'T') is False: win = False break if win is True: return True for i in range(4): win = True ...
import sys, math #Notes: #Practice on small snipet before attempting small or large. #If they ask for indices, they want indices starting at 1 #Can break out of multiple loops if you match for statement with else continue break #Main parses file and puts it into a dictionary removing end of line characters #Function ...
def make_tidy(num): numl = [int(x) for x in str(num)] for i in range(len(numl)-1,0,-1): if numl[i] < numl[i-1]: numl[i:] = [9] * (len(numl) - i) numl[i-1] = numl[i-1] - 1 return int("".join([str(x) for x in numl])) num_tests = int(input()) for i in range(1, num_tests + 1): ...
#!/usr/bin/env python3 def solve(rows, cols, grid): for r in range(rows): for c in range(cols): initial = grid[r][c] if initial != '?': d = r while d+1 < rows and grid[d+1][c] == '?': grid[d+1][c] = initial d +=...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from copy import deepcopy def flip(case, k, start): """Flip of case k things starting at start.""" for i in range(start, start + k): case[i] = (case[i] + 1) % 2 return case def check(situation, k, solution): for start, val in ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Apr 7 22:30:50 2017 @author: ansli """ def flipOne(a): if a == '+': return '-' elif a == '-': return '+' else: raise Exception("Wrong input: " + a) def flip(p, index, num): return p[:index] + ''.join(map(flipOne...
#!/usr/bin/env python import sys import string filename = sys.argv[-1] file = open(filename) ldn = file.readline() l = int(ldn.split(" ")[0]) d = int(ldn.split(" ")[1]) n = int(ldn.split(" ")[2]) words = [] for i in range(d): word = file.readline()[0:l] words.append(word) def word_has_char(word, char): ...
""" Ejercicio 2 """ import sys def log(cadena): """ Muestra cadena por sys error """ print >> sys.stderr, cadena pass def donde_rompe(cadena): for i in xrange(len(cadena)-1): if cadena[i] > cadena[i+1]: return i return -1 def caso(linea): """ Resuelve un caso concreto """...
def isqrt(n): x1, x2 = 1, n while abs(x1 - x2) > 1: x1, x2 = x2, (x2 + n // x2) // 2 return min(x1, x2) def main(): input = open("input.txt", "r") output = open("output.txt", "w") # Read the number of tests. tests = int(input.readline()) print("There are " + str(tests) + " tests.") # Itera...
#!/usr/bin/python import sys import string import itertools def read_int(file): return int(file.readline()) def read_int_array(file): return [int(i) for i in file.readline().split()] class Cell(): def __init__(self, map, index, row, col, value): self.map = map self.index = index ...
#!/usr/bin/env python # Run file like so: # python filename.py input.in import sys DEBUG = False def main(args): # File to read input_file = "D-large.in" if (len(args) > 0): input_file = args[0].strip() # Open files f_in = open(input_file, 'r') f_out = open('output.txt', 'w') # Get number of cases case...
__author__ = 'hansihe' import reader import time input_reader = reader.read_test_file(open('input', 'r'), reader.fixed_length_case_reader()) class GameState(object): def __init__(self, farm_cost, farm_production): self.farm_cost = farm_cost self.farm_production = farm_production self.c...
import sys, itertools cases = int(sys.stdin.readline()) case = 0 DEBUG=False def atleast_min_score(total_score, min_score, surprising=False): if not surprising: score = total_score // 3 score3 = score * 3 if score3 == total_score: return score >= min_score else: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys dic = { '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',...
def greatest_power_of_10(num): div=10 power = 0 while((num/div) >=1): div*=10 power+=1 return power+1 def get_digits(num,place_value): digit =num%(10**(place_value+1))-num%(10**place_value) return int(digit/(10**(place_value))) def check_if_tidy(num): is_tidy=True first_digit = num%10 second_digit = nu...
#!/usr/bin/env python # -*- coding=utf-8 -*- import sys def main(): # get num of cases n = int(sys.stdin.readline()) for case in range(n): process(case) def move(robot, dest): if robot < dest: return robot+1 else: return robot-1 def pushstay(robot): pass de...
#!/usr/bin/env python3 import sys import re def read(): return sys.stdin.readline().strip() def transpose(matrix): return [list(row) for row in zip(*matrix)] def complete_cake(cake): for direction in range(2): for row in cake: for index in range(len(row)): if index...
def read_input(file_name): with open(file_name, "r") as fid: N = int(fid.readline()) P = [] for n in range(N): fid.readline() test_case = { "Naomi": [float(x) for x in fid.readline().split()], "Ken": [float(x) for x in fid.readline().sp...
import sys def replaceTiles(tiles, i, j): if i+1 >= len(tiles) or j+1 >= len(tiles[i]): return False if tiles[i+1][j] != '#' or tiles[i][j+1] != '#' or tiles[i+1][j+1] != '#': return False tiles[i][j] = '/' tiles[i][j+1] = '\\' tiles[i+1][j] = '\\' tiles[i+1][j+1] = '/...