query
stringlengths
22
16.4k
answer
stringlengths
0
413k
Solve the following coding problem using the programming language python: You have an array $a_1, a_2, \dots, a_n$. Let's call some subarray $a_l, a_{l + 1}, \dots , a_r$ of this array a subpermutation if it contains all integers from $1$ to $r-l+1$ exactly once. For example, array $a = [2, 2, 1, 3, 2, 3, 1]$ contai...
```python import math mod = int(1000000007) i = lambda : map(int, input().split()) n = int(input()) a = [int(x) for x in input().split()] t = [[0] * 21 for i in range(300005)] for i in range(n): t[i][0] = a[i] def build(n): for j in range(1, 20): for i in range(n): if i + (1 << j) - 1 > n - 1: break t[i]...
Solve the following coding problem using the programming language python: Given two integers N and K, the task is to find the count of palindromic strings of length lesser than or equal to N, with first K characters of lowercase English language, such that each character in a string doesn’t appear more than twice. Not...
```python def rec(N, K, dp): if N == 0: return 1 if K == 0: return 0 if N == 1: return K dp[N][K] = rec(N - 2, K - 1, dp) * K return dp[N][K] class Solution: def palindromicStrings(self, N, K): mod = int(1000000000.0 + 7) dp = [[0 for i in range(K + 1)] for j in range(N + 1)] c = 0 for i in range(...
Solve the following coding problem using the programming language python: Chef usually likes to play cricket, but now, he is bored of playing it too much, so he is trying new games with strings. Chef's friend Dustin gave him binary strings $S$ and $R$, each with length $N$, and told him to make them identical. However...
```python for i in range(int(input())): a = int(input()) b = input() c = input() d = b.count('0') e = c.count('0') if d == e: print('YES') else: print('NO') ```
Solve the following coding problem using the programming language python: Implement a Stack using two queues q1 and q2. Example 1: Input: push(2) push(3) pop() push(4) pop() Output: 3 4 Explanation: push(2) the stack will be {2} push(3) the stack will be {2 3} pop() poped element will be 3 the stack will be...
```python def push(x): global queue_1 global queue_2 queue_1.append(x) while queue_2: val = queue_2.pop(0) queue_1.append(val) (queue_1, queue_2) = (queue_2, queue_1) def pop(): global queue_1 global queue_2 if not queue_2: return -1 return queue_2.pop(0) ```
Solve the following coding problem using the programming language python: An employee's wallet can contain no more than M notes or coins. A boss pays his salary by the minimum notes possible. However the employee may have to leave out some money. Find how much money he has to lose if his original salary is N. Note: Th...
```python class Solution: def getLoss(self, n, m): notes = [1000, 500, 100, 50, 20, 10, 5, 2, 1] count = 0 i = 0 while count < m and n > 0: if n >= notes[i]: n = n - notes[i] count += 1 else: i += 1 return n ```
Solve the following coding problem using the programming language python: Sid is a superior salesperson. So he gets a task from his boss. The task is that he will be given some number of products say k (All the products are same) and he has to travel N cities [1...N] to sell them. The main objective of the task is tha...
```python primes = [2, 3] class Solution: def primeMoney(self, arr, n): maxi = max(arr) i = primes[-1] + 2 while maxi >= i: flag = True for item in primes: if i % item == 0: flag = False break if flag: primes.append(i) i += 2 setti = set(primes) count = 0 summa = 0 last = ...
Solve the following coding problem using the programming language python: Ricky has N different balls and John has R different bags. Their teacher Ms.Samara wants them to distribute these N balls into R bags such that each bag gets at least one ball. Can you find the number of ways of doing so ? Input: The one and o...
```python ''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' from math import factorial n,k=list(map(int,input().split())) if n>=k: f=factorial(n-1)/(factorial(n-k)*factorial(k-1)) print(f%10000007) else: print(...
Solve the following coding problem using the programming language python: Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Fol...
```python class Solution: def maxSubArray(self, nums): max_sum = csum = nums[0] for num in nums[1:]: if num >= csum + num: csum = num else: csum += num if csum > max_sum: max_sum = csum return max_sum ```
Solve the following coding problem using the programming language python: Alexa has two stacks of non-negative integers, stack $a[n]$ and stack $b[m]$ where index $0$ denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack ...
```python import sys g = int(input().strip()) for a0 in range(g): (n, m, x) = input().strip().split(' ') (n, m, x) = [int(n), int(m), int(x)] a = list(map(int, input().strip().split(' '))) b = list(map(int, input().strip().split(' '))) i = 0 while i < len(a) and x >= a[i]: x -= a[i] i += 1 ans = i j = 0 fo...
Solve the following coding problem using the programming language python: You are given N integers \{A_{1}, A_{2}, \ldots, A_{N}\}. Determine whether they can be reordered such that each pair of consecutive differences differ by a factor of 2. Formally, determine whether there exists a rearrangement of the given inte...
```python for _ in range(int(input())): n = int(input()) a = sorted(list(map(int, input().split()))) l = [a[i + 1] - a[i] for i in range(n - 1)] c = 0 for i in range(len(l) - 1): if l[i] == 2 * l[i + 1] or l[i] // 2 == l[i + 1] or 2 * l[i] == l[i + 1]: c += 1 else: break if len(l) - 1 == c: print('Yes...
Solve the following coding problem using the programming language python: In Python, a string of text can be aligned left, right and center. .ljust(width) This method returns a left aligned string of length width. >>> width = 20 >>> print 'HackerRank'.ljust(width,'-') HackerRank---------- .center(width) This me...
```python thickness = int(input()) c = 'H' for i in range(thickness): print((c * i).rjust(thickness - 1) + c + (c * i).ljust(thickness - 1)) for i in range(thickness + 1): print((c * thickness).center(thickness * 2) + (c * thickness).center(thickness * 6)) for i in range((thickness + 2) // 2): print((c * thickness *...
Solve the following coding problem using the programming language python: Example Input 4 4 1 2 3 1 3 3 2 3 3 2 4 3 Output 1 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python (N, M) = map(int, input().split()) E0 = [] for i in range(M): (S, D, C) = map(int, input().split()) E0.append((C, S - 1, D - 1)) E0.sort() (*parent,) = range(N) def root(x): if x == parent[x]: return x y = parent[x] = root(parent[x]) return y def unite(x, y): px = root(x) py = root(y) if px < py: ...
Solve the following coding problem using the programming language python: Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length...
```python import sys input = sys.stdin.readline import heapq (n, m, k) = map(int, input().split()) adj = [[] for _ in range(n + 5)] for _ in range(m): (u, v, w) = map(int, input().split()) adj[u].append((v, w)) adj[v].append((u, w)) train = [-1 for _ in range(n + 5)] ans = 0 dist = [int(1000000000000000.0) for _ in ...
Solve the following coding problem using the programming language python: In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a t...
```python from itertools import combinations_with_replacement from collections import deque (n, m) = map(int, input().split()) G = [[] for i in range(n)] for i in range(m): (x, y) = map(int, input().split()) x -= 1 y -= 1 G[x].append(y) G[y].append(x) def BFS(s): dist = [-1 for i in range(n)] dist[s] = 0 Q = d...
Solve the following coding problem using the programming language python: A tennis tournament is about to take place with $N$ players participating in it. Every player plays with every other player exactly once and there are no ties. That is, every match has a winner and a loser. With Naman's birthday approaching, he...
```python from math import comb a = int(input()) for i in range(a): N = int(input()) matche = comb(N, 2) win = matche / N ans = [] if win != int(win): print('NO') continue print('YES') for k in range(N): list = [] for j in range(N): list.append(0) ans.append(list) list = [] for k in range(N): t...
Solve the following coding problem using the programming language python: Given a set of $N$ axis-aligned rectangular seals, find the number of overlapped seals on the region which has the maximum number of overlapped seals. Constraints * $ 1 \leq N \leq 100000 $ * $ 0 \leq x1_i < x2_i \leq 1000 $ * $ 0 \leq y1_i < ...
```python from itertools import accumulate import sys n = int(input()) ys = [0] * 1001 rects = [None] * 2 * n i = 0 for line in sys.stdin: (x1, y1, x2, y2) = [int(j) for j in line.split()] rects[i] = (x2, -1, y1, y2) rects[i + n] = (x1, 1, y1, y2) i += 1 rects.sort(key=lambda x: x[0]) max_overlap = 0 for (x, t, y1,...
Solve the following coding problem using the programming language python: You are given an array of integers $a_1, a_2, \ldots, a_n$ and an integer $x$. You need to select the maximum number of elements in the array, such that for every subsegment $a_l, a_{l + 1}, \ldots, a_r$ containing strictly more than one elemen...
```python for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) x = int(input()) a = [c - x for c in a] begin = True unchosen = 0 sum = 0 for i in range(n): if begin: sum = a[i] begin = False else: sum += a[i] if sum < 0: begin = True unchosen += 1 else: ...
Solve the following coding problem using the programming language python: 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 function that determ...
```python def match(usefulness, months): return 'Match!' if sum(usefulness) >= 0.85 ** months * 100 else 'No match!' ```
Solve the following coding problem using the programming language python: A number is called faithful if you can write it as the sum of distinct powers of 7. e.g., 2457 = 7 + 7^{2} + 7^{4 . }If we order all the faithful numbers, we get the sequence 1 = 7^{0}, 7 = 7^{1}, 8 = 7^{0} + 7^{1}, 49 = 7^{2}, 50 = 7^{0} + 7^...
```python class Solution: def nthFaithfulNum(self, N): ans = 0 power = 0 while N: if N & 1: ans = ans + pow(7, power) power = power + 1 N = N // 2 return ans ```
Solve the following coding problem using the programming language python: There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on blac...
```python from collections import deque y = [-1, 0, 1, 0] x = [0, -1, 0, 1] def main(): (h, w) = (0, 0) c = [] def check(i, j): return 0 <= i and i < h and (0 <= j) and (j < w) def bfs(a, b): res = 0 d = deque() d.append([a, b]) f = [[False] * w for _ in range(h)] while len(d): (i, j) = d.popleft(...
Solve the following coding problem using the programming language python: Given an array Arr of size N, print second largest distinct element from an array. Example 1: Input: N = 6 Arr[] = {12, 35, 1, 10, 34, 1} Output: 34 Explanation: The largest element of the array is 35 and the second largest element is 34. Exam...
```python class Solution: def print2largest(self, arr, n): if n < 2: return -1 (largest, second_largest) = (float('-inf'), float('-inf')) for i in range(n): if arr[i] > largest: second_largest = largest largest = arr[i] elif arr[i] > second_largest and arr[i] != largest: second_largest = ar...
Solve the following coding problem using the programming language python: Problem Statement Mr. Takatsuki, who is planning to participate in the Aizu training camp, has a poor house and always tries to save as much paper as possible. She decided to play a ghost leg with other participants to decide the team for the A...
```python from itertools import permutations (N, M) = map(int, input().split()) k = [int(input()) - 1 for i in range(M)] g = [i for i in range(N)] for i in range(N): for j in k: if g[i] == j: g[i] = j + 1 elif g[i] == j + 1: g[i] = j s = 10 for K in permutations(k): G = [i for i in range(N)] for i in range...
Solve the following coding problem using the programming language python: While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive intege...
```python class InputHandlerObject(object): inputs = [] def getInput(self, n=0): res = '' inputs = self.inputs if not inputs: inputs.extend(input().split(' ')) if n == 0: res = inputs[:] inputs[:] = [] while n > len(inputs): inputs.extend(input().split(' ')) if n > 0: res = inputs[:n] i...
Solve the following coding problem using the programming language python: Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some num...
```python def song_decoder(song): return ' '.join(song.replace('WUB', ' ').split()) ```
Solve the following coding problem using the programming language python: You are given array nums of n length and an integer k .return the maximum number of consecutive 1's in the array if you can flip at most k 0's. Example: Input: n = 11 nums = [1,1,1,0,0,0,1,1,1,1,0] k = 2 Output: 6 Explanation: You can flip 2 0 a...
```python class Solution: def longestOnes(self, n, arr, k): (left, right) = (0, 0) zero_count = 0 maxlen = 0 while right < n: if arr[right] == 1: right += 1 elif zero_count == k: zero_count -= 1 - arr[left] left += 1 else: zero_count += 1 right += 1 maxlen = max(maxlen, right -...
Solve the following coding problem using the programming language python: The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows. [Image] The event coord...
```python k = int(input()) output = ['+------------------------+', '|#.#.#.#.#.#.#.#.#.#.#.|D|)', '|#.#.#.#.#.#.#.#.#.#.#.|.|', '|#.......................|', '|#.#.#.#.#.#.#.#.#.#.#.|.|)', '+------------------------+'] ls = [1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2,...
Solve the following coding problem using the programming language python: Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The $k$-th layer of the triangle contains $k$ points, numbered from left to right. Each point of an i...
```python import os import math true = True false = False from collections import defaultdict, deque, Counter from functools import reduce from heapq import * is_dev = 'vscode' in os.environ if is_dev: inF = open('in.txt', 'r') outF = open('out.txt', 'w') def ins(): return list(map(int, input_().split(' '))) def i...
Solve the following coding problem using the programming language python: Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi. Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distan...
```python (l, n) = [int(item) for item in input().split()] right = [] left = [] for i in range(n): a = int(input()) right.append(a) left.append(l - a) left.reverse() rsum = [0] * (n + 1) lsum = [0] * (n + 1) for i in range(n): rsum[i + 1] += rsum[i] + right[i] lsum[i + 1] += lsum[i] + left[i] ans = max(right[-1], ...
Solve the following coding problem using the programming language python: Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one. Vasya drew s...
```python import sys def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) N = int(input()) A = [None] * N for i in range(N): (x, y) = map(int, sys.stdin.readline().split()) A[i] = (x, y - x * x) A.sort() upper = [] for p in reversed(A): while len(upper) >= 2 and cross(upper[-2],...
Solve the following coding problem using the programming language python: Given N bits to an AND - Gate find the output that will be produced. AND - Gate Table: 1 & 1 = 1 1 & 0 = 0 0 & 1 = 0 0 & 0 = 0 Example 1: Input: N = 4 arr: 1 1 1 0 Output: 0 Explanation: 1 & 1 = 1 1 & 1 = 1 1 & 0 = 0 hence output is 0 Example...
```python class Solution: def andGate(self, arr, N): if 0 in arr: return 0 return 1 ```
Solve the following coding problem using the programming language python: You are given a string $s$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For ex...
```python def mergeSort(arr, n): temp_arr = [0] * n return _mergeSort(arr, temp_arr, 0, n - 1) def _mergeSort(arr, temp_arr, left, right): inv_count = 0 if left < right: mid = (left + right) // 2 inv_count += _mergeSort(arr, temp_arr, left, mid) inv_count += _mergeSort(arr, temp_arr, mid + 1, right) inv_co...
Solve the following coding problem using the programming language python: # Valid HK Phone Number ## Overview In Hong Kong, a valid phone number has the format ```xxxx xxxx``` where ```x``` is a decimal digit (0-9). For example: ## Task Define two functions, ```isValidHKPhoneNumber``` and ```hasValidHKPhoneNumber...
```python import re HK_PHONE_NUMBER = '\\d{4} \\d{4}' def is_valid_HK_phone_number(number): return bool(re.match(HK_PHONE_NUMBER + '\\Z', number)) def has_valid_HK_phone_number(number): return bool(re.search(HK_PHONE_NUMBER, number)) ```
Solve the following coding problem using the programming language python: ```if-not:sql Create a function (or write a script in Shell) that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. ``` ```if:sql ## SQL Notes: You will be given a table, `numbers`, with one column `n...
```python def even_or_odd(number): return 'Odd' if number % 2 else 'Even' ```
Solve the following coding problem using the programming language python: Takahashi received otoshidama (New Year's money gifts) from N of his relatives. You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of t...
```python n = int(input()) btc = 380000.0 a = 0 for _ in range(n): (x, u) = input().split() if u == 'JPY': a += int(x) elif u == 'BTC': a += float(x) * btc print(a) ```
Solve the following coding problem using the programming language python: Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some ...
```python (n, x) = (int(input()), list(map(int, input().split(' ')))) tmp = sorted(x, reverse=True) for i in x: print(tmp.index(i) + 1) ```
Solve the following coding problem using the programming language python: Like any good boss, the Chef has delegated all cooking jobs to his employees so he can take care of other tasks. Occasionally, one of the cooks needs a tool that is out of reach. In some of these cases, the cook cannot leave their workstation to...
```python def dist(pos1: list, pos2: list) -> int: return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) def list2bin(n: int, lst: list) -> str: num = 0 for x in lst: num += 1 << x return f'{num:08b}' def pos2str(pos: list) -> str: return '--'.join(map(str, pos)) def min_chef(chefs: list, tools: list, htools...
Solve the following coding problem using the programming language python: In the final of CODE FESTIVAL in some year, there are N participants. The height and power of Participant i is H_i and P_i, respectively. Ringo is hosting a game of stacking zabuton (cushions). The participants will line up in a row in some or...
```python N = int(input()) men = [] for _ in range(N): (H, P) = map(int, input().split()) men.append((H, P, H + P)) men.sort(key=lambda x: x[2]) maxH = max(men)[0] inf = maxH + 1 dp = [[-1] * (N + 1) for _ in range(N + 1)] dp[0][0] = 0 for i in range(1, N + 1): (h, p, a) = men[i - 1] for j in range(1, N + 1): if ...
Solve the following coding problem using the programming language python: Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap betwee...
```python n = int(input()) p = lambda a, b: print(a + 1, b + 1) if n % 4 > 1: print('NO') else: print('YES') for i in range(n % 4, n, 4): for x in range(2): for j in range(i): p(j, i + 2 * x) p(i + 2 * x, i + 2 * x + 1) for j in range(i, 0, -1): p(j - 1, i + 2 * x + 1) p(i, i + 3) p(i + 1, i +...
Solve the following coding problem using the programming language python: In this Kata, you will be given a multi-dimensional array containing `2 or more` sub-arrays of integers. Your task is to find the maximum product that can be formed by taking any one element from each sub-array. ``` Examples: solve( [[1, 2],[3,...
```python def solve(arr): (p, q) = (1, 1) for k in arr: (x, y) = (max(k), min(k)) a = p * x b = q * x c = p * y d = q * y p = max(a, b, c, d) q = min(a, b, c, d) return max(p, q) ```
Solve the following coding problem using the programming language python: # Introduction The Condi (Consecutive Digraphs) cipher was introduced by G4EGG (Wilfred Higginson) in 2011. The cipher preserves word divisions, and is simple to describe and encode, but it's surprisingly difficult to crack. # Encoding Algori...
```python LOWER = 'abcdefghijklmnopqrstuvwxyz' def encode(message, key, shift, encode=True): key = sorted(LOWER, key=f'{key}{LOWER}'.index) result = [] for char in message: if char in key: i = key.index(char) char = key[(i + shift) % 26] shift = i + 1 if encode else -(key.index(char) + 1) result.append...
Solve the following coding problem using the programming language python: Write a program which reads the two dices constructed in the same way as Dice I, and determines whether these two dices are identical. You can roll a dice in the same way as Dice I, and if all integers observed from the six directions are the sa...
```python roll_dict = dict(E=(3, 1, 0, 5, 4, 2), W=(2, 1, 5, 0, 4, 3), S=(4, 0, 2, 3, 5, 1), N=(1, 5, 2, 3, 0, 4)) dice1 = list(map(int, input().split())) dice2 = list(map(int, input().split())) dices = [] dices.append(dice1) judge = False for i in 'EWSN': dice = dices[0] new_dice = [] for j in range(6): new_dice....
Solve the following coding problem using the programming language python: Humpy, the little elephant, has his birthday coming up. He invited all his cousins but doesn’t know how many of them are really coming as some of them are having exams coming up. He will only get to know how many of them are coming on the day of...
```python from sys import stdin, stdout n = int(stdin.readline()) while n: n -= 1 (k, l, e) = map(int, stdin.readline().strip().split(' ')) a = map(int, stdin.readline().strip().split(' ')) x = float(l) / float(e + sum(a)) if x - int(x): stdout.write('NO\n') else: stdout.write('YES\n') ```
Solve the following coding problem using the programming language python: We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i). Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there? We remind you that the...
```python def main(): (N, D) = [int(n) for n in input().split(' ')] cnt = 0 for i in range(N): (X, Y) = [int(x) for x in input().split(' ')] if X ** 2 + Y ** 2 <= D ** 2: cnt += 1 print(cnt) main() ```
Solve the following coding problem using the programming language python: You are given a tree that is built in a following way: initially there is single vertex 1. All the other vertices are added one by one, from vertex 2 to vertex N, by connecting it to one of those that have been added before. You are to find the ...
```python def update(M, level, u, v): level[u] = level[v] + 1 M[u][0] = v for j in range(1, 18): if M[u][j - 1]: M[u][j] = M[M[u][j - 1]][j - 1] def LCA(M, level, u, v): if u == v: return u if level[u] < level[v]: (u, v) = (v, u) for i in range(17, -1, -1): if M[u][i] and level[M[u][i]] >= level[v]: ...
Solve the following coding problem using the programming language python: 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 dice th...
```python 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(' '))) py = [0, y...
Solve the following coding problem using the programming language python: Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have ...
```python (n, k) = map(int, input().split()) a = [] b = [] both = [] for _ in range(n): (x, y, z) = map(int, input().split()) if y == 1 and z == 1: both.append(x) elif y == 1: a.append(x) elif z == 1: b.append(x) a.sort() b.sort() for i in range(min(len(a), len(b))): both.append(a[i] + b[i]) both.sort() if l...
Solve the following coding problem using the programming language python: You are given an array A consisting of N integers. In one operation, you can: Choose any two indices i and j (i \neq j); Subtract min(A_{i} , A_{j}) from both A_{i} and A_{j}. Note that min(A_{i} , A_{j}) denotes the minimum of A_{i} and A_{j}....
```python for _ in range(int(input())): n = int(input()) a = [int(x) for x in input().split()] assert len(a) == n assert all((x > 0 for x in a)) sm = sum(a) if sm % 2 != 0: print(-1) continue ps_sm = {0: []} for (i, x) in enumerate(a): ps_sm_new = ps_sm.copy() for (v, indices) in ps_sm.items(): if v ...
Solve the following coding problem using the programming language python: Ted$Ted$ loves prime numbers. One day he is playing a game called legendary$legendary$ with his girlfriend Robin$Robin$. Ted$Ted$ writes a number N$N$ on a table and the number is in the form of : N = P1A1 * P2A2 * ……….. * PnAn Ted$Ted$ asks Ro...
```python d = 10 ** 9 + 7 t = int(input()) while t: t -= 1 n = int(input()) p = list(map(int, input().strip().split())) a = list(map(int, input().strip().split())) b = list(map(int, input().strip().split())) ans = 1 for i in range(n): c = a[i] - b[i] + 1 tmp = pow(p[i], b[i], d) * ((pow(p[i], c, d) - 1 + d) ...
Solve the following coding problem using the programming language python: Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that t...
```python class Solution: def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: oneArrSum = sum(arr) twoArr = arr + arr def findMaxSub(array): if len(array) == 1: return array[0] cur = 0 small = 0 ret = -999999 for i in array: cur += i small = cur if cur < small else small ...
Solve the following coding problem using the programming language python: Given a string s and a string t, check if s is subsequence of t. You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string ( A subsequence ...
```python class Solution: def isSubsequence(self, s, t): if len(s) > len(t): return False for i in s: if i in t: index = t.find(i) t = t[index + 1:] else: return False return True ```
Solve the following coding problem using the programming language python: A wildlife study involving ducks is taking place in North America. Researchers are visiting some wetlands in a certain area taking a survey of what they see. The researchers will submit reports that need to be processed by your function. ## In...
```python def create_report(names): result = {} for name in names: if name.startswith('Labrador Duck'): return ['Disqualified data'] name = name.upper().replace('-', ' ').split() count = int(name.pop()) if len(name) == 1: code = name[0][:6] elif len(name) == 2: code = name[0][:3] + name[1][:3] el...
Solve the following coding problem using the programming language python: Given a non-empty array of unique positive integers A, consider the following graph: There are A.length nodes, labelled A[0] to A[A.length - 1]; There is an edge between A[i] and A[j] if and only if A[i] and A[j] share a common factor greater t...
```python from collections import defaultdict class Solution: MAXPRIME = 100001 isPrime = [0 for _ in range(MAXPRIME + 1)] isPrime[0] = -1 isPrime[1] = -1 for i in range(2, MAXPRIME): if isPrime[i] == 0: for multiple in range(i * i, MAXPRIME + 1, i): if isPrime[multiple] == 0: isPrime[multiple] = i ...
Solve the following coding problem using the programming language python: Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that...
```python def min_squares(canvas, length, width): def find_top(): for i in range(length): for j in range(width): if canvas[i][j] == 'B': return i return -1 def find_left(): for j in range(width): for i in range(length): if canvas[i][j] == 'B': return j def find_bottom(): for i in r...
Solve the following coding problem using the programming language python: There is a one-dimensional garden of length N. In each position of the N length garden, a sprinkler has been installed. Given an array a[]such that a[i] describes the coverage limit of the i^{th} sprinkler. A sprinkler can cover the range from t...
```python class Solution: def minSprinkler(self, arr, N): coverages = [-1] * N for (i, a) in enumerate(arr): min_coverage = max(0, i - a) max_coverage = min(i + a, N - 1) coverages[min_coverage] = max(coverages[min_coverage], max_coverage) needed_sprinklers_count = 0 current_coverage = -1 next_max_...
Solve the following coding problem using the programming language python: Juggler Sequence is a series of integers in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation: Given a number N, find the Juggl...
```python import math class Solution: def jugglerSequence(self, N): if N == 1: return [1] seq = [N] if N % 2 == 0: seq.extend(self.jugglerSequence(int(N ** 0.5))) else: seq.extend(self.jugglerSequence(int(N ** 1.5))) return seq ```
Solve the following coding problem using the programming language python: Read problems statements in Mandarin Chinese and Russian. This summer, there is a worldwide competition being held in Chef Town and some of the best chefs of the world are participating. The rules of this competition are quite simple. Each ...
```python def find(child): new_parent = child while new_parent != parents[new_parent]: new_parent = parents[new_parent] while child != parents[child]: temp = parents[child] parents[child] = new_parent child = temp return new_parent def union(root1, root2): (real_root1, real_root2) = (find(root1), find(roo...
Solve the following coding problem using the programming language python: Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is lo...
```python import sys import math MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(' ')) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans): s...
Solve the following coding problem using the programming language python: You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game. The boss battle consists of $n$ turns. During each turn, you will get several cards. Each card has two parameters: it...
```python from sys import stdin, stdout, exit n = int(input()) inf = 10 ** 18 dp = [[-inf] * 10 for i in range(n + 1)] dp[0][0] = 0 for i in range(n): k = int(stdin.readline()) cards = [] for j in range(k): (c, d) = map(int, stdin.readline().split()) cards.append((c, d)) cards.sort(reverse=True) cards_by_cost ...
Solve the following coding problem using the programming language python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test case...
```python t = int(input()) for _ in range(t): k = int(input()) count = 1 for _ in range(k): output = [] for index in range(1, k + 1): output.append(bin(count).replace('0b', '')) count += 1 print(*output) ```
Solve the following coding problem using the programming language python: There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i. Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in thi...
```python import sys input = sys.stdin.readline from collections import defaultdict n = int(input()) abd = [list(map(int, input().split())) for i in range(n - 1)] if n == 2: print(abd[0][2]) exit() graph = [[] for i in range(n + 1)] deg = [0 for i in range(n + 1)] for (a, b, d) in abd: graph[a].append((b, d)) graph...
Solve the following coding problem using the programming language python: Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).   Example 1: Input: text = "abcabcabc" Output: 3 Explanation...
```python from collections import defaultdict, deque class Solution: def distinctEchoSubstrings(self, text: str) -> int: if all((x == text[0] for x in text)): return len(text) // 2 res = set() character_locations = defaultdict(lambda : deque()) for (i, c) in enumerate(text): for j in character_location...
Solve the following coding problem using the programming language python: Given a triangle of consecutive odd numbers: ``` 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... ``` find the triangle's row knowing its index (the rows are 1-indexed), e.g.: ``` od...
```python odd_row = lambda n: list(range(n * (n - 1) + 1, n * (n + 1), 2)) ```
Solve the following coding problem using the programming language python: Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds. Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner co...
```python (X, n) = list(map(int, input().split())) Taken = [True] * (X + 1) for i in range(n): x = list(map(int, input().split())) if x[0] == 1: Taken[x[1]] = False Taken[x[2]] = False else: Taken[x[1]] = False cnt = 0 minn = 0 maxx = 0 ans = 0 for i in range(1, X): if Taken[i]: cnt += 1 maxx += 1 else: ...
Solve the following coding problem using the programming language python: Chef lives in a big apartment in Chefland. The apartment charges maintenance fees that he is supposed to pay monthly on time. But Chef is a lazy person and sometimes misses the deadlines. The apartment charges 1000 Rs per month as maintenance fe...
```python for i in range(int(input())): n = int(input()) p = list(map(int, input().split())) amount = p.count(0) * 1000 if p.count(0) != 0: q = p.index(0) print(100 * (n - q) + amount) else: print(amount) ```
Solve the following coding problem using the programming language python: This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems. After struggling and failing many times, Ujan decided to try to clean up his house agai...
```python t = int(input()) for x in range(t): n = int(input()) s = input() t = input() i = c = 0 a = b = '' while c < 4 and i < n: if s[i] != t[i]: c += 1 a += s[i] b += t[i] i += 1 if c == 2 and len(set(a)) == len(set(b)) == 1: print('Yes') else: print('No') ```
Solve the following coding problem using the programming language python: You are given a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$ and an integer $k$, such that $1 \leq k \leq n$. A permutation means that every number from $1$ to $n$ is contained in $p$ exactly once. Let's consider all partitio...
```python (n, k) = [int(el) for el in input().split()] per = [int(el) for el in input().split()] sp = sorted(per, reverse=True) sp.append(0) mod = 998244353 result = 1 prev = 0 for (i, p) in enumerate(per, 1): if p > sp[k]: if not prev: prev = i else: result *= i - prev result %= mod prev = i print(sum...
Solve the following coding problem using the programming language python: You are given $\textit{q}$ queries where each query consists of a set of $n$ points on a two-dimensional plane (i.e., $(x,y)$). For each set of points, print YES on a new line if all the points fall on the edges (i.e., sides and/or corners) of a...
```python def main(): for i in range(int(input())): p = [list(map(int, input().split())) for j in range(int(input()))] (px, py) = zip(*p) x0 = min(px) x1 = max(px) y0 = min(py) y1 = max(py) result = all((x in (x0, x1) or y in (y0, y1) for (x, y) in p)) print('YES' if result else 'NO') main() ```
Solve the following coding problem using the programming language python: *Words that contain many consecutive consonants, like "schtschurowskia", are generally considered somewhat hard to pronounce.* We say that a word is *hard to pronounce* if it contains 4 or more consonants in a row; otherwise it is *easy to pron...
```python for _ in range(int(input())): n = int(input()) s = input() if n <= 3: print('YES') else: for i in range(n - 3): string = s[i:i + 4] vow1 = 'a' in string or 'e' in string or 'i' in string vow2 = 'o' in string or 'u' in string if not vow1 and (not vow2): print('NO') break else: ...
Solve the following coding problem using the programming language python: Singh is getting bored at work. He has a lot of ideas (N) to work on (as side projects) but is unable to choose one. He chooses a random number (R) and lines up his ideas in a circle. He starts counting from first and removes the R^th idea in t...
```python N, R = [int(i) for i in input().split()] r = 0 for i in range(1, N+1): r = (r+R)%i print(r+1) ```
Solve the following coding problem using the programming language python: Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework. The teacher gave Seryozha the coordinates of n d...
```python length = int(input()) sequence = list(map(int, input().split())) if length <= 3: print('no') else: for i in range(length - 1): (w, x) = sorted([sequence[i], sequence[i + 1]]) for j in range(length - 1): (y, z) = sorted([sequence[j], sequence[j + 1]]) if w < y < x < z or y < w < z < x: print('y...
Solve the following coding problem using the programming language python: You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calcula...
```python n = int(input()) arr = [0] arr = arr + list(map(int, input().split(' '))) def getCounts(arr): last = {} ans = 0.0 prev = 0.0 res = 0.0 for i in range(1, len(arr)): if arr[i] not in last: ans = prev + i else: ans = prev + i - last[arr[i]] prev = ans res += ans last[arr[i]] = i return res...
Solve the following coding problem using the programming language python: Rachel, being an awesome android programmer, just finished an App that will let us draw a triangle by selecting three points on the touch-plane.Now She asks her friend Bruce to draw a Right-Angled Triangle (we'll call it RAT) by selecting 3 inte...
```python def dist(x1,y1,x2,y2): return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2) def is_RAT(a): ab = dist(a[0],a[1],a[2],a[3]) bc = dist(a[4],a[5],a[2],a[3]) ca = dist(a[0],a[1],a[4],a[5]) if ab == bc+ca or ca == bc+ab or bc == ab+ca: return True return False def samepoint(a): if a[0]==a[2] and a[1] == a[3]: return...
Solve the following coding problem using the programming language python: Given a binary heap implementation of Priority Queue. Extract the maximum element from the queue i.e. remove it from the Queue and return it's value. Example 1: Input: 4 2 8 16 24 2 6 5 Output: 24 Priority Queue after extracting maximum: 16 8...
```python class Solution: def extractMax(self): global s ans = H[0] H[0] = H[s] s -= 1 shiftDown(0) return ans ```
Solve the following coding problem using the programming language python: Natasha's favourite numbers are $n$ and $1$, and Sasha's favourite numbers are $m$ and $-1$. One day Natasha and Sasha met and wrote down every possible array of length $n+m$ such that some $n$ of its elements are equal to $1$ and another $m$ el...
```python P = 998244853 N = 4000 (f, fi) = ([0] * (N + 1), [0] * (N + 1)) f[0] = 1 for i in range(N): f[i + 1] = f[i] * (i + 1) % P fi[-1] = pow(f[-1], P - 2, P) for i in reversed(range(N)): fi[i] = fi[i + 1] * (i + 1) % P def C(n, r): c = 1 while n or r: (a, b) = (n % P, r % P) if a < b: return 0 c = c *...
Solve the following coding problem using the programming language python: Given a matrix Grid[][] of size NxN. Calculate the absolute difference between the sums of its diagonals. Example 1: Input: N=3 Grid=[[1,2,3],[4,5,6],[7,8,9]] Output: 0 Explanation: Sum of primary diagonal = 1+5+9 = 15. Sum of secondary diagona...
```python class Solution: def diagonalSumDifference(self, N, Grid): (Grid1, Grid2) = (0, 0) for i in range(N): for j in range(N): if i == j: Grid1 += Grid[i][j] if i + j == N - 1: Grid2 += Grid[i][j] return abs(Grid1 - Grid2) ```
Solve the following coding problem using the programming language python: Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader. Example 1: Inp...
```python class Solution: def leaders(self, A, N): leaders = [] max_right = A[N - 1] leaders.append(max_right) for i in range(N - 2, -1, -1): if A[i] >= max_right: leaders.append(A[i]) max_right = A[i] leaders.reverse() return leaders ```
Solve the following coding problem using the programming language python: You should write a simple function that takes string as input and checks if it is a valid Russian postal code, returning `true` or `false`. A valid postcode should be 6 digits with no white spaces, letters or other symbols. Empty string should ...
```python def zipvalidate(postcode): return len(postcode) == 6 and postcode.isdigit() and (postcode[0] not in '05789') ```
Solve the following coding problem using the programming language python: Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height a_{i}. The Innopolis administratio...
```python from sys import stdin from math import ceil n = int(stdin.readline().strip()) s = tuple([0] + list(map(int, stdin.readline().strip().split())) + [0]) lim = ceil(n / 2) + 1 dp = [[2000000002 for i in range(n + 1)] for j in range(lim)] vis = [[False for i in range(n + 1)] for j in range(lim)] for i in range(n +...
Solve the following coding problem using the programming language python: Given two numbers A and B. Your task is to return the sum of A and B. Example 1: Input: A = 1, B = 2 Output: 3 Explanation: Addition of 1 and 2 is 3. Example 2: Input: A = 10, B = 20 Output: 30 Explanation: Addition os 10 and 20 is 30. You...
```python class Solution: def addition(ob, A, B): return A + B ```
Solve the following coding problem using the programming language python: Lia is fascinated by anything she considers to be a twin. She calls a pairs of positive integers, $\boldsymbol{i}$ and $j$, twins if: They are both prime. A prime number is an integer greater than $\mbox{1}$ that has no positive divisors other ...
```python limit = 1000000 (beg, end) = map(int, input().strip().split(' ')) is_prime = [False] * (limit + 1) prime = [] for x in range(1, int(limit ** 0.5) + 1): for y in range(1, int(limit ** 0.5) + 1): n = 4 * x ** 2 + y ** 2 if n <= limit and (n % 12 == 1 or n % 12 == 5): is_prime[n] = not is_prime[n] n = ...
Solve the following coding problem using the programming language python: Given a Binary Search Tree (BST) and a range [min, max], remove all keys which are outside the given range. The modified tree should also be BST. Example 1: Input: Range = [-10, 13] Output: -8 6 7 13 Explanation: Nodes with values -13, 14 and 15...
```python class Solution: def removekeys(self, root, l, r): if root is None: return root root.left = self.removekeys(root.left, l, r) root.right = self.removekeys(root.right, l, r) if root.data > r: return root.left if root.data < l: return root.right return root ```
Solve the following coding problem using the programming language python: # Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an *array/list [] of integers* , **_Find_** *the Nth smallest e...
```python def nth_smallest(arr, pos): return sorted(arr)[pos - 1] ```
Solve the following coding problem using the programming language python: Pak Chanek, a renowned scholar, invented a card puzzle using his knowledge. In the puzzle, you are given a board with $n$ rows and $m$ columns. Let $(r, c)$ represent the cell in the $r$-th row and the $c$-th column. Initially, there are $k$ ca...
```python import sys input = sys.stdin.readline def readList(): return list(map(int, input().split())) def readInt(): return int(input()) def readInts(): return map(int, input().split()) def readStr(): return input().strip() def solve(): (n, m, k) = readInts() arr = readList() isPresent = [False] * (k + 1) ...
Solve the following coding problem using the programming language python: You are given two string S and T. Find the maximal length of some prefix of the string S which occurs in strings T as subsequence. Input The first line contains string S. The second line contains string T. Both strings consist of lowecase Latin...
```python from collections import deque, defaultdict, Counter from math import factorial from fractions import gcd from sys import stdin, exit from itertools import * import heapq import string import re def prase(T): if T == 1: return list(map(int, testcase.next().strip().split())) return testcase.next().strip(...
Solve the following coding problem using the programming language python: We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba". Given a string, you have to find two values: t...
```python def R(): return map(int, input().split()) def I(): return int(input()) def S(): return str(input()) def L(): return list(R()) from collections import Counter import math import sys from itertools import permutations import bisect mod = 10 ** 9 + 7 s = S() l = len(s) A = [0] * 2 B = [0] * 2 for i in ran...
Solve the following coding problem using the programming language python: Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding ...
```python import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x)...
Solve the following coding problem using the programming language python: Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule. A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — th...
```python a = list(map(int, input().split())) if sum(a) % 2 == 1 or max(a) > sum(a) - max(a): print('Impossible') elif len(set(a)) == 1: print(a[0] // 2, a[0] // 2, a[0] // 2) elif a.count(min(a)) == 2: pos = a.index(max(a)) ans = [0] * 3 ans[pos] = ans[pos - 1] = max(a) // 2 ans[pos - 2] = (min(a) * 2 - max(a)) ...
Solve the following coding problem using the programming language python: One day, Delta, the dog, got very angry. He has $N$ items with different values, and he decided to destroy a few of them. However, Delta loves his hooman as well. So he only destroyed those items whose Least Significant Bit in binary representat...
```python for test in range(int(input())): n = int(input()) ar = list(map(int, input().split())) count = 0 for item in ar: if bin(item)[-1] == '0': count += item print(count) ```
Solve the following coding problem using the programming language python: Chef's college is starting next week. There are $S$ subjects in total, and he needs to choose $K$ of them to attend each day, to fulfill the required number of credits to pass the semester. There are $N + 1$ buildings. His hostel is in building ...
```python from collections import deque def BFS(bldg, s): queue = deque() queue.append(s) cost = [-1 for i in range(n + 1)] cost[s] = 0 while queue: s = queue.popleft() for i in bldg[s]: if cost[i] == -1: queue.append(i) cost[i] = cost[s] + 1 return cost for _ in range(int(input())): (n, m, s, k)...
Solve the following coding problem using the programming language python: Given an array arr[ ] of size n such that elements of arr[ ] in range [0, 1, ..n-1]. Our task is to divide the array into the maximum number of partitions that can be sorted individually, then concatenated to make the whole array sorted. Exampl...
```python def maxPartitions(arr, n): a = arr[0] c = 0 for i in range(n): if a < arr[i]: a = arr[i] if a == i: c += 1 return c ```
Solve the following coding problem using the programming language python: A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. ...
```python input() l1 = [int(x) for x in input().split() if x != '0'] l2 = [int(x) for x in input().split() if x != '0'] m = len(l1) x = l1.index(l2[0]) b = True for i in range(len(l1)): b &= l2[i] == l1[(x + i) % m] print('YES' if b else 'NO') ```
Solve the following coding problem using the programming language python: Given an integer, $n$, print the following values for each integer $\boldsymbol{i}$ from $\mbox{1}$ to $n$: Decimal Octal Hexadecimal (capitalized) Binary Function Description Complete the print_formatted function in the editor below. ...
```python N = int(input()) width = len(str(bin(N))) - 2 for n in range(1, N + 1): for base in 'doXb': print('{0:{width}{base}}'.format(n, base=base, width=width), end=' ') print() ```
Solve the following coding problem using the programming language python: #Sorting on planet Twisted-3-7 There is a planet... in a galaxy far far away. It is exactly like our planet, but it has one difference: #The values of the digits 3 and 7 are twisted. Our 3 means 7 on the planet Twisted-3-7. And 7 means 3. Your...
```python def sort_twisted37(arr): def key(x): return int(str(x).translate(str.maketrans('37', '73'))) return sorted(arr, key=key) ```
Solve the following coding problem using the programming language python: One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of st...
```python from sys import stdin s = [ord(i) - 97 for i in stdin.readline().strip()] s1 = [ord(i) - 97 for i in stdin.readline().strip()] n = len(s) m = len(s1) mod = 1000000007 dp = [[0 for i in range(n)] for j in range(26)] for i in range(m): arr = [0 for j in range(n)] for j in range(n): if s1[i] == s[j]: arr[...