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 |
---|---|---|---|---|---|---|
I found an interesting problem on https://www.codechef.com/LTIME40/problems/LTM40AB:
Chef likes inequalities. Please help him to solve next one.
Given four integers a, b, c, d. Find number of solutions x < y, where a ≤ x ≤ b and c ≤ y ≤ d and x, y integers.
-----Input-----
The first line contains an integer T denoting number of tests.
First line of each test case contains four positive integer numbers a, b, c and d.
-----Output-----
For each test case, output a single number each in separate line denoting number of integer solutions as asked in the problem.
-----Constraints-----
- 1 ≤ T ≤ 20
- 1 ≤ a, b, c, d ≤ 106
-----Subtasks-----
- Subtask #1: (30 points) 1 ≤ a, b, c, d ≤ 103.
- Subtask #2: (70 points) Original constraints.
-----Example-----
Input:1
2 3 3 4
Output:3
Input:1
2 999999 1 1000000
Output:499998500001
I tried it in Python, but could not do it. Can you solve it? | # Akhilesh Ravi
# Codechef - Chef and Inequality
T = int(input())
l = []
for i in range(T):
l += [[int(j) for j in input().split()]]
l1 = []
for i in l:
a,b,c,d = tuple(i)
if a >= d:
l1 += [0]
elif b < c:
l1 += [(b-a+1)*(d-c+1)]
elif c <= a <= d <= b:
n = d-a
l1 += [n*(n+1)/2]
elif c <= a <= b <= d:
l1 += [(d-a) * (d-a+1)/2
- (d-b-1) * (d-b)/2]
elif a < c <= d <= b:
l1 += [ (d-c+1) * (c-a)
+ (d-c) * (d-c+1)/2 ]
elif a < c <= b <= d:
l1 += [ (d-c+1) * (c-a)
+ (d-c) * (d-c+1)/2
- (d-b-1) * (d-b)/2]
else:
l1 += [0]
for i in l1:
print(i) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1165/E:
You are given two arrays $a$ and $b$, both of length $n$.
Let's define a function $f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$.
Your task is to reorder the elements (choose an arbitrary order of elements) of the array $b$ to minimize the value of $\sum\limits_{1 \le l \le r \le n} f(l, r)$. Since the answer can be very large, you have to print it modulo $998244353$. Note that you should minimize the answer but not its remainder.
-----Input-----
The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of elements in $a$ and $b$.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$), where $a_i$ is the $i$-th element of $a$.
The third line of the input contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_j \le 10^6$), where $b_j$ is the $j$-th element of $b$.
-----Output-----
Print one integer — the minimum possible value of $\sum\limits_{1 \le l \le r \le n} f(l, r)$ after rearranging elements of $b$, taken modulo $998244353$. Note that you should minimize the answer but not its remainder.
-----Examples-----
Input
5
1 8 7 2 4
9 7 2 9 3
Output
646
Input
1
1000000
1000000
Output
757402647
Input
2
1 3
4 2
Output
20
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
for i in range(n):
A[i] *= (i + 1) * (n - i)
A.sort()
B.sort(reverse=True)
C = []
cnt = 0
M = 998244353
for i in range(n):
cnt += A[i] * B[i]
cnt %= M
print(cnt) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good.
Heidi knows that the lair can be represented as a rectangle on a lattice, with sides parallel to the axes. Each vertex of the polygon occupies an integer point on the lattice. For each cell of the lattice, Heidi can check the level of Zombie Contamination. This level is an integer between 0 and 4, equal to the number of corners of the cell that are inside or on the border of the rectangle.
As a test, Heidi wants to check that her Zombie Contamination level checker works. Given the output of the checker, Heidi wants to know whether it could have been produced by a single non-zero area rectangular-shaped lair (with axis-parallel sides). [Image]
-----Input-----
The first line of each test case contains one integer N, the size of the lattice grid (5 ≤ N ≤ 50). The next N lines each contain N characters, describing the level of Zombie Contamination of each cell in the lattice. Every character of every line is a digit between 0 and 4.
Cells are given in the same order as they are shown in the picture above: rows go in the decreasing value of y coordinate, and in one row cells go in the order of increasing x coordinate. This means that the first row corresponds to cells with coordinates (1, N), ..., (N, N) and the last row corresponds to cells with coordinates (1, 1), ..., (N, 1).
-----Output-----
The first line of the output should contain Yes if there exists a single non-zero area rectangular lair with corners on the grid for which checking the levels of Zombie Contamination gives the results given in the input, and No otherwise.
-----Example-----
Input
6
000000
000000
012100
024200
012100
000000
Output
Yes
-----Note-----
The lair, if it exists, has to be rectangular (that is, have corners at some grid points with coordinates (x_1, y_1), (x_1, y_2), (x_2, y_1),... | n = int(input())
aux = []
grid = []
flag = True
ans = -1
um = 0
dois = 0
quatro = 0
while(n):
n-=1
x = str(int(input()))
if(x!='0'):
aux.append(x)
for i in aux:
txt = ''
for j in i:
if(j!='0'):
txt+=j
grid.append(txt)
for i in grid:
for j in i:
if(j == '1'):
um+=1
if(j == '2'):
dois+=1
if(j == '4'):
quatro+=1
if(ans==-1 or len(i)==ans):
ans = len(i)
else:
flag = False
if(um!=4 or dois!=len(grid)*2+len(grid[0])*2-8 or quatro!=(len(grid)*len(grid[0]))-(len(grid)*2+len(grid[0])*2-4)):
flag = False
if(flag):
for i in range(0, len(grid)):
if(len(grid)-i-1 < i):
break
if(grid[i] != grid[len(grid)-i-1]):
flag = False
for i in range(0, len(grid)):
for j in range(0, len(grid[0])):
if(len(grid)-j-1 < j):
break
if(grid[i][j] != grid[i][len(grid[i])-j-1]):
flag = False
if(flag and ans!=-1):
print('Yes')
else:
print('No')
# 1523803863385 | python | test | qsol | codeparrot/apps | all |
Solve in Python:
An integer partition of n is a weakly decreasing list of positive integers which sum to n.
For example, there are 7 integer partitions of 5:
[5], [4,1], [3,2], [3,1,1], [2,2,1], [2,1,1,1], [1,1,1,1,1].
Write a function named partitions which returns the number of integer partitions of n. The function should be able to find the number of integer partitions of n for n as least as large as 100. | def partitions(n, k=1, cache={}):
if k > n: return 0
if n == k: return 1
if (n,k) in cache: return cache[n,k]
return cache.setdefault((n,k), partitions(n, k+1) + partitions(n-k, k)) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/WGHTNUM:
VK gave a problem to Chef, but Chef is too lazy, so he asked you to solve the problem for him. The statement of the problem follows.
Consider an integer with $N$ digits (in decimal notation, without leading zeroes) $D_1, D_2, D_3, \dots, D_N$. Here, $D_1$ is the most significant digit and $D_N$ the least significant. The weight of this integer is defined as ∑i=2N(Di−Di−1).∑i=2N(Di−Di−1).\sum_{i=2}^N (D_i - D_{i-1})\,.
You are given integers $N$ and $W$. Find the number of positive integers with $N$ digits (without leading zeroes) and weight equal to $W$. Compute this number modulo $10^9+7$.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains two space-separated integers $N$ and $W$ denoting the number of digits and the required weight.
-----Output-----
For each test case, print a single line containing one integer — the number of $N$-digit positive integers with weight $W$, modulo $10^9+7$.
-----Constraints-----
- $1 \le T \le 10^5$
- $2 \le N \le 10^{18}$
- $|W| \le 300$
-----Subtasks-----
Subtask #1 (20 points):
- $1 \le T \le 10^3$
- $2 \le N \le 10^3$
Subtask #2 (80 points): original constraints
-----Example Input-----
1
2 3
-----Example Output-----
6
-----Explanation-----
Example case 1: Remember that the digits are arranged from most significant to least significant as $D_1, D_2$. The two-digit integers with weight $3$ are $14, 25, 36, 47, 58, 69$. For example, the weight of $14$ is $D_2-D_1 = 4-1 = 3$. We can see that there are no other possible numbers.
I tried it in Python, but could not do it. Can you solve it? | m = 10**9 + 7
def findNumbers(n, w):
x,s = 0,0
if (w >= 0 and w <= 8):
x = 9 - w;
elif (w >= -9 and w <= -1):
x = 10 + w;
s = (pow(10, n - 2,m)*(x%m));
return s%m;
for _ in range(int(input())):
n,w = map(int,input().split())
print(findNumbers(n,w)) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
In this kata, the number 0 is infected. You are given a list. Every turn, any item in the list that is adjacent to a 0 becomes infected and transforms into a 0. How many turns will it take for the whole list to become infected?
```
[0,1,1,0] ==> [0,0,0,0]
All infected in 1 turn.
[1,1,0,1,1] --> [1,0,0,0,1] --> [0,0,0,0,0]
All infected in 2 turns
[0,1,1,1] --> [0,0,1,1] --> [0,0,0,1] --> [0,0,0,0]
All infected in 3 turns.
```
All lists will contain at least one item, and at least one zero, and the only items will be 0s and 1s. Lists may be very very long, so pure brute force approach will not work. | def infected_zeroes(lst):
one = "".join(str(d) for d in lst).split("0")
return max(len(one[0]), len(one[-1]), *((len(o) + 1)//2 for o in one[1:-1])) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Fox Ciel is playing a game with numbers now.
Ciel has n positive integers: x_1, x_2, ..., x_{n}. She can do the following operation as many times as needed: select two different indexes i and j such that x_{i} > x_{j} hold, and then apply assignment x_{i} = x_{i} - x_{j}. The goal is to make the sum of all numbers as small as possible.
Please help Ciel to find this minimal sum.
-----Input-----
The first line contains an integer n (2 ≤ n ≤ 100). Then the second line contains n integers: x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 100).
-----Output-----
Output a single integer — the required minimal sum.
-----Examples-----
Input
2
1 2
Output
2
Input
3
2 4 6
Output
6
Input
2
12 18
Output
12
Input
5
45 12 27 30 18
Output
15
-----Note-----
In the first example the optimal way is to do the assignment: x_2 = x_2 - x_1.
In the second example the optimal sequence of operations is: x_3 = x_3 - x_2, x_2 = x_2 - x_1. | n = int(input())
a = list(map(int, input().split()))
while(1):
T = True
for i in range(n):
for j in range(n):
if a[i] > a[j]:
a[i] = a[i] - a[j]
T = False
elif a[i] < a[j]:
a[j] = a[j] - a[i]
T = False
if T:
break
print(sum(a)) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
- The string does not contain characters other than A, C, G and T.
- The string does not contain AGC as a substring.
- The condition above cannot be violated by swapping two adjacent characters once.
-----Notes-----
A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.
For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.
-----Constraints-----
- 3 \leq N \leq 100
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
-----Sample Input-----
3
-----Sample Output-----
61
There are 4^3 = 64 strings of length 3 that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is 64 - 3 = 61. | import numpy as np
N = int(input())
mod = 10**9+7
dp = np.zeros([N+1,4,4,4],dtype=int)
dp[0,-1,-1,-1] = 1
for i in range(N):
for c1 in range(4):
for c2 in range(4):
for c3 in range(4):
if not dp[i,c1,c2,c3]:continue
for a in range(4):
if c1 == 0 and c3 == 1 and a == 2:continue
if c1 == 0 and c2 == 1 and a == 2:continue
if c2 == 0 and c3 == 1 and a == 2:continue
if c2 == 0 and c3 == 2 and a == 1:continue
if c2 == 1 and c3 == 0 and a == 2:continue
dp[i+1,c2,c3,a] += dp[i,c1,c2,c3]
dp[i+1,c2,c3,a] %= mod
print(dp[-1].sum()%mod) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/search-a-2d-matrix/:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
I tried it in Python, but could not do it. Can you solve it? | class Solution:
def searchMatrix(self, matrix, target):
if not matrix or target is None:
return False
n = len(matrix[0])
lo, hi = 0, len(matrix) * n
while lo < hi:
mid = (lo + hi) / 2
x = matrix[int(mid/n)][int(mid%n)]
if x < target:
lo = mid + 1
elif x > target:
hi = mid
else:
return True
return False
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
""" | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5711fc7c159cde6ac70003e2:
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once.
Find all the combinations of n elements of the array that their sum are 0.
```python
arr = [1, -1, 2, 3, -2]
n = 3
find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0
```
The function should ouput every combination or group in increasing order.
We may have more than one group:
```python
arr = [1, -1, 2, 3, -2, 4, 5, -3 ]
n = 3
find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]]
```
In the case above the function should output a sorted 2D array.
The function will not give a group twice, or more, only once.
```python
arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ]
n = 3
find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]]
```
If there are no combinations with sum equals to 0, the function will output an alerting message.
```python
arr = [1, 1, 2, 3]
n = 2
find_zero_sum_groups(arr, n) == "No combinations"
```
If the function receives an empty array will output an specific alert:
```python
arr = []
n = 2
find_zero_sum_groups(arr, n) == "No elements to combine"
```
As you have seen the solutions may have a value occurring only once.
Enjoy it!
I tried it in Python, but could not do it. Can you solve it? | from itertools import combinations
def find_zero_sum_groups(a, n):
li = sorted(map(sorted,filter(lambda x:sum(x)==0,combinations(set(a),n))))
return li if len(li)>1 else li[0] if li else "No combinations" if a else "No elements to combine" | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/SEBIHWY:
Sebi goes to school daily with his father. They cross a big highway in the car to reach to the school. Sebi sits in front seat beside his father at driving seat. To kill boredom, they play a game of guessing speed of other cars on the highway. Sebi makes a guess of other car's speed being SG kph, his father FG kph.
The highway is usually empty, so the drivers use cruise control, i.e. vehicles run at a constant speed. There are markers on the highway at a gap of 50 meters. Both father-son duo wants to check the accuracy of their guesses. For that, they start a timer at the instant at which their car and the other car (which speed they are guessing) are parallel to each other (they need not to be against some marker, they can be in between the markers too). After some T seconds, they observe that both the cars are next to some markers and the number of markers in between the markers of their car and the other car is D - 1 (excluding the markers next to both the cars). Also, they can observe these markers easily because the other car is faster than their. Speed of Sebi's father's car is S. Using this information, one can find the speed of the other car accurately.
An example situation when Sebi's father starts the timer. Notice that both the car's are parallel to each other.
Example situation after T seconds. The cars are next to the markers. Here the value of D is 1. The green car is Sebi's and the other car is of blue color.
Sebi's a child, he does not know how to find the check whose guess is close to the real speed of the car. He does not trust his father as he thinks that he might cheat. Can you help to resolve this issue between them by telling whose guess is closer. If Sebi's guess is better, output "SEBI". If his father's guess is better, output "FATHER". If both the guess are equally close, then output "DRAW".
-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
Each of the next T lines contain five space separated integers S, SG, FG, D, T...
I tried it in Python, but could not do it. Can you solve it? | # cook your dish here
n=int(input())
for i in range(n):
S, SG, FG, D, T = map(int, input().split())
speed = (D*180)/T + S
if abs(SG-speed) == abs(FG-speed):
print('DRAW')
elif abs(SG-speed) > abs(FG-speed):
print('FATHER')
else:
print('SEBI') | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
A *[Hamming number][1]* is a positive integer of the form 2*i*3*j*5*k*, for some non-negative integers *i*, *j*, and *k*.
Write a function that computes the *n*th smallest Hamming number.
Specifically:
- The first smallest Hamming number is 1 = 2^(0)3^(0)5^(0)
- The second smallest Hamming number is 2 = 2^(1)3^(0)5^(0)
- The third smallest Hamming number is 3 = 2^(0)3^(1)5^(0)
- The fourth smallest Hamming number is 4 = 2^(2)3^(0)5^(0)
- The fifth smallest Hamming number is 5 = 2^(0)3^(0)5^(1)
The 20 smallest Hamming numbers are given in example test fixture.
Your code should be able to compute all of the smallest 5,000 (Clojure: 2000, NASM: 13282) Hamming numbers without timing out.
[1]:https://en.wikipedia.org/wiki/Regular_number | def hamming(n):
bases = [2, 3, 5]
expos = [0, 0, 0]
hamms = [1]
for _ in range(1, n):
next_hamms = [bases[i] * hamms[expos[i]] for i in range(3)]
next_hamm = min(next_hamms)
hamms.append(next_hamm)
for i in range(3):
expos[i] += int(next_hamms[i] == next_hamm)
return hamms[-1] | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Takahashi is standing on a multiplication table with infinitely many rows and columns.
The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).
In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).
Given an integer N, find the minimum number of moves needed to reach a square that contains N.
-----Constraints-----
- 2 \leq N \leq 10^{12}
- N is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the minimum number of moves needed to reach a square that contains the integer N.
-----Sample Input-----
10
-----Sample Output-----
5
(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves. | N = int(input())
N_ri = round(pow(N, 1/2))
for i in range(N_ri, 0, -1):
if N % i == 0:
j = N // i
break
print(i + j - 2) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/802/A:
Your search for Heidi is over – you finally found her at a library, dressed up as a human. In fact, she has spent so much time there that she now runs the place! Her job is to buy books and keep them at the library so that people can borrow and read them. There are n different books, numbered 1 through n.
We will look at the library's operation during n consecutive days. Heidi knows in advance that on the i-th day (1 ≤ i ≤ n) precisely one person will come to the library, request to borrow the book a_{i}, read it in a few hours, and return the book later on the same day.
Heidi desperately wants to please all her guests, so she will make sure to always have the book a_{i} available in the library on the i-th day. During the night before the i-th day, she has the option of going to the bookstore (which operates at nights to avoid competition with the library) and buying any book for the price of 1 CHF. Of course, if she already has a book at the library, she does not need to buy it again. Initially, the library contains no books.
There is a problem, though. The capacity of the library is k – this means that at any time, there can be at most k books at the library. If buying a new book would cause Heidi to have more than k books, she must first get rid of some book that she already has, in order to make room for the new book. If she later needs a book that she got rid of, she will need to buy that book again.
You are given k and the sequence of requests for books a_1, a_2, ..., a_{n}. What is the minimum cost (in CHF) of buying new books to satisfy all the requests?
-----Input-----
The first line of input will contain two integers n and k (1 ≤ n, k ≤ 80). The second line will contain n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) – the sequence of book requests.
-----Output-----
On a single line print the minimum cost of buying books at the store so as to satisfy all requests.
-----Examples-----
Input
4 80
1 2 2 1
Output
2
Input
4 1
1 2 2 1
Output
3
Input
4 2
1 2 3...
I tried it in Python, but could not do it. Can you solve it? | n, k = [int(x) for x in input().split()]
requests = [int(x) for x in input().split()]
req_list = {}
def find_last(bucket):
last_book = None
last_date = None
nonlocal req_list
i = 0
for item in bucket:
#print(item, req_list)
if last_book is None:
last_book = item
if len(req_list[item]) < 1:
last_date = float('inf')
return item, i
else:
last_date = req_list[item][0]
index = i
elif len(req_list[item]) >= 1 and req_list[item][0] > last_date:
last_book = item
last_date = req_list[item][0]
index = i
elif len(req_list[item]) < 1 and last_date < float('inf'):
return item, i
i += 1
return last_book, index
def update_reqlist(book):
nonlocal req_list
req_list[book] = req_list[book][1:]
for i in range(n):
if requests[i] in req_list:
req_list[requests[i]].append(i)
else:
req_list[requests[i]] = [i]
bucket = []
bucket_size = 0
cost = 0
for book in requests:
if book in bucket:
update_reqlist(book)
continue
if bucket_size < k:
bucket.append(book)
bucket_size += 1
cost += 1
update_reqlist(book)
else:
last_book, index = find_last(bucket)
if len(bucket) > 1:
bucket.pop(index)
else:
bucket = []
bucket.append(book)
update_reqlist(book)
cost += 1
#print(bucket, req_list)
#print(req_list)
print(cost) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
[Image]
-----Input-----
The input contains a single integer $a$ ($0 \le a \le 15$).
-----Output-----
Output a single integer.
-----Example-----
Input
3
Output
13 | n = int(input())
a = [0] * 4
i = 0
for i in range(4):
a[i] = n % 2
n = n // 2
a[3] = a[3] ^ 1
a[2] = a[3] ^ a[2]
a[1] = (a[3] and a[2]) ^ a[1]
a[0] = (a[3] and a[2] and a[1]) ^ a[0]
sum_ = 0
for i in range(4):
sum_ += a[i] * 2 ** i
print(sum_) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
# Task
Consider the following algorithm for constructing 26 strings S(1) .. S(26):
```
S(1) = "a";
For i in [2, 3, ..., 26]:
S(i) = S(i - 1) + character(i) + S(i - 1).```
For example:
```
S(1) = "a"
S(2) = S(1) + "b" + S(1) = "a" + "b" + "a" = "aba"
S(3) = S(2) + "c" + S(2) = "aba" + "c" +"aba" = "abacaba"
...
S(26) = S(25) + "z" + S(25)```
Finally, we got a long string S(26). Your task is to find the `k`th symbol (indexing from 1) in the string S(26). All strings consist of lowercase letters only.
# Input / Output
- `[input]` integer `k`
1 ≤ k < 2^(26)
- `[output]` a string(char in C#)
the `k`th symbol of S(26) | def abacaba(k):
alph = 'abcdefghijklmnopqrstuvwxyz'
s = ''
for i in range(26):
s = s + alph[i] + s
return s[k-1] | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc177/tasks/abc177_b:
Given are two strings S and T.
Let us change some of the characters in S so that T will be a substring of S.
At least how many characters do we need to change?
Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.
-----Constraints-----
- The lengths of S and T are each at least 1 and at most 1000.
- The length of T is at most that of S.
- S and T consist of lowercase English letters.
-----Input-----
Input is given from Standard Input in the following format:
S
T
-----Output-----
Print the minimum number of characters in S that need to be changed.
-----Sample Input-----
cabacc
abc
-----Sample Output-----
1
For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.
Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.
I tried it in Python, but could not do it. Can you solve it? | s=input()
t=input()
ls=len(s)
lt=len(t)
ans=ls
for i in range(ls-lt+1):
cnt=0
for j in range(lt):
if s[i+j]!=t[j]:
cnt+=1
ans=min(ans,cnt)
print(ans) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Vasya and Petya wrote down all integers from 1 to n to play the "powers" game (n can be quite large; however, Vasya and Petya are not confused by this fact).
Players choose numbers in turn (Vasya chooses first). If some number x is chosen at the current turn, it is forbidden to choose x or all of its other positive integer powers (that is, x^2, x^3, ...) at the next turns. For instance, if the number 9 is chosen at the first turn, one cannot choose 9 or 81 later, while it is still allowed to choose 3 or 27. The one who cannot make a move loses.
Who wins if both Vasya and Petya play optimally?
-----Input-----
Input contains single integer n (1 ≤ n ≤ 10^9).
-----Output-----
Print the name of the winner — "Vasya" or "Petya" (without quotes).
-----Examples-----
Input
1
Output
Vasya
Input
2
Output
Petya
Input
8
Output
Petya
-----Note-----
In the first sample Vasya will choose 1 and win immediately.
In the second sample no matter which number Vasya chooses during his first turn, Petya can choose the remaining number and win. | from sys import stdin, stdout
import math, collections
mod = 10**9+7
def isPower(n):
if (n <= 1):
return True
for x in range(2, (int)(math.sqrt(n)) + 1):
p = x
while (p <= n):
p = p * x
if (p == n):
return True
return False
n = int(input())
arr = [0,1,2,1,4,3,2,1,5,6,2,1,8,7,5,9,8,7,3,4,7,4,2,1,10,9,3,6,11,12]
ans = arr[int(math.log(n, 2))]
s = int(math.log(n, 2))
for i in range(3, int(n**0.5)+1):
if not isPower(i):
ans^=arr[int(math.log(n, i))]
s+=int(math.log(n, i))
ans^=((n-s)%2)
print("Vasya" if ans else "Petya") | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/ZCOPRAC/problems/ZCO14002:
Zonal Computing Olympiad 2014, 30 Nov 2013
In ICO School, all students have to participate regularly in SUPW. There is a different SUPW activity each day, and each activity has its own duration. The SUPW schedule for the next term has been announced, including information about the number of minutes taken by each activity.
Nikhil has been designated SUPW coordinator. His task is to assign SUPW duties to students, including himself. The school's rules say that no student can go three days in a row without any SUPW duty.
Nikhil wants to find an assignment of SUPW duty for himself that minimizes the number of minutes he spends overall on SUPW.
-----Input format-----
Line 1: A single integer N, the number of days in the future for which SUPW data is available.
Line 2: N non-negative integers, where the integer in position i represents the number of minutes required for SUPW work on day i.
-----Output format-----
The output consists of a single non-negative integer, the minimum number of minutes that Nikhil needs to spend on SUPW duties this term
-----Sample Input 1-----
10
3 2 1 1 2 3 1 3 2 1
-----Sample Output 1-----
4
(Explanation: 1+1+1+1)
-----Sample Input 2-----
8
3 2 3 2 3 5 1 3
-----Sample Output 2-----
5
(Explanation: 2+2+1)
-----Test data-----
There is only one subtask worth 100 marks. In all inputs:
• 1 ≤ N ≤ 2×105
• The number of minutes of SUPW each day is between 0 and
104, inclusive.
-----Live evaluation data-----
There are 12 test inputs on the server during the exam.
I tried it in Python, but could not do it. Can you solve it? | dp = [-1] * int(1e6)
def solve(nums, n) :
if n < 2 : return 0
if dp[n] != - 1 : return dp[n]
dp[n] = min( nums[n] + solve(nums, n - 1),
nums[n - 1] + solve(nums, n - 2),
nums[n - 2] + solve(nums, n - 3)
)
return dp[n]
def main():
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(int(5e5))
N = int(input())
hours = list(map(int, input().split()))
solution = solve(hours, N - 1)
print(solution)
main() | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1436/C:
Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number $x$ in an array. For an array $a$ indexed from zero, and an integer $x$ the pseudocode of the algorithm is as follows:
BinarySearch(a, x)
left = 0
right = a.size()
while left < right
middle = (left + right) / 2
if a[middle] <= x then
left = middle + 1
else
right = middle
if left > 0 and a[left - 1] == x then
return true
else
return false
Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down).
Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find $x$!
Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size $n$ such that the algorithm finds $x$ in them. A permutation of size $n$ is an array consisting of $n$ distinct integers between $1$ and $n$ in arbitrary order.
Help Andrey and find the number of permutations of size $n$ which contain $x$ at position $pos$ and for which the given implementation of the binary search algorithm finds $x$ (returns true). As the result may be extremely large, print the remainder of its division by $10^9+7$.
-----Input-----
The only line of input contains integers $n$, $x$ and $pos$ ($1 \le x \le n \le 1000$, $0 \le pos \le n - 1$) — the required length of the permutation, the number to search, and the required position of that number, respectively.
-----Output-----
Print a single number — the remainder of the division of the number of valid permutations by $10^9+7$.
-----Examples-----
Input
4 1 2
Output
6
Input
123 42 24
Output
824071958
-----Note-----
All possible permutations in the first test case: $(2, 3, 1, 4)$, $(2, 4, 1, 3)$, $(3, 2,...
I tried it in Python, but could not do it. Can you solve it? | import sys
input = sys.stdin.readline
MOD = 10 ** 9 + 7
N = 2000
fact = [0 for _ in range(N)]
invfact = [0 for _ in range(N)]
fact[0] = 1
for i in range(1, N):
fact[i] = fact[i - 1] * i % MOD
invfact[N - 1] = pow(fact[N - 1], MOD - 2, MOD)
for i in range(N - 2, -1, -1):
invfact[i] = invfact[i + 1] * (i + 1) % MOD
def nCk(n, k):
if k < 0 or n < k:
return 0
else:
return fact[n] * invfact[k] * invfact[n - k] % MOD
def main():
n, x, pos = map(int, input().split())
b = 0
s = 0
l = 0
r = n
while l < r:
m = (l + r) // 2
if m <= pos:
l = m + 1
if m != pos:
s += 1
else:
r = m
if m != pos:
b += 1
b_cnt = n - x
s_cnt = x - 1
c = n - 1 - b - s
ans = fact[c] * nCk(b_cnt, b) * nCk(s_cnt, s) * fact[b] * fact[s]
print(ans % MOD)
for _ in range(1):
main() | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Story:
In the realm of numbers, the apocalypse has arrived. Hordes of zombie numbers have infiltrated and are ready to turn everything into undead. The properties of zombies are truly apocalyptic: they reproduce themselves unlimitedly and freely interact with each other. Anyone who equals them is doomed. Out of an infinite number of natural numbers, only a few remain. This world needs a hero who leads remaining numbers in hope for survival: The highest number to lead those who still remain.
Briefing:
There is a list of positive natural numbers. Find the largest number that cannot be represented as the sum of this numbers, given that each number can be added unlimited times. Return this number, either 0 if there are no such numbers, or -1 if there are an infinite number of them.
Example:
```
Let's say [3,4] are given numbers. Lets check each number one by one:
1 - (no solution) - good
2 - (no solution) - good
3 = 3 won't go
4 = 4 won't go
5 - (no solution) - good
6 = 3+3 won't go
7 = 3+4 won't go
8 = 4+4 won't go
9 = 3+3+3 won't go
10 = 3+3+4 won't go
11 = 3+4+4 won't go
13 = 3+3+3+4 won't go
```
...and so on. So 5 is the biggest 'good'. return 5
Test specs:
Random cases will input up to 10 numbers with up to 1000 value
Special thanks:
Thanks to Voile-sama, mathsisfun-sama, and Avanta-sama for heavy assistance. And to everyone who tried and beaten the kata ^_^ | from functools import reduce
from math import gcd
def survivor(a):
"""Round Robin by Bocker & Liptak"""
def __residue_table(a):
n = [0] + [None] * (a[0] - 1)
for i in range(1, len(a)):
d = gcd(a[0], a[i])
for r in range(d):
try:
nn = min(n[q] for q in range(r, a[0], d) if n[q] is not None)
except ValueError:
continue
for _ in range(a[0] // d):
nn += a[i]
p = nn % a[0]
if n[p] is not None: nn = min(nn, n[p])
n[p] = nn
return n
a.sort()
if len(a) < 1 or reduce(gcd, a) > 1: return -1
if a[0] == 1: return 0
return max(__residue_table(a)) - a[0] | python | train | qsol | codeparrot/apps | all |
Solve in Python:
There is a tree with N vertices numbered 1 through N.
The i-th edge connects Vertex x_i and y_i.
Each vertex is painted white or black.
The initial color of Vertex i is represented by a letter c_i.
c_i = W represents the vertex is white; c_i = B represents the vertex is black.
A cat will walk along this tree.
More specifically, she performs one of the following in one second repeatedly:
- Choose a vertex that is adjacent to the vertex where she is currently, and move to that vertex. Then, invert the color of the destination vertex.
- Invert the color of the vertex where she is currently.
The cat's objective is to paint all the vertices black. She may start and end performing actions at any vertex.
At least how many seconds does it takes for the cat to achieve her objective?
-----Constraints-----
- 1 ≤ N ≤ 10^5
- 1 ≤ x_i,y_i ≤ N (1 ≤ i ≤ N-1)
- The given graph is a tree.
- c_i = W or c_i = B.
-----Input-----
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N-1} y_{N-1}
c_1c_2..c_N
-----Output-----
Print the minimum number of seconds required to achieve the objective.
-----Sample Input-----
5
1 2
2 3
2 4
4 5
WBBWW
-----Sample Output-----
5
The objective can be achieved in five seconds, for example, as follows:
- Start at Vertex 1. Change the color of Vertex 1 to black.
- Move to Vertex 2, then change the color of Vertex 2 to white.
- Change the color of Vertex 2 to black.
- Move to Vertex 4, then change the color of Vertex 4 to black.
- Move to Vertex 5, then change the color of Vertex 5 to black. | from collections import deque
def first_cut(links, colors):
tmp_links = links.copy()
for v, neighbors in list(tmp_links.items()):
while len(neighbors) == 1 and colors[v]:
del links[v]
par = neighbors.pop()
links[par].remove(v)
v = par
neighbors = links[par]
return links
def diameter(links, flags):
def dfs(s):
fs = flags[s]
d, v = 0, 0
q = deque(sorted((fs + flags[v], v, s) for v in links[s]))
while q:
d, v, a = q.popleft()
for u in links[v]:
if u == a:
continue
fu = flags[u]
if fu:
q.append((d + 1, u, v))
else:
q.appendleft((d, u, v))
return d, v
s = next(iter(links))
_, t = dfs(s)
d, _ = dfs(t)
return d
def solve(links, colors):
if all(colors):
return 0
links = first_cut(links, colors)
k = len(links)
if k == 1:
return 1
flags = {v: colors[v] ^ (len(link) % 2 == 0) for v, link in list(links.items())}
euler_tour = 2 * (k - 1) + sum(flags.values())
return euler_tour - 2 * diameter(links, flags)
n = int(input())
links = {i: set() for i in range(n)}
for _ in range(n - 1):
x, y = list(map(int, input().split()))
x -= 1
y -= 1
links[x].add(y)
links[y].add(x)
colors = [c == 'B' for c in input()]
print((solve(links, colors))) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Write a function generator that will generate the first `n` primes grouped in tuples of size `m`. If there are not enough primes for the last tuple it will have the remaining values as `None`.
## Examples
```python
For n = 11 and m = 2:
(2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, None)
For n = 11 and m = 3:
(2, 3, 5), (7, 11, 13), (17, 19, 23), (29, 31, None)
For n = 11 and m = 5:
(2, 3, 5, 7, 11), (13, 17, 19, 23, 29), (31, None, None, None, None)]
For n = 3 and m = 1:
(2,), (3,), (5,)
```
Note: large numbers of `n` will be tested, up to 50000 | # generate primes up to limit
LIMIT = 10**6
sieve = [0]*2 + list(range(2, LIMIT))
for n in sieve:
if n:
for i in range(n*n, LIMIT, n):
sieve[i] = 0
PRIMES = list(n for n in sieve if n)
def get_primes(n, m=2):
primes_ = PRIMES[:n] + [None] * m
return ( tuple(primes_[i:i+m]) for i in range(0, n, m) ) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Given an array $A$ of size $N$ , count number of pairs of index $i,j$ such that $A_i$ is even, $A_j$ is odd and $i < j$
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases.
- The first line of each test case contains integer $N$.
- The second line of each test case contains $N$ space separated integers $A_i$.
-----Output-----
For each test case, print a single line containing an integer denoting number of pairs.
-----Constraints-----
- $1 \le T \le 100$
- $2 \le N \le 10^5$
- $1 \le A_i \le 10^9$
- Sum of $N$ over all test cases doesn't exceed $10^6 $
-----Subtasks-----
Subtask #1 (30 points):
- $2 \le N \le 100$
Subtask #2 (70 points): original constraints
-----Example Input-----
2
4
1 2 1 3
5
5 4 1 2 3
-----Example Output-----
2
3
-----Explanation-----
Example case 1:$(A_2,A_3)$ and $(A_2,A_4)$ .
Example case 2:$(A_2,A_3)$ , $(A_2,A_5)$ and $(A_4,A_5)$ . | for i in range(int(input())):
n = int(input())
l = list(map(int,input().split()))
c = p = 0
for i in range(n):
if l[i]%2==0:
c+=1
else:
p+=c
print(p) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions: Only segments already presented on the picture can be painted; The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment; The numbers of points from the beginning of the tail to the end should strictly increase.
Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.
Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.
-----Input-----
First line of the input contains two integers n and m(2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number segments on the picture respectively.
Then follow m lines, each containing two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.
-----Output-----
Print the maximum possible value of the hedgehog's beauty.
-----Examples-----
Input
8 6
4 5
3 5
2 5
1 2
2 8
6 7
Output
9
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
12
-----Note-----
The picture below... | def main():
n, m = [int(t) for t in input().split()]
edge_count = [0 for _ in range(n)]
tail_length = [0 for _ in range(n)]
adj_list = [set() for _ in range(n)]
for _ in range(m):
u, v = [int(t) - 1 for t in input().split()]
edge_count[u] += 1
edge_count[v] += 1
adj_list[u].add(v)
adj_list[v].add(u)
tail_length[0] = 1
beauty = tail_length[0] * edge_count[0]
for u in range(1, n):
candidate_tail_lengths = [tail_length[v] + 1 for v in adj_list[u] if v < u]
if len(candidate_tail_lengths) != 0:
tail_length[u] = max(candidate_tail_lengths)
else:
tail_length[u] = 1
beauty = max(beauty, tail_length[u] * edge_count[u])
print(beauty)
def __starting_point():
main()
__starting_point() | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/740/A:
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of three copybooks for c rubles. Alyona already has n copybooks.
What is the minimum amount of rubles she should pay to buy such number of copybooks k that n + k is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase.
-----Input-----
The only line contains 4 integers n, a, b, c (1 ≤ n, a, b, c ≤ 10^9).
-----Output-----
Print the minimum amount of rubles she should pay to buy such number of copybooks k that n + k is divisible by 4.
-----Examples-----
Input
1 1 3 4
Output
3
Input
6 2 1 1
Output
1
Input
4 4 4 4
Output
0
Input
999999999 1000000000 1000000000 1000000000
Output
1000000000
-----Note-----
In the first example Alyona can buy 3 packs of 1 copybook for 3a = 3 rubles in total. After that she will have 4 copybooks which she can split between the subjects equally.
In the second example Alyuna can buy a pack of 2 copybooks for b = 1 ruble. She will have 8 copybooks in total.
In the third example Alyona can split the copybooks she already has between the 4 subject equally, so she doesn't need to buy anything.
In the fourth example Alyona should buy one pack of one copybook.
I tried it in Python, but could not do it. Can you solve it? | """
ATSTNG's ejudge Python3 solution template
(actual solution is below)
"""
import sys, queue
try:
import dev_act_ffc429465ab634 # empty file in directory
DEV = True
except:
DEV = False
def log(*s):
if DEV: print('LOG', *s)
class EJudge:
def __init__(self, problem="default", reclim=1<<30):
self.problem = problem
sys.setrecursionlimit(reclim)
def use_files(self, infile='', outfile=''):
if infile!='':
self.infile = open(infile)
sys.stdin = self.infile
if infile!='':
self.outfile = open(outfile, 'w')
sys.stdout = self.outfile
def use_bacs_files(self):
self.use_files(self.problem+'.in', self.problem+'.out')
def get_tl(self):
while True: pass
def get_ml(self):
tmp = [[[5]*100000 for _ in range(1000)]]
while True: tmp.append([[5]*100000 for _ in range(1000)])
def get_re(self):
s = (0,)[8]
def get_wa(self, wstr='blablalblah'):
for _ in range(3): print(wstr)
return
class IntReader:
def __init__(self):
self.ost = queue.Queue()
def get(self):
return int(self.sget())
def sget(self):
if self.ost.empty():
for el in input().split():
self.ost.put(el)
return self.ost.get()
def release(self):
res = []
while not self.ost.empty():
res.append(self.ost.get())
return res
###############################################################################
ej = EJudge( )
int_reader = IntReader()
fmap = lambda f,*l: list(map(f,*l))
parse_int = lambda: fmap(int, input().split())
# input
n,t1,t2,t3 = parse_int()
t3 = min(t3, t2+t1, t1*3)
t2 = min(t2, t1*2, t3*2)
t1 = min(t1, t3+t2, t3*3)
n = n%4
if n==0: ans = 0
if n==1: ans = t3
if n==2: ans = t2
if n==3: ans = t1
print(ans) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5a4a391ad8e145cdee0000c4:
Similarly to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-i/), you will need to return a boolean value if the base string can be expressed as the repetition of one subpattern.
This time there are two small changes:
* if a subpattern has been used, it will be repeated at least twice, meaning the subpattern has to be shorter than the original string;
* the strings you will be given might or might not be created repeating a given subpattern, then shuffling the result.
For example:
```python
has_subpattern("a") == False #no repeated shorter sub-pattern, just one character
has_subpattern("aaaa") == True #just one character repeated
has_subpattern("abcd") == False #no repetitions
has_subpattern("babababababababa") == True #repeated "ba"
has_subpattern("bbabbaaabbaaaabb") == True #same as above, just shuffled
```
Strings will never be empty and can be composed of any character (just consider upper- and lowercase letters as different entities) and can be pretty long (keep an eye on performances!).
If you liked it, go for either the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-i/) or the [next kata](https://www.codewars.com/kata/string-subpattern-recognition-iii/) of the series!
I tried it in Python, but could not do it. Can you solve it? | from collections import Counter
from functools import reduce
from math import gcd
def has_subpattern(string):
return reduce(gcd, Counter(string).values()) != 1 | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/590bdaa251ab8267b800005b:
# Task
Consider an array of integers `a`. Let `min(a)` be its minimal element, and let `avg(a)` be its mean.
Define the center of the array `a` as array `b` such that:
```
- b is formed from a by erasing some of its elements.
- For each i, |b[i] - avg(a)| < min(a).
- b has the maximum number of elements among all the arrays
satisfying the above requirements.
```
Given an array of integers, return its center.
# Input/Output
`[input]` integer array `a`
Unsorted non-empty array of integers.
`2 ≤ a.length ≤ 50,`
`1 ≤ a[i] ≤ 350.`
`[output]` an integer array
# Example
For `a = [8, 3, 4, 5, 2, 8]`, the output should be `[4, 5]`.
Here `min(a) = 2, avg(a) = 5`.
For `a = [1, 3, 2, 1]`, the output should be `[1, 2, 1]`.
Here `min(a) = 1, avg(a) = 1.75`.
I tried it in Python, but could not do it. Can you solve it? | from statistics import mean
def array_center(arr):
low, avg = min(arr), mean(arr)
return [b for b in arr if abs(b - avg) < low] | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
-----Input-----
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c_1, c_2, ..., c_{k} (1 ≤ c_{i} ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n). This denotes an undirected edge between nodes u_{i} and v_{i}.
It is guaranteed that the graph described by the input is stable.
-----Output-----
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
-----Examples-----
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
-----Note-----
For the first sample test, the graph looks like this: [Image] Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this: $\infty$ We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must... | n,m,c=list(map(int,input().split()))
l=list(map(int,input().split()))
qa=n
d=[[] for i in range(n+1)]
Visited=[False for i in range(n+1)]
f=0
L=[]
for i in range(m) :
a,b=list(map(int,input().split()))
d[a].append(b)
d[b].append(a)
L.append([a,b])
ma=0
d1={}
for x in l:
q=[x]
r=0
t=0
while q :
v=q[0]
r+=1
Visited[v]=True
t+=len(d[v])
for y in d[v] :
if Visited[y]==False :
q.append(y)
Visited[y]=True
del q[0]
qa-=r
d1[r]=d1.get(r,[])+[t]
for x in L :
if Visited[x[0]]==Visited[x[1]]==False :
f+=1
rr=True
y=sorted(d1,reverse=True)
out=-f
for x in y :
for e in d1[x] :
if rr :
u=qa+x
out+=u*(u-1)//2-e//2
rr=False
else :
out+=x*(x-1)//2-e//2
print(out) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5e602796017122002e5bc2ed:
**The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.
Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.
Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)
**Example**
```python
o = partial_keys({"abcd": 1})
o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true
o['b'] == 1 # false!
o['b'] == None # true
list(o.keys()) # ['abcd']
```
I tried it in Python, but could not do it. Can you solve it? | class partial_keys(dict):
def __getitem__(self, key):
keys = sorted(k for k in self.keys() if k.startswith(key))
if keys: return super().__getitem__(keys[0]) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/401/C:
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that: there wouldn't be a pair of any side-adjacent cards with zeroes in a row; there wouldn't be a group of three consecutive cards containing numbers one.
Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.
-----Input-----
The first line contains two integers: n (1 ≤ n ≤ 10^6) — the number of cards containing number 0; m (1 ≤ m ≤ 10^6) — the number of cards containing number 1.
-----Output-----
In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.
-----Examples-----
Input
1 2
Output
101
Input
4 8
Output
110110110101
Input
4 10
Output
11011011011011
Input
1 5
Output
-1
I tried it in Python, but could not do it. Can you solve it? | from math import ceil
n, m = list(map(int, input().split()))
s1 = ""
s2 = ""
if not (n-1 <= m and m <= 2 * (n+1)):
print(-1)
elif m == n-1:
print("01"*m+"0")
elif m == n:
print("10"*m)
else:
s1 = "10"*n+"1"
for i in s1:
s2 += i
if i == "1" and m-n-1:
s2 += "1"
m -= 1
print(s2) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5503013e34137eeeaa001648:
Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help.
## Task
You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (`*`) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (`\n`).
Return `null/nil/None/...` if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.
## Examples
A size 3 diamond:
```
*
***
*
```
...which would appear as a string of `" *\n***\n *\n"`
A size 5 diamond:
```
*
***
*****
***
*
```
...that is: `" *\n ***\n*****\n ***\n *\n"`
I tried it in Python, but could not do it. Can you solve it? | def diamond(n):
if n < 0 or n % 2 == 0:
return None
result = "*" * n + "\n";
spaces = 1;
n = n - 2
while n > 0:
current = " " * spaces + "*" * n + "\n"
spaces = spaces + 1
n = n - 2
result = current + result + current
return result | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
In Russia regular bus tickets usually consist of 6 digits. The ticket is called lucky when the sum of the first three digits equals to the sum of the last three digits. Write a function to find out whether the ticket is lucky or not. Return true if so, otherwise return false. Consider that input is always a string. Watch examples below. | def is_lucky(ticket):
try:
if ticket == '':
return False
else:
idk = [int(x) for x in ticket]
first = sum(idk[0:3])
second = sum(idk[3:6])
if first == second:
return True
else:
return False
except:
return False | python | train | qsol | codeparrot/apps | all |
Solve in Python:
To decide which is the strongest among Rock, Paper, and Scissors, we will hold an RPS tournament.
There are 2^k players in this tournament, numbered 0 through 2^k-1. Each player has his/her favorite hand, which he/she will use in every match.
A string s of length n consisting of R, P, and S represents the players' favorite hands.
Specifically, the favorite hand of Player i is represented by the ((i\text{ mod } n) + 1)-th character of s; R, P, and S stand for Rock, Paper, and Scissors, respectively.
For l and r such that r-l is a power of 2, the winner of the tournament held among Players l through r-1 will be determined as follows:
- If r-l=1 (that is, there is just one player), the winner is Player l.
- If r-l\geq 2, let m=(l+r)/2, and we hold two tournaments, one among Players l through m-1 and the other among Players m through r-1. Let a and b be the respective winners of these tournaments. a and b then play a match of rock paper scissors, and the winner of this match - or a if the match is drawn - is the winner of the tournament held among Players l through r-1.
Find the favorite hand of the winner of the tournament held among Players 0 through 2^k-1.
-----Notes-----
- a\text{ mod } b denotes the remainder when a is divided by b.
- The outcome of a match of rock paper scissors is determined as follows:
- If both players choose the same hand, the match is drawn;
- R beats S;
- P beats R;
- S beats P.
-----Constraints-----
- 1 \leq n,k \leq 100
- s is a string of length n consisting of R, P, and S.
-----Input-----
Input is given from Standard Input in the following format:
n k
s
-----Output-----
Print the favorite hand of the winner of the tournament held among Players 0 through 2^k-1, as R, P, or S.
-----Sample Input-----
3 2
RPS
-----Sample Output-----
P
- The favorite hand of the winner of the tournament held among Players 0 through 1 is P.
- The favorite hand of the winner of the tournament held among Players 2 through 3 is R.
- The favorite hand of the winner of the tournament held... | n, k = list(map(int, input().split()))
s = list(input()[::-1]) * 2
ptn, win = 'PR_RP_PP_RS_SR_RR_SP_PS_SS', 'PRS'
for _ in range(k):
tmp = []
while s:
hand = ptn.index(s.pop() + s.pop())
tmp.append(win[hand // 9])
s = tmp[::-1] * 2
print((s.pop())) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces.
You are asked to calculate the number of ways he can do it. Two ways to break chocolate are considered distinct if one of them contains a break between some two adjacent pieces and the other one doesn't.
Please note, that if Bob doesn't make any breaks, all the bar will form one piece and it still has to have exactly one nut.
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 100) — the number of pieces in the chocolate bar.
The second line contains n integers a_{i} (0 ≤ a_{i} ≤ 1), where 0 represents a piece without the nut and 1 stands for a piece with the nut.
-----Output-----
Print the number of ways to break the chocolate into multiple parts so that each part would contain exactly one nut.
-----Examples-----
Input
3
0 1 0
Output
1
Input
5
1 0 1 0 1
Output
4
-----Note-----
In the first sample there is exactly one nut, so the number of ways equals 1 — Bob shouldn't make any breaks.
In the second sample you can break the bar in four ways:
10|10|1
1|010|1
10|1|01
1|01|01 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
# = input()
n = int(input())
a = [int(i) for i in input().split()]
start = time.time()
s = sum(a)
if s == 0:
ans = 0
elif s == 1:
ans = 1
else:
ans = 1
l = 0
while( a[l] != 1):
l += 1
r = l
while(r < n-1):
r += 1
if a[r] == 1:
ans *= (r-l)
l = r
print(ans)
finish = time.time()
#print(finish - start) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
Example:
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. | class Solution:
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
if n ==1:
return [["Q"]]
elif n==2 or n==3:
return []
elif n==4:
return [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
elif n ==5:
return [["Q....","..Q..","....Q",".Q...","...Q."],["Q....","...Q.",".Q...","....Q","..Q.."],[".Q...","...Q.","Q....","..Q..","....Q"],[".Q...","....Q","..Q..","Q....","...Q."],["..Q..","Q....","...Q.",".Q...","....Q"],["..Q..","....Q",".Q...","...Q.","Q...."],["...Q.","Q....","..Q..","....Q",".Q..."],["...Q.",".Q...","....Q","..Q..","Q...."],["....Q",".Q...","...Q.","Q....","..Q.."],["....Q","..Q..","Q....","...Q.",".Q..."]]
elif n == 6:
return [[".Q....","...Q..",".....Q","Q.....","..Q...","....Q."],["..Q...",".....Q",".Q....","....Q.","Q.....","...Q.."],["...Q..","Q.....","....Q.",".Q....",".....Q","..Q..."],["....Q.","..Q...","Q.....",".....Q","...Q..",".Q...."]]
elif n == 7:
return... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/662/D:
International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.
For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.
You are given a list of abbreviations. For each of them determine the year it stands for.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process.
Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.
-----Output-----
For each abbreviation given in the input, find the year of the corresponding Olympiad.
-----Examples-----
Input
5
IAO'15
IAO'2015
IAO'1
IAO'9
IAO'0
Output
2015
12015
1991
1989
1990
Input
4
IAO'9
IAO'99
IAO'999
IAO'9999
Output
1989
1999
2999
9999
I tried it in Python, but could not do it. Can you solve it? | for i in range(int(input())):
t = input()[4:]
q, d = int(t), 10 ** len(t)
while q < 1988 + d // 9: q += d
print(q) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
```if:java
___Note for Java users:___ Due to type checking in Java, inputs and outputs are formated quite differently in this language. See the footnotes of the description.
```
You have the following lattice points with their corresponding coordinates and each one with an specific colour.
```
Point [x , y] Colour
----------------------------
A [ 3, 4] Blue
B [-7, -1] Red
C [ 7, -6] Yellow
D [ 2, 5] Yellow
E [ 1, -5] Red
F [-1, 4] Red
G [ 1, 7] Red
H [-3, 5] Red
I [-3, -5] Blue
J [ 4, 1] Blue
```
We want to count the triangles that have the three vertices with the same colour. The following picture shows the distribution of the points in the plane with the required triangles.
![source: imgur.com](http://i.imgur.com/sP0l1i1.png)
The input that we will have for the field of lattice points described above is:
```
[[[3, -4], "blue"], [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"],
[[1, -5], "red"], [[-1, 4], "red"], [[1, 7], "red"], [[-3, 5], "red"],
[[-3, -5], "blue"], [[4, 1], "blue"] ]
```
We see the following result from it:
```
Colour Amount of Triangles Triangles
Yellow 0 -------
Blue 1 AIJ
Red 10 BEF,BEG,BEH,BFG,BFH,BGH,EFG,EFH,EHG,FGH
```
As we have 5 different points in red and each combination of 3 points that are not aligned.
We need a code that may give us the following information in order:
```
1) Total given points
2) Total number of colours
3) Total number of possible triangles
4) and 5) The colour (or colours, sorted alphabetically) with the highest amount of triangles
```
In Python our function will work like:
```
[10, 3, 11, ["red",10]]) == count_col_triang([[[3, -4], "blue"], [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"],
[[1, -5], "red"], [[-1, 4], "red"], [[1, 7], "red"], [[-3, 5],... | from collections import defaultdict
from itertools import combinations
def count_col_triang(points_colors):
point_count = len(points_colors)
colors = set(color for points, color in points_colors)
color_count = len(colors)
color_points = defaultdict(lambda: False)
for c in colors:
color_points[c] = [points
for points, color in points_colors if color == c]
# get all with 3 or more points, kasi 3 points min sa triangle
color_points = defaultdict(lambda: False, ((color, points)
for color, points in color_points.items() if len(points) >= 3))
triangle_count = 0
color_triangle_count = defaultdict(lambda: False)
for color, points in color_points.items():
comb_points = combinations(points, 3)
color_triangle_count[color] = 0
x, y = 0, 1
# get the side lengths and compute area
for vertices in comb_points:
va, vb, vc = vertices
# get sides using distance between 2 points formula
a = (((vb[x] - va[x])**2) + (vb[y] - va[y])**2)**0.5
b = (((vc[x] - vb[x])**2) + (vc[y] - vb[y])**2)**0.5
c = (((va[x] - vc[x])**2) + (va[y] - vc[y])**2)**0.5
s = (a + b + c) / 2 # semi-perimeter
area = (s*(s-a)*(s-b)*(s-c))**0.5
# any 3 points with an area is a triangle
if area != 0:
triangle_count += 1
color_triangle_count[color] += 1
max_count = max(color_triangle_count.values())
# get all colors with highest triangle count, append sa dulo count for format
colors_max_count = sorted([color for color, count in color_triangle_count.items()
if count == max_count])
colors_max_count.append(max_count)
if max_count <= 0:
colors_max_count = []
return [point_count, color_count, triangle_count, colors_max_count] | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/287/B:
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only one pipe with flowing water. Besides, Vova has several splitters.
A splitter is a construction that consists of one input (it can be connected to a water pipe) and x output pipes. When a splitter is connected to a water pipe, water flows from each output pipe. You can assume that the output pipes are ordinary pipes. For example, you can connect water supply to such pipe if there's water flowing out from it. At most one splitter can be connected to any water pipe. [Image] The figure shows a 4-output splitter
Vova has one splitter of each kind: with 2, 3, 4, ..., k outputs. Help Vova use the minimum number of splitters to build the required pipeline or otherwise state that it's impossible.
Vova needs the pipeline to have exactly n pipes with flowing out water. Note that some of those pipes can be the output pipes of the splitters.
-----Input-----
The first line contains two space-separated integers n and k (1 ≤ n ≤ 10^18, 2 ≤ k ≤ 10^9).
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
Print a single integer — the minimum number of splitters needed to build the pipeline. If it is impossible to build a pipeline with the given splitters, print -1.
-----Examples-----
Input
4 3
Output
2
Input
5 5
Output
1
Input
8 4
Output
-1
I tried it in Python, but could not do it. Can you solve it? | import math
from decimal import Decimal
def sum2(s, e):
return sum1(e) - sum1(s - 1) - (e - s)
def sum1(i):
return i * (i + 1) / 2
line = input().split()
n = Decimal(line[0])
k = Decimal(line[1])
if(n == 1):
print(0)
elif(k > n):
print(1)
elif(sum2(Decimal(2),k) < n):
print(-1)
else:
c = 2 * n + k - k * k
discriminant = (9 - 4 * c).sqrt()
tmp = discriminant / 2
const = Decimal(3/2)
res1 = math.floor(const + tmp)
res2 = math.floor(const - tmp)
res1 = max(res1, res2)
print(k - res1 + 1); | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/584cfac5bd160694640000ae:
You're given a string of dominos. For each slot, there are 3 options:
* "|" represents a standing domino
* "/" represents a knocked over domino
* " " represents a space where there is no domino
For example:
```python
"||| ||||//| |/"
```
What you must do is find the resulting string if the first domino is pushed over. Now, tipping a domino will cause the next domino to its right to fall over as well, but if a domino is already tipped over, or there is a domino missing, the reaction will stop.
So in out example above, the result would be:
"/// ||||//| |/"
since the reaction would stop as soon as it gets to a space.
I tried it in Python, but could not do it. Can you solve it? | def domino_reaction(s):
i = next((i for i,j in enumerate(s) if j in "/ "),len(s))
return "/"*i+s[i:] | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/PTRN2020/problems/ITGUY39:
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 cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, output as the pattern.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$
-----Sample Input:-----
3
2
3
4
-----Sample Output:-----
12
21
123
231
312
1234
2341
3412
4123
-----EXPLANATION:-----
No need, else pattern can be decode easily.
I tried it in Python, but could not do it. Can you solve it? | t=int(input())
for i in range(t):
k=int(input())
m=0
for j in range(1,k+1):
for m in range(j,k+1):
print(m,end="")
for n in range(1,j):
print(n,end="")
print() | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1405/A:
A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
Let $p$ be any permutation of length $n$. We define the fingerprint $F(p)$ of $p$ as the sorted array of sums of adjacent elements in $p$. More formally,
$$F(p)=\mathrm{sort}([p_1+p_2,p_2+p_3,\ldots,p_{n-1}+p_n]).$$
For example, if $n=4$ and $p=[1,4,2,3],$ then the fingerprint is given by $F(p)=\mathrm{sort}([1+4,4+2,2+3])=\mathrm{sort}([5,6,5])=[5,5,6]$.
You are given a permutation $p$ of length $n$. Your task is to find a different permutation $p'$ with the same fingerprint. Two permutations $p$ and $p'$ are considered different if there is some index $i$ such that $p_i \ne p'_i$.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 668$). Description of the test cases follows.
The first line of each test case contains a single integer $n$ ($2\le n\le 100$) — the length of the permutation.
The second line of each test case contains $n$ integers $p_1,\ldots,p_n$ ($1\le p_i\le n$). It is guaranteed that $p$ is a permutation.
-----Output-----
For each test case, output $n$ integers $p'_1,\ldots, p'_n$ — a permutation such that $p'\ne p$ and $F(p')=F(p)$.
We can prove that for every permutation satisfying the input constraints, a solution exists.
If there are multiple solutions, you may output any.
-----Example-----
Input
3
2
1 2
6
2 1 6 5 4 3
5
2 4 3 1 5
Output
2 1
1 2 5 6 3 4
3 1 5 2 4
-----Note-----
In the first test case, $F(p)=\mathrm{sort}([1+2])=[3]$.
And $F(p')=\mathrm{sort}([2+1])=[3]$.
In the second test case, $F(p)=\mathrm{sort}([2+1,1+6,6+5,5+4,4+3])=\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11]$.
And $F(p')=\mathrm{sort}([1+2,2+5,5+6,6+3,3+4])=\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11]$.
In the third test case,...
I tried it in Python, but could not do it. Can you solve it? | t=int(input())
while t:
t-=1
n=int(input())
a=[int(i) for i in input().split()]
a.reverse()
print(*a,sep=" ") | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Background
There is a message that is circulating via public media that claims a reader can easily read a message where the inner letters of each words is scrambled, as long as the first and last letters remain the same and the word contains all the letters.
Another example shows that it is quite difficult to read the text where all the letters are reversed rather than scrambled.
In this kata we will make a generator that generates text in a similar pattern, but instead of scrambled or reversed, ours will be sorted alphabetically
Requirement
return a string where:
1) the first and last characters remain in original place for each word
2) characters between the first and last characters must be sorted alphabetically
3) punctuation should remain at the same place as it started, for example: shan't -> sahn't
Assumptions
1) words are seperated by single spaces
2) only spaces separate words, special characters do not, for example: tik-tak -> tai-ktk
3) special characters do not take the position of the non special characters, for example: -dcba -> -dbca
4) for this kata puctuation is limited to 4 characters: hyphen(-), apostrophe('), comma(,) and period(.)
5) ignore capitalisation
for reference: http://en.wikipedia.org/wiki/Typoglycemia | import re
def scramble_words(words):
def sort_letters(match):
s = match.group()
letters = iter(sorted(filter(str.isalpha, s[1:-1])))
return s[0] + "".join(next(letters) if c.isalpha() else c for c in s[1:-1]) + s[-1]
return re.sub(r'[a-z][^\s]*[a-z]', sort_letters, words) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Let's say we have a number, `num`. Find the number of values of `n` such that: there exists `n` consecutive **positive** values that sum up to `num`. A positive number is `> 0`. `n` can also be 1.
```python
#Examples
num = 1
#1
return 1
num = 15
#15, (7, 8), (4, 5, 6), (1, 2, 3, 4, 5)
return 4
num = 48
#48, (15, 16, 17)
return 2
num = 97
#97, (48, 49)
return 2
```
The upper limit is `$10^8$` | def consecutive_sum(num):
count = 0
N = 1
while( N * (N + 1) < 2 * num):
a = (num - (N * (N + 1) ) / 2) / (N + 1)
if (a - int(a) == 0.0):
count += 1
N += 1
return count+1 | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.
When writing such an expression, we adhere to the following conventions:
The division operator (/) returns rational numbers.
There are no parentheses placed anywhere.
We use the usual order of operations: multiplication and division happens before addition and subtraction.
It's not allowed to use the unary negation operator (-). For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation.
We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.
Example 1:
Input: x = 3, target = 19
Output: 5
Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations.
Example 2:
Input: x = 5, target = 501
Output: 8
Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations.
Example 3:
Input: x = 100, target = 100000000
Output: 3
Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.
Note:
2 <= x <= 100
1 <= target <= 2 * 10^8 | #
from functools import lru_cache
class Solution:
def leastOpsExpressTarget(self, x: int, target: int) -> int:
cost = list(range(40))
cost[0] = 2
@lru_cache(None)
def dp(i, targ):
if targ == 0: return 0
if targ == 1: return cost[i]
if i >= 39: return float('inf')
t, r = divmod(targ, x)
return min(r * cost[i] + dp(i+1, t),
(x-r) * cost[i] + dp(i+1, t+1))
return dp(0, target) - 1 | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Buses run between the cities A and B, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city A departs every a minutes and arrives to the city B in a t_{a} minutes, and a bus from the city B departs every b minutes and arrives to the city A in a t_{b} minutes.
The driver Simion wants to make his job diverse, so he counts the buses going towards him. Simion doesn't count the buses he meet at the start and finish.
You know the time when Simion departed from the city A to the city B. Calculate the number of buses Simion will meet to be sure in his counting.
-----Input-----
The first line contains two integers a, t_{a} (1 ≤ a, t_{a} ≤ 120) — the frequency of the buses from the city A to the city B and the travel time. Both values are given in minutes.
The second line contains two integers b, t_{b} (1 ≤ b, t_{b} ≤ 120) — the frequency of the buses from the city B to the city A and the travel time. Both values are given in minutes.
The last line contains the departure time of Simion from the city A in the format hh:mm. It is guaranteed that there are a bus from the city A at that time. Note that the hours and the minutes are given with exactly two digits.
-----Output-----
Print the only integer z — the number of buses Simion will meet on the way. Note that you should not count the encounters in cities A and B.
-----Examples-----
Input
10 30
10 35
05:20
Output
5
Input
60 120
24 100
13:00
Output
9
-----Note-----
In the first example Simion departs form the city A at 05:20 AM and arrives to the city B at 05:50 AM. He will meet the first 5 buses from the city B that departed in the period [05:00 AM - 05:40 AM]. Also Simion will meet a bus in the city B at 05:50 AM, but he will not count it.
Also note that the first encounter will be between 05:26 AM and 05:27 AM (if we suggest that the buses are go with the sustained speed). | a,b=map(int,input().split())
n,m=map(int,input().split())
t1,t2=map(int,input().split(':'))
h=t1-5
t2=t2
st=t2+h*60
fin=st+b
now=0
ans=0
while now<fin and now<1140:
if now+m>st:
ans+=1
now+=n
print(ans) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Complete the method that takes a sequence of objects with two keys each: country or state, and capital. Keys may be symbols or strings.
The method should return an array of sentences declaring the state or country and its capital.
## Examples
```python
[{'state': 'Maine', 'capital': 'Augusta'}] --> ["The capital of Maine is Augusta"]
[{'country' : 'Spain', 'capital' : 'Madrid'}] --> ["The capital of Spain is Madrid"]
[{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}] --> ["The capital of Maine is Augusta", "The capital of Spain is Madrid"]
``` | def capital(capitals):
return [f"The capital of {d['state'] if 'state' in d else d['country'] } is {d['capital']}" for d in capitals] | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/number-of-good-pairs/:
Given an array of integers nums.
A pair (i,j) is called good if nums[i] == nums[j] and i < j.
Return the number of good pairs.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3]
Output: 0
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
I tried it in Python, but could not do it. Can you solve it? | class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
tracker = {}
for num in nums:
if num not in tracker:
tracker[num] = 0
else:
tracker[num] += 1
sum = 0
for num in tracker:
sum += tracker[num] * (tracker[num]+1) // 2
return sum | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
# The Problem
Dan, president of a Large company could use your help. He wants to implement a system that will switch all his devices into offline mode depending on his meeting schedule. When he's at a meeting and somebody texts him, he wants to send an automatic message informing that he's currently unavailable and the time when he's going to be back.
# What To Do
Your task is to write a helper function `checkAvailability` that will take 2 arguments:
* schedule, which is going to be a nested array with Dan's schedule for a given day. Inside arrays will consist of 2 elements - start and finish time of a given appointment,
* *currentTime* - is a string with specific time in hh:mm 24-h format for which the function will check availability based on the schedule.
* If no appointments are scheduled for `currentTime`, the function should return `true`. If there are no appointments for the day, the output should also be `true`
* If Dan is in the middle of an appointment at `currentTime`, the function should return a string with the time he's going to be available.
# Examples
`checkAvailability([["09:30", "10:15"], ["12:20", "15:50"]], "11:00");`
should return `true`
`checkAvailability([["09:30", "10:15"], ["12:20", "15:50"]], "10:00");`
should return `"10:15"`
If the time passed as input is *equal to the end time of a meeting*, function should also return `true`.
`checkAvailability([["09:30", "10:15"], ["12:20", "15:50"]], "15:50");`
should return `true`
*You can expect valid input for this kata* | def check_availability(schedule, current_time):
for meeting in schedule: return meeting[1] if meeting[0] <= current_time < meeting[1] else True
return True | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/488/B:
There is an old tradition of keeping 4 boxes of candies in the house in Cyberland. The numbers of candies are special if their arithmetic mean, their median and their range are all equal. By definition, for a set {x_1, x_2, x_3, x_4} (x_1 ≤ x_2 ≤ x_3 ≤ x_4) arithmetic mean is $\frac{x_{1} + x_{2} + x_{3} + x_{4}}{4}$, median is $\frac{x_{2} + x_{3}}{2}$ and range is x_4 - x_1. The arithmetic mean and median are not necessary integer. It is well-known that if those three numbers are same, boxes will create a "debugging field" and codes in the field will have no bugs.
For example, 1, 1, 3, 3 is the example of 4 numbers meeting the condition because their mean, median and range are all equal to 2.
Jeff has 4 special boxes of candies. However, something bad has happened! Some of the boxes could have been lost and now there are only n (0 ≤ n ≤ 4) boxes remaining. The i-th remaining box contains a_{i} candies.
Now Jeff wants to know: is there a possible way to find the number of candies of the 4 - n missing boxes, meeting the condition above (the mean, median and range are equal)?
-----Input-----
The first line of input contains an only integer n (0 ≤ n ≤ 4).
The next n lines contain integers a_{i}, denoting the number of candies in the i-th box (1 ≤ a_{i} ≤ 500).
-----Output-----
In the first output line, print "YES" if a solution exists, or print "NO" if there is no solution.
If a solution exists, you should output 4 - n more lines, each line containing an integer b, denoting the number of candies in a missing box.
All your numbers b must satisfy inequality 1 ≤ b ≤ 10^6. It is guaranteed that if there exists a positive integer solution, you can always find such b's meeting the condition. If there are multiple answers, you are allowed to print any of them.
Given numbers a_{i} may follow in any order in the input, not necessary in non-decreasing.
a_{i} may have stood at any positions in the original set, not necessary on lowest n first...
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
ar = [int(input()) for x in range(n)]
ar.sort()
foobar = 1
def out(*g):
g = list(g)
g.sort()
print("YES")
for x in g:
print(x)
def check(x1,x2,x3,x4):
l = [x1,x2,x3,x4]
s = sum(l) /4
if s != int(s):
return False
l.sort()
m = (l[1]+l[2])/2
if m != int(m):
return False
d = l[3] - l[0]
if not (s==m==d):
return False
return True
def _0():
print('YES')
print(1)
print(1)
print(3)
print(3)
def _1():
x = ar[0]
print("YES")
# print(x)
print(x)
print(3*x)
print(3*x)
def _2():
x,y = ar
if x*3 < y:
print("NO")
else:
print('YES')
# print(x)
# print(y)
print(4*x-y)
print(3*x)
def _3():
x = ar[0]
y = ar[1]
z = ar[2]
if x*3 < z:
print("NO")
else:
print('YES')
# print(x)
# print(y)
# print(z)
print(3*x)
def _3():
ar.sort()
m = (max(ar)+10)*10
for x in range(1, m):
if check(x, *ar):
out(x)
return
print("NO")
def _4():
r = check(*ar)
if r == False:
print('NO')
else:
print("YES")
# for x in ar: print(x)
vars()['_' + str(n)]() | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1389/A:
Let $LCM(x, y)$ be the minimum positive integer that is divisible by both $x$ and $y$. For example, $LCM(13, 37) = 481$, $LCM(9, 6) = 18$.
You are given two integers $l$ and $r$. Find two integers $x$ and $y$ such that $l \le x < y \le r$ and $l \le LCM(x, y) \le r$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10000$) — the number of test cases.
Each test case is represented by one line containing two integers $l$ and $r$ ($1 \le l < r \le 10^9$).
-----Output-----
For each test case, print two integers:
if it is impossible to find integers $x$ and $y$ meeting the constraints in the statement, print two integers equal to $-1$; otherwise, print the values of $x$ and $y$ (if there are multiple valid answers, you may print any of them).
-----Example-----
Input
4
1 1337
13 69
2 4
88 89
Output
6 7
14 21
2 4
-1 -1
I tried it in Python, but could not do it. Can you solve it? | for tc in range(int(input())):
L, R = map(int, input().split())
if L * 2 <= R:
print (L, L * 2)
else:
print ("-1 -1") | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Consider a billiard table of rectangular size $n \times m$ with four pockets. Let's introduce a coordinate system with the origin at the lower left corner (see the picture). [Image]
There is one ball at the point $(x, y)$ currently. Max comes to the table and strikes the ball. The ball starts moving along a line that is parallel to one of the axes or that makes a $45^{\circ}$ angle with them. We will assume that: the angles between the directions of the ball before and after a collision with a side are equal, the ball moves indefinitely long, it only stops when it falls into a pocket, the ball can be considered as a point, it falls into a pocket if and only if its coordinates coincide with one of the pockets, initially the ball is not in a pocket.
Note that the ball can move along some side, in this case the ball will just fall into the pocket at the end of the side.
Your task is to determine whether the ball will fall into a pocket eventually, and if yes, which of the four pockets it will be.
-----Input-----
The only line contains $6$ integers $n$, $m$, $x$, $y$, $v_x$, $v_y$ ($1 \leq n, m \leq 10^9$, $0 \leq x \leq n$; $0 \leq y \leq m$; $-1 \leq v_x, v_y \leq 1$; $(v_x, v_y) \neq (0, 0)$) — the width of the table, the length of the table, the $x$-coordinate of the initial position of the ball, the $y$-coordinate of the initial position of the ball, the $x$-component of its initial speed and the $y$-component of its initial speed, respectively. It is guaranteed that the ball is not initially in a pocket.
-----Output-----
Print the coordinates of the pocket the ball will fall into, or $-1$ if the ball will move indefinitely.
-----Examples-----
Input
4 3 2 2 -1 1
Output
0 0
Input
4 4 2 0 1 1
Output
-1
Input
10 10 10 1 -1 0
Output
-1
-----Note-----
The first sample: [Image]
The second sample: [Image]
In the third sample the ball will never change its $y$ coordinate, so the ball will never fall into a pocket. | def gcd(a, b):
if (b == 0):
return a
return gcd(b, a % b)
def exgcd(a, b):
if (b == 0):
return (1, 0, a)
(p, q, r) = exgcd(b, a % b)
t = p
p = q
q = t - (a // b) * q
return (p, q, r)
list = input().split()
n = int(list[0]); m = int(list[1]);
x = int(list[2]); y = int(list[3])
vx = int(list[4]); vy = int(list[5])
if (vx == 0):
if ((x != 0) and (x != n)):
print(-1)
else:
if (vy == 1):
print(x, m)
else:
print(x, 0)
if (vy == 0):
if ((y != 0) and (y != m)):
print(-1)
else:
if (vx == 1):
print(n, y)
else:
print(0, y)
if ((vx != 0) and (vy != 0)):
fx = 0; fy = 0
if (vx == -1):
fx = 1
x = n - x
if (vy == -1):
fy = 1
y = m - y
(p, q, r) = exgcd(n, m)
if ((x - y) % r != 0):
print(-1)
else:
p *= (x - y) // r
q *= (x - y) // r
mn = m * n // gcd(m, n)
a = (p * n - x) % mn
while (a <= 0):
a += mn
p = (x + a) // n
q = (y + a) // m
ansx = 0; ansy = 0;
if ((p + fx) % 2 == 1):
ansx = n
if ((q + fy) % 2 == 1):
ansy = m
print(ansx, ansy) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions.
Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions. Spells of this type speed up the preparation time of one potion. There are m spells of this type, the i-th of them costs b_{i} manapoints and changes the preparation time of each potion to a_{i} instead of x. Spells of this type immediately prepare some number of potions. There are k such spells, the i-th of them costs d_{i} manapoints and instantly create c_{i} potions.
Anton can use no more than one spell of the first type and no more than one spell of the second type, and the total number of manapoints spent should not exceed s. Consider that all spells are used instantly and right before Anton starts to prepare potions.
Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least n potions.
-----Input-----
The first line of the input contains three integers n, m, k (1 ≤ n ≤ 2·10^9, 1 ≤ m, k ≤ 2·10^5) — the number of potions, Anton has to make, the number of spells of the first type and the number of spells of the second type.
The second line of the input contains two integers x and s (2 ≤ x ≤ 2·10^9, 1 ≤ s ≤ 2·10^9) — the initial number of seconds required to prepare one potion and the number of manapoints Anton can use.
The third line contains m integers a_{i} (1 ≤ a_{i} < x) — the number of seconds it will take to prepare one potion if the i-th spell of the first type is used.
The fourth line contains m integers b_{i} (1 ≤ b_{i} ≤ 2·10^9) — the number of manapoints to use the i-th spell of the first type.
There are k integers c_{i} (1 ≤ c_{i} ≤ n) in the fifth line — the number of potions that will be immediately created if the i-th spell of the second type is used. It's guaranteed that c_{i} are not... | class First:
def __init__(self, seconds, cost):
self.seconds = seconds
self.cost = cost
class Second:
def __init__(self, numCreated, cost):
self.numCreated = numCreated
self.cost = cost
def solve():
potionCount, firstCount, secondCount = map(int, input().split())
secondsOne, manaPoints = map(int, input().split())
first = list()
a, b = list(map(int, input().split())), list(map(int, input().split()))
for i in range(firstCount):
first.append(First(a[i], b[i]))
first.append(First(secondsOne, 0))
second = [Second(0, 0)]
a, b = list(map(int, input().split())), list(map(int, input().split()))
for i in range(secondCount):
second.append(Second(a[i], b[i]))
res = int(1e20)
for f in first:
low = 0
high = len(second) - 1
while low < high:
mid = (low + high + 1) // 2
if f.cost + second[mid].cost > manaPoints:
high = mid - 1
else:
low = mid
if f.cost + second[low].cost <= manaPoints:
moar = max(0, potionCount - second[low].numCreated)
time = moar * f.seconds
res = min(res, time)
print(res)
solve() | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/656/E:
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
-----Input-----
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line a_{ij} is the length of the edge that connects vertices i and j. a_{ij} = a_{ji}, a_{ii} = 0, 1 ≤ a_{ij} ≤ 100 for i ≠ j.
-----Output-----
Output the maximum length of the shortest path between any pair of vertices in the graph.
-----Examples-----
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
-----Note-----
You're running short of keywords, so you can't use some of them:define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
I tried it in Python, but could not do it. Can you solve it? | import sys, itertools, collections
n = int(input())
d = list([list(map(int, s.split())) for s in sys.stdin.readlines()])
def assign(t):
k,i,j = t
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
collections.deque(maxlen=0).extend(list(map(assign, itertools.product(list(range(n)), **{'taeper'[::-1]:3}))))
print(max(list(map(max, d)))) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1010/C:
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.
There are $n$ banknote denominations on Mars: the value of $i$-th banknote is $a_i$. Natasha has an infinite number of banknotes of each denomination.
Martians have $k$ fingers on their hands, so they use a number system with base $k$. In addition, the Martians consider the digit $d$ (in the number system with base $k$) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base $k$ is $d$, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet.
Determine for which values $d$ Natasha can make the Martians happy.
Natasha can use only her banknotes. Martians don't give her change.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le n \le 100\,000$, $2 \le k \le 100\,000$) — the number of denominations of banknotes and the base of the number system on Mars.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) — denominations of banknotes on Mars.
All numbers are given in decimal notation.
-----Output-----
On the first line output the number of values $d$ for which Natasha can make the Martians happy.
In the second line, output all these values in increasing order.
Print all numbers in decimal notation.
-----Examples-----
Input
2 8
12 20
Output
2
0 4
Input
3 10
10 20 30
Output
1
0
-----Note-----
Consider the first test case. It uses the octal number system.
If you take one banknote with the value of $12$, you will get $14_8$ in octal system. The last digit is $4_8$.
If you take one banknote with the value of $12$ and one banknote with the value of $20$, the total value will be $32$. In the octal system, it is $40_8$. The last digit is $0_8$.
If you take...
I tried it in Python, but could not do it. Can you solve it? | def nod(a,b):
while a!=0 and b!=0:
if a>b:
a,b=b,a%b
else:
b,a=a,b%a
return a+b
n ,k = map(int, input().split())
a = [int(j) for j in input().split()]
c = a[0]
for i in range(1,n):
c = nod(c,a[i])
if c==1:
break
e = nod(c,k)
if c==1 or e==1:
print(k)
for i in range(k):
print(i, end=" ")
if e>1:
c = k//e
print(c)
for i in range(c):
print(i*e, end=' ') | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Lot of museum allow you to be a member, for a certain amount `amount_by_year` you can have unlimitted acces to the museum.
In this kata you should complete a function in order to know after how many visit it will be better to take an annual pass. The function take 2 arguments `annual_price` and `individual_price`. | from math import ceil
def how_many_times(annual, individual):
return ceil(annual / individual) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Regex Failure - Bug Fixing #2
Oh no, Timmy's received some hate mail recently but he knows better. Help Timmy fix his regex filter so he can be awesome again! | from re import sub, I
def filter_words(phrase):
return sub(r"(bad|mean|ugly|horrible|hideous)","awesome",phrase,flags=I) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You have to create a function that converts integer given as string into ASCII uppercase letters.
All ASCII characters have their numerical order in table.
For example,
```
from ASCII table, character of number 65 is "A".
```
Numbers will be next to each other, So you have to split given number to two digit long integers.
For example,
```
'658776' to [65, 87, 76] and then turn it into 'AWL'.
``` | def convert(number):
return ''.join(chr(int(f'{e1}{e2}')) for e1,e2 in zip(*[iter(number)]*2)) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation.
### Examples
```
"1999" --> "20th"
"2011" --> "21st"
"2154" --> "22nd"
"2259" --> "23rd"
"1124" --> "12th"
"2000" --> "20th"
``` | def what_century(year):
y = int(year)
c, r = divmod(y, 100)
if r:
c += 1
ones = c%10
tens = (c//10)%10
if tens == 1:
suffix = "th"
elif ones == 1:
suffix = "st"
elif ones == 2:
suffix = "nd"
elif ones == 3:
suffix = "rd"
else:
suffix = "th"
return str(c)+suffix | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/888/F:
There are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with each other (directly or indirectly).
But there are some restrictions. Firstly, some pairs of points cannot be connected directly and have to be connected undirectly. Secondly, the segments you draw must not intersect in any point apart from the marked points (that is, if any two segments intersect and their intersection is not a marked point, then the picture you have drawn is invalid).
How many ways are there to connect all vertices with n - 1 segments? Two ways are considered different iff there exist some pair of points such that a segment is drawn between them in the first way of connection, but it is not drawn between these points in the second one. Since the answer might be large, output it modulo 10^9 + 7.
-----Input-----
The first line contains one number n (3 ≤ n ≤ 500) — the number of marked points.
Then n lines follow, each containing n elements. a_{i}, j (j-th element of line i) is equal to 1 iff you can connect points i and j directly (otherwise a_{i}, j = 0). It is guaranteed that for any pair of points a_{i}, j = a_{j}, i, and for any point a_{i}, i = 0.
-----Output-----
Print the number of ways to connect points modulo 10^9 + 7.
-----Examples-----
Input
3
0 0 1
0 0 1
1 1 0
Output
1
Input
4
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0
Output
12
Input
3
0 0 0
0 0 1
0 1 0
Output
0
I tried it in Python, but could not do it. Can you solve it? | import sys
from array import array
n = int(input())
edge = [list(map(int, input().split())) for _ in range(n)]
mod = 10**9 + 7
dp_f = [array('i', [-1])*n for _ in range(n)]
dp_g = [array('i', [-1])*n for _ in range(n)]
for i in range(n):
dp_f[i][i] = dp_g[i][i] = 1
for i in range(n-1):
dp_f[i][i+1] = dp_g[i][i+1] = 1 if edge[i][i+1] else 0
def f(l, r):
if dp_f[l][r] != -1:
return dp_f[l][r]
dp_f[l][r] = g(l, r) if edge[l][r] else 0
for m in range(l+1, r):
if edge[l][m]:
dp_f[l][r] = (dp_f[l][r] + g(l, m) * f(m, r)) % mod
return dp_f[l][r]
def g(l, r):
if dp_g[l][r] != -1:
return dp_g[l][r]
dp_g[l][r] = f(l+1, r)
for m in range(l+1, r):
dp_g[l][r] = (dp_g[l][r] + f(l, m) * f(m+1, r)) % mod
return dp_g[l][r]
print(f(0, n-1)) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks.
The second line contains n integers a_{i} ( - 10^9 ≤ a_{i} ≤ 10^9), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all a_{i} is equal to 0.
-----Output-----
Print the minimum number of operations required to change balance in each bank to zero.
-----Examples-----
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
-----Note-----
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer: transfer 1 from the first bank to the second bank; transfer 3 from the second bank to the third; transfer 6 from the third bank to the fourth. | n = int(input())
a = list(map(int, input().split()))
d = dict()
total = 0
for i in range(n):
total += a[i]
d[total] = 0
total = 0
ans = 0
for i in range(n):
total += a[i]
d[total] += 1
ans = max(ans, d[total])
print(n - ans) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Well known investigative reporter Kim "Sherlock'' Bumjun needs your help! Today, his mission is to sabotage the operations of the evil JSA. If the JSA is allowed to succeed, they will use the combined power of the WQS binary search and the UFDS to take over the world!
But Kim doesn't know where the base is located. He knows that the base is on the highest peak of the Himalayan Mountains. He also knows the heights of each of the $N$ mountains. Can you help Kim find the height of the mountain where the base is located?
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line in each testcase contains one integer, $N$.
- The following $N$ lines of each test case each contain one integer: the height of a new mountain.
-----Output:-----
For each testcase, output one line with one integer: the height of the tallest mountain for that test case.
-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 100000$
- $0 \leq$ height of each mountain $\leq 10^9$
-----Subtasks:-----
- 100 points: No additional constraints.
-----Sample Input:-----
1
5
4
7
6
3
1
-----Sample Output:-----
7 | for t in range(int(input())):
n=int(input())
x=int(input())
for i in range(n-1):
y=int(input())
if y>x:
x=y
print(x) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Ivan has number $b$. He is sorting through the numbers $a$ from $1$ to $10^{18}$, and for every $a$ writes $\frac{[a, \,\, b]}{a}$ on blackboard. Here $[a, \,\, b]$ stands for least common multiple of $a$ and $b$. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the board if he would finish the task. Help him to find the quantity of different numbers he would write on the board.
-----Input-----
The only line contains one integer — $b$ $(1 \le b \le 10^{10})$.
-----Output-----
Print one number — answer for the problem.
-----Examples-----
Input
1
Output
1
Input
2
Output
2
-----Note-----
In the first example $[a, \,\, 1] = a$, therefore $\frac{[a, \,\, b]}{a}$ is always equal to $1$.
In the second example $[a, \,\, 2]$ can be equal to $a$ or $2 \cdot a$ depending on parity of $a$. $\frac{[a, \,\, b]}{a}$ can be equal to $1$ and $2$. | b = int(input())
divs = 0
i = 1
while i <= b ** 0.5:
if i == b ** 0.5:
divs += 1
elif b % i == 0:
divs += 2
i += 1
print(divs) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1092/C:
Ivan wants to play a game with you. He picked some string $s$ of length $n$ consisting only of lowercase Latin letters.
You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $1$ to $n-1$), but he didn't tell you which strings are prefixes and which are suffixes.
Ivan wants you to guess which of the given $2n-2$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!
-----Input-----
The first line of the input contains one integer number $n$ ($2 \le n \le 100$) — the length of the guessed string $s$.
The next $2n-2$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $1$ to $n-1$ consisting only of lowercase Latin letters. They can be given in arbitrary order.
It is guaranteed that there are exactly $2$ strings of each length from $1$ to $n-1$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $n$.
-----Output-----
Print one string of length $2n-2$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $i$-th character of this string should be 'P' if the $i$-th of the input strings is the prefix and 'S' otherwise.
If there are several possible answers, you can print any.
-----Examples-----
Input
5
ba
a
abab
a
aba
baba
ab
aba
Output
SPPSPSPS
Input
3
a
aa
aa
a
Output
PPSS
Input
2
a
c
Output
PS
-----Note-----
The only string which Ivan can guess in the first example is "ababa".
The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.
In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP"...
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
lst = []
for i in range((2*n)-2):
curr = str(input())
lst.append([i,curr])
lst.sort(key=lambda val: len(val[1]),reverse = True)
word1 = lst[0][1] + lst[1][1][-1]
word2 = lst[1][1] + lst[0][1][-1]
bool1 = True
bool2 = True
sp1 = [0 for i in range((2*n)-2)]
sp1[0] = 'P'
sp1[1] = 'S'
sp2 = [0 for i in range((2*n)-2)]
sp2[0] = 'S'
sp2[1] = 'P'
for i in range(2,(2*n)-2,2):
curr1 = lst[i][1]
curr2 = lst[i+1][1]
# print(curr1," ",curr2,word1[:n-int(i/2)-1],word1[int(i/2)+1:])
if curr1 == word1[:n-int(i/2)-1] and curr2 == word1[int(i/2)+1:]:
sp1[i] = 'P'
sp1[i+1] = 'S'
## print("yes1\n")
## print(sp1,sp2)
elif curr2 == word1[:n-int(i/2)-1] and curr1 == word1[int(i/2)+1:]:
sp1[i] = 'S'
sp1[i+1] = 'P'
## print("yes2\n")
if curr1 == word2[:n-int(i/2)-1] and curr2 == word2[int(i/2)+1:]:
sp2[i] = 'P'
sp2[i+1] = 'S'
## print("yes3\n")
elif curr2 == word2[:n-int(i/2)-1] and curr1 == word2[int(i/2)+1:]:
sp2[i] = 'S'
sp2[i+1] = 'P'
## print("yes4\n")
for i in sp1:
if i == 0:
bool1 = False
break
for i in sp2:
if i == 0:
bool2 = False
##print(sp1,sp2)
if bool1:
ans = ''
newl = []
for j in range(len(lst)):
newl.append(lst[j]+[sp1[j]])
newl.sort(key=lambda val: val[0])
for j in newl:
ans = ans + j[2]
print(ans)
elif bool2:
ans = ''
newl = []
for j in range(len(lst)):
newl.append(lst[j]+[sp2[j]])
newl.sort(key=lambda val: val[0])
for j in newl:
ans = ans + j[2]
print(ans) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (bread), 'S' (sausage) и 'C' (cheese). The ingredients in the recipe go from bottom to top, for example, recipe "ВSCBS" represents the hamburger where the ingredients go from bottom to top as bread, sausage, cheese, bread and sausage again.
Polycarpus has n_{b} pieces of bread, n_{s} pieces of sausage and n_{c} pieces of cheese in the kitchen. Besides, the shop nearby has all three ingredients, the prices are p_{b} rubles for a piece of bread, p_{s} for a piece of sausage and p_{c} for a piece of cheese.
Polycarpus has r rubles and he is ready to shop on them. What maximum number of hamburgers can he cook? You can assume that Polycarpus cannot break or slice any of the pieces of bread, sausage or cheese. Besides, the shop has an unlimited number of pieces of each ingredient.
-----Input-----
The first line of the input contains a non-empty string that describes the recipe of "Le Hamburger de Polycarpus". The length of the string doesn't exceed 100, the string contains only letters 'B' (uppercase English B), 'S' (uppercase English S) and 'C' (uppercase English C).
The second line contains three integers n_{b}, n_{s}, n_{c} (1 ≤ n_{b}, n_{s}, n_{c} ≤ 100) — the number of the pieces of bread, sausage and cheese on Polycarpus' kitchen. The third line contains three integers p_{b}, p_{s}, p_{c} (1 ≤ p_{b}, p_{s}, p_{c} ≤ 100) — the price of one piece of bread, sausage and cheese in the shop. Finally, the fourth line contains integer r (1 ≤ r ≤ 10^12) — the number of rubles Polycarpus has.
Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
Print the maximum number of hamburgers... | def Divide(a,b):
if(b==0):
return 10**100
return a//b
def main():
s=input()
Nb,Ns,Nc=list(map(int,input().split()))
Pb,Ps,Pc=list(map(int,input().split()))
r=int(input())
B=s.count('B')
S=s.count('S')
C=s.count('C')
needed=B*Pb+C*Pc+S*Ps
ans=0
while(1):
x=needed
if(Nb!=0):
if(Nb>B):
x-=B*Pb
Nb-=B
else:
x-=Nb*Pb
Nb=0
if(Nc!=0):
if(Nc>C):
x-=C*Pc
Nc-=C
else:
x-=Nc*Pc
Nc=0
if(Ns!=0):
if(Ns>S):
x-=S*Ps
Ns-=S
else:
x-=Ns*Ps
Ns=0
if(x<=r):
r-=x
ans+=1
else:
break
if((Nb==0 or B==0) and (Nc==0 or C==0) and (Ns==0 or S==0)):
break
ans+=r//needed
print(ans)
return
main() | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1059/C:
Let's call the following process a transformation of a sequence of length $n$.
If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of $n$ integers: the greatest common divisors of all the elements in the sequence before each deletion.
You are given an integer sequence $1, 2, \dots, n$. Find the lexicographically maximum result of its transformation.
A sequence $a_1, a_2, \ldots, a_n$ is lexicographically larger than a sequence $b_1, b_2, \ldots, b_n$, if there is an index $i$ such that $a_j = b_j$ for all $j < i$, and $a_i > b_i$.
-----Input-----
The first and only line of input contains one integer $n$ ($1\le n\le 10^6$).
-----Output-----
Output $n$ integers — the lexicographically maximum result of the transformation.
-----Examples-----
Input
3
Output
1 1 3
Input
2
Output
1 2
Input
1
Output
1
-----Note-----
In the first sample the answer may be achieved this way: Append GCD$(1, 2, 3) = 1$, remove $2$. Append GCD$(1, 3) = 1$, remove $1$. Append GCD$(3) = 3$, remove $3$.
We get the sequence $[1, 1, 3]$ as the result.
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
mult = 1
res = []
remain = n
while remain >0:
if remain == 2:
res.extend([mult, mult*2])
remain = 0
elif remain == 3:
res.extend([mult, mult, mult *3])
remain = 0
else:
half = remain // 2
extra = remain - half
res.extend([mult]*extra)
remain = half
mult = mult *2
print(*res) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/SAD:
Our Chef is very happy that his son was selected for training in one of the finest culinary schools of the world.
So he and his wife decide to buy a gift for the kid as a token of appreciation.
Unfortunately, the Chef hasn't been doing good business lately, and is in no mood on splurging money.
On the other hand, the boy's mother wants to buy something big and expensive.
To settle the matter like reasonable parents, they play a game.
They spend the whole day thinking of various gifts and write them down in a huge matrix.
Each cell of the matrix contains the gift's cost.
Then they decide that the mother will choose a row number r while the father will choose a column number c,
the item from the corresponding cell will be gifted to the kid in a couple of days.
The boy observes all of this secretly.
He is smart enough to understand that his parents will ultimately choose a gift whose cost is smallest in its row,
but largest in its column.
If no such gift exists, then our little chef has no option but to keep guessing.
As the matrix is huge, he turns to you for help.
He knows that sometimes the gift is not determined uniquely even if a gift exists whose cost is smallest in its row,
but largest in its column.
However, since the boy is so smart, he realizes that the gift's cost is determined uniquely.
Your task is to tell him the gift's cost which is smallest in its row,
but largest in its column, or to tell him no such gift exists.
-----Input-----
First line contains two integers R and C, the number of rows and columns in the matrix respectively. Then follow R lines, each containing C space separated integers - the costs of different gifts.
-----Output-----
Print a single integer - a value in the matrix that is smallest in its row but highest in its column. If no such value exists, then print "GUESS" (without quotes of course)
-----Constraints-----
1 <= R, C <= 100
All gift costs are positive and less than 100000000 (10^8)
-----Example 1-----
Input:
2 3
9 8 8
2 6 11
Output:
8
-----Example...
I tried it in Python, but could not do it. Can you solve it? | r,c=map(int,input().split())
mat=[]
rmin=[]
cmax=[]
d={}
f=0
for i in range(r):
l=list(map(int,input().split()))
mat.append(l)
for i in range(r):
x=min(mat[i])
rmin.append(x)
for i in range(c):
x=[]
for j in range(r):
x.append(mat[j][i])
cmax.append(max(x))
for i in rmin:
if(i in cmax):
print(i)
f=1
break
if(f==0):
print("GUESS") | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Given a Complete Binary Tree of ‘n’ depth, you can perform 4 types of mirror operation on the tree:-
Mirror on the right. The tree is mirrored to the right and rightmost node on every level is connected with the mirrored corresponding node.
Mirror on the left. The tree is mirrored to the left and leftmost node on every level is connected with the mirrored corresponding node.
Mirror on the top. The tree is mirrored to the top and topmost nodes are connected with corresponding nodes.
Mirror on the bottom. The tree is mirrored to the bottom and bottom most nodes are connected with the corresponding nodes.
See the image for details.
Mirror Right:
Mirror Bottom:
You are given ‘q’ queries, each performing this type of operation or asking for the no of edges in the produced graph.
Queries are of the form “1 x” or “2” where x is 1 for right, 2 for left, 3 for top or 4 for bottom.
1 x: Perform x operation on the result graph.
2: Print the no of edges in the graph. Since it can be very large, print it modulo 1000000007.
-----Input:-----
- First line will contain $n$, the depth of the initial tree and $q$, the number of queries.
- Next $q$ lines contain queries of the form "1 $x$" or "2".
-----Output:-----
For each query of type "2", output a single line containing the no of edges in the graph modulo 1000000007.
-----Constraints-----
- $1 \leq n \leq 1000$
- $1 \leq q \leq 10^5$
- $1 \leq x \leq 4$
-----Sample Input:-----
2 3
1 1
1 4
2
-----Sample Output:-----
38
-----EXPLANATION:-----
Initial no of edges = 6
After the operation 1 1, no of edges = 15
After the operation 1 4, no of edges = 38
At operation 2, we print the no of edges that is 38. | def main():
n,q = list(map(int,input().split()))
edges = ((pow(2,n,1000000007)-1)*2)%1000000007
bottom = pow(2,n,1000000007)
top = 1
right = n+1
left = n+1
for i in range(q):
query = list(map(int,input().split()))
if len(query) == 1:
print(edges)
else:
op = query[1]
if op == 1:
edges *= 2
edges += right
edges = edges%1000000007
bottom *= 2
top *= 2
elif op == 2:
edges *= 2
edges += left
edges = edges%1000000007
bottom *= 2
top *= 2
elif op == 3:
edges *= 2
edges += top
edges = edges%1000000007
left *= 2
right *= 2
top = bottom
else:
edges *= 2
edges += bottom
edges = edges%1000000007
left *= 2
right *= 2
bottom = top
left = left%1000000007
right = right%1000000007
bottom = bottom%1000000007
top = top%1000000007
main() | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Your task is to create function```isDivideBy``` (or ```is_divide_by```) to check if an integer number is divisible by each out of two arguments.
A few cases:
```
(-12, 2, -6) -> true
(-12, 2, -5) -> false
(45, 1, 6) -> false
(45, 5, 15) -> true
(4, 1, 4) -> true
(15, -5, 3) -> true
``` | def is_divide_by(number, a, b):
result = True
if number % a == 0 and number % b == 0:
result = True
else:
result = False
return result | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/245/B:
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>]
where: <protocol> can equal either "http" (without the quotes) or "ftp" (without the quotes), <domain> is a non-empty string, consisting of lowercase English letters, the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters.
If string <context> isn't present in the address, then the additional character "/" isn't written. Thus, the address has either two characters "/" (the ones that go before the domain), or three (an extra one in front of the context).
When the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters ":", "/", ".".
Help Vasya to restore the possible address of the recorded Internet resource.
-----Input-----
The first line contains a non-empty string that Vasya wrote out in his notebook. This line consists of lowercase English letters only.
It is guaranteed that the given string contains at most 50 letters. It is guaranteed that the given string can be obtained from some correct Internet resource address, described above.
-----Output-----
Print a single line — the address of the Internet resource that Vasya liked. If there are several addresses that meet the problem limitations, you are allowed to print any of them.
-----Examples-----
Input
httpsunrux
Output
http://sun.ru/x
Input
ftphttprururu
Output
ftp://http.ru/ruru
-----Note-----
In the second sample there are two more possible answers: "ftp://httpruru.ru" and "ftp://httpru.ru/ru".
I tried it in Python, but could not do it. Can you solve it? | s=input()
n=len(s)
if s[0]=='h':
print(s[0:4]+'://',end='')
print(s[4],end='')
for i in range(5,n-1):
if s[i]=='r' and s[i+1]=='u':
break
else:
print(s[i],end='')
print('.'+'ru',end='')
if i+2!=n :
print('/'+s[i+2:n])
else:
print(s[0:3]+'://',end='')
print(s[3],end='')
for i in range(4,n-1):
if s[i]=='r' and s[i+1]=='u':
break
else:
print(s[i],end='')
print('.'+'ru',end='')
if i+2!=n :
print('/'+s[i+2:n]) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that $\sum_{k = 1}^{i - 1} a_{k} = \sum_{k = i}^{j} a_{k} = \sum_{k = j + 1}^{n} a_{k}$.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 5·10^5), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≤ 10^9) — the elements of array a.
-----Output-----
Print a single integer — the number of ways to split the array into three parts with the same sum.
-----Examples-----
Input
5
1 2 3 0 3
Output
2
Input
4
0 1 -1 0
Output
1
Input
2
4 1
Output
0 | n=int(input())
lis=input().split()
for i in range(n):
lis[i]=int(lis[i])
lis=[0]+lis
lis1=[0]
for i in range(1,n+1):
lis1.append(lis1[i-1]+lis[i])
if lis1[n]==0:
lis2=[]
for i in range(1,n):
if lis1[i]==0:
lis2.append(i)
m=len(lis2)
if m>=2:
print(int(m*(m-1)/2))
else:
print(0)
else:
lis2=[]
lis3=[]
for i in range(n):
if lis1[i]==lis1[n]/3:
lis2.append(i)
if lis1[i]==lis1[n]*2/3:
lis3.append(i)
m1=len(lis2)
m2=len(lis3)
if m1>=1 and m2>=1:
lis4=[0 for k in range(m1)]
for i in range(m1):
j=0
while j<=m2-1 and lis3[j]<=lis2[i]:
j+=1
lis4[i]=m2-j
print(sum(lis4))
else:
print(0) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/816/B:
To stay woke and attentive during classes, Karen needs some coffee! [Image]
Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".
She knows n coffee recipes. The i-th recipe suggests that coffee should be brewed between l_{i} and r_{i} degrees, inclusive, to achieve the optimal taste.
Karen thinks that a temperature is admissible if at least k recipes recommend it.
Karen has a rather fickle mind, and so she asks q questions. In each question, given that she only wants to prepare coffee with a temperature between a and b, inclusive, can you tell her how many admissible integer temperatures fall within the range?
-----Input-----
The first line of input contains three integers, n, k (1 ≤ k ≤ n ≤ 200000), and q (1 ≤ q ≤ 200000), the number of recipes, the minimum number of recipes a certain temperature must be recommended by to be admissible, and the number of questions Karen has, respectively.
The next n lines describe the recipes. Specifically, the i-th line among these contains two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 200000), describing that the i-th recipe suggests that the coffee be brewed between l_{i} and r_{i} degrees, inclusive.
The next q lines describe the questions. Each of these lines contains a and b, (1 ≤ a ≤ b ≤ 200000), describing that she wants to know the number of admissible integer temperatures between a and b degrees, inclusive.
-----Output-----
For each question, output a single integer on a line by itself, the number of admissible integer temperatures between a and b degrees, inclusive.
-----Examples-----
Input
3 2 4
91 94
92 97
97 99
92 94
93 97
95 96
90 100
Output
3
3
0
4
Input
2 1 1
1 1
200000 200000
90 100
Output
0
-----Note-----
In the first test case, Karen knows 3 recipes. The first one recommends brewing the coffee between 91 and 94 degrees, inclusive. The second one...
I tried it in Python, but could not do it. Can you solve it? | n,k,q = list(map(int,input().split()))
from itertools import accumulate
count = [0 for _ in range(200002)]
for _ in range(n):
l,r = list(map(int,input().split()))
count[l] += 1
count[r+1] -= 1
ok = 0
count2 = [0 for _ in range(200002)]
for i,v in enumerate(count):
ok += v
if ok >= k:
count2[i] = 1
else:
count2[i] = 0
prefixe = list(accumulate(count2))
res = []
for _ in range(q):
l,r = list(map(int,input().split()))
res.append(str(prefixe[r]-prefixe[l-1]))
print('\n'.join(res)) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1245/D:
Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows:
There are $n$ new cities located in Prefecture X. Cities are numbered from $1$ to $n$. City $i$ is located $x_i$ km North of the shrine and $y_i$ km East of the shrine. It is possible that $(x_i, y_i) = (x_j, y_j)$ even when $i \ne j$.
Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections.
Building a power station in City $i$ will cost $c_i$ yen; Making a connection between City $i$ and City $j$ will cost $k_i + k_j$ yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City $i$ and City $j$ are connected by a wire, the wire will go through any shortest path from City $i$ to City $j$. Thus, the length of the wire if City $i$ and City $j$ are connected is $|x_i - x_j| + |y_i - y_j|$ km.
Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help.
And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made.
If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.
-----Input-----
First line of input contains a single integer $n$ ($1 \leq n \leq 2000$) — the number of cities.
Then,...
I tried it in Python, but could not do it. Can you solve it? | n=int(input())
X=[[0]*7 for _ in range(n)]
for i in range(n):
x,y=map(int,input().split())
X[i][0]=i+1
X[i][1]=x
X[i][2]=y
C=[int(i) for i in input().split()]
K=[int(i) for i in input().split()]
for i in range(n):
X[i][3]=C[i]
X[i][4]=K[i]
ans_am=0
ans_ps=0
Ans=[]
ans_con=0
Con=[]
def m(X):
ret=0
cur=X[0][3]
for i in range(1,len(X)):
if X[i][3]<cur:
ret=i
cur=X[i][3]
return ret
while X:
r=m(X)
ind,x,y,c,k,flag,source=X.pop(r)
ans_am+=c
if flag==0:
ans_ps+=1
Ans.append(ind)
else:
ans_con+=1
Con.append([ind,source])
for i in range(len(X)):
indi,xi,yi,ci,ki,flagi,sourcei=X[i]
if (k+ki)*(abs(x-xi)+abs(y-yi))<ci:
X[i][3]=(k+ki)*(abs(x-xi)+abs(y-yi))
X[i][5]=1
X[i][6]=ind
print(ans_am)
print(ans_ps)
print(*Ans)
print(ans_con)
for i,j in Con:
print(i,j) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/MTYFRI:
Motu and Tomu are very good friends who are always looking for new games to play against each other and ways to win these games. One day, they decided to play a new type of game with the following rules:
- The game is played on a sequence $A_0, A_1, \dots, A_{N-1}$.
- The players alternate turns; Motu plays first, since he's earlier in lexicographical order.
- Each player has a score. The initial scores of both players are $0$.
- On his turn, the current player has to pick the element of $A$ with the lowest index, add its value to his score and delete that element from the sequence $A$.
- At the end of the game (when $A$ is empty), Tomu wins if he has strictly greater score than Motu. Otherwise, Motu wins the game.
In other words, Motu starts by selecting $A_0$, adding it to his score and then deleting it; then, Tomu selects $A_1$, adds its value to his score and deletes it, and so on.
Motu and Tomu already chose a sequence $A$ for this game. However, since Tomu plays second, he is given a different advantage: before the game, he is allowed to perform at most $K$ swaps in $A$; afterwards, the two friends are going to play the game on this modified sequence.
Now, Tomu wants you to determine if it is possible to perform up to $K$ swaps in such a way that he can win this game.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $K$ denoting the number of elements in the sequence and the maximum number of swaps Tomu can perform.
- The second line contains $N$ space-separated integers $A_0, A_1, \dots, A_{N-1}$.
-----Output-----
For each test case, print a single line containing the string "YES" if Tomu can win the game or "NO" otherwise (without quotes).
-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 10,000$
- $0 \le K \le 10,000$
- $1 \le A_i \le 10,000$ for each valid $i$
-----Subtasks-----
Subtask #1 (20 points): $1...
I tried it in Python, but could not do it. Can you solve it? | for _ in range(int(input())):
n,k = list(map(int,input().split()))
a = list(map(int,input().split()))
m = []
t = []
for i in range(n):
if(i%2 == 0):
m.append(a[i])
else:
t.append(a[i])
m.sort(reverse=True)
t.sort()
mi=min(len(m),len(t))
x1=0
x2=0
while(k!=0 and x1<len(m) and x2<len(m)):
if(m[x1]>t[x2]):
m[x1],t[x2] = t[x2],m[x1]
x1+=1
x2+=1
else:
break
k-=1
if(sum(t) > sum(m)):
print("YES")
else:
print("NO") | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/ENDE2020/problems/ENCDEC5:
Chef is playing a game with his childhood friend. He gave his friend a list of N numbers named $a_1, a_2 .... a_N$ (Note: All numbers are unique). Adjust the numbers in the following order:
$(i)$ swap every alternate number with it's succeeding number (If N is odd, do not swap the last number i.e. $a_N$ ).
$(ii)$ add %3 of every number to itself.
$(iii)$ swap the ith number and the (N-i-1) th number.
After this, Chef will give a number to his friend and he has to give the nearest greater and smaller number to it.
If there is no greater or lesser number, put -1.
Help his friend to find the two numbers.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, an integers $N$.
- Next line contains $N$ integers separated by a space.
- Next line contains a number to be found, $M$.
-----Output:-----
For each test case, output in a single line answer given the immediate smaller and greater number separated by a space.
-----Constraints-----
- $1 \leq T \leq 1000$
- $3 \leq N \leq 10^5$
- $1 \leq N_i \leq 10^9$
- $1 \leq M \leq 10^9$
-----Sample Input:-----
1
10
5 15 1 66 55 32 40 22 34 11
38
-----Sample Output:-----
35 41
-----Explaination:-----
Step 1: 15 5 66 1 32 55 22 40 11 34
Step 2: 15 7 66 2 34 56 23 41 13 35
Step 3: 35 13 41 23 56 34 2 66 7 15
35 is the number lesser than 38 and 41 is the number greater than 38 in the given set of numbers.
I tried it in Python, but could not do it. Can you solve it? | # cook your dish here
t=int(input())
while t>0:
n=int(input())
arr=list(map(int,input().split()))
m=int(input())
p=-1
q=-1
for x in arr:
x+=x%3
if x<m:
if p==-1 or x>p:
p=x
elif x>m:
if q==-1 or x<q:
q=x
print(p,' ',q)
t-=1 | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Chef likes prime numbers. However, there is one thing he loves even more. Of course, it's semi-primes! A semi-prime number is an integer which can be expressed as a product of two distinct primes. For example, $15 = 3 \cdot 5$ is a semi-prime number, but $1$, $9 = 3 \cdot 3$ and $5$ are not.
Chef is wondering how to check if an integer can be expressed as a sum of two (not necessarily distinct) semi-primes. Help Chef with this tough task!
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single integer $N$.
-----Output-----
For each test case, print a single line containing the string "YES" if it is possible to express $N$ as a sum of two semi-primes or "NO" otherwise.
-----Constraints-----
- $1 \le T \le 200$
- $1 \le N \le 200$
-----Example Input-----
3
30
45
62
-----Example Output-----
YES
YES
NO
-----Explanation-----
Example case 1: $N=30$ can be expressed as $15 + 15 = (3 \cdot 5) + (3 \cdot 5)$.
Example case 2: $45$ can be expressed as $35 + 10 = (5 \cdot 7) + (2 \cdot 5)$.
Example case 3: $62$ cannot be expressed as a sum of two semi-primes. | def sievearray():
n=200
sieve=[1 for i in range(n+1)]
sieve[0]=0
sieve[1]=0
i=2
while i*i<=n:
if sieve[i]==1:
for j in range(i*i,n+1,i):
sieve[j]=0
i+=1
return sieve
def semiprime(n):
i=2
m2=0
m1=0
while i!=n:
if n%i==0 and sieve[i]==1:
m1=i
if n==m1*m2 and m1!=m2:
return 1
else:
m2=m1
i+=1
return 0
def sum_of_two(n):
for i in range(2,n//2+1):
p=i
q=n-i
if semiprime(p) and semiprime(q):
return 1
try:
t=0
t=int(input())
sieve=sievearray()
except Exception:
pass
l1=[0 for i in range(0,t)]
for i in range(0,t):
l1[i]=int(input())
for i in range(0,len(l1)):
if sum_of_two(l1[i]):
print("YES")
else:
print("NO") | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/409/F:
-----Input-----
The input contains a single integer a (1 ≤ a ≤ 64).
-----Output-----
Output a single integer.
-----Examples-----
Input
2
Output
1
Input
4
Output
2
Input
27
Output
5
Input
42
Output
6
I tried it in Python, but could not do it. Can you solve it? | number=[0, 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51, 1, 2, 1, 14, 1, 2, 2, 14, 1, 6, 1, 4, 2, 2, 1, 52, 2, 5, 1, 5, 1, 15, 2, 13, 2, 2, 1, 13, 1, 2, 4, 267, 1, 4, 1, 5, 1, 4, 1, 50, 1, 2, 3, 4, 1, 6, 1, 52, 15, 2, 1, 15, 1, 2, 1, 12, 1, 10, 1, 4, 2]
print(number[int(input())]) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.
Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. [Image]
However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.
Write a program that models the behavior of Ankh-Morpork residents.
-----Input-----
The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks.
The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.
-----Output-----
Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.
-----Examples-----
Input
3
3 1 2
Output
3
2 1
Input
5
4 5 1 2 3
Output
5 4
3 2 1
-----Note-----
In the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before. | n = int(input())
maxsn = n-1
a = list(map(int, input().split()))
snacks = [0] * 100001
for i in range(n):
snacks[a[i]-1] = 1
while snacks[maxsn] == 1:
snacks[maxsn] = 0
print(maxsn + 1, end=' ')
maxsn -= 1
print() | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Let's say you have a bunch of points, and you want to round them all up and calculate the area of the smallest polygon containing all of the points (nevermind why, you just want a challenge). What you're looking for is the area of the *convex hull* of these points. Here is an example, delimited in blue :
## Your task
Implement a function that will compute the area covered by the convex hull that can be formed from an array of points, the area being rounded to two decimal places. The points are given as `(x,y)`, like in an orthonormal coordinates system.
```python
points = [(0, 0), (0, 3), (4, 0)]
convex_hull_area(points) == 6.00
```
*Note* : In Python, the scipy module has a [ready made solution](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html) for this. Of course, if you use it here, you are lame.
*P. S.* : If you enjoy this kata, you may also like this one, which asks you to compute a convex hull, without finding its area. | def cross(p1,p2,p):
return (p[1] - p1[1]) * (p2[0] - p1[0]) - (p2[1] - p1[1]) * (p[0] - p1[0])
def dist_to(p1):
def f(p):
return (p1[0]-p[0]) * (p1[0]-p[0]) + (p1[1]-p[1]) * (p1[1]-p[1])
return f
def xy_yx(p1,p2):
return p1[0]*p2[1] - p1[1]*p2[0]
def convex_hull_area(pts):
if len(pts) == 0:
return 0
pts = set(pts)
new = min(pts)
head = new
area = 0
while 1 :
tail = new
d_fn = dist_to(tail)
new = next(iter(pts))
for test in pts:
if test != new and test != tail:
c = cross(tail,new,test)
if tail == new or c > 0:
new = test
elif c == 0 :
new = max(new,test,key=d_fn)
area += xy_yx(tail, new)
if new is head:
return round(abs(area)/2.0,2) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.)
Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?
(We assume that there are six kinds of coins available: 500-yen, 100-yen, 50-yen, 10-yen, 5-yen, and 1-yen coins.)
-----Constraints-----
- 0 \leq X \leq 10^9
- X is an integer.
-----Input-----
Input is given from Standard Input in the following format:
X
-----Output-----
Print the maximum number of happiness points that can be earned.
-----Sample Input-----
1024
-----Sample Output-----
2020
By exchanging his money so that he gets two 500-yen coins and four 5-yen coins, he gains 2020 happiness points, which is the maximum number of happiness points that can be earned. | def __starting_point():
x = int(input())
ans = (x // 500)
if ans > 0:
x = x - (500 * ans)
ans *= 1000
ans += (x // 5) * 5
print(ans)
__starting_point() | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5b713d7187c59b53e60000b0:
If we multiply the integer `717 (n)` by `7 (k)`, the result will be equal to `5019`.
Consider all the possible ways that this last number may be split as a string and calculate their corresponding sum obtained by adding the substrings as integers. When we add all of them up,... surprise, we got the original number `717`:
```
Partitions as string Total Sums
['5', '019'] 5 + 19 = 24
['50', '19'] 50 + 19 = 69
['501', '9'] 501 + 9 = 510
['5', '0', '19'] 5 + 0 + 19 = 24
['5', '01', '9'] 5 + 1 + 9 = 15
['50', '1', '9'] 50 + 1 + 9 = 60
['5', '0', '1', '9'] 5 + 0 + 1 + 9 = 15
____________________
Big Total: 717
____________________
```
In fact, `717` is one of the few integers that has such property with a factor `k = 7`.
Changing the factor `k`, for example to `k = 3`, we may see that the integer `40104` fulfills this property.
Given an integer `start_value` and an integer `k`, output the smallest integer `n`, but higher than `start_value`, that fulfills the above explained properties.
If by chance, `start_value`, fulfills the property, do not return `start_value` as a result, only the next integer. Perhaps you may find this assertion redundant if you understood well the requirement of the kata: "output the smallest integer `n`, but higher than `start_value`"
The values for `k` in the input may be one of these: `3, 4, 5, 7`
### Features of the random tests
If you want to understand the style and features of the random tests, see the *Notes* at the end of these instructions.
The random tests are classified in three parts.
- Random tests each with one of the possible values of `k` and a random `start_value` in the interval `[100, 1300]`
- Random tests each with a `start_value` in a larger interval for each value of `k`, as follows:
- for `k = 3`, a random `start value` in the range...
I tried it in Python, but could not do it. Can you solve it? | def partitions(s):
if s:
for i in range(1, len(s)+1):
for p in partitions(s[i:]):
yield [s[:i]] + p
else:
yield []
def add_values (product_string):
product_list = partitions(product_string)
return sum([sum (map(int,items)) for items in list(product_list)[:-1]])
def next_higher(start_value,k):
product = (start_value+1) * k
while add_values(str(product)) != start_value:
start_value+=1
product = start_value*k
return start_value | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc143/tasks/abc143_c:
There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.
Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.
Ultimately, how many slimes will be there?
-----Constraints-----
- 1 \leq N \leq 10^5
- |S| = N
- S consists of lowercase English letters.
-----Input-----
Input is given from Standard Input in the following format:
N
S
-----Output-----
Print the final number of slimes.
-----Sample Input-----
10
aabbbbaaca
-----Sample Output-----
5
Ultimately, these slimes will fuse into abaca.
I tried it in Python, but could not do it. Can you solve it? | N = int(input())
S = str(input())
cnt = 1
for i in range(1,N):
if S[i] == S[i-1]:
pass
else:
cnt += 1
print(cnt) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
The new £5 notes have been recently released in the UK and they've certainly became a sensation! Even those of us who haven't been carrying any cash around for a while, having given in to the convenience of cards, suddenly like to have some of these in their purses and pockets. But how many of them could you get with what's left from your salary after paying all bills? The programme that you're about to write will count this for you!
Given a salary and the array of bills, calculate your disposable income for a month and return it as a number of new £5 notes you can get with that amount. If the money you've got (or do not!) doesn't allow you to get any £5 notes return 0.
£££ GOOD LUCK! £££ | def get_new_notes(salary,bills):
return max((salary-sum(bills))//5, 0) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?
-----Input-----
The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion.
The second line contains n distinct space-separated numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — the values of the banknotes.
-----Output-----
Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print - 1.
-----Examples-----
Input
5
1 2 3 4 5
Output
-1 | def __starting_point():
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
if a[0] == 1:
print(-1)
else:
print(1)
__starting_point() | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $k$ have the same sum. A subarray of an array is any sequence of consecutive elements.
Phoenix currently has an array $a$ of length $n$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $1$ and $n$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.
-----Input-----
The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 50$) — the number of test cases.
The first line of each test case contains two integers $n$ and $k$ ($1 \le k \le n \le 100$).
The second line of each test case contains $n$ space-separated integers ($1 \le a_i \le n$) — the array that Phoenix currently has. This array may or may not be already beautiful.
-----Output-----
For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines.
The first line should contain the length of the beautiful array $m$ ($n \le m \le 10^4$). You don't need to minimize $m$.
The second line should contain $m$ space-separated integers ($1 \le b_i \le n$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $a$. You may print integers that weren't originally in array $a$.
If there are multiple solutions, print any. It's guaranteed that if we can make array $a$ beautiful, we can always make it with resulting length no more than $10^4$.
-----Example-----
Input
4
4 2
1 2 2 1
4 3
1 2 2 1
3 2
1 2 3
4 4
4 3 4 2
Output
5
1 2 1 2 1
4
1 2 2 1
-1
7
4 3 2 1 4 3 2
-----Note-----
In the first test case, we can make array $a$ beautiful by inserting the integer $1$ at index $3$ (in between the two existing $2$s). Now, all subarrays of length $k=2$ have the same sum $3$. There exists many other possible solutions, for example: $2, 1, 2, 1, 2, 1$... | for _ in range(int(input())):
n, k = list(map(int, input().split()))
arr = list(map(int, input().split()))
if len(set(arr)) > k:
print(-1)
else:
result = []
temp = list(set(arr))
for i in range(1, n + 1):
if len(temp) == k:
break
if i not in temp:
temp.append(i)
for i in range(len(arr)):
result.extend(temp)
print(len(result))
print(*result) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/707/C:
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 to triple. Such triples are called Pythagorean triples.
For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.
Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.
Katya had no problems with completing this task. Will you do the same?
-----Input-----
The only line of the input contains single integer n (1 ≤ n ≤ 10^9) — the length of some side of a right triangle.
-----Output-----
Print two integers m and k (1 ≤ m, k ≤ 10^18), such that n, m and k form a Pythagorean triple, in the only line.
In case if there is no any Pythagorean triple containing integer n, print - 1 in the only line. If there are many answers, print any of them.
-----Examples-----
Input
3
Output
4 5
Input
6
Output
8 10
Input
1
Output
-1
Input
17
Output
144 145
Input
67
Output
2244 2245
-----Note-----[Image]
Illustration for the first sample.
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
if n % 4 == 0:
temp = n // 4
m = temp * 3
k = temp * 5
elif n % 2 == 0:
n //= 2
m = n**2 // 2
k = m + 1
m *= 2
k *= 2
else:
m = n**2 // 2
k = m + 1
if 3 > n:
print("-1")
else:
print(m,k) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
----- Statement -----
You need to find a string which has exactly K positions in it such that the character at that position comes alphabetically later than the character immediately after it. If there are many such strings, print the one which has the shortest length. If there is still a tie, print the string which comes the lexicographically earliest (would occur earlier in a dictionary).
-----Input-----
The first line contains the number of test cases T. Each test case contains an integer K (≤ 100).
-----Output-----
Output T lines, one for each test case, containing the required string. Use only lower-case letters a-z.
-----Sample Input -----
2
1
2
-----Sample Output-----
ba
cba | x = 'abcdefghijklmnopqrstuvwxyz'
for i in range(int(input())):
num = int(input())
r = ''
while 1:
r = x[num::-1]+r
if num<26:
break
num-=25
print(r) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", str = "dog dog dog dog"
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space. | class Solution:
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
return list(map(pattern.find, pattern)) == list(map(str.split().index, str.split())) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You are given two positive integers a and b.
Let x be the average of a and b.
Print x rounded up to the nearest integer.
-----Constraints-----
- a and b are integers.
- 1 \leq a, b \leq 100
-----Input-----
Input is given from Standard Input in the following format:
a b
-----Output-----
Print x rounded up to the nearest integer.
-----Sample Input-----
1 3
-----Sample Output-----
2
The average of 1 and 3 is 2.0, and it will be rounded up to the nearest integer, 2. | #ABC082A
a,b = list(map(int,input().split()))
a+=b
print(((a+2-1)//2)) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/ALGT2013/problems/TNMALG07:
In a bizarre game of chess ,knight was so drunk, that instead of his usual move he started walking straight. In every move Knight jumps on 2n steps forward (n is number of block that he had travelled so far from starting) but after that he has to take either 1 step forward or backward.
Now the Knight needs to get to position X so King (i.e. You) needs to decide the order of his backward or forward step in such a way that he can reach its destination in minimum number of steps. Remember he always travels in a straight line and the length of the board is infinite.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases, for each test case enter value X ( i.e. destination)
Note : initially knight is at n = 1.
-----Output-----
For each test case the output should be string of numbers 1 & 2 where 1 denotes backward step and 2 denote the forward step
Note : for no solution print 0.
-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ X ≤ 10^10
-----Example-----
Input:
2
17
10
Output:
2111
0
-----Explanation-----
Case 1 : starting from n = 1 , knight moves to n = 3 ('2') , 5 ('1') , 9 ('1') , 17 ('1') i.e. string printed is 2 1 1 1
Case 2 : no solution is possible
I tried it in Python, but could not do it. Can you solve it? | t=int(input())
getBin = lambda x: x >= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:]
while(t):
n=int(input())
if(n%2==0):
print(0)
else:
lst=[]
arr=getBin(n)
for i in range(0,len(arr)-1):
if(arr[i]=='1'):
lst.append("2")
if(arr[i]=='0'):
lst.append("1")
print("".join(lst))
t=t-1 | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
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 String. Your task is to capitalize every word that has length greater than 2, leaving smaller words as they are.
*should work also on Leading and Trailing Spaces and caps.
```python
drop_cap('apple') => "Apple"
drop_cap('apple of banana'); => "Apple of Banana"
drop_cap('one space'); => "One Space"
drop_cap(' space WALK '); => " Space Walk "
```
**Note:** you will be provided atleast one word and should take string as input and return string as output. | import re
def drop_cap(s):
return re.sub(r'\S{3,}', lambda m: m.group(0).title(), s) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Stepan has n pens. Every day he uses them, and on the i-th day he uses the pen number i. On the (n + 1)-th day again he uses the pen number 1, on the (n + 2)-th — he uses the pen number 2 and so on.
On every working day (from Monday to Saturday, inclusive) Stepan spends exactly 1 milliliter of ink of the pen he uses that day. On Sunday Stepan has a day of rest, he does not stend the ink of the pen he uses that day.
Stepan knows the current volume of ink in each of his pens. Now it's the Monday morning and Stepan is going to use the pen number 1 today. Your task is to determine which pen will run out of ink before all the rest (that is, there will be no ink left in it), if Stepan will use the pens according to the conditions described above.
-----Input-----
The first line contains the integer n (1 ≤ n ≤ 50 000) — the number of pens Stepan has.
The second line contains the sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is equal to the number of milliliters of ink which the pen number i currently has.
-----Output-----
Print the index of the pen which will run out of ink before all (it means that there will be no ink left in it), if Stepan will use pens according to the conditions described above.
Pens are numbered in the order they are given in input data. The numeration begins from one.
Note that the answer is always unambiguous, since several pens can not end at the same time.
-----Examples-----
Input
3
3 3 3
Output
2
Input
5
5 4 5 4 4
Output
5
-----Note-----
In the first test Stepan uses ink of pens as follows: on the day number 1 (Monday) Stepan will use the pen number 1, after that there will be 2 milliliters of ink in it; on the day number 2 (Tuesday) Stepan will use the pen number 2, after that there will be 2 milliliters of ink in it; on the day number 3 (Wednesday) Stepan will use the pen number 3, after that there will be 2 milliliters of ink in it; on the day number 4 (Thursday) Stepan will use the pen number 1, after that there will be 1... | import sys
def Min(x, y):
if x > y:
return y
else:
return x
def Gcd(x, y):
if x == 0:
return y
else:
return Gcd(y % x, x)
def Lcm(x, y):
return x * y // Gcd(x, y)
n = int(input())
a = [int(i) for i in input().split()]
d = [int(0) for i in range(0, n)]
ok = 0
cur = 0
len = Lcm(7, n)
for i in range(0, 7 * n):
if a[i % n] == 0 :
print(i % n + 1)
ok = 1
break
if cur != 6:
a[i % n] -= 1
d[i % n] += 1
cur = (cur + 1) % 7
if ok == 0:
k = 10**20
for i in range(0, n):
a[i] += d[i]
if d[i] == 0: continue
if a[i] % d[i] > 0:
k = Min(k, a[i] // d[i])
else:
k = Min(k, a[i] // d[i] - 1)
if k == 10**20:
k = 0
for i in range(0, n):
a[i] -= k * d[i]
iter = 0
cur = 0
while True:
if a[iter] == 0:
print(iter % n + 1)
break
else:
if cur != 6:
a[iter] -= 1
cur = (cur + 1) % 7
iter = (iter + 1) % n | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Anna Hazare is a well known social activist in India.
On 5th April, 2011 he started "Lokpal Bill movement".
Chef is very excited about this movement. He is thinking of contributing to it. He gathers his cook-herd and starts thinking about how our community can contribute to this.
All of them are excited about this too, but no one could come up with any idea. Cooks were slightly disappointed with this and went to consult their friends.
One of the geekiest friend gave them the idea of spreading knowledge through Facebook. But we do not want to spam people's wall. So our cook came up with the idea of dividing Facebook users into small friend groups and then identify the most popular friend in each group and post on his / her wall. They started dividing users into groups of friends and identifying the most popular amongst them.
The notoriety of a friend is defined as the averaged distance from all the other friends in his / her group. This measure considers the friend himself, and the trivial distance of '0' that he / she has with himself / herself.
The most popular friend in a group is the friend whose notoriety is least among all the friends in the group.
Distance between X and Y is defined as follows:
Minimum number of profiles that X needs to visit for reaching Y's profile(Including Y's profile). X can open only those profiles which are in the friend list of the current opened profile. For Example:
- Suppose A is friend of B.
- B has two friends C and D.
- E is a friend of D.
Now, the distance between A and B is 1, A and C is 2, C and E is 3.
So, one of our smart cooks took the responsibility of identifying the most popular friend in each group and others will go to persuade them for posting. This cheeky fellow knows that he can release his burden by giving this task as a long contest problem.
Now, he is asking you to write a program to identify the most popular friend among all the friends in each group. Also, our smart cook wants to know the average distance of everyone from the most... | from collections import deque
from sys import stdin
import psyco
psyco.full()
graph = [[]]
WHITE, GRAY, BLACK = 0, 1, 2
def notoriety(x, f_count):
queue = deque([x])
d = [0 for i in range(f_count+1)]
p = [0 for i in range(f_count+1)]
color = [WHITE for i in range(f_count+1)]
while len(queue) > 0:
top = queue.pop()
for node in graph[top]:
if color[node] == WHITE:
queue.appendleft(node)
color[node], p[node], d[node] = GRAY, top, d[top] + 1
color[top] = BLACK
return sum(d)/(f_count*1.0)
def main():
groups = int(stdin.readline())
for g in range(groups):
global graph
graph = [[]]
no_of_friends = int(stdin.readline())
for i in range(no_of_friends):
graph.append(list(map(int,stdin.readline().split())))
min_notoriety, popular = 10000000, -1 # yet another magic number
for f in range(1,no_of_friends+1):
curr_not = notoriety(f, no_of_friends)
if curr_not < min_notoriety:
min_notoriety,popular = curr_not, f
assert popular != -1
print(popular, "%.6f" %min_notoriety)
def __starting_point():
main()
__starting_point() | python | train | qsol | codeparrot/apps | all |
Solve in Python:
## The story you are about to hear is true
Our cat, Balor, sadly died of cancer in 2015.
While he was alive, the three neighborhood cats Lou, Mustache Cat, and Raoul all recognized our house and yard as Balor's territory, and would behave respectfully towards him and each other when they would visit.
But after Balor died, gradually each of these three neighborhood cats began trying to claim his territory as their own, trying to drive the others away by growling, yowling, snarling, chasing, and even fighting, when one came too close to another, and no human was right there to distract or extract one of them before the situation could escalate.
It is sad that these otherwise-affectionate animals, who had spent many afternoons peacefully sitting and/or lying near Balor and each other on our deck or around our yard, would turn on each other like that. However, sometimes, if they are far enough away from each other, especially on a warm day when all they really want to do is pick a spot in the sun and lie in it, they will ignore each other, and once again there will be a Peaceable Kingdom.
## Your Mission
In this, the first and simplest of a planned trilogy of cat katas :-), all you have to do is determine whether the distances between any visiting cats are large enough to make for a peaceful afternoon, or whether there is about to be an altercation someone will need to deal with by carrying one of them into the house or squirting them with water or what have you.
As input your function will receive a list of strings representing the yard as a grid, and an integer representing the minimum distance needed to prevent problems (considering the cats' current states of sleepiness). A point with no cat in it will be represented by a "-" dash. Lou, Mustache Cat, and Raoul will be represented by an upper case L, M, and R respectively. At any particular time all three cats may be in the yard, or maybe two, one, or even none.
If the number of cats in the yard is one or none, or if the distances between all cats are... | from itertools import combinations
from math import hypot
def peaceful_yard(yard, min_distance):
l, yard = len(yard[0]), "".join(yard)
cats = (divmod(yard.index(c), l) for c in "LMR" if c in yard)
distances = (hypot(x2-x1, y2-y1) for (x1, y1), (x2, y2) in combinations(cats, 2))
return all(min_distance <= d for d in distances)
# one-liner
#peaceful_yard = lambda y, m: all(m <= d for d in (hypot(x2-x1, y2-y1) for (x1, y1), (x2, y2) in combinations((divmod(i, len(y[0])) for i, c in enumerate("".join(y)) if c != "-"), 2)))
# alternatives:
# more intuitive but much slower:
# cats = [divmod(i, l) for i, c in enumerate(yard) if c != "-"]
# less readable but avoid imports:
# distances = [((x2-x1)**2 + (y2-y1)**2)**0.5 for i, (x1, y1) in enumerate(cats, 1) for (x2, y2) in cats[i:]] | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
-----Input-----
The first and only line of input contains a single integer $n$ ($1 \le n \le 10^9$).
-----Output-----
Output the minimum number of bills that Allen could receive.
-----Examples-----
Input
125
Output
3
Input
43
Output
5
Input
1000000000
Output
10000000
-----Note-----
In the first sample case, Allen can withdraw this with a $100$ dollar bill, a $20$ dollar bill, and a $5$ dollar bill. There is no way for Allen to receive $125$ dollars in one or two bills.
In the second sample case, Allen can withdraw two $20$ dollar bills and three $1$ dollar bills.
In the third sample case, Allen can withdraw $100000000$ (ten million!) $100$ dollar bills. | n=int(input())
c=0
c+=n//100
n=n%100
c+=n//20
n=n%20
c+=n//10
n=n%10
c+=n//5
n=n%5
c+=n//1
n=n%1
print(c) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/975/C:
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.
Ivar has $n$ warriors, he places them on a straight line in front of the main gate, in a way that the $i$-th warrior stands right after $(i-1)$-th warrior. The first warrior leads the attack.
Each attacker can take up to $a_i$ arrows before he falls to the ground, where $a_i$ is the $i$-th warrior's strength.
Lagertha orders her warriors to shoot $k_i$ arrows during the $i$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $t$, they will all be standing to fight at the end of minute $t$.
The battle will last for $q$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.
-----Input-----
The first line contains two integers $n$ and $q$ ($1 \le n, q \leq 200\,000$) — the number of warriors and the number of minutes in the battle.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) that represent the warriors' strengths.
The third line contains $q$ integers $k_1, k_2, \ldots, k_q$ ($1 \leq k_i \leq 10^{14}$), the $i$-th of them represents Lagertha's order at the $i$-th minute: $k_i$ arrows will attack the warriors.
-----Output-----
Output $q$ lines, the $i$-th of them is the number of standing warriors after the $i$-th minute.
-----Examples-----
Input
5 5
1 2 1 2 1
3 10 1 1 1
Output
3
5
4
4
3
Input
4 4
1 2 3 4
9 1 10 6
Output
1
4
4
1
-----Note-----
In the first example: after the 1-st minute, the 1-st and 2-nd warriors die. after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 — all warriors are alive. after the 3-rd minute, the 1-st warrior...
I tried it in Python, but could not do it. Can you solve it? | #!/usr/bin/env python3
import bisect
[n, q] = list(map(int, input().strip().split()))
ais = list(map(int, input().strip().split()))
kis = list(map(int, input().strip().split()))
iais = [0 for _ in range(n + 1)]
for i in range(n):
iais[i + 1] = iais[i] + ais[i]
s = 0
tot = iais[-1]
r = 0
for k in kis:
s += k
if s >= tot:
print (n)
s = 0
r = 0
else:
r = bisect.bisect_right(iais, s, r) - 1
print(n - r) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Chef just come up with a very good idea for his business. He needs to hire two group of software engineers. Each group of engineers will work on completely different things and people from different groups don't want to disturb (and even hear) each other. Chef has just rented a whole floor for his purposes in business center "Cooking Plaza". The floor is a rectangle with dimensions N over M meters. For simplicity of description the floor's structure, let's imagine that it is split into imaginary squares of size 1x1 called "cells".
The whole floor is split into rooms (not necessarily rectangular). There are some not noise-resistant walls between some of the cells. Two adjacent cells belong to the same room if they don't have the wall between them. Cells are considered adjacent if and only if they share an edge. Also, we say that relation "belong to the same room" is transitive. In other words we say that if cells A and B belong to the same room and B and C belong to the same room then A and C belong to the same room.
So we end up having a partition of the floor into rooms. It also means, that each point on the floor belongs to some room.
Chef have to distribute the rooms between engineers of two groups. Engineers from the different groups cannot seat in the same room. If engineers from a different groups seat in adjacent rooms, the walls these rooms share have to be noise-resistant. The cost of having one meter of wall isolated is K per month. Due to various reasons Chef has to pay an additional cost for support of each of the room (e.g. cleaning costs money as well). Interesting to know that support cost for a particular room may differ depending on engineers of which group seat in this room.
Chef doesn't know the number of people he needs in each group of engineers so he wants to minimize the money he needs to pay for all the floor rent and support. He will see how it goes and then redistribute the floor or find another floor to rent or whatever. Either way, you don't need to care about this.
Please pay... | import sys
def findRoom(x,y,i):
R = [(x,y)]
GRID[x][y] = i
for n in R:
GRID[n[0]][n[1]] = i
if n[0]>0 and GRID[n[0]-1][n[1]]==0 and H[n[0]-1][n[1]]:
GRID[n[0]-1][n[1]] = i
R.append((n[0]-1,n[1]))
if n[0]<N-1 and GRID[n[0]+1][n[1]]==0 and H[n[0]][n[1]]:
GRID[n[0]+1][n[1]] = i
R.append((n[0]+1,n[1]))
if n[1]>0 and GRID[n[0]][n[1]-1]==0 and V[n[0]][n[1]-1]:
GRID[n[0]][n[1]-1] = i
R.append((n[0],n[1]-1))
if n[1]<M-1 and GRID[n[0]][n[1]+1]==0 and V[n[0]][n[1]]:
GRID[n[0]][n[1]+1] = i
R.append((n[0],n[1]+1))
def roomPrice(r):
wall_price_0 = wall_price_1 = 0
for i in range(R):
if C[i][r] and T[i] != 1:
wall_price_0 += C[i][r]*K
else:
wall_price_1 += C[i][r]*K
return [wall_price_0 + Rooms[r][0], wall_price_1 + Rooms[r][1]]
def total_price():
price = 0
for r in range(R):
for i in range(r):
if C[i][r] and T[i] != T[r]:
price += C[i][r]*K
price += Rooms[r][T[r]-1]
return price
def solve(r):
if r==R:
return 0
wall_price_0 = 0
wall_price_1 = 0
for i in range(r):
if C[i][r] and T[i] != 1:
wall_price_0 += C[i][r]*K
else:
wall_price_1 += C[i][r]*K
if T[r]!=0:
return [wall_price_0,wall_price_1][T[r]-1]+Rooms[r][T[r]-1]+solve(r+1)
T[r] = 1
result = solve(r+1)+wall_price_0+Rooms[r][0]
T[r] = 2
result = min(solve(r+1)+wall_price_1+Rooms[r][1], result)
T[r] = 0
return result
f = sys.stdin
N,M,W,K,R = list(map(int, f.readline().split(' ')))
T = [0] * R
GRID = list(map(list,[[0]*M]*N))
H = list(map(list,[[1]*M]*N))
V = list(map(list,[[1]*M]*N))
Walls = []
for _ in range(W):
x0,y0,x1,y1 = list(map(int, f.readline().split(' ')))
x0 -= 1
x1 -= 1
y0 -= 1
y1 -= 1
if x0==x1:
V[x0][y0] = 0
else:
H[x0][y0] = 0
Walls.append([x0,y0,x1,y1])
Rooms = []
for i in range(R):
x,y,t1,t2 = list(map(int, f.readline().split(' ')))
findRoom(x-1,y-1,i+1)
Rooms.append([t1,t2])
C = list(map(list,[[0]*R]*R))
for w in Walls:
r1 = GRID[w[0]][w[1]]-1
r2 = GRID[w[2]][w[3]]-1
C[r1][r2] += 1
C[r2][r1] += 1
Stable = [False]*R
for r in range(R):
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?
-----Constraints-----
- 1≦N≦100
-----Input-----
The input is given from Standard Input in the following format:
N
-----Output-----
Print the necessary number of candies in total.
-----Sample Input-----
3
-----Sample Output-----
6
The answer is 1+2+3=6. | n = int(input())
print((n*(n+1)//2)) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is the height of the animal occupying the i-th place.
-----Output-----
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers l_{i} and r_{i} (1 ≤ l_{i} < r_{i} ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
-----Examples-----
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
-----Note-----
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed. | n = int(input())
a = list(map(int, input().split()))
swaps = []
for i in range(n):
# find the value at element i
smallest = a[i]
best_pos = i
for j in range(i + 1, n):
if a[j] < smallest:
smallest = a[j]
best_pos = j
# swap from i to j
while best_pos > i:
a[best_pos - 1], a[best_pos] = a[best_pos], a[best_pos - 1]
swaps.append((best_pos, best_pos + 1))
best_pos -= 1
for a, b in swaps:
print(a, b) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/580a0347430590220e000091:
Find the area of a rectangle when provided with one diagonal and one side of the rectangle. If the input diagonal is less than or equal to the length of the side, return "Not a rectangle". If the resultant area has decimals round it to two places.
`This kata is meant for beginners. Rank and upvote to bring it out of beta!`
I tried it in Python, but could not do it. Can you solve it? | def area(d, l):
if d <= l: return 'Not a rectangle'
a = l * (d ** 2 - l ** 2) ** 0.5
return round(a, 2) if a % 1 else int(a) | python | train | abovesol | codeparrot/apps | all |