text
stringlengths
37
1.41M
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/17 11:35 # @Author : tanxw # @Desc : 推导式使用案例 ret = [(x, y) for x in range(10) if x % 2 if x > 3 for y in range(10) if y > 7 if y != 8] print(ret) # 元组推导结果,与下雷同; ret_str = "" for x in range(10): if x % 2 == 1: if x > 3: ret_...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/4/9 11:55 # @Author : tanxw # @Desc : 用列表实现 堆栈和队列 """ 堆栈和队列是数据结构中常用的数据结构,使用列表的append(),pop() 方法可以模拟这俩种数据结构; 1.堆栈是指最先进入堆栈的元素最后才输出,符合“后进先出”的原则。 2.队列是指最先进入队列的元素最早输出,符合“先进先出”的原则 """ list = ["apple", "banana", "grape", "peach", "orange", "pear"] list.appe...
class DoubleNode: def __init__(self, key=None, value=None): self.value = value self.key = key self.previous = None self.next = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def prepend(self,key,value): node = Dou...
import sys class Node: def __init__(self, char=None, frequency=None): self.left = None self.right = None self.char = char self.frequency = frequency def get_frequency(self): return self.frequency def get_char(self): return self.char def has_left_child(...
#Códigos y ejercicios del Modulo 4 #Funciones def mensaje(): print("Ingresa un valor: ") print("Se comienza aquí.") mensaje() print("Se termina aquí.") #Funciones con parámetros def mensaje(numero): print("Ingresa un número:", numero) mensaje(1) def mensaje(que, numero): print("Ingresa", que, "número", ...
#coding=gbk #е ''' Pyhton УıĸλöԷʵģȨ޾︳ֵġ һֳԷĸضıơı£ ȫֱ ֲ ''' total = 0; # һȫֱ # д˵ def sum( arg1, arg2 ): #2ĺ." total = arg1 + arg2; # totalǾֲ. print ("local variable: ", total) return total; #sum sum( 10, 20 ); print ("global variable : ", total)
import random DESCRIPTION = 'What number is missing in the progression?' def generate_progression(first_number, step, length): last_number = first_number + length * step progression = list(range(first_number, last_number, step)) return progression def get_question_and_correct_answer(): PROG_LENGT...
#!/usr/bin/python import sys x = 1; y = 10; z = 0 if x == 1: print 1 z += 1; if x > -1: z += z print 1 if x >= -1: print 1 if x < 2: print 1 if x < y: print 1 if x <= y: print 1 if x != y: print 1 if x <> y: print 1 if x <> 1: print 0 if x == 1 and x > -1: print 1 ...
p1=int(input("Digite o primeiro termo da Progressão Aritimética: ")) r=int(input("Digite a razão da Progressão Aritimética: ")) décimo = p1 + (10-1) * r for c in range(p1,décimo,r): print("{}".format(c), end=' → ') print("FIM!")
peso=float(input("Digite o peso: (kg) ")) altura=float(input("Digite a altura: (m) ")) imc=peso/(altura**2) print("Seu IMC é de {:.1f}".format(imc)) if imc < 18.5: print("Você está ABAIXO do peso ideal.") elif imc <= 25: print("Vocês está no PESO IDEAL. Parabéns!") elif imc <= 30: print("Você está em SOBREP...
#CONVERSAO DE TEMPERATURA #ESCREVA UM ALGORITIMO QUE LEIA A TEMPERATURA EM CELCIUS E #CONVERTA PARA FARENHEIT c = int(input("Informe a temperatura em ºC: ")) print("A temperatura de {}ºC corresponde a {}ºF".format(c,c*9/5+32))
n = int(input("Quantos termos? ")) t1 = 0 t2 = 1 print cont = 3 while cont <= n: t3 = t1 + t2 t1 = t2 t2 = t3 cont += 1
a, b, c = map (int, input().split()) #MENOR if a < b and a < c: menor = a if b < a and b < c: menor = b if c < a and c < b: menor = c #MEDIO if a < b and a > c or a < c and a > b: medio = a if b < a and b > c or b < c and b > a: medio = b if c < a and c > b or c < b and c > a: medio = c #MAIOR...
#ESCREVA UM PROGRAMA QUE LEIA A ALTURA E LARGURA DE UMA PAREDE #EM METROS, CALCULE A AREA E A QUANTIDADE DE TINTA PARA PINTÁ-LA #SABENDO QUE UM LITRO PINTA UMA ÁREA DE 2M QUADRADOS b=float(input("Qual é o comprimento da parede? ")) h=float(input("Qual é a altura da parede? ")) a=b*h lt=a/2 print("Serão necessários {:.2...
#ESCREVA UM PROGRAMA QUE LEIA UM VALOR #E MOSTRE SUA TABUADA #-------------A FORMA QUE EU FIZ-------------- #v0 = int(input('Digite um valor qualquer: ')) #v1 = v0*1 #v2 = v0*2 #v3 = v0*3 #v4 = v0*4 #v5 = v0*5 #v6 = v0*6 #v7 = v0*7 #v8 = v0*8 #v9 = v0*9 #v10 = v0*10 #print('============TABUADA DE {}============'.forma...
from datetime import date nasc=int(input("Qual o ano de nascimento do atleta? ")) atual= date.today().year idade=atual-nasc if idade <= 9: print("Classificação: MIRIM") elif idade <= 14: print("INFANTIL") elif idade <=19: print("JUNIOR") elif idade <= 25: print("SÊNIOR") else: print("MASTER")
from random import randint comp = randint(0,10) print("Olá! Escolhi um número entre 0 e 10. Tente acertar!") acertou = False cont = 0 while not acertou: ent = int(input("Escolha um número: ")) cont += 1 if ent == comp: acertou = True if cont < 3: print("Parabéns, você acertou!") ...
#CRIE UM PROGRAMA QUE LEIA UM NÚMERO INTEIRO E MOSTRE NA TELA SE ELE É PAR #OU ÍMPAR. num=int(input("Digite um número qualquer: ")) resultado=num%2 if resultado==0: print("O número {} é PAR.".format (num)) else: print("O número {} é ÍMPAR.".format (num))
import random print('-----------------------------') print(' Guess that number ') print('-----------------------------') print() the_number = random.randint(1, 100) guess = -1 tries = 0 name = input('What is your name? ') print() while guess != the_number: guess_text = input('{0}, what number am I thi...
import queue NUM_PLAYERS = 2 class Trie: def __init__(self) -> None: self.root = TrieNode('*', parent=None) def add(self, word: str) -> None: '''adds a node to the Trie''' node = self.root for char in word: flag = False flag = char in node.children.key...
from rm import parse_line ######### ENCODING ######## # Encodes a list of encoded instruction bodies into a final coding def encodeList(l): if len(l) == 0: return 0 return (2 ** l[0]) * (2 * calc(l[1:]) + 1) def doubleBrackets(x, y): return (2 ** x) * (2*y + 1) def singleBrackets(x, y): ret...
def ratatuj(input): lines = input.split('\n') cases = int(lines.pop(0)) for case in range(cases): destination, num_horses = (int(x) for x in lines.pop(0).split(' ')) horses = [] for i in range(num_horses): horses.append([float(x) for x in lines.pop(0).split(' ')]) ...
def count(maxShy, occurrences): currentStanding = 0 friends = 0 for i in range(0, int(maxShy)+1): currentShy = int(occurrences[i]) if currentStanding < i and currentShy > 0: friends += (i - currentStanding) currentStanding += (i - currentStanding) currentSta...
def solve(c, f, x): i = 0 best = x / 2.0 factory_cost = 0.0 while True: factory_cost += c / (i * f + 2.0) total_cost = factory_cost + (x / ((i + 1) * f + 2.0)) i += 1 if total_cost < best: best = total_cost else: break return best if ...
x = int(input()) for num in range(1, x + 1): curr = list(input()); for i in range(len(curr) - 2, -1, -1): if curr[i] > curr[i + 1]: curr[i] = str(int(curr[i]) - 1); for j in range(i + 1, len(curr)): curr[j] = '9' print(str(int("".join(curr))));
def is_tidy(x): if to_list(x)==sorted(x): return True return False def to_list(x): temp=[] for a in x: temp.append(a) return temp t = int(input()) for z in range(t): n = int(input()) if n<=int((len(str(n))-1)*'1'+'0'): print("Case #{}: {}".format(z+1,(len(str(n))-1)*'9')) ...
def print_2d(tab): for e in tab: print(e) def zlicz(num, cmp): ret = [] for el in str(num): if(int(el) not in cmp): ret.append(-1) break if(int(el) != 0): ret.append(int(el)) ret.sort() return ret if __name__ == '__main__': fin = o...
def istidy(number): stringnumber = str(number) digits = len(stringnumber) if(digits == 1): return True for i in range(1, digits): if int(stringnumber[i]) < int(stringnumber[i - 1]): return False return True def getresult(number): result = number while...
#! /usr/bin/python import os import sys from math import sqrt def transform(n, i): N = [] while n > 0: mod = n % i n /= i N.append(mod) return N if len(sys.argv) != 2: print 'USAGE: q1.py input.in' sys.exit() fIn = open(sys.argv[1], 'r') param = fIn.readline().split() caseNo = int(param[0]) for i in range...
#!/usr/bin/python import sys from fractions import Fraction EXAMPLE = 0 def solve(case): N, Pd, Pg = case if Pd == 0 and Pg == 0: return "Possible" if Pd == 100 and Pg == 100: return "Possible" if Pg == 0 or Pg == 100: return "Broken" if N < Fraction(Pd, 100).denominator: ...
def back_to_num(digits): return int(''.join([str(x) for x in digits])) def counting_on_you(digits): nine_spray = False for i in range(len(digits)-1): if nine_spray: digits[i] = 9 elif digits[i] > digits[i+1]: digits[i] -= 1 if i != 0 and digits[i] < dig...
import math def check_triangle(a,b,c,target): x1,y1 = a x2,y2 = b x3,y3 = c area = abs((x1-x2)*(y1-y3)-(y1-y2)*(x1-x3)) return area == target def enum_triangles(N,M,target): N += 1 M += 1 x1 = 0 y1 = 0 for x2 in range(N): for x3 in range(N): for y2 in range(...
#!/usr/bin/env python import sys def find_number(row1, row2): row1_ints = set(int(i) for i in row1.split()) row2_ints = set(int(i) for i in row2.split()) intersect = row1_ints & row2_ints if not intersect: return "Volunteer cheated!" elif len(intersect) == 1: return str(intersect.p...
#!/usr/bin/env python def read_int(): return int(raw_input()) tr = dict(y='a', e='o', q='z', z='q') def learn(cipher, plain): for c, p in zip(cipher, plain): assert c not in tr or tr[c] == p tr[c] = p learn('ejp mysljylc kd kxveddknmc re jsicpdrysi', 'our language is impossible to und...
def readint(input): return int(input.readline().strip('\n')) def readstr(input): return input.readline().strip('\n') def readintline(intput): return [int(i) for i in input.readline().strip('\n').split(' ')] def readstrline(intput): return [i for i in input.readline().strip('\n').split(' ')] def s...
# Enter your code here. Read input from STDIN. Print output to STDOUT #!/usr/bin/env python import sys import random import numpy as np from time import time import math def color(x): if x == 0: return "R" if x == 1: return "O" if x == 2: return "Y" if x == 3: return "G" if x == 4: return "B" if x == ...
import sys def compute_velocity(destination, horses, case): horses.sort(reverse=True) worst_time = (destination - horses[0][0]) / horses[0][1] # time = space / velocity for horse in horses: todo = destination - horse[0] time = todo / horse[1] if time > worst_time: worst...
import sys,math cases = int(raw_input()) def reverse(n): rn = str(n)[::-1] return int(rn) def checkIfToBeReversed(n,fn): if len(str(n)) == 1: return False for i in range(len(str(n))/2): tenpow = 10**i rn0 = reverse(n) rn1 = reverse(n+tenpow) #print " n: " + str(n) + " rn0: " + str(rn0) #print "rn0...
def is_tiddy(num): num = map(int, str(num)) prev = 0 flag = True for i in num: if i < prev: flag = False prev = i return flag def last_tiddy(num): while num > 0: if is_tiddy(num): return int(num) num -=1 return 0 # raw_input() reads a string with a line of input, stripping th...
# -*- coding: utf-8 -*- """ Created on Sat Apr 8 10:48:24 2017 @author: Henry """ def tidy(N): N = str(N) N= list(N) for i in range(len(N)-1): if int(N[i]) > int(N[i+1]): return False return True def maketidynaive(N): while not tidy(N): N = N-1 ...
import math import itertools def check_palindrome(strng): if (len(strng) == 1): return True if (len(strng) == 2): return strng[0] == strng[1] if (strng[0] == strng[-1]): return check_palindrome(strng[1:-1]) return False def check_square(num): sqr = num * num return che...
import fileinput def stringListToRealList(stringList): result = list() for number in stringList: result.append(float(number)) return result # L - Length of words in the alien language # D - Number of words in the alien language # N - Number of test cases infile = fileinput.input() ...
#!/usr/bin/env python from collections import deque FILENAME = 'A-small-attempt1.in' def load_board(q): result = deque() max = 4 for x in range(0, max): item = q.popleft() result.append(item.split()) return result def load_from_file(): result = None with open(FILENAME) as...
""" Basic idea: Brute force it, but make it a little faster by phrasing it as an XOR question Basically, we start with the pancake string and try XORing it by binary strings where the string has a 1 in the places where a pancake is flipped. Our goal is to get to the string with all ones. """ numInpu...
#!/usr/bin/env python from collections import defaultdict def create_mapping(goog, eng): '''return the mapping of googlerese characters to english characters.''' mapping = {} for g, e in zip(goog, eng): mapping.update(dict(zip(g, e))) return mapping def solve(goog, m): return ''.join(m[c]...
def find_untidiness(N): # A tidy number is one such that N[i-1] > N[i] is never true for i in range(1,len(N)): if N[i-1] > N[i]: return i return -1 for t in range(int(input())): case_t = input() digit_list = [int(x) for x in list(case_t)] digits_n = len(digit_list) ans = "not found" while True: # f...
#!/usr/bin/env python def is_pal(x): r=str(x) return r == r[::-1] import sys import math def readint(): return map(int, sys.stdin.readline().strip().split()) t, = readint() def test(): a,b = readint() wy=0 for i in range(a,b+1): x = int(math.sqrt(i)) if is_pal(i) and is_pal(x) and x*x ==i: wy+=1 ret...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Scott Patterson # asp742@gmail.com # import sys from itertools import cycle def min_scalar(v1, v2): v1.sort() v2.sort() return sum(x*y for x, y in zip(v1, v2[::-1])) def main(): file = sys.argv[1] data = (lines.strip() for lines in open(file)) ...
import numpy as np import math def is_palindrome(number): number_string = str(number) length = len(number_string) first_half = number_string[0:length/2] # print number, ":", first_half if length%2 == 1: second_half = number_string[(length/2):length] else: second_half = number_string[(lengt...
from math import sqrt, ceil def is_palyndrome(number): nStr = str(number) half = len(nStr) / 2 for i in xrange(half): if nStr[i] != nStr[-1-i]: return False return True def solve(A, B, roots): a = 0 while roots[a]*roots[a] < A: a += 1 b = len(roots)-1 while ...
import os, sys, re, string def readint(): return int(sys.stdin.readline()) def readints(sp=" "): return map(lambda x: int(x), sys.stdin.readline().split(sp)) class Node: def __init__(self, value): self.value = value self.name = None self.first = None self.second = None def output(self): print self.nam...
#!/usr/bin/python import sys # Memoization pattern class basic_mem: def __init__ (self, function): self.function = function self.cache = {} def __call__ (self, *args, **kwargs): key = str(args) + str(kwargs) if key in self.cache: return self.cache[key] else: result = self.function(*args, **kwargs...
if __name__ == '__main__': num_of_cases = int(raw_input()) for case_index in range(num_of_cases): num_candies = int(raw_input()) candies = [int(k) for k in raw_input().strip().split()] candies.sort() if reduce(lambda x,y: x^y, candies) == 0: print "Case #%d: %d" % (case_index+1, reduce(lambda ...
def int_to_based_list(integer, base): based_list = [] if integer < 0 or base <= 1: return based_list if integer == 0: based_list.append(integer) return based_list div = integer while div > 0: (div, rem) = divmod(div, base) based_list.append(rem) ...
#!/usr/bin/env python3 # # Google code jam - qual round - 2014 # problem 1 - magic trick # # written by mark grandi - april 12 2014 import argparse, sys def main(args): '''@param args - the arguments given to us by argparse.parse_args''' # here we parse the input # read the number of tes...
class Problem: def __init__(self) : self.L = 0 self.X = 0 self.str = "" def readProblem(input): problem = Problem() line = input.readline().rstrip().split() problem.L = int(line[0]) problem.X = int(line[1]) problem.str = input.readline().rstrip() return p...
import sys from StringIO import StringIO def translate(): example = """ejp mysljylc kd kxveddknmc re jsicpdrysizq our language is impossible to understandqz rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd there are twenty six factorial possibilities de kr kd eoya kw aej tysr re ujdr lkgc jv so it is okay if you want to...
lower = 1 upperpower = 100 upper = 10**upperpower halfpower = upperpower//2 halfupper = 10**halfpower squarepalindromes = [1,4,9] #roots = [] from math import sqrt def ispalindrome(n): s = str(n) return s == s[::-1] def search(n): low = 0 high = len(squarepalindromes) mid = (low+high)//2 ...
# check the last digit with second last t = int(input()) for test in range(1, t+1): num = int(input()) digits = [int(d) for d in str(num)] if len(digits) is 1: print("Case #" + str(test) + ": " + str(int("".join(str(d) for d in digits)))) continue for index in range(len(digits) - 1, 0...
def multi_input(): """Take multiple inputs.""" case_num = int(input()) # First line, determines how many for __ in range(case_num): pancakes, k = input().split() yield (list(pancakes), int(k)) def main(): test_cases = multi_input() flip = {'+': '-', '-': '+'} answer...
def flips(s, k): if len(s) < k: for pancake in s: if pancake=="-": return "IMPOSSIBLE" return 0 else: if s[0]=="-": a = "" for i in range(k): if s[i]=="-": a += "+" else: ...
#!/usr/bin/env python3 # I'm participating in CodeJam to learn some Python (and because the problems are really interesting) # # The script expects it's input on stdin, and writes it's output to stdout # # This problem is really easy. If K+1 is divisible with 2**N, the light is on, otherwise it's off import s...
#!/usr/bin/env python3.2 # -*- coding: utf-8 -*- import math import sys def solve(A, B): sqrt = math.sqrt(A) if sqrt > int(sqrt): lowest = int(sqrt) + 1 else: lowest = int(sqrt) highest = int(math.sqrt(B)) cnt = 0 for n in range(lowest, highest + 1): sq = n * n ...
#!/usr/bin/python2 def readf(f): board = [] for i in range(4): board.append(f.readline()[:-1]) f.readline() return board def try_row(board, r, s): line = board[r]; for c in line: if c != s and c != 'T': return False return True def try_col(board, c, s): for...
# code jam qualification round # Problem A. Speaking in Tongues def get_char_mapping(encrypted, decrypted, dic): pos=0 for e in encrypted: d = decrypted[pos] dic[e] = d pos += 1 return dic def decrypt (encrypted, d): res="" for c in encrypted: if '\n' == c: ...
import fileinput from collections import Counter import sys 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++) #...
#!/usr/bin/python import sys, os, re def find_ith(i, lines): width = len(lines[0]) n = 0 for k in range(i, len(lines)): line = lines[k] ok = True #print line, i for j in range(i+1,width): #print "check", line[j] if line[j] == '1': ok ...
import sys import heapq def process_case(input, case): N, K = input.split(" ") K = int(K) N = int(N) h = [-N] spaces = {N: 1} mins, maxs = -1, -1 while K > 0: largest_space = -heapq.heappop(h) num_spaces = spaces[largest_space] del spaces[largest_space] if ...
def tile(picture): picture = picture.strip().split("\n") for x in range(len(picture[0]) - 1): for y in range(len(picture) - 1): if picture[y][x] == "#" and picture[y + 1][x] == "#" and picture[y][x + 1] == "#" and picture[y + 1][x + 1] == "#": picture[y] = picture[y][:x]...
#!/usr/bin/python """ Google Code Jam 2009 philfifi@free.fr All rigths reserved """ from math import sqrt from decimal import * getcontext().prec = 100 import psyco psyco.full() _debug = 0 def this_word_matches_test_cases(word, test_case_parsed): pass def solve_case(case_no,L, words_l, test_case ): ...
#!/usr/bin/env python3 import argparse import math import logging def read_input(): f = open(args.inputfile) T = int(f.readline()) for i in range(T): yield [int(i) for i in f.readline().split()] def output(n, s): outstring = "Case #{}: {}\n".format(n, s) print(outstring, end="") out...
#!/usr/bin/python """ Train Timetable problem solution (GCJ 2008, Qualification Round) Author: madrezaan """ import sys # open input file if len(sys.argv) == 2 and sys.argv[1] != '--help': in_file = open(sys.argv[1]) else: print "Usage: train_timetable.py <input file>" sys.exit(0) # get number of cases ...
#!/usr/bin/python import re #import logging FILE='A-small-attempt1' # logging.basicConfig(level = logging.DEBUG, # format = '%(message)s', # filename = FILE + '.log', # filemode = 'w') def isinvocab(word): for a in vocab: if a.find(word) != -1: ...
import sys from math import sqrt, floor, log2 f = open(sys.argv[1], 'r') numOfTest = int(f.readline()) for i in range(1, numOfTest + 1) : print("Case #" + str(i) + ":", end=' ') # read test case temp = f.readline().split('/') p = int(temp[0]) q = int(temp[1]) if log2(q) != ...
#!/usr/bin/python2.6 def testCase(): raw_input() values = [int(v) for v in raw_input().split()] if reduce(lambda x, y: x ^ y, values, 0): return "NO" values.sort() return sum(values[1:]) if __name__ == '__main__': for i in xrange(int(raw_input())): print "Case #%d: %s" % (i + 1, testCase())
#!/usr/bin/env python import sys def checkwin(board, symbol): for r in range(0, 4): win = True for c in range(0, 4): if board[r][c] not in ['T', symbol]: win = False break if win: return True for c in range(0, 4): win = Tru...
def should_add(s,p,ts): if(p == 0): return True,s if(ts == 0): return False,s d = int(ts/3) if(ts%3 == 0): if(d >= p): return True,s elif (d+1 >= p) and (s>0): return True,s-1 else: return False,s elif ((ts-1)%3...
""" Pancake Flipping Problem again""" from sys import stdin def flip_cakes(stack, start_pos, length): """ Helper function for performing a single flip""" if start_pos + length > len(stack): return False, stack else: new_stack = "" for i in range(len(stack)): if i >= sta...
import logging import Queue as Q import math logging.basicConfig(filename='log.txt', level=logging.DEBUG) def compute(n, k): if k * 2 > n: return 0, 0 q = Q.PriorityQueue() q.put(-n) while not q.empty(): cur = -q.get() k -= 1 a, b = cur / 2, (cur-1) / 2 if k == ...
import argparse def is_tidy(n): N = str(n) for i in range(1, len(N)): if N[i-1] > N[i]: return False return True def last_tidy(N): for n in xrange(int(N), -1, -1): if is_tidy(n): return n return -1 parser = argparse.ArgumentParser() parser.add_argumen...
def Simplify(elements, combine, opposed): repeat = True while repeat: repeat = False # Check combinations for combination in combine: try: if combination[0] == elements[-1] and combination[1] == elements[-2] or combination[1] == elements[-1] and combina...
#!/usr/bin/env python def solve(R, C, rows): for i in range(0, R): for j in range(0, C): if rows[i][j] == '#' and j+1<C and rows[i][j+1] == '#' and i+1<R and rows[i+1][j] == '#' and rows[i+1][j+1] == '#': rows[i][j] = '/' rows[i+1][j] = "\\" rows[i][j+1] = "\\" rows[i+1][j+1...
#!/usr/bin/env python DEBUG = False def read_stdin_lines(): import fileinput return [line for line in fileinput.input()] def parse_lines(lines): lines.pop(0) return [map(int, line.split()) for line in lines] def solve(i): assert(len(i) == 3) X, R, C = i if X > 6: if DEBUG: ...
def build_table(): table = [] for i in range( 0, 31 ): table.append( ( get_max_score( i ), get_max_surprise_score( i ) ) ) return table def get_max_score( i ): return max( 0, min( 10, ( i + 2 ) / 3 ) ) def get_max_surprise_score( i ): return min( i, max( 0, min( 10, ( i + 4 ) / 3 ) ) ) def get_max( x, score...
def split(str): return list ( str ) def final_total(total_km, distance, speed): return float(total_km/(float((total_km-distance)/speed))) def remaining_hours(total_km, distance, speed): return float((total_km-distance)/speed) def final_speed(total_km, hours): return float(total_km/hours) def calcula...
# To change this template, choose Tools | Templates # and open the template in the editor. __author__="assim" __date__ ="$Sep 3, 2009 3:31:06 PM$" def is_exist(word_list, case): def is_in_case_list(w, c): #print "w: ", w, "c: ", c for i in range(len(w)): if w[i] not in c[i]: break else: return True...
#!/usr/bin/env python3 import os import sys def is_tidy(n): perv_i = int(str(n)[-1]) for i in list(reversed(str(n)[:-1])): if perv_i < int(i): return False else: perv_i = int(i) return True def main(): T = int(input()) for i in range(T): N = int(in...
def isTidy(num): num = str(num) tidy = True for x in range(0, len(num)-1): if int(num[x]) > int(num[x+1]): return False return True def findTidy(num): for x in range(num, 0, -1): if isTidy(x): return x caseNum = int(input()) for x in range(1, c...
#!/usr/bin/python import sys def solve_problem(r, t): #print "Solving: ", r, t num = 0 circles = 0 ml = t while True: #print "ml=", ml, "r=", (r+num), "spent:", t-ml ml -= (2*(r+num) + 1) if ml >= 0: circles += 1 num += 2 else: br...
def tidy_num(target_num): temp_num = target_num digit_list = [] while temp_num > 0: digit_list.append(temp_num % 10) temp_num /= 10 num_length = len(digit_list) for i in xrange(1, num_length): if digit_list[num_length - i - 1] < digit_list[num_length - i]: next_try = target_nu...
import timeit start = timeit.default_timer() def numberOfFriends(test): numberOfFriends = 0 numberOfStandingPeople = 0 realTest = test[2:] firstPosPassed = False while int(realTest[numberOfFriends]) is 0: numberOfFriends+=1 numberOfStandingPeople = numberOfFriends for i in xrange(numberOfFriends, int(test[0...
from sys import stdin def min_time(farm_cost, extra, targt, current, cur_time): time_with_current = target/ current #import pdb;pdb.set_trace() time_to_farm =farm_cost/ current future_speed =extra + current future_time = target/ future_speed future_time =future_time+ time_to_farm if future_time >= ...
import math def addPerson(c,last): sec = [] dist = 0 first = 0 for place in range(len(c)): stall = c[place] if(place != 0): if(stall == "."): dist += 1 elif(stall == "O"): section = { "top": first-1, ...
for case in range(1, int(input()) + 1): Y, X = map(int, input().split()) tiles = [list(input()) for _ in range(Y)] print('Case #%d:' % case) def replace(y, x): for a, b in [(y, x), (y, x+1), (y+1, x), (y+1, x+1)]: if tiles[a][b] != '#': return False tiles[a][b] = '\\' if (a == y) ^ (b ...
#!/usr/bin/env python3 import sys VOWELS = ['a', 'e', 'i', 'o', 'u'] def count_consonantes(name): max_count, count = 0, 0 index = 0 #print('Evaluating', name) while index < len(name): if name[index] not in VOWELS: count = count + 1 #print('More cons', count) else: max_count = max(count, max_count) ...
from StringIO import StringIO def all_indices(str, chr): for i, cc in enumerate(str): if cc == chr: yield i def num_substrings( line, phrase ): paths = [(x,1) for x in all_indices(line,phrase[0])] for c in phrase[1:]: nextpaths = [] indices = list(all_indices(line,...
__author__ = 'David' def break_string(string): double_array = string.split() array = list(double_array[1]) return (double_array[1],array) def solve_problem(input): array = break_string(input) total = int(array[1][0]) needed_friends = 0 for i in range(1,len(array[1])): ...
#!/usr/bin/python import sys import string import logging import time # logging.basicConfig(level=logging.INFO) WELCOME = "welcome to code jam" def count(goal, supply, mod=0): # In this puzzle, "x" is not a substring of "x" so, # we special case that. if goal == supply: return 0 assert len(goal), "Only ...
# 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. HAPPY = '+' BLANK = '-' flips = 0 def all_happy(cakes): for i in cakes: if not i: return False return True def flip(cakes, i): j = i whi...
def powerset(seq): """ Returns all the subsets of this set. This is a generator. """ if len(seq) <= 1: yield seq yield [] else: for item in powerset(seq[1:]): yield [seq[0]]+item yield item def np(a): return ' '.join([str(x) for x in a]) def mai...