text stringlengths 37 1.41M |
|---|
import mysql.connector
# below are hre connection details
conn=mysql.connector.connect(user="root",password="root123",host="localhost",database="testcompany")
#conn=mysql.connector.connect(user="abc",password="rajesh",host="localhost",database="testcompany")
#cursor created
mycursor=conn.cursor()
mycursor.execute("Dr... |
import pandas as pd
def sanitize_gene_col(metadata_df, gene_col, control_barcodes):
"""
Sanitize metadata information
Arguments:
metadata_df - a pandas dataframe storing at least a column indicated by gene_col
gene_col - the column to sanitize
control_barcodes - a list of entries in the gene ... |
#Main file to run
#for all the imports
from game import Game
#The class where all the program runs
class Guess:
''' This is the main Guess class where the program is run
This primarily has one static method to run the program called as run()
Implicitly, it calls the Game class to run'''
@staticmeth... |
def get_twice():
strings = []
with open("frequency_input.txt") as infile:
strings = infile.readlines()
inputs = [int(x) for x in strings]
frequency_set = set()
frequency = 0
frequency_set.add(frequency)
found_twice = False
while not found_twice:
for number in inputs:
... |
import sys
INF = sys.maxsize
class Graph:
def __init__(self, n):
self.vertixes = n
self.matrix = [[INF for x in range(n)] for y in range(n)] # initialize with infinite first
for x in range(n):
self.matrix[x][x] = 0 # the distances on diagonal will be 0
# now it looks som... |
# Python Program to detect cycle in an undirected graph
# from geeksforgeeks
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, v, w):
self.graph[v].append(w)
self.graph[w].append(v)
self.noOfNodes = len(self.g... |
'''
Created on Nov 16, 2018
@author: Winterberger
'''
train_mass = 22680
train_acceleration = 10
train_distance = 100
bomb_mass = 1
def f_to_c(f_temp):
c_temp = 5/9 * (f_temp - 32)
return c_temp
f100_in_celsius = f_to_c(100)
print (f100_in_celsius)
def c_to_f(c_temp):
f_temp = c_temp *... |
'''
Created on Dec 29, 2018
@author: Winterberger
'''
premium_cost = 125.
ground_flat = 20.
drone_flat = 0.
ground_U2 = 1.5
ground_U6 = 3.
ground_U10 = 4.
ground_Heavy = 4.75
drone_U2 = 4.5
drone_U6 = 9.
drone_U10 = 12.
drone_Heavy = 14.25
def main():
#prompt for weight
weight = float... |
'''
Use special python None (immutable, falsy, unique value) to determine if we do something
'''
from review_lib import get_next_review, submit_review
# define review here!
review = get_next_review()
if review is not None:
submit_review(review)
'''
Common functions that do something but don't retur... |
'''
Created on Apr 10, 2019
@author: Winterberger
'''
class SortedList(list):
def __init__(self, lst):
self.selflist = lst
print(self.selflist)
self.selfsort()
print(self)
def selfsort(self):
srtd = [0 for i in range(len(self.selflist))]
index = 0
while len(self.se... |
import datetime
import person
me = person.Person(
"Ryan",
"Moriarty",
datetime.date(1980, 4, 1), # year, month, day
"8 Ossian Road",
"07968199004",
"ryan.moriarty@btinternet.com"
)
somone = person.Person(
"Jane",
"Doe",
datetime.date(1992, 3, 12), # year, month, day
"No. 12 Sho... |
__author__ = 'Nafiul Islam'
__title__ = 'Special Pythagorean triplet'
def main(argv):
for c in range(1, argv+1):
for b in range(1, c):
for a in range(1, b):
if a + b + c == argv:
# print a, b, c
if a**2 + b**2 == c**2:
... |
import os
import unittest
from datetime import datetime
from csv_writer.csv_writer import write_highest_earthquakes, write_daily_stats
from database.dbmanager import DatabaseManager
class TestCsv(unittest.TestCase):
"""Test case for the correct creation of non-empty csv files"""
def setUp(self):
... |
list = "AGCAGCAGCAGCAGC"
def instance_count(list, DNA_String):
aa = []
for char in list:
aa.append(char)
count = 0
for chars in range(0, len(aa)- 1, len(DNA_String)):
if chars == DNA_String:
count += 1
return count
print(instance_count(list, "AGC")) |
"""
Utility classes and functions for type conversion.
:author: Jeremy Biggs (jbiggs@ets.org)
:author: Anastassia Loukina (aloukina@ets.org)
:author: Nitin Madnani (nmadnani@ets.org)
:organization: ETS
"""
from skll.data import safe_float as string_to_number
def int_to_float(value):
"""
Convert integer to ... |
__author__ = 'Marie Hoffmann ozymandiaz147@googlemail.com'
import math
# test for palindrome of decimal represenation
def isPalindrome(x):
digits = int(math.ceil(math.log10(x)))
x1 = x
while digits > 1:
if (x1 % 10) != (x1 // 10**(digits-1)):
return False
x1 //= 10 # clip right... |
__author__ = 'Marie Hoffmann ozymandiaz147@googlemail.com'
import random
# create random subset of size k from A and store it in A
# idea: build permutation P[:k] = unique random idcs , P[k:] = identity
# runtime: O(k) sampling and application of first k permutation mappings
# space: O(k)
def rndSubset(A, k):
idc... |
class Cat:
def __init__(self, new_name):
self.name = new_name
print("%s 我来了" % self.name)
def __str__(self):
return "我是小猫%s" % self.name
def __del__(self):
print("%s 我走了" % self.name)
# 使用类名()创建对象的时候,会自动调用__init__方法
# 创建猫对象
tom = Cat("Tom")
print(tom) |
class HouseItem:
def __init__(self, name, area):
self.name = name
self.area = area
def __str__(self):
return "【%s】占地%.2f平方米" % (self.name, self.area)
class House:
def __init__(self, house_type, area):
self.house_type = house_type
self.area = area
# 剩余面... |
data = input('enter word(s) to be translated to pig latin: ')
data_a = data.split(' ')
print('')
for i in data_a:
a = i[0:1]
i=i[1:]
print(i+a+'ay', end=' ')
|
"""Python2- and Python3-compatible. That's all."""
from time import clock
from sys import argv
#import math
#import itertools
#import numpy
from fractions import gcd
from decimal import Decimal
def read(f):
return next(f).strip("\n")
def read_singles(f):
# returns chars of a word
# or digits (as strin... |
import sys
def Remove(numberString, removeString):
for i in range(0,len(removeString)):
numberString = numberString.replace(removeString[i], '', 1)
return numberString
inputStrings = open('A-large.in', 'r').read().splitlines()
caseNum = int(inputStrings[0])
outString = ""
for case in ran... |
def solve(word):
new_word = word[0]
for char in word[1:]:
if new_word[0] > char:
new_word = new_word + char
else:
new_word = char + new_word
return new_word
T = input()
for i in range(T):
word = raw_input()
print 'Case #' + str(i + 1) + ': ' + str(solve(word)) |
#!/usr/bin/python3
import math
def canFill(x, r, c):
if x >= 7:
return False
if (r * c) % x != 0:
return False
if r < x and c < x:
return False
s = (x - 1) // 2 + 1
if r < s or c < s:
return False
if x == 4 and (r == 2 or c == 2):
return False
return... |
#!/usr/bin/python3
from common import *
def gcd(a, b):
if a < b:
a, b = b, a
while b > 0:
q = a // b
r = (a - b * q)
a, b = b, r
return a
def lcm(a, b):
return a * b // gcd(a, b)
def lcms(xs):
l = 1
for x in xs:
l = lcm(l, x)
return l
def intlog(b... |
def sign(a, b):
if a == "1" or b == "1":
return False
if a == b:
return True
if a == "i" and b == "k" or a =="j" and b == "i" or a == "k" and b=="j":
return True
return False
def multiply(a, b):
if a == "1":
return b
if b == "1":
return a
if a == ... |
from collections import defaultdict
import fileinput
round_one_words = ("ZERO", #Z
"ONE",
"TWO", #W
"THREE",
"FOUR", #U
"FIVE",
"SIX", #X
"SEVEN",
"EIGHT", #G
... |
def diamond(graph):
for start in graph:
queue = [start]
path = []
while queue:
node = queue.pop(0)
if node in path:
return True
else:
path.append(node)
queue += graph[node]
return False
if __name__ == '_... |
#!/usr/bin/python3
#
# @author Andres Ayala (killerrex@gmail.com)
#
def linecheck(line):
"""
X => X Won
O => O Won
K => Keep playing
D => Draw
"""
prev = None
red = set(line)
if red.issubset("TX"):
return "X"
if red.issubset("TO"):
return "O"
if "." in red:
... |
"""Solve the 'Less Money, More Problems' problem."""
from solver import solver
def solve(c, s, v):
r, l = 0, 0
for x in s:
while x > l+1:
if l >= v:
return r
r += 1
l += c * (l+1)
l += c * x
while True:
if l >= v:
retu... |
def opposite(pancakes):
return pancakes.replace('-', '*').replace('+', '-').replace('*', '+')
def process(pancakes):
if '-' not in pancakes:
return 0
if len(set(pancakes)) == 1:
return 1
for i in xrange(1, len(pancakes)):
if pancakes[i] != pancakes[i-1]:
return pro... |
#!/usr/bin/env python3
def solve(N):
if N == 0: return "INSOMNIA"
c = N
D = set()
for i in range(1000):
D |= set(str(c))
if len(D) == 10: return c
c += N
raise "WE PLAYED AND LOST"
tests = int(input())
for test in range(tests):
N = int(input())
result = solve(N)
... |
#! /usr/bin/env python
def check_paths(paths, goal):
return paths.get(goal)
def find_path(X,Y):
goal = (X,Y)
paths = {(0,0): ''}
correct_path = None
i = 1
while correct_path is None:
new_paths = dict()
for XY,path in paths.iteritems():
new_paths[(XY[0], XY... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import sys
from itertools import product
#96989
#76777
#96989
#11111
#96989
def subrow_is_lower(row, cell):
return all(item <= cell for item in row)
class Lawn(object):
def __init__(self, n, m, lines):
self.n = n
self.m = m
self.lines = lin... |
from math import sqrt
def transform():
values = raw_input().split()
r = int( values[0] )
t = int( values[1] )
count = 0;
c2p1 = count+1
expresion = (2*r+1)
if expresion <= t:
l = 0
right = sqrt(t)
while l < right:
count = l + (int) (right-l)/2
if ... |
#!/usr/bin/env python
# Python 3
import platform
assert platform.python_version_tuple()[0] == '3'
def solution(s):
charcount = {}
for char in s:
if char in charcount:
charcount[char] += 1
else:
charcount[char] = 1
def dropwords(by_char, drop_chars):
if by... |
import itertools
from math import sqrt
def isprime(n):
upper = int(sqrt(n))
for i in range(2, upper+1):
if n%i==0:
return i;
return -1;
def Converttodec(s, b):
ans = 0
for j,i in enumerate(s[::-1]):
ans += int(i)*(b**j)
return ans
inpu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def solve(s):
s_len = len(s)
result = [s[0]]
for i in range(1, s_len):
if result[0] <= s[i]:
result.insert(0, s[i])
else:
result.append(s[i])
return ''.join(result)
if __name__ == '__main__':
test_cases = int(... |
# Language : Python 3
# Compiled Using : py_compile
# Version : Python 3.4.3
def replace_string(chars, pos, new_c):
result = ""
for j in range(len(chars)):
if pos == j:
result += new_c
else:
result += chars[j]
return result
with open("B... |
#!/usr/bin/env python
import sys
import random
_mrpt_num_trials = 5 # number of bases to test
def is_probable_prime(n):
"""
Miller-Rabin primality test.
A return value of False means n is certainly not prime. A return value of
True means n is very likely a prime.
>>> is_probable_prime(1)
... |
def hasWon(boardState, winningSymbol):
# Horizontal Check
for row in range(len(boardState)):
rowWinner = True
for column in range(len(boardState)):
if boardState[row][column] == winningSymbol or boardState[row][column] == "T":
continue
else:
... |
NumberOfTestCases = int( input() )
for NumTestCases in range(1,NumberOfTestCases+1):
print('Case #',NumTestCases,': ',sep='',end='')
Smax,str=input().split()
Smax=int(Smax)
ans = 0
sum = 0
for i in range(0,Smax+1):
if sum < i:
ans += 1
sum += 1
sum += int(str[i])
print(ans)
|
def remove_char(s, c):
return s.replace(c, '', 1)
def remove_word(s, word):
for c in word:
s = remove_char(s, c)
return s
def solve(s):
digits = []
while 'Z' in s:
s = remove_word(s, 'ZERO')
digits.append(0)
while 'X' in s:
s = remove_word(s, 'SIX')
digits.append(6)
while 'G' in s:
... |
#!/bin/python
# -*- coding: utf-8 -*-
import sys
import math
import itertools
def is_palindromes(num):
str_num = str(num)
return str_num == str_num[::-1]
def check_small(s, e):
ret = 0
ss = int(math.ceil(math.sqrt(s)))
ee = int(math.floor(math.sqrt(e)))
for i in range(ss, ee + 1):
if ... |
input_count = int(raw_input())
for i in xrange(input_count):
values = [int(value) for value in raw_input().split(" ")]
count = 0
for a in xrange(values[0]):
for b in xrange(values[1]):
if a & b < values[2]:
count += 1
print "Case #" + str(i + 1) + ": " + str(count)
|
import sys
def main():
name, pathin, pathout = sys.argv
filein = open(pathin)
fileout = open(pathout,'w')
fileout.write('Case #1:\n')
total = int(filein.readline())
results = []
for case in range(total):
N, J = [int(_) for _ in filein.readline().split()]
g = generate(N-2)
for i in range(J):
... |
import math
import itertools
from fractions import Fraction
class Hiker:
def __init__(self, start, speed):
self.start = start
self.speed = speed
f = open("C-small-1-attempt1.in", "r")
tests = int(f.readline())
out = open("C-small.out", "w")
for t in range(tests):
n = int(f.readline())
hikers = []
for... |
#!/usr/bin/env python3
"""
Slides!
Code Jam 2016, Round 1C, Problem B
HOW TO USE:
#~: python b.py < input.in > output.out
"""
def slides(buildings, ways):
if ways > 2 ** (buildings - 2):
return None
middle_slides = ["".join(["0"] * (s + 1) + ["1"] * (buildings - s - 1))
for s in... |
#!/usr/bin/env python3
import sys
import math
import decimal
def give_up(A, B):
return B+2
def optimal_backspace(A, B, p):
wrong_cost = A+B+1+B+1
right_cost = A+B+1
p_total = decimal.Decimal(1)
min_cost = A+B+1
for prob in p:
expected = right_cost*p_total + wrong_cost*(1-p_total)
... |
cases = int(raw_input())
def isPrime(n):
#if n==2 or n==3: return True not possible for jamcoins
if n%2==0: return 2
#if n<2: return 2 not possible for jamcoins
for i in range(3,int(n**0.5)+1,2): # only odd numbers
if n%i==0:
return i
return -1
def isJamCoin(binaryCoin):
deviders = []
for i in ... |
t = int(input())
def addD(used, a):
if a == 0:
used.add(0)
while a > 0:
used.add(a % 10)
a //= 10
for curt in range(1, t + 1):
n = int(input())
if n == 0:
print("Case #%d: INSOMNIA" % curt)
else:
used = set()
nn = n
... |
from math import *
def read_line():
return raw_input().strip()
def read_words():
return read_line().split()
def read_integer():
return int( read_line() )
def read_integers():
return [ int( x ) for x in read_words() ]
def build( number, length, position ):
global count
for di... |
#!/usr/bin/env python
dictionary = {}
def init():
input = []
output = []
input.append('ejp mysljylc kd kxveddknmc re jsicpdrysizq')
input.append('rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd')
input.append('de kr kd eoya kw aej tysr re ujdr lkgc jv')
output.append('our language is impossible t... |
import math
def pal(num):
for i in range(len(num)/2 + 1):
if num[i] != num[-(i+1)]:
return False
return True
def fair_and_square(num):
if not pal(num):
#print "Not pal"
return False
sqrt_root = math.sqrt(int(num))
if (sqrt_root - int(sqrt_root)) != 0:
#print "not a square"
return False
if not pal(s... |
import operator
def fonction(s):
a = "ejp mysljylc kd kxveddknmc re jsicpdrysi"
b = "rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd"
c = "de kr kd eoya kw aej tysr re ujdr lkgc jv"
aa = "our language is impossible to understand"
bb = "there are twenty six factorial possibilities"
cc = "so it is okay if you want to... |
def enlarge(list_of_circles):
if len(list_of_circles) == 0:
return 0
maxx = len(list_of_circles[0])
for circle in list_of_circles:
for other_circle in list_of_circles:
if circle[-1] == other_circle[-2] and circle[-2] == other_circle[-1]:
new_l = len(set(circle+oth... |
testCaseIndex = 0
def generateBoard(R, C):
datas = []
for rn in range(R):
datas.append([])
for cn in range(C):
datas[rn].append(0)
return datas
def printBoard(datas):
for rn in range(len(datas)):
for cn in range(len(datas[rn])):
print data... |
#!/usr/bin/env python3
import sys
def read_input():
words = []
with open(sys.argv[1]) as input_file:
total = int(input_file.readline().strip())
for l in input_file.readlines():
word, n = l.strip().split()
words.append((word, int(n)))
assert(len(words) =... |
__author__ = 'caseyvu'
import sys, math
def readInput(fileName):
global inputData
inputFile = open(fileName)
inputFile.readline() # number of test cases
dataLine = False
for line in inputFile:
if dataLine:
dataLine = False
inputData.append([int(n) for n in line.st... |
import sys
def canFill(x, r, c):
if x>=7:
return False # Richard picks a nasty shape with a hole
if r*c % x != 0:
return False # Obvious
if r<x and c<x:
return False # Richard picks the 1*x shape
if min(r,c) < (x+1)/2:
return False # Richard picks a shape who... |
# -*- coding: utf-8 -*-
#
# Copyright 2013 Eric Shtivelberg
#
import sys
practice = False
problem = 'C-small-attempt0'
lines = '''3
4
HYDROCARBON COMBUSTION
QUAIL BEHAVIOR
QUAIL COMBUSTION
HYDROCARBON QUAIL
3
CODE JAM
SPACE JAM
PEARL JAM
2
INTERGALACTIC PLANETARY
PLANETARY INTERGALACTIC'''.sp... |
import sys
import math
file = sys.stdin
def getInt():
return (file.readline())
def getInts():
vals = list()
for s in file.readline().split():
vals.append(s)
return vals
cases = int(getInt())
for i in range(cases):
numbers = getInts()
k = int(numbers[0])
c = int(numbers[1])
s = ... |
#!/usr/bin/env python3
# Google Code Jam
# Qualification Round 2016
# Problem D. Fractiles
# Solution in Python by Smithers
def tileindex(k, c, s, i):
n = 1
for j in range(c):
n += (i + j * s if i + j * s < k else 0) * (k ** j)
return n
def solve(k, c, s):
if s * c < k:
return 'IMPOSS... |
# Written for Python 2.7.9
from optparse import OptionParser
from StringIO import StringIO
import sys
# Expected format of TEST_CASES is a list of tuples of (input, expected_output)
TEST_CASES = [("""5
2 2 2
2 1 3
4 4 1
3 2 3
4 4 3
""","""Case #1: GABRIEL
Case #2: RICHARD
Case #3: RICHARD
Case #4: GABRIEL
Case #5: GA... |
num = input()
for i in range(num):
numbers = set()
n = input()
ans = "INSOMNIA"
if n != 0:
new_n = n
count = 1
while True:
temp = new_n
while True:
numbers.add(temp % 10)
temp /= 10
if temp == 0:
... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
import sys
fh = sys.stdin
case_num = int(fh.readline())
def flip_one(ss, target):
idx = len(ss) - 1
while idx >=0 and ss[idx] == target:
idx -= 1
return idx
def flip(ss):
target = '+'
res = 0
while True:
idx = flip_one... |
#!/usr/bin/python
import sys
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 answer
def... |
#!/usr/bin/python
"""
Diamond Inheritance problem solution
(GCJ 2012, Round 1C)
Author: a5kin
"""
import sys
# open input file
if len(sys.argv) == 2 and sys.argv[1] != '--help':
in_file = open(sys.argv[1])
else:
print "Usage: diamond_inheritance.py <input file>"
sys.exit(0)
# get number of cases
T = int... |
T = int(input())
for i in range(1, T+1):
line = input().split(' ')
K = int(line[0])
C = int(line[1])
S = int(line[2])
print("Case #"+str(i) + ":", end = '')
for j in range(1, S+1):
print(' ' + str(j), end = '')
print()
|
numLines = raw_input()
for case in range(1, int(numLines) + 1):
fraction = raw_input()
numerator, denominator = fraction.split("/")
numerator, denominator = int(numerator), int(denominator)
currentTry = 1
generations = 0
while True:
newNumerator = denominator / currentTry
... |
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import sys
import math
with open(sys.argv[1], 'r') as f:
for k in range(int(f.readline())):
N = int(f.readline())
if N == 0:
print("Case #"+str(k+1)+": INSOMNIA")
else:
present = [False for i in range(10)]
ac... |
import math
import collections
HAPPY_PANCAKE = '+'
UNHAPPY_PANCAKE = '-'
# pancake_min_flips = None
# pancake_map = {} # {pancake: {value: value, parents}}
pancake_value_map = {} #{pancake: steps to final}
pancake_parent_map = {} #{pancake: [parent1, parent2]}
super_parent = ""
def all_happy(pancakes):
return (UNHA... |
import fileinput
import logging
logging.basicConfig(level=logging.DEBUG)
def find_answer(n):
''' Find the answer for this question '''
history = set()
digits = set()
all_digits = set(xrange(0, 10))
cur_n = n
while digits != all_digits:
if cur_n in history:
return 'INSOMNIA'
logging.debug(cur_... |
#!/usr/bin/python3
testsNb = int(input()) # Get input
for test in range(1, testsNb+1):
N = int(input())
if N != 0:
digits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
currentValue=N
while 0 in digits:
for char in str(currentValue):
digits[int(char)] = 1
curre... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from math import sqrt
import sys
def readint(): return int(raw_input())
def readfloat(): return float(raw_input())
def readarray(N, foo):
res = []
for _ in xrange(N):
res.append(foo())
return res
def readlinearray(foo):... |
#!/usr/bin/python3
from collections import defaultdict
from codejam import CodeJam
def docase(f):
n = int(f.readline())
groups = []
for i in range(2*n-1):
groups.append([int(_) for _ in f.readline().split()])
heights = defaultdict(int)
for group in groups:
for soldier in group:
... |
"ONE", "THREE"
1. for each Z in the string, output 1 zero. delete letters "ZERO" from initial string
2. for each G in the string, output 1 eight. delete "eight" from initial string
3. x - for 6
4. w - for 2
5. u - for 4
6. f - for 5
7. v - for 7
8. i - for 9
9. r - for 3
10. remaining letters - divide len()... |
#!/usr/bin/python
import sys
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 answer
f ... |
import sys
import math
class memoize(object):
"""A decorator that caused a function to cache its result to avoid repeated
computation.
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
try:
return self.cache[args]
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not graph.has_key(start):
return []
paths = []
for node in graph[start]:
if node not in path:
n... |
# 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.
# Returns a positive value, if OAB makes a counter-clockwise turn,
# negative for clockwise turn, and zero if the points are collinear.
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def co... |
# Written in Python 3.3
import math
import sys
def findsol(F,D,N,L):
# Define each of the switches
S = []
for i in range(L):
S.append(0)
# Set the first device in each of the ports in turn, and
# determine the required switching
minswitch = L+1
for i in range(N... |
import sys
from time import time as ti
import numpy as np
def step(li,n):
# a string of 1s and 0s of length (N-2) in this problem
li = list(li)
if '0' not in li:
return(-1)
elif li[len(li)-1] == '1':
return step("".join(li[0:(len(li)-1)]),n)
elif li[len(li)-1] == '0':
li[len(li)... |
import sys
mapping = {32: ' ', 97: 'y', 98: 'h', 99: 'e', 100: 's', 101: 'o', 102: 'c', 103: 'v', 104: 'x', 105: 'd', 106: 'u', 107: 'i', 108: 'g', 109: 'l', 110: 'b', 111: 'k', 112: 'r', 113: 'z', 114: 't', 115: 'n', 116: 'w', 117: 'j', 118: 'p', 119: 'f', 120: 'm', 121: 'a', 122: 'q'}
def speaking_in_tongues(ar... |
#!/usr/bin/python
import sys
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 answer
f ... |
t = int(input())
for i in range(1, t + 1):
output = ''
input_string = input().split(" ")
line = [0]* int(input_string[0])
matrix_a = []
for z in range(0, len(line) + 1):
next_row = list(line)
matrix_a.append(next_row)
for j in range(0, int(input_string[0])):
for z in ran... |
from math import sqrt
def isprime(num):
if num==1:
return False
if num%2==0:
return 2
for i in range(3,int(sqrt(num))+1,2):
if num%i==0:
return i
return True
def gencoin(l):
if l==1:
return '1'
s='1'
for i in range(0,l-2):
s+='0'
s+='1'
return s
t=int(input(''))
n=input('')
j=int(n[n.index(' ')... |
import sys
import math
primesSample = [2, 3, 5, 7, 11, 13, 17, 19]
def isPrimeSlow(number):
if number == 2:
return True
elif number < 2 or number % 2 == 0:
return False
limit = int(math.sqrt(number)) + 1
for div in range(2, limit):
if number % div == 0:
return False... |
#!/usr/bin/python3
import sys
def main():
with open(sys.argv[1]) as input_file:
content = [line.strip('\n') for line in input_file.readlines()]
case_count = int(content[0])
with open('output', 'w') as output_file:
for case_number in range(1, case_count + 1):
party_count = co... |
#!/usr/bin/python3
from random import randint
def rabbin_miller_test(n, a):
s = n - 1
while (s & 1) == 0:
s >>= 1
tr = False
k = pow(a, s, n)
while s < n - 1:
if k != 1 and k != n - 1:
tr = True
elif k == 1:
if tr:
return False
... |
from math import floor
from math import ceil
def is_palin(number):
"""Returns True if number is a palindrome. Else returns False."""
if number % 10 == 0:
return False
temp = str(number)
return temp == temp[::-1]
def fairsquare(A,B):
"""Returns a list of fair and square... |
#!/usr/bin/python
def findForInt(integer, A, B):
n = int(integer)
length = len(integer)
count = 0
seen = []
for i in range(1, length):
m = int(integer[i:] + integer[0:i])
if A <= n and n < m and m <= B:
if m in seen:
continue
seen.append(m)
count += 1
return count
def f... |
import re
library = {} # False means prime, otherwise it maps numbers to divisors
primes = []
def getDivisor(n):
if (n in library):
return library[n]
test = 0
while (test < len(primes) and primes[test] < n ** (0.5)):
if (n % primes[test] == 0):
library[n] = primes[test]
return pr... |
def get_longest_loop(friends):
friends = [int(x) for x in friends]
pairs = set()
max_for_pairs = dict()
max_loop_size = 0
for person in range(len(friends)):
person += 1
in_loop = True
current_loop = {}
while in_loop:
if person in current_loop:
... |
__author__ = 'Ben'
from string import Template
def main():
number_of_instances = int(input())
result = ""
result_line = Template('Case #$n: $res\n')
for instance in range(1, number_of_instances + 1):
row1 = int(input())
for r1 in range(1, 5):
temp = input()
... |
infile = "1Asmall.txt"
"""
Area of a ring with inner radius r cm is:
pi((r+1)^2) - pi(r^2)
= pi(r^2 + 2r + 1) - pi(r^2)
= pi(2r + 1)
Area for n rings is:
= area(r) + area(r+2) + area(r+4)... + area(r + 2n - 2)
= pi(2r + 1) + pi(2r + 5) + pi(2r + 9)... + pi(2r + 4n - 3)
= pi(2rn) + 1pi + 5pi + 9pi... + (4... |
#!/usr/bin/python3
import math
import sys
from heapq import heappush, heappop
import math
X =0
Y = 0
class point():
def __init__(self, x, y, parent, dest,i):
self.x = x
self.y = y
self.parent = parent
self.dest = dest
self.i = i
global X,Y
self.dist = math... |
import re
# 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):
n = [s for s in input()] # read a list of integers, 2 in this case
index ... |
#!/usr/bin/env python
import sys, math
DIGITS = 14
def num_digits(n):
return int(math.log10(n)) + 1
def is_palindrome(n):
s = str(n)
for l in xrange(len(s)):
r = len(s) - (1 + l)
if s[l] != s[r]:
return False
return True
def main(argv=None):
if argv is None:
argv = sys.argv
# Pre-build the list of ... |
#coding=UTF-8
__author__ = 'jesus'
FILE = 'r1-a.in'
FILEOUT = 'r1-a.out'
f = open(FILE, 'r')
fout = open (FILEOUT, 'w')
def evaluar (numcadenas, letras, ocurrencias):
for i in range (numcadenas-1):
if len(letras[i])!=len(letras[i+1]):
return 'Fegla Won'
numletras = len(letras... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.