inputs
stringlengths
175
2.22k
targets
stringlengths
10
2.05k
language
stringclasses
1 value
split
stringclasses
2 values
template
stringclasses
2 values
dataset
stringclasses
1 value
config
stringclasses
1 value
Solve in Python: You play your favourite game yet another time. You chose the character you didn't play before. It has $str$ points of strength and $int$ points of intelligence. Also, at start, the character has $exp$ free experience points you can invest either in strength or in intelligence (by investing one point yo...
T = int(input()) for i in range(T): s, k, f = map(int, input().split()) print(min(f + 1, max(0, (s + f - k + 1) // 2)))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/factorial-trailing-zeroes/: Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solut...
class Solution: def trailingZeroes(self, n): """ :type n: int :rtype: int """ c=0 while n>0: n//=5 c+=n return c
python
train
abovesol
codeparrot/apps
all
Solve in Python: Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not. Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the ...
x, y, m = list(map(int, input().split())) if max(x, y) >= m: print(0) elif m < 0 or max(x, y) <= 0: print(-1) else: if x + y < 0: cnt = (max(x, y) - min(x, y)) // max(x, y) x, y = min(x, y) + max(x, y) * cnt, max(x, y) else: cnt = 0 while max(x, y) < m: x, y = max(x, ...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1062/B: JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer $n$, you can perform the following operations zero or more times: mul $x$: multip...
n = int(input()) fac = {} nn = n maxe = 1 while nn%2 == 0: fac[2] = fac.get(2, 0) + 1 nn >>= 1 for i in range(3, nn+1, 2): if i*i > nn: break while nn%i == 0: fac[i] = fac.get(i, 0) + 1 nn //= i if nn > 1: fac[nn] = 1 # print(nn) # print(fac) maxe = 1 mine = n prod = 1 for f...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1183/A: Polycarp knows that if the sum of the digits of a number is divisible by $3$, then the number itself is divisible by $3$. He assumes that the numbers, the sum of the digits of which is divisible by $4$, are also somewhat interesting. Th...
n = int(input()) def s(n): k = 0 for i in str(n): k += int(i) return k while s(n) % 4 != 0: n += 1 print(n)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/NEWB2020/problems/CNFCT: Oliver and Nova are true lovers. Inspite of knowing that Nova will die Oliver married her at the lake where they met. But they had a conflict about even and odd numbers. Nova likes the odd numbers and Oliver prefers even. One day they w...
import math def lcm(a, b): return (a*b)//gcd(a, b) def gcd(a, b): if b == 0: return a return gcd(b, a%b) for _ in range(int(input())): n = int(input()) na = math.ceil((2*n)/math.acos(-1)) nb = ((n+1)//2)**2 nlcm = lcm(na, nb) oa = math.ceil(n/2) ob = (n//2)*(n//...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/MAXSC: You are given N integer sequences A1, A2, ..., AN. Each of these sequences contains N elements. You should pick N elements, one from each sequence; let's denote the element picked from sequence Ai by Ei. For each i (2 ≤ i ≤ N), Ei should be stri...
# cook your dish here t=int(input()) for cases in range(t): n=int(input()) lis=[] for i in range(n): lis1=sorted(list(map(int,input().split()))) lis.append(lis1) summ=lis[-1][-1] maxx=summ c=1 for i in range(n-2,-1,-1): for j in range(n-1,-1,-1): if lis[i][j]<maxx: maxx=lis[i][j] c+=1 summ+=...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible. Omkar currently has $n$ supports arranged in a line, the $i$-th of which has height $a_i$. Omkar wants to build his waterslide from the right to the left, so his supports must...
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ans=0 for i in range(1,n): if a[i]<a[i-1]: ans+=a[i-1]-a[i] print(ans)
python
test
qsol
codeparrot/apps
all
Solve in Python: The chef was busy in solving algebra, he found some interesting results, that there are many numbers which can be formed by sum of some numbers which are prime. Chef wrote those numbers in dairy. Cheffina came and saw what the chef was doing. Cheffina immediately closed chef's dairy and for testing che...
from math import sqrt def isprime(n): if (n % 2 == 0 and n > 2) or n == 1: return 0 else: s = int(sqrt(n)) + 1 for i in range(3, s, 2): if n % i == 0: return 0 return 1 def find(N, K): if (N < 2 * K): return 0 if (K == 1): return i...
python
train
qsol
codeparrot/apps
all
Solve in Python: # Task A noob programmer was given two simple tasks: sum and sort the elements of the given array `arr` = [a1, a2, ..., an]. He started with summing and did it easily, but decided to store the sum he found in some random position of the original array which was a bad idea. Now he needs to cope wit...
def shuffled_array(a): a.remove(sum(a) / 2) return sorted(a)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/valid-anagram/: Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Note: You may assume the string con...
class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s)!=len(t): return False ssort=sorted(list(s)) tsort=sorted(list(t)) return ssort==tsort
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/702/A: You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array. A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each e...
n=int(input()) l=input().split() best=1 curr=1 for i in range (n-1): if int(l[i])<int(l[i+1]): curr+=1 else: curr=1 best=max(best,curr) print (best)
python
test
abovesol
codeparrot/apps
all
Solve in Python: PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall re...
def __starting_point(): n,k = list(map(int, input().strip().split())) if k > n//2: k = n - k intersection = n * [0] count = 1 done = False i=0 result = [] for i in range(1,n+1): nn = (i*k) // n j = (i*k)%n if j < k: count += (2*nn ) ...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/875/A: Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is t...
n=int(input()) m=[] if n<=18: a=0 else: a=n-len(str(n))*9 for i in range(a,n): x=i for j in str(i): x+=int(j) if n==x: m.append(i) print(len(m)) [print(i) for i in m]
python
train
abovesol
codeparrot/apps
all
Solve in Python: Let's call an array $t$ dominated by value $v$ in the next situation. At first, array $t$ should have at least $2$ elements. Now, let's calculate number of occurrences of each number $num$ in $t$ and define it as $occ(num)$. Then $t$ is dominated (by $v$) if (and only if) $occ(v) > occ(v')$ for any ot...
import sys T = int(sys.stdin.readline()) for i in range(T): n = int(sys.stdin.readline()) array = sys.stdin.readline().split(" ") lastSeen = [-10**6 for i in range(n + 1)] best = 10**6 for j in range(len(array)): if j - lastSeen[int(array[j])] < best: best = j - lastSeen[int(array[j])] lastSeen[int(array[j]...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1081/A: Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games. He came up with the following game. The player has a positive integer $n$. In...
n = int(input()) if n == 2: print(2) else: print(1)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/550cc572b9e7b563be00054f: Scheduling is how the processor decides which jobs(processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One ...
def SJF(jobs, index): return sum(n for i, n in enumerate(jobs) if n < jobs[index] + (i <= index))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1152/D: Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys... It took Ne...
ans = [...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5a53a17bfd56cb9c14000003: # Definition **_Disarium number_** is the number that *The sum of its digits powered with their respective positions is equal to the number itself*. ____ # Task **_Given_** a number, **_Find if it is Disarium or not_** . ____...
def disarium_number(number): newNumber = 0 for index, value in enumerate(str(number)): newNumber += int(value)**(int(index)+1) if newNumber == number: return "Disarium !!" return "Not !!"
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5c46ea433dd41b19af1ca3b3: ### Description As hex values can include letters `A` through to `F`, certain English words can be spelled out, such as `CAFE`, `BEEF`, or `FACADE`. This vocabulary can be extended by using numbers to represent other letters, such...
def hex_word_sum(string): string = string.upper().replace('S', '5') string = string.replace('O', '0') sum = 0 for word in string.split(' '): try: sum += int(word.strip(), 16) except: pass return sum
python
train
abovesol
codeparrot/apps
all
Solve in Python: You are given three positive integers $n$, $a$ and $b$. You have to construct a string $s$ of length $n$ consisting of lowercase Latin letters such that each substring of length $a$ has exactly $b$ distinct letters. It is guaranteed that the answer exists. You have to answer $t$ independent test cases...
t = int(input('')) c = [] for i in range(97,123,1): c.append(chr(i)) for _ in range(t): n,a,b = list(map(int,input('').split(' '))) s = '' for i in range(n): s = s+c[i%b] print(s)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1313/B: Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $n$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds...
t = int(input()) for _ in range(t): n, x, y = [int(item) for item in input().split()] total = x + y maximum = min(x + y - 1, n) minimum = min(n - min((2 * n - total), n) + 1, n) print(minimum, maximum)
python
test
abovesol
codeparrot/apps
all
Solve in Python: Mike and Joe are fratboys that love beer and games that involve drinking. They play the following game: Mike chugs one beer, then Joe chugs 2 beers, then Mike chugs 3 beers, then Joe chugs 4 beers, and so on. Once someone can't drink what he is supposed to drink, he loses. Mike can chug at most A beer...
def game(a, b): if a * b: c = int(a ** 0.5) return ('Mike', 'Joe')[c * (c + 1) <= b] return "Non-drinkers can't play"
python
train
qsol
codeparrot/apps
all
Solve in Python: Consider the sequence `a(1) = 7, a(n) = a(n-1) + gcd(n, a(n-1)) for n >= 2`: `7, 8, 9, 10, 15, 18, 19, 20, 21, 22, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 69, 72, 73...`. Let us take the differences between successive elements of the sequence and get a second sequence `g: 1, 1, 1, 5, 3, 1, 1...
def count_ones(n): a, ones = 7, 1 for i in range(2, n+1): b = a + gcd(i, a) if b == a + 1: ones += 1 a = b return ones def max_pn(n): a, p, i = 7, {1}, 1 while len(p) < n + 1: i += 1 b = a + gcd(i, a) p.add(b - a) a = b return max(p)...
python
train
qsol
codeparrot/apps
all
Solve in Python: A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: * 232 * 110011 * 54322345 Complete the function to test if the given number (`num`) **can be rearranged** to form a numerical palindrome or not. Re...
def palindrome(num): s = str(num) return "Not valid" if not isinstance(num, int) or num < 0 \ else num > 10 and sum(s.count(d) % 2 > 0 for d in set(s)) < 2
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1183/E: The only difference between the easy and the hard versions is constraints. A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters...
import sys input = sys.stdin.readline n,W=list(map(int,input().split())) s=input().strip() NEXTLIST=[[n]*26 for i in range(n+1)] for i in range(n-1,-1,-1): for j in range(26): NEXTLIST[i][j]=NEXTLIST[i+1][j] NEXTLIST[i][ord(s[i])-97]=i DP=[[0]*(n+1) for i in range(n+1)] DP[0][0]=1 for i in range(n...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day. Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule ...
from heapq import heappush,heappop,heapify n,k=list(map(int,input().split())) *l,=list(map(int,input().split())) q=[(-l[i],i)for i in range(k)] heapify(q) a=[0]*n s=0 for i in range(k,n) : heappush(q,(-l[i],i)) x,j=heappop(q) s-=x*(i-j) a[j]=i+1 for i in range(n,n+k) : x,j=heappop(q) s-=x*(i-j) ...
python
train
qsol
codeparrot/apps
all
Solve in Python: You are given an array A of strings. A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S. Two strings S and T are special-equivalent if after any number of moves onto S, S == T. For example, S = "zzxy" and T = "xyzz" are special-equivalent bec...
class Solution: def numSpecialEquivGroups(self, A: List[str]) -> int: # set1 = set() even_set = [] odd_set = [] for i in A: even = [] odd = [] for j in range(len(i)): if j %2 == 0: even.append(i[j]) ...
python
train
qsol
codeparrot/apps
all
Solve in Python: Mobile Display Keystrokes Do you remember the old mobile display keyboards? Do you also remember how inconvenient it was to write on it? Well, here you have to calculate how much keystrokes you have to do for a specific word. This is the layout: Return the amount of keystrokes of input str (! only...
def mobile_keyboard(s): a = "12abc3def4ghi5jkl6mno7pqrs8tuv9wxyz*0#" b = "11234123412341234123412345123412345111" d = {x: int(y) for x, y in zip(a, b)} return sum(d[x] for x in s)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1417/B: RedDreamer has an array $a$ consisting of $n$ non-negative integers, and an unlucky integer $T$. Let's denote the misfortune of array $b$ having length $m$ as $f(b)$ — the number of pairs of integers $(i, j)$ such that $1 \le i < j \le...
import sys import math input = sys.stdin.readline t = int(input()) for _ in range(t): n,k = list(map(int, input().split())) arr = list(map(int, input().split())) alt = 0 ans = [] for i in range(len(arr)): if k%2==1: if arr[i] < k/2: ans.append(0) ...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/57f4ccf0ab9a91c3d5000054: Lot of junior developer can be stuck when they need to change the access permission to a file or a directory in an Unix-like operating systems. To do that they can use the `chmod` command and with some magic trick they can change...
def chmod_calculator(perm): return str(sum([wbin(perm[k]) * {"user":100, "group":10, "other":1}[k] for k in perm])).zfill(3) def wbin(w): return int(w.translate(str.maketrans('rwx-', '1110')), 2)
python
train
abovesol
codeparrot/apps
all
Solve in Python: One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal $s$ towards a faraway galaxy. Recently they've received a response $t$ which they believe to be a response from aliens! The scientists now want to check if the signal $t$ is similar to $s$. The o...
import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def add(a,b): return (a+b)%1000000007 def sub(a,b): return (a+1000000007-b)%1000000007 def mul(a,b): return (a*b)%1000000007 p = 102367 s = list(map(int,...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/979/C: Kuro is living in a country called Uberland, consisting of $n$ towns, numbered from $1$ to $n$, and $n - 1$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $a$ an...
from collections import defaultdict n,x,y = list(map(int,input().split())) graph = defaultdict(list) vis = [False for i in range(n+1)] mat = [False for i in range(n+1)] subtree = [0 for i in range(n+1)] for i in range(n-1): u,v = list(map(int,input().split())) graph[u].append(v) graph[v].append(u) q = [] cur = 0 f...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Vasya has a sequence $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number $6$ $(\dots 00000000110_2)$ into $3$ $(\dots 0000000...
#!/usr/bin/env python3 import sys def rint(): return list(map(int, sys.stdin.readline().split())) #lines = stdin.readlines() def get_num1(i): cnt = 0 while i: if i%2: cnt +=1 i //=2 return cnt n = int(input()) a = list(rint()) b = [get_num1(aa) for aa in a] ans = 0 #S0[...
python
test
qsol
codeparrot/apps
all
Solve in Python: You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table abcd edfg hijk   we obtain t...
import sys n, m = [int(i) for i in input().split()] a = [[0] * n for i in range(m)] for i in range(n): temp = input() for j in range(m): a[j][i] = temp[j] c = 0 def blatant(a): for i in range(1,len(a)): if a[i] < a[i-1]: return True return False match = [] while True: ...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1328/F: You are given the array $a$ consisting of $n$ elements and the integer $k \le n$. You want to obtain at least $k$ equal elements in the array $a$. In one move, you can make one of the following two operations: Take one of the minimu...
#!usr/bin/env python3 from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Let's denote a function $d(x, y) = \left\{\begin{array}{ll}{y - x,} & {\text{if}|x - y|> 1} \\{0,} & {\text{if}|x - y|\leq 1} \end{array} \right.$ You are given an array a consisting of n integers. You have to calculate the sum of d(a_{i}, a_{j}) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n. ----...
N = 2 * 10**5 + 3 n = int(input()) A, cnt = list(map(int,input().split(' '))), {} s, a = 0, 0 for i in range(n-1,-1,-1): a += s if (A[i]-1) in cnt: a += cnt[A[i]-1] if (A[i]+1) in cnt: a -= cnt[A[i]+1] a -= (n-(i+1))*A[i] s += A[i] if A[i] not in cnt: cnt[A[i]]=0 cn...
python
test
qsol
codeparrot/apps
all
Solve in Python: *** No Loops Allowed *** You will be given an array (a) and a value (x). All you need to do is check whether the provided array contains the value, without using a loop. Array can contain numbers or strings. X can be either. Return true if the array contains the value, false if not. With strings you ...
def check(a, x): test = a.count(x) if test >= 1: return True else: return False
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/327/A: Iahub got bored, so he invented a game to be played on paper. He writes n integers a_1, a_2, ..., a_{n}. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) a...
n = int(input()) I = list(map(int, input().split())) d = [] for val in I: d.append(val) res = 0; for i in range (0, n): for j in range (i, n): cnt = 0; for k in range (0, n): if k >= i and k <= j: cnt = cnt + 1 - d[k]; else: cnt = cnt + d[k...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least $3$ (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself $k$-multihedgehog. Let us define $...
n,k = list(map(int,input().split(" "))) degrees = [0] * n neighbors = [list() for x in range(n)] for i in range(n-1): first,second = list(map(int,input().split(" "))) degrees[first-1] += 1 degrees[second-1] += 1 neighbors[first-1] += [second] neighbors[second-1] += [first] # start at a leaf curr = 0 for i in rang...
python
test
qsol
codeparrot/apps
all
Solve in Python: On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove a...
(n, m), f, s = list(map(int, input().split())), [int(x) for x in input().split()], 0 for i in range(m): (a, b) = list(map(int, input().split())) s = s + min(f[a - 1], f[b - 1]) print( s )
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/559e5b717dd758a3eb00005a: DropCaps means that the first letter of the starting word of the paragraph should be in caps and the remaining lowercase, just like you see in the newspaper. But for a change, let's do that for each and every word of the given S...
import re def drop_cap(s): return re.sub(r'\S{3,}', lambda m: m.group(0).title(), s)
python
train
abovesol
codeparrot/apps
all
Solve in Python: #It's show time! Archers have gathered from all around the world to participate in the Arrow Function Faire. But the faire will only start if there are archers signed and if they all have enough arrows in their quivers - at least 5 is the requirement! Are all the archers ready? #Reference https://deve...
def archers_ready(archers): if not archers: return False for arrows in archers: if arrows < 5: return False return True
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5750699bcac40b3ed80001ca: It is 2050 and romance has long gone, relationships exist solely for practicality. MatchMyHusband is a website that matches busy working women with perfect house husbands. You have been employed by MatchMyHusband to write a funct...
def match(a, n): return "Match!" if sum(a) >= 100 * 0.85**n else "No match!"
python
train
abovesol
codeparrot/apps
all
Solve in Python: Complete the function which returns the weekday according to the input number: * `1` returns `"Sunday"` * `2` returns `"Monday"` * `3` returns `"Tuesday"` * `4` returns `"Wednesday"` * `5` returns `"Thursday"` * `6` returns `"Friday"` * `7` returns `"Saturday"` * Otherwise returns `"Wrong, please ente...
def whatday(num): dict={ 2:"Monday", 3:"Tuesday", 4:"Wednesday", 5:"Thursday", 6:"Friday", 7:"Saturday", 1:"Sunday" } return dict.get(num,'Wrong, please enter a number between 1 and 7')
python
train
qsol
codeparrot/apps
all
Solve in Python: Bizon the Champion isn't just attentive, he also is very hardworking. Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right ...
import sys oo=1000000000000 ar=[] def solve(l, r, val): if(r<l): return 0 indx=l+ar[l:r+1].index(min(ar[l:r+1])) tot=r-l+1 cur=ar[indx]-val+solve(l, indx-1, ar[indx])+solve(indx+1, r, ar[indx]) return min(tot, cur) sys.setrecursionlimit(10000) n=int(input()) ar=list(map(int, input().split())) print(solve(0, n-1, 0...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/APRIL14/problems/BINTREE: Consider an infinite full binary tree (each node has two children except the leaf nodes) defined as follows. For a node labelled v its left child will be labelled 2*v and its right child will be labelled 2*v+1. The root is labelled as ...
import math import sys import time def getLevel(number): _level = math.floor(math.log(number,2)) return int(_level) def isPair(number): return (number%2 == 0) def getInterval(a,b, max): _max = max _loop = -1 _apart = 0 while (_apart == 0) and (_max != 1): _loop += 1 _max = _max >> 1 if (a < _max) an...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1105/A: Salem gave you $n$ sticks with integer positive lengths $a_1, a_2, \ldots, a_n$. For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's l...
n = int(input()) arr = list(map(int, input().split())) arr.sort() a = [] for t in range(1, 101): tot = 0 for item in arr: if (abs(item - t) >= 1): tot += abs(item - t) - 1 a.append((tot, t)) a.sort() print(a[0][1], a[0][0])
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are given a set $S$ and $Q$ queries. Initially, $S$ is empty. In each query: - You are given a positive integer $X$. - You should insert $X$ into $S$. - For each $y \in S$ before this query such that $y \neq X$, you should also insert $y \oplus X$ into $S$ ($\oplus$ denotes the XOR operation). - Th...
import collections def bits(x): return bin(x).count('1') t=int(input()) for _ in range(t): q=int(input()) s=[] d=collections.defaultdict(lambda:-1) e=0 o=0 p=-1 for i in range(q): x=int(input()) # print(d) if d[x]!=-1: print(e,o) continue s.append(x) d[x]=1 #z=len(s) for j in s: if j!=x: ...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/IGNS2012/problems/IG04: In a fictitious city of CODASLAM there were many skyscrapers. The mayor of the city decided to make the city beautiful and for this he decided to arrange the skyscrapers in descending order of their height, and the order must be strictly...
import sys num=int(sys.stdin.readline()) s=sys.stdin.readline().split() sky=list(map(int,s)) sky.reverse() cuts=0 change=0 t=False i=1 while i<len(sky): if sky[i]<=sky[i-1]: for j in range(i-1,-1,-1): if sky[j]<=sky[i]-(i-j): break else: change+=sky[j]-(sky[i]-(i-j)) if change>=sky[i]: ...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1205/A: You are given integer $n$. You have to arrange numbers from $1$ to $2n$, using each of them exactly once, on the circle, so that the following condition would be satisfied: For every $n$ consecutive numbers on the circle write their su...
# 1205A Almost Equal n = int(input()) if n % 2 == 0: print("NO") else: print("YES") d = 1 for i in range(n): print(d, end=' ') d += 3 if i % 2 == 0 else 1 d = 2 for i in range(n): print(d, end=' ') d += 1 if i % 2 == 0 else 3
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc077/tasks/abc077_a: You are given a grid with 2 rows and 3 columns of squares. The color of the square at the i-th row and j-th column is represented by the character C_{ij}. Write a program that prints YES if this grid remains the same when rotated 180 d...
c1 = input() c2 = input() print("YES" if c1 == c2[::-1] else "NO")
python
test
abovesol
codeparrot/apps
all
Solve in Python: Chef bought a huge (effectively infinite) planar island and built $N$ restaurants (numbered $1$ through $N$) on it. For each valid $i$, the Cartesian coordinates of restaurant $i$ are $(X_i, Y_i)$. Now, Chef wants to build $N-1$ straight narrow roads (line segments) on the island. The roads may have ar...
t=int(input()) for i in range(t): n=int(input()) x=[] y=[] dx=[] dy=[] for j in range(n): c=list(map(int,input().split())) x.append(c[0]-c[1]) y.append(c[0]+c[1]) x.sort() y.sort() for j in range(1,n): dx.append(x[j]-x[j-1]) dy.append(y[j]-y[j-1]) a=min(dx) b=min(dy) print('{0:.6f}'.format(min(a,b...
python
train
qsol
codeparrot/apps
all
Solve in Python: *** No Loops Allowed *** You will be given an array (a) and a limit value (limit). You must check that all values in the array are below or equal to the limit value. If they are, return true. Else, return false. You can assume all values in the array are numbers. Do not use loops. Do not modify inpu...
small_enough = lambda a, x: False not in map(lambda i: i <= x, a)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/758/D: Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter A he will write the number...
n=int(input()) #print(n) d=input() l=len(d) dp=[[0,0] for i in range(0,l+1)] dp[l-1]=[ord(d[l-1])-ord('0'),1] for i in range(1,l): w=l-1-i; m=(ord(d[w])-ord('0'))*(n**i)+dp[w+1][0] dp[w]=[m,i+1]; if (d[w]=='0'): dp[w][0]=dp[w+1][0] dp[w][1]=dp[w+1][1]+1 continue for j in range(w,l): subs=int(d[w:j+1]) u=...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/526/C: A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his pla...
import sys f = sys.stdin C, Hr, Hb, Wr, Wb = map(int, f.readline().strip().split()) if Hr/Wr < Hb/Wb: Hr, Hb, Wr, Wb = Hb, Hr, Wb, Wr if (C % Wr) == 0 and (C // Wr) > 0: print((C // Wr)*Hr) elif (C // Wr) == 0: print((C // Wb)*Hb) else: nmax = (C // Wr) pmax = nmax*Hr + ((C - nmax*Wr) // W...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Ashish has an array $a$ of size $n$. A subsequence of $a$ is defined as a sequence that can be obtained from $a$ by deleting some elements (possibly none), without changing the order of the remaining elements. Consider a subsequence $s$ of $a$. He defines the cost of $s$ as the minimum between: The...
def check(num): count = 0 flag = -1 s = 0 for i in range(n): if a[i]<=num: count += 1 s += 1 else: if flag == -1: flag = s%2 count += 1 s += 1 else: if (s+1)%2!=flag: count += 1 s += 1 if count==k: return True return False n,k = map(int,input().split()) a = list(map(...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.hackerrank.com/challenges/word-order/problem: =====Problem Statement===== You are given n words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/o...
#!/usr/bin/env python3 from collections import OrderedDict def __starting_point(): num = int(input().strip()) history = OrderedDict() for _ in range(num): word = str(input().strip().split()) if word not in list(history.keys()): history[word] = 1 else: h...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length. A block with side a has volume a^3. A tower consisting of blocks with sides a_1, a_2, ..., a_{k} has the total volume...
def g(m, s, n): k = int(m ** (1 / 3)) if m == 0 or k == 1: return s + m, n + m x, y = k ** 3, (k - 1) ** 3 a = g(m - x, s + x, n + 1) b = g(x - y - 1, s + y, n + 1) return b if a[1] < b[1] else a s, n = g(int(input()), 0, 0) print(n, s)
python
test
qsol
codeparrot/apps
all
Solve in Python: Task ====== Make a custom esolang interpreter for the language [InfiniTick](https://esolangs.org/wiki/InfiniTick). InfiniTick is a descendant of [Tick](https://esolangs.org/wiki/tick) but also very different. Unlike Tick, InfiniTick has 8 commands instead of 4. It also runs infinitely, stopping the pr...
from collections import defaultdict from itertools import cycle def interpreter(tape): i, skip, D, res = 0, False, defaultdict(int), [] for c in cycle(tape): if skip: skip = False elif c == '>': i += 1 elif c == '<': i -= 1 elif c == '+': D[i] = (D[i] + 1)%256 elif c == ...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5a32526ae1ce0ec0f10000b2: Given an integer, take the (mean) average of each pair of consecutive digits. Repeat this process until you have a single integer, then return that integer. e.g. Note: if the average of two digits is not an integer, round the res...
import math def digits_average(input): m = str(input) for i in range(len(str(input))-1): m = ''.join(str(math.ceil(int(m[i])/2 + int(m[i+1])/2)) for i in range(len(m) - 1)) return int(m)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/641/D: Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them. Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each...
def tle(): k=0 while (k>=0): k+=1 def quad(a, b, c): disc = (b**2-4*a*c) if disc<0: disc=0 disc = (disc)**0.5 return ((-b+disc)/2/a, (-b-disc)/2/a) x = int(input()) y = list(map(float, input().strip().split(' '))) z = list(map(float, input().strip().split(' '))) p...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5ecc1d68c6029000017d8aaf: In this kata, your task is to find the maximum sum of any straight "beam" on a hexagonal grid, where its cell values are determined by a finite integer sequence seq. In this context, a beam is a linear sequence of cells in any of ...
from itertools import cycle def max_hexagon_beam(n: int,seq: tuple): l=n*2-1 #the number of rows of the hexagon ll =[l-abs(n-i-1) for i in range(l)] #the lengths of each row c=cycle(seq) hex = [[next(c) for i in range(j)] for j in ll] # the hexagon sums = [su...
python
train
abovesol
codeparrot/apps
all
Solve in Python: # Task IONU Satellite Imaging, Inc. records and stores very large images using run length encoding. You are to write a program that reads a compressed image, finds the edges in the image, as described below, and outputs another compressed image of the detected edges. A simple edge detection algorit...
from itertools import chain def parse_ascii(image_ascii): """ Parses the input string Returns a 3-tuple: - :width: - the width in pixels of the image - :height: - the height in pixels of the image - List of pairs (pixel_value, run_length) run_length is the number of succes...
python
train
qsol
codeparrot/apps
all
Solve in Python: Well, those numbers were right and we're going to feed their ego. Write a function, isNarcissistic, that takes in any amount of numbers and returns true if all the numbers are narcissistic. Return false for invalid arguments (numbers passed in as strings are ok). For more information about narcissist...
is_narcissistic=lambda*a:all(n.isdigit()and int(n)==sum(int(d)**len(n)for d in n)for n in map(str,a))
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1144/E: You are given two strings $s$ and $t$, both consisting of exactly $k$ lowercase Latin letters, $s$ is lexicographically less than $t$. Let's consider list of all strings consisting of exactly $k$ lowercase Latin letters, lexicographica...
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().s...
python
test
abovesol
codeparrot/apps
all
Solve in Python: In some other world, today is Christmas Eve. There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters. He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decora...
n,k = map(int,input().split()) s = [] for i in range(n): s.append(int(input())) s.sort() s.reverse() ans = s[0]-s[-1] for i in range(n-k+1): ans = min(ans,s[i]-s[i+k-1]) print(ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/maximum-width-of-binary-tree/: Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are nul...
class Solution: def widthOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 maxlen=1 start=1 end=1 tlen=1 l=[[root,1]] while tlen: llen=tlen ...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/621/B: Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right. Wet Shark thinks that two bi...
def nC2(n): return n * (n - 1) // 2 SIZE = 1000 N = int(input()) a = [[0] * SIZE for i in range(SIZE)] for i in range(N): x, y = map(int, input().split()) a[x-1][y-1] = 1 ans = 0 #1 for sx in range(SIZE): t_cnt = 0 x = sx; y = 0; while x >= 0: t_cnt += a[x][y] x -= 1; y ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. Example 1: Input: nums = [5,7,7,8,8,10], target ...
class Solution: def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ #m = int(len(nums)/2) #upper, lower = nums[:m], nums[m:] s, e = -1, -1 l, u = 0, len(nums)-1 if not nums o...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5ac69d572f317bdfc3000124: In mathematics, a **pandigital number** is a number that in a given base has among its significant digits each digit used in the base at least once. For example, 1234567890 is a pandigital number in base 10. For simplification, i...
from itertools import permutations as perms def is_pand(n): return len(set(list(str(n)))) == len(str(n)) def next_pan(n): while True: if is_pand(n):yield n n += 1 def get_sequence(n, k): if n < 1023456789: n = 1023456789 elif n >= 9999999999: return [] if not is_pand(n): n = next(...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Example 1: Input: 1->2->3->3->4->4->5 Output: 1->2->5 Example 2: Input: 1->1->1->2->3 Output: 2->3
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from collections import OrderedDict class Solution: def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ ...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/53c93982689f84e321000d62: ~~~if-not:java You have to code a function **getAllPrimeFactors** wich take an integer as parameter and return an array containing its prime decomposition by ascending factors, if a factors appears multiple time in the decompositi...
def getAllPrimeFactors(n): if n == 0: return [] elif n == 1: return [1] elif type(n) != int: return errora elif n < 0: return errora allfacts = [] current = 2 n_copy = n while current <= n: if n_copy % current == 0: allfacts.append(current) n_copy /= curre...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths. If it is impossible to form any triangle of non-zero area, return 0.   Example 1: Input: [2,1,2] Output: 5 Example 2: Input: [1,2,1] Output: 0 Example 3: Input: [3...
class Solution: def largestPerimeter(self, A: List[int]) -> int: if len(A)<3: return 0 A.sort(reverse=True) while len(A)>2: max_num = A.pop(0) if max_num >= A[0] + A[1]: continue else: return ma...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc086/tasks/abc086_a: AtCoDeer the deer found two positive integers, a and b. Determine whether the product of a and b is even or odd. -----Constraints----- - 1 ≤ a,b ≤ 10000 - a and b are integers. -----Input----- Input is given from Standard Input in ...
a,b=list(map(int,input().split())) if(a*b)%2==0: print('Even') else: print('Odd')
python
test
abovesol
codeparrot/apps
all
Solve in Python: An array is called `centered-N` if some `consecutive sequence` of elements of the array sum to `N` and this sequence is preceded and followed by the same number of elements. Example: ``` [3,2,10,4,1,6,9] is centered-15 because the sequence 10,4,1 sums to 15 and the sequence is preceded by two elemen...
def is_centered(arr,n): for i in range(len(arr)): for j in range(len(arr)+1): if j>i: if sum(arr[i:j]) == n and i == len(arr)-j: return True return True if n==0 and arr!=arr[::-1] else False
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5897cdc26551af891c000124: Hofstadter sequences are a family of related integer sequences, among which the first ones were described by an American professor Douglas Hofstadter in his book Gödel, Escher, Bach. ### Task Today we will be implementing the ra...
import sys; sys.setrecursionlimit(10000) from functools import lru_cache @lru_cache(maxsize=None) def Q(n): if n <= 2: return 1 return Q(n - Q(n-1)) + Q(n - Q(n-2)) def hofstadter_Q(n): return Q(n)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/PRFYIT: We say that a binary string (a string containing only characters '0' and '1') is pure if it does not contain either of the strings "0101" or "1010" as a subsequence. Recall that string T is a subsequence of string S if we can delete some of the...
for _ in range(int(input())): bi = input().strip() dp = [0 if i < 2 else len(bi) for i in range(6)] for c in bi: if c == '1': dp[3] = min(dp[3], dp[0]) dp[0] += 1 dp[5] = min(dp[5], dp[2]) dp[2] += 1 dp[4] += 1 else: dp[2] = min(dp[2], dp[1]) dp[1] += 1 dp[4] = min(dp[4], dp[3]) dp[3] ...
python
train
abovesol
codeparrot/apps
all
Solve in Python: We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s. We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen? -----Constraints----- - All values in input are integers. - 0...
A, B, C, K = list(map(int, input().split())) a, c = min(A, K), max(0, min(C, K - A - B)) print((a - c))
python
test
qsol
codeparrot/apps
all
Solve in Python: There are $n$ warriors in a row. The power of the $i$-th warrior is $a_i$. All powers are pairwise distinct. You have two types of spells which you may cast: Fireball: you spend $x$ mana and destroy exactly $k$ consecutive warriors; Berserk: you spend $y$ mana, choose two consecutive warriors, and ...
n, m = list(map(int, input().split())) x, k, y= list(map(int, input().split())) start_ls = list(map(int, input().split())) end_ls = list(map(int, input().split())) len_start_ls = len(start_ls) len_end_ls = len(end_ls) mark = [] end_p = 0 curr = None for item in start_ls: if end_p < (len_end_ls): if item =...
python
test
qsol
codeparrot/apps
all
Solve in Python: n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will: Take their own seat if it is still available,  Pick other seats randomly when they find their seat occupied  What is the probability tha...
class Solution: def nthPersonGetsNthSeat(self, n: int) -> float: # if n == 1: # return 1.0 # else: # return 0.5 if n == 1: return 1.0 sum_results = 0.0 for i in range(2, n+1): p = 1/i * (1 + sum_results) sum...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/276/C: The little girl loves the problems on array queries very much. One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, ea...
n, q = map(int, input().split()) t = [0] + list(map(int, input().split())) p = [0] * (n + 1) for i in range(q): l, r = map(int, input().split()) p[l - 1] += 1 p[r] -= 1 for i in range(1, n + 1): p[i] += p[i - 1] t.sort() p.sort() j = 0 while p[j] == 0: j += 1 print(sum(p[i] * t[i] for i in range(j,...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/448/D: Bizon the Champion isn't just charming, he also is very smart. While some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an n × m multiplication table, where the el...
from sys import stdin n, m, k = [int(x) for x in stdin.readline().split()] be, en = 1, k + 1 while be < en: mid = (be + en + 1) >> 1 be1, cur = (mid + m - 1) // m, 0 for i in range(1, be1): cur += m for i in range(be1, n + 1): cur += (mid - 1) // i if cur <= k - 1: be = m...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Binod and his family live in Codingland. They have a festival called N-Halloween. The festival is celebrated for N consecutive days. On each day Binod gets some candies from his mother. He may or may not take them. On a given day , Binod will be sad if he collected candies on that day and he does not...
# cook your dish here import copy import bisect n,q=list(map(int,input().split())) a=list(map(int,input().split())) a.sort() b=copy.copy(a) for i in range(1,len(b)): b[i]+=b[i-1] ##print(b) for i in range(q): x=int(input()) ans=bisect.bisect_left(a,x*2) if ans==0: ans1=b[n-1] else: ans1=b[n-1]-b[ans-1] prin...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/56445cc2e5747d513c000033: In Russia, there is an army-purposed station named UVB-76 or "Buzzer" (see also https://en.wikipedia.org/wiki/UVB-76). Most of time specific "buzz" noise is being broadcasted, but on very rare occasions, the buzzer signal is inter...
import re def validate(message): return bool(re.fullmatch(r'MDZHB \d{2} \d{3} [A-Z]+ \d{2} \d{2} \d{2} \d{2}', message))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5899f1df27926b7d000000eb: The Tower of Hanoi problem involves 3 towers. A number of rings decreasing in size are placed on one tower. All rings must then be moved to another tower, but at no point can a larger ring be placed on a smaller ring. Your task...
def tower_of_hanoi(rings): moves = 0 for r in range(rings): moves *= 2 moves += 1 return moves
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/596c26187bd547f3a6000050: # Task A newspaper is published in Walrusland. Its heading is `s1` , it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order...
import re def buy_newspaper(s1, s2): if not set(s2) <= set(s1): return -1 regex = ''.join(c + '?' for c in s1) return len([match for match in re.findall(regex, s2) if match])
python
train
abovesol
codeparrot/apps
all
Solve in Python: Bob has ladder. He wants to climb this ladder, but being a precocious child, he wonders about exactly how many ways he could to climb this `n` size ladder using jumps of up to distance `k`. Consider this example... n = 5\ k = 3 Here, Bob has ladder of length 5, and with each jump, he can ascend up t...
def count_ways(n, k): steps = [1] * (n + 1) for i in range(1, n + 1): if i <= k: steps[i] = sum(steps[j] for j in range(0, i)) else: steps[i] = sum(steps[i - j] for j in range(1, k + 1)) return steps[-1]
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/485/A: One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were x details in the factory storage, then by the end of the day the factory has to ...
a,m = map(int,input().split()) for i in range(100000): if a%m==0: print("Yes") quit() else: a+=a%m print("No")
python
test
abovesol
codeparrot/apps
all
Solve in Python: We have a board with a 2 \times N grid. Snuke covered the board with N dominoes without overlaps. Here, a domino can cover a 1 \times 2 or 2 \times 1 square. Then, Snuke decided to paint these dominoes using three colors: red, cyan and green. Two dominoes that are adjacent by side should be painted by ...
#template def inputlist(): return [int(j) for j in input().split()] #template mod = 10**9+7 N = int(input()) if N == 1: print((3)) return S1 = list(input()) S2 = list(input()) blocks = [] s = S1[0] for i in range(1,N): if S1[i] == S1[i-1]: s += S1[i] else: blocks.append(s) s...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/509/B: There are n piles of pebbles on the table, the i-th pile contains a_{i} pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pe...
n, colors = map(int, input().split()) lens = list(map(int, input().split())) q = [[] for i in range(n)] def end(): for i in range(n): if lens[i] != len(q[i]): return False return True mi = min(lens) for i in range(n): while len(q[i]) < min(lens[i], 1 + mi): q[i].append(1) k = ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: For every string, after every occurrence of `'and'` and `'but'`, insert the substring `'apparently'` directly after the occurrence. If input does not contain 'and' or 'but', return the original string. If a blank string, return `''`. If substring `'apparently'` is already directly after an `'and'` an...
def apparently(string): a, r = string.split(), [] for i in range(len(a)): if a[i] in ('and', 'but') and i == len(a)-1: r.append(a[i]+' apparently') elif a[i] in ('and', 'but') and a[i+1] != 'apparently': r.append(a[i]+' apparently') else: r.append(a[i]) return ' '.join(r)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5ae43ed6252e666a6b0000a4: Welcome This kata is inspired by This Kata We have a string s We have a number n Here is a function that takes your string, concatenates the even-indexed chars to the front, odd-indexed chars to the back. Examples s = "...
def jumbled_string(s, n): idx = list(range(0,len(s),2)) + list(range(1,len(s),2)) lst = [] while not lst or s != lst[0]: lst.append(s) s = ''.join(s[i] for i in idx) if len(lst) == n: return s return lst[ n%len(lst) ]
python
train
abovesol
codeparrot/apps
all
Solve in Python: =====Function Descriptions===== Basic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module. import numpy a = numpy.array([1,2,3,4], float) b = numpy.array([5,6,7,8], float) print a + b #[ 6. 8...
import numpy n,m = list(map(int,input().split())) ar1 = [] ar2 = [] for i in range(n): tmp = list(map(int,input().split())) ar1.append(tmp) for i in range(n): tmp = list(map(int,input().split())) ar2.append(tmp) np_ar1 = numpy.array(ar1) np_ar2 = numpy.array(ar2) print((np_ar1 + np_ar2)) print((np_ar1 -...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/691/C: You are given a positive decimal number x. Your task is to convert it to the "simple exponential notation". Let x = a·10^{b}, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zer...
string_list = input().split(sep='.') integer = string_list[0].lstrip('0') if len(string_list) == 1: fractional = '' else: fractional = string_list[1].rstrip('0') if integer: if fractional: a = "{}.{}{}".format(integer[0], integer[1:], fractional) else: a = "{}.{}".format(integer[0], inte...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/LTIME40/problems/LTM40CD: Chef likes problems on geometry a lot. Please help him to solve one such problem. Find all possible triangles with integer sides which has the radius of inscribed circle (also known as incircle) equal to R. Two triangles are said to be...
from math import sqrt r = int(input()) cnt=0 rt=[] for i in range(1,16*r): for j in range(i, 460): for k in range(j+1, j+i): #print i,j,k s = float((i+j+k))/2 #print s,i,j,k,s*(s-i)*(s-j)*(s-k) area = sqrt(abs(s*(s-i)*(s-j)*(s-k))) #print(float(2*area))/(i+j+k) if (r==(float(2*area))/(i+j+k)): ...
python
train
abovesol
codeparrot/apps
all
Solve in Python: There are $n$ chips arranged in a circle, numbered from $1$ to $n$. Initially each chip has black or white color. Then $k$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $i$, three chips are considered: chip $i$ itself and two its...
import sys input = sys.stdin.readline n,k=list(map(int,input().split())) S=input().strip() ANS=["?"]*n for i in range(n-1): if S[i]=="B": if S[i-1]=="B" or S[i+1]=="B": ANS[i]="B" else: if S[i-1]=="W" or S[i+1]=="W": ANS[i]="W" if S[n-1]=="B": if S[n-2]=="B" or S...
python
test
qsol
codeparrot/apps
all
Solve in Python: Write a function that when given a number >= 0, returns an Array of ascending length subarrays. ``` pyramid(0) => [ ] pyramid(1) => [ [1] ] pyramid(2) => [ [1], [1, 1] ] pyramid(3) => [ [1], [1, 1], [1, 1, 1] ] ``` **Note:** the subarrays should be filled with `1`s
def pyramid(n): result = [] for i in range (1, n + 1): result.append(i * [1]) return result
python
train
qsol
codeparrot/apps
all
Solve in Python: Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th ...
n, m, x, y, z, p = list(map(int, input().split())) n, m, x, y, z = n + 1, m + 1, x % 4, y % 2, (4 - z) % 4 def a(i, j, n, m, k): if k == 0: return i, j, n, m if k == 1: return j, n - i, m, n if k == 2: return n - i, m - j, n, m return m - j, i, m, n def b(i, j, m, k): if k == 0: return i, j if...
python
test
qsol
codeparrot/apps
all
Solve in Python: Leonardo Fibonacci in a rare portrait of his younger days I assume you are all familiar with the famous Fibonacci sequence, having to get each number as the sum of the previous two (and typically starting with either `[0,1]` or `[1,1]` as the first numbers). While there are plenty of variation on it ...
from collections import deque def custom_fib(signature,indexes,n): s = deque(signature, maxlen=len(signature)) for i in range(n): s.append(sum(s[i] for i in indexes)) return s[0]
python
train
qsol
codeparrot/apps
all