Muennighoff/xP3x-sample huggingface dataset:
inputs: I found an interesting problem on https://www.codechef.com/TSTIND16/problems/AMR15A:
Kattapa, as you all know was one of the greatest warriors of his time. The kingdom of Maahishmati had never lost a battle under him (as army-chief), and the reason for that was their really powerful army, also called as Mahasena.
Kattapa was known to be a very superstitious person. He believed that a soldier is "lucky" if the soldier is holding an even number of weapons, and "unlucky" otherwise. He considered the army as "READY FOR BATTLE" if the count of "lucky" soldiers is strictly greater than the count of "unlucky" soldiers, and "NOT READY" otherwise.
Given the number of weapons each soldier is holding, your task is to determine whether the army formed by all these soldiers is "READY FOR BATTLE" or "NOT READY".
Note: You can find the definition of an even number here.

-----Input-----

The first line of input consists of a single integer N denoting the number of soldiers. The second line of input consists of N space separated integers A1, A2, ..., AN, where Ai denotes the number of weapons that the ith soldier is holding.

-----Output-----
Generate one line output saying "READY FOR BATTLE", if the army satisfies the conditions that Kattapa requires or "NOT READY" otherwise (quotes for clarity).

-----Constraints-----
- 1 ≤ N ≤ 100
- 1 ≤ Ai ≤ 100

-----Example 1-----
Input:
1
1

Output:
NOT READY

-----Example 2-----
Input:
1
2

Output:
READY FOR BATTLE

-----Example 3-----
Input:
4
11 12 13 14

Output:
NOT READY

-----Example 4-----
Input:
3
2 3 4

Output:
READY FOR BATTLE

-----Example 5-----
Input:
5
1 2 3 4 5

Output:
NOT READY

-----Explanation-----

- Example 1: For the first example, N = 1 and the array A = [1]. There is only 1 soldier and he is holding 1 weapon, which is odd. The number of soldiers holding an even number of weapons = 0, and number of soldiers holding an odd number of weapons = 1. Hence, the answer is "NOT READY" since the number of soldiers holding an even number of weapons is not greater than the number of soldiers holding an odd number of weapons.

- Example 2: For the second...

I tried it in Python, but could not do it. Can you solve it?
targets: n = int(input())
l = list(map(int, input().split()))
even = 0
for i in range(n):
	if l[i]%2 == 0:
		even += 1
odd = n - even
if even > odd:
	print('READY FOR BATTLE')
else:
	print('NOT READY')
inputs: I found an interesting problem on https://leetcode.com/problems/two-city-scheduling/:
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.
Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.
 
Example 1:
Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation: 
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.

The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.

Example 2:
Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859

Example 3:
Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
Output: 3086

 
Constraints:

2n == costs.length
2 <= costs.length <= 100
costs.length is even.
1 <= aCosti, bCosti <= 1000

I tried it in Python, but could not do it. Can you solve it?
targets: # sort by difference, where greatest difference is first?
# [[400, 50], [30, 200], [30, 20], [10, 20]]
#   B           A           B         A

# [[840, 118], [259, 770], [448, 54], [926, 667], [577, 469], [184, 139]]
#       B           A           B          B          A            A 

# [[631, 42], [343, 819], [457, 60], [650, 359], [451, 713], [536, 709], [855, 779], [515, 563]]
#      B          A           B          B           A           A           B           A

# seemingly works for the given cases

# why??

# positives outweight the negatives 
# we will be positive for at least the first n iterations (worst case we pick one city for the first n iterations)

# since we sorted by greatest difference first we will be maximizing our profits by taking 
# the optimal choice when the difference is greatest

# we have costs[i] and costs[j] where i <= n and n < j < 2n and difference[i] > difference[j]
# if we make the optimal choice we will be up difference[i] - difference[j]

class Solution:
    def twoCitySchedCost(self, costs: List[List[int]]) -> int:
        sortedCosts = sorted(costs, key = lambda x: abs(x[0] - x[1]), reverse=True)
        numA = 0
        numB = 0
        res = 0
        
        for cost in sortedCosts:
            if numB >= len(sortedCosts) / 2:
                res += cost[0]
            
            elif numA >= len(sortedCosts) / 2:
                res += cost[1]
            
            else:
                if cost[0] < cost[1]:
                    res += cost[0]
                    numA += 1
                else:
                    res += cost[1]
                    numB += 1
        
        return res
inputs: Solve in Python:
Given an array of positive integers, replace every element with the least greater element to its right.
 If there is no greater element to its right, replace it with -1. For instance, given the array 
 
 `[8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28]`,
 
 the desired output is 
 
 `[18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1]`.

Your task is to create a function "arrayManip()" that takes in an array as its argument, manipulates the array as described above, then return the resulting array.

Note: Return a new array, rather than modifying the passed array.
targets: def array_manip(array):
    return [
        min((x for x in array[i:] if x > n), default=-1)
        for i, n in enumerate(array)]
inputs: Solve in Python:
A number `n` is called `prime happy` if there is at least one prime less than `n` and the `sum of all primes less than n` is evenly divisible by `n`. Write `isPrimeHappy(n)` which returns `true` if `n` is `prime happy` else `false`.
targets: def isPrime(n): 
    for i in range(2,int(n**.5)+1): 
        if n%i == 0:
            return False
    return True 
def is_prime_happy(n):
    sum = 0
    for i in range(2,n): 
        if isPrime(i): 
            sum += i 
    if sum > 0 and not sum%n: 
        return True
    return False
inputs: I found an interesting problem on https://leetcode.com/problems/count-good-nodes-in-binary-tree/:
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
 
Example 1:

Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:

Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1]
Output: 1
Explanation: Root is considered as good.
 
Constraints:

The number of nodes in the binary tree is in the range [1, 10^5].
Each node's value is between [-10^4, 10^4].

I tried it in Python, but could not do it. Can you solve it?
targets: # Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        return self.count_good_nodes(root, root.val)
    
    def count_good_nodes(self, root: TreeNode, highest_val: int) -> int:
        current_highest = highest_val
        total = 0
        
        if root.val >= current_highest:
            total += 1
            current_highest = root.val

        if root.left:
            total += self.count_good_nodes(root.left, current_highest)
        if root.right:
            total += self.count_good_nodes(root.right, current_highest)
        
        return total
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/979/A:
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.

Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.

She has ordered a very big round pizza, in order to serve her many friends. Exactly $n$ of Shiro's friends are here. That's why she has to divide the pizza into $n + 1$ slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.

Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.

As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?


-----Input-----

A single line contains one non-negative integer $n$ ($0 \le n \leq 10^{18}$) — the number of Shiro's friends. The circular pizza has to be sliced into $n + 1$ pieces.


-----Output-----

A single integer — the number of straight cuts Shiro needs.


-----Examples-----
Input
3

Output
2
Input
4

Output
5


-----Note-----

To cut the round pizza into quarters one has to make two cuts through the center with angle $90^{\circ}$ between them.

To cut the round pizza into five equal parts one has to make five cuts.

I tried it in Python, but could not do it. Can you solve it?
targets: n = int(input())
if n == 0:
    print(0)
elif n % 2 == 1:
    print((n + 1) // 2)
else:
    print(n + 1)
inputs: Solve in Python:
Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the half-backs and forwards (plays attack).

Two teams of company Q decided to battle each other. Let's enumerate players from both teams by integers from 1 to 4. The first and second player play in the first team, the third and the fourth one play in the second team. For each of the four players we know their game skills in defence and attack. The defence skill of the i-th player is a_{i}, the attack skill is b_{i}.

Before the game, the teams determine how they will play. First the players of the first team decide who will play in the attack, and who will play in the defence. Then the second team players do the same, based on the choice of their opponents.

We will define a team's defence as the defence skill of player of the team who plays defence. Similarly, a team's attack is the attack skill of the player of the team who plays attack. We assume that one team is guaranteed to beat the other one, if its defence is strictly greater than the opponent's attack and its attack is strictly greater than the opponent's defence.

The teams of company Q know each other's strengths and therefore arrange their teams optimally. Identify the team that is guaranteed to win (if both teams act optimally) or tell that there is no such team.


-----Input-----

The input contain the players' description in four lines. The i-th line contains two space-separated integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 100) — the defence and the attack skill of the i-th player, correspondingly.


-----Output-----

If the first team can win, print phrase "Team 1" (without the quotes), if the second team can win, print phrase "Team 2" (without the quotes). If no of the teams can definitely win, print "Draw" (without the...
targets: team1, team2 = (lambda t : [[list(map(int, input().split())) for x in range(2)] for y in range(2)])('input')
if (lambda t1, t2 : any(all(t1[x][0] > t2[y][1] and t1[1 - x][1] > t2[1 - y][0] for y in range(2)) for x in range(2)))(team1, team2):
    print('Team 1')
elif (lambda t1, t2 : all(any(t2[y][0] > t1[x][1] and t2[1 - y][1] > t1[1 - x][0] for y in range(2)) for x in range(2)))(team1, team2):
    print('Team 2')
else:
    print('Draw')
inputs: I found an interesting problem on https://www.codewars.com/kata/5a045fee46d843effa000070:
The aim of the kata is to decompose `n!` (factorial n) into its prime factors.

Examples:
```
n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11"
since 12! is divisible by 2 ten times, by 3 five times, by 5 two times and by 7 and 11 only once.

n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19"

n = 25; decomp(25) -> 2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23
```

Prime numbers should be in increasing order. When the exponent of a prime is 1 don't put the exponent.

Notes

- the function is `decomp(n)` and should return the decomposition of `n!` into its prime factors in increasing order of the primes, as a string.
- factorial can be a very big number (`4000! has 12674 digits`, n will go from 300 to 4000).
- In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use `dynamically allocated character strings`.

I tried it in Python, but could not do it. Can you solve it?
targets: def primes(n):
    primes = [2]
    for i in range(3,n+1):
        if all(i%p!= 0 for p in primes) == True:
            primes.append(i)
    return(primes)
def decomp(n):
    prim = primes(n)
    factors = {}
    for i in range(2, n+1):
        if i in prim:
            factors[i] = 1
        else:
            for p in prim:
                while i%p == 0:
                    factors[p] += 1
                    i /= p
                if i == 1:
                    break
    res = ''
    for x, y in factors.items():
        res += '{0}^{1} * '.format(x,y) if y != 1 else '{0} * '.format(x)
    return(res[:-3])
inputs: Solve in Python:
Do you remember how Kai constructed the word "eternity" using pieces of ice as components?

Little Sheldon plays with pieces of ice, each piece has exactly one digit between 0 and 9. He wants to construct his favourite number t. He realized that digits 6 and 9 are very similar, so he can rotate piece of ice with 6 to use as 9 (and vice versa). Similary, 2 and 5 work the same. There is no other pair of digits with similar effect. He called this effect "Digital Mimicry".

Sheldon favourite number is t. He wants to have as many instances of t as possible. How many instances he can construct using the given sequence of ice pieces. He can use any piece at most once. 


-----Input-----

The first line contains integer t (1 ≤ t ≤ 10000). The second line contains the sequence of digits on the pieces. The length of line is equal to the number of pieces and between 1 and 200, inclusive. It contains digits between 0 and 9.


-----Output-----

Print the required number of instances.


-----Examples-----
Input
42
23454

Output
2

Input
169
12118999

Output
1



-----Note-----

This problem contains very weak pretests.
targets: t = input().replace('5', '2').replace('9', '6')
s = input().replace('5', '2').replace('9', '6')

res = 10 ** 100

for i in t:
    res = min(res, s.count(i) // t.count(i))
print(res)
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/1311/A:
You are given two positive integers $a$ and $b$.

In one move, you can change $a$ in the following way:

  Choose any positive odd integer $x$ ($x > 0$) and replace $a$ with $a+x$;  choose any positive even integer $y$ ($y > 0$) and replace $a$ with $a-y$. 

You can perform as many such operations as you want. You can choose the same numbers $x$ and $y$ in different moves.

Your task is to find the minimum number of moves required to obtain $b$ from $a$. It is guaranteed that you can always obtain $b$ from $a$.

You have to answer $t$ independent test cases.


-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

Then $t$ test cases follow. Each test case is given as two space-separated integers $a$ and $b$ ($1 \le a, b \le 10^9$).


-----Output-----

For each test case, print the answer — the minimum number of moves required to obtain $b$ from $a$ if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain $b$ from $a$.


-----Example-----
Input
5
2 3
10 10
2 4
7 4
9 3

Output
1
0
2
2
1



-----Note-----

In the first test case, you can just add $1$.

In the second test case, you don't need to do anything.

In the third test case, you can add $1$ two times.

In the fourth test case, you can subtract $4$ and add $1$.

In the fifth test case, you can just subtract $6$.

I tried it in Python, but could not do it. Can you solve it?
targets: t = int(input())

for i in range(t):
    line = input()
    [a, b] = [int(x) for x in line.split(' ')]
    
    if a == b:
        print(0)
    
    if a > b:
        if a % 2 == b % 2:
            print(1)
        else:
            print(2)
    
    elif a < b:
        if a % 2 == b % 2:
            print(2)
        else:
            print(1)
inputs: Solve in Python:
You are given an integer $n$. In one move, you can either multiply $n$ by two or divide $n$ by $6$ (if it is divisible by $6$ without the remainder).

Your task is to find the minimum number of moves needed to obtain $1$ from $n$ or determine if it's impossible to do that.

You have to answer $t$ independent test cases.


-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow. 

The only line of the test case contains one integer $n$ ($1 \le n \le 10^9$).


-----Output-----

For each test case, print the answer — the minimum number of moves needed to obtain $1$ from $n$ if it's possible to do that or -1 if it's impossible to obtain $1$ from $n$.


-----Example-----
Input
7
1
2
3
12
12345
15116544
387420489

Output
0
-1
2
-1
-1
12
36



-----Note-----

Consider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $15116544$:

  Divide by $6$ and get $2519424$;  divide by $6$ and get $419904$;  divide by $6$ and get $69984$;  divide by $6$ and get $11664$;  multiply by $2$ and get $23328$;  divide by $6$ and get $3888$;  divide by $6$ and get $648$;  divide by $6$ and get $108$;  multiply by $2$ and get $216$;  divide by $6$ and get $36$;  divide by $6$ and get $6$;  divide by $6$ and get $1$.
targets: for testcase in range(int(input())):
    n = int(input())
    cnt2, cnt3 = 0, 0
    while n % 2 == 0:
        n //= 2
        cnt2 += 1
    while n % 3 == 0:
        n //= 3
        cnt3 += 1

    if n > 1 or cnt3 < cnt2:
        print(-1)
        continue

    print(2 * cnt3 - cnt2)
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/879/A:
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.

Doctors have a strange working schedule. The doctor i goes to work on the s_{i}-th day and works every d_{i} day. So, he works on days s_{i}, s_{i} + d_{i}, s_{i} + 2d_{i}, ....

The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?


-----Input-----

First line contains an integer n — number of doctors (1 ≤ n ≤ 1000). 

Next n lines contain two numbers s_{i} and d_{i} (1 ≤ s_{i}, d_{i} ≤ 1000).


-----Output-----

Output a single integer — the minimum day at which Borya can visit the last doctor.


-----Examples-----
Input
3
2 2
1 2
2 2

Output
4

Input
2
10 1
6 5

Output
11



-----Note-----

In the first sample case, Borya can visit all doctors on days 2, 3 and 4.

In the second sample case, Borya can visit all doctors on days 10 and 11.

I tried it in Python, but could not do it. Can you solve it?
targets: n = int(input())
ans = 0
c = 1
import math
for i in range(n):
    s,d = map(int, input().split())
    p = int(math.ceil(max(0, c - s) / d))
    c = s + p*d + 1
print(c-1)
inputs: I found an interesting problem on https://www.codewars.com/kata/51e04f6b544cf3f6550000c1:
Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers, because let's pretend it's Friday too. 

A beer can pyramid will square the number of cans in each level - 1 can in the top level, 4 in the second, 9 in the next, 16, 25... 

Complete the beeramid function to return the number of **complete** levels of a beer can pyramid you can make, given the parameters of: 

1) your referral bonus, and

2) the price of a beer can

For example:

I tried it in Python, but could not do it. Can you solve it?
targets: from itertools import count

def beeramid(bonus, price):
    bonus = max(bonus,0)
    n = bonus//price
    return next(x for x in count(int((n*3)**(1/3)+1),-1) if x*(x+1)*(2*x+1)//6 <= n)
inputs: I found an interesting problem on https://www.codewars.com/kata/558db3ca718883bd17000031:
< PREVIOUS KATA
NEXT KATA >

## Task:

You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows. 

* Note:```Returning``` the pattern is not the same as ```Printing``` the pattern.

### Parameters:
    
    pattern(        n        ,        x        ,        y        );
                    ^                 ^                 ^   
                    |                 |                 |
             Term upto which   Number of times   Number of times
              Basic Pattern     Basic Pattern     Basic Pattern
                should be         should be         should be
                 created          repeated           repeated
                                horizontally        vertically
    
* Note: `Basic Pattern` means what we created in Complete The Pattern #12

## Rules/Note:

* The pattern should be created using only unit digits.
* If `n < 1` then it should return "" i.e. empty string.
* If `x <= 1` then the basic pattern should not be repeated horizontally.
* If `y <= 1` then the basic pattern should not be repeated vertically.
* `The length of each line is same`, and is equal to the length of longest line in the pattern.
* Range of Parameters (for the sake of CW Compiler) :
  + `n ∈ (-∞,25]`
  + `x ∈ (-∞,10]`
  + `y ∈ (-∞,10]`
* If only two arguments are passed then the function `pattern` should run as if `y <= 1`.
* If only one argument is passed then the function `pattern` should run as if `x <= 1` & `y <= 1`.
* The function `pattern` should work when extra arguments are passed, by ignoring the extra arguments.
   
   
## Examples:

* Having Three Arguments-

 + pattern(4,3,2):

        1     1     1     1
         2   2 2   2 2   2 
          3 3   3 3   3 3  
           4     4     4   
          3 3   3 3   3 3  
         2   2 2   2 2   2 
        1     1     1     1
         2   2 2   2 2   2 
          3 3   3 3   3 3  
           4     4     4   
          3 3   3 3   3 3  
         2   2 2   2 2   2 
        1     1     1 ...

I tried it in Python, but could not do it. Can you solve it?
targets: def pattern(n,m=1,l=1,*args):
    if n < 1:return ''
    m = max(1,m)
    li, mid, r = ['1'+' '*((n*2-1)-2)+'1'+(' '*((n*2-1)-2)+'1')*(m-1)],1,(n*2-1)-2-2
    for i in range(2, n + 1):
        li.append(' '*(i-1)+f"{' '*mid}".join([str(i%10)+' '*r+(str(i%10)if i!=n else '')for o in range(m)])+' '*(i-1))
        r -= 2 ; mid += 2
    li = li + li[:-1][::-1]
    well = li.copy()
    return "\n".join(li + ["\n".join(well[1:]) for i in range(l-1)])
inputs: I found an interesting problem on https://www.codechef.com/LOCAPR16/problems/BLTOUR:
In Byteland there are N cities, numbered 1 through N. Some pairs of cities are connected by bi-directional roads in such a way that starting from any one city you can visit all other cities either directly or indirectly.

Chef is currently at city A and wants to visit all other cities in Byteland. Chef can only move according to following rule. 

If Chef is at city A then he continues to move from city A to city B, city B to city C (provided A is directly connected to B, B is directly connected to C) and so on unless there are no more cities leading from current city.

If so he jumps back to previous city and repeat the same tour with other cities leading from it which are not visited. Chef repeat this step unless all cities are not visited.

Help Chef to count number of ways in which he can visit all other cities . As this number can be large print it modulo 109+7

-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains a single integer N denoting the number of cities in Byteland.
-  Next N-1 lines contain two space-separated integers u and v denoting there is bi-directional road between city numbered u and v. 
-  Next line contains a single integer A denoting the city number where Chef is present.

-----Output-----
- For each test case, output a single line containing number of ways in which Chef can visit all cities modulo 109+7.

-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ N ≤ 105
- 1 ≤ A ≤ N

-----Subtasks-----
Subtask #1 : (10 points) 
- 1 ≤ N ≤ 5
Subtask #2 : (30 points) 
- 1 ≤ N ≤ 100
Subtask #3 : (60 points) 
- 1 ≤ N ≤ 105

-----Example-----
Input:
2
3
1 2
1 3
1
5
1 2
1 3
2 4
2 5
1

Output:
2
4

-----Explanation-----
Example case 1. Chef can visit cities in two ways according to the problem: 1-2-3 and 1-3-2
Example case 1. Chef can visit cities in four ways according to the problem:

1-2-4-5-3
1-2-5-4-3
1-3-2-4-5
1-3-2-5-4

I tried it in Python, but could not do it. Can you solve it?
targets: import sys
sys.setrecursionlimit(10**8)

MOD = 10**9+7

fac = [0]*(10**5+1)
def pre() :
 fac[0] = 1
 for i in range(1,10**5+1) :
  fac[i] = fac[i-1]*i
  fac[i] = fac[i]%MOD

def dfs(gp , vertex , visited , deg , ans) :
 visited[vertex] = 1
 stack = []
 stack.append(vertex)
 while len(stack)>0 :
  vertex = stack.pop()
  ans = ans%MOD * fac[deg[vertex]]%MOD
  ans %= MOD
  for i in gp[vertex] :
   if not visited[i] :
    visited[i] = 1
    if vertex in gp[i] :
     deg[i] -= 1
    stack.append(i)
 return ans%MOD

pre()
for __ in range(eval(input())) :
 n = eval(input())
 deg = [0]*(n+1)
 st = [[] for __ in range(n+1)]
 for _ in range(n-1) :
  a , b = list(map(int,sys.stdin.readline().split()))
  st[a].append(b)
  st[b].append(a)
  deg[a] += 1
  deg[b] += 1
 k = eval(input())
 visited = [0]*(n+1)
 print(dfs(st ,k,visited,deg , 1)%MOD)
inputs: Solve in Python:
Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.

Let's assume that we are given a connected weighted undirected graph G = (V, E) (here V is the set of vertices, E is the set of edges). The shortest-path tree from vertex u is such graph G_1 = (V, E_1) that is a tree with the set of edges E_1 that is the subset of the set of edges of the initial graph E, and the lengths of the shortest paths from u to any vertex to G and to G_1 are the same. 

You are given a connected weighted undirected graph G and vertex u. Your task is to find the shortest-path tree of the given graph from vertex u, the total weight of whose edges is minimum possible.


-----Input-----

The first line contains two numbers, n and m (1 ≤ n ≤ 3·10^5, 0 ≤ m ≤ 3·10^5) — the number of vertices and edges of the graph, respectively.

Next m lines contain three integers each, representing an edge — u_{i}, v_{i}, w_{i} — the numbers of vertices connected by an edge and the weight of the edge (u_{i} ≠ v_{i}, 1 ≤ w_{i} ≤ 10^9). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices.

The last line of the input contains integer u (1 ≤ u ≤ n) — the number of the start vertex.


-----Output-----

In the first line print the minimum total weight of the edges of the tree.

In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order.

If there are multiple answers, print any of them.


-----Examples-----
Input
3 3
1 2 1
2 3 1
1 3 2
3

Output
2
1 2 

Input
4 4
1 2 1
2 3 1
3 4 1
4 1 2
4

Output
4
2 3 4 



-----Note-----

In the first sample there are two possible shortest path trees:

  with edges 1 – 3...
targets: import heapq
n,m = list(map(int, input().split()))
g = [[] for i in range(n)]
for i in range(1,m+1):
    x,y,z = list(map(int, input().split()))
    x -= 1
    y -= 1
    g[x].append((y,z,i))
    g[y].append((x,z,i))
v = int(input())-1
q = [(0,0,v,0)]
s = []
u = [0] * n
a = 0
while len(q) :
    d,l,x,e = heapq.heappop(q)
    if not u[x]:
        u[x] = 1
        s.append(str(e))
        a += l
        for i,k,f in g[x]:
            if not u[i]:
                heapq.heappush(q, (d+k,k,i,f))
print(a)
print(' '.join(s[1:]))
inputs: Solve in Python:
# Task
 You are given an array of integers `a` and a non-negative number of operations `k`, applied to the array. Each operation consists of two parts:
```
find the maximum element value of the array;
replace each element a[i] with (maximum element value - a[i]).```
How will the array look like after `k` such operations?

# Example

 For `a = [-4, 0, -1, 0]` and `k = 2`, the output should be `[0, 4, 3, 4]`.
 ```
 initial array: [-4, 0, -1, 0]
 1st operation: 
 find the maximum value --> 0
 replace each element:  --> [(0 - -4), (0 - 0), (0 - -1), (0 - 0)]
                        --> [4, 0, 1, 0]
 2nd operation: 
 find the maximum value --> 4
 replace each element:  --> [(4 - 4), (4 - 0), (4 - 1), (4 - 0)]
                        --> [0, 4, 3, 4]
 
 ```
 For `a = [0, -1, 0, 0, -1, -1, -1, -1, 1, -1]` and `k = 1`, 
 
 the output should be `[1, 2, 1, 1, 2, 2, 2, 2, 0, 2]`.
 ```
 initial array: [0, -1, 0, 0, -1, -1, -1, -1, 1, -1]
 1st operation: 
 find the maximum value --> 1
 replace each element:  -->
 [(1-0),(1- -1),(1-0),(1-0),(1- -1),(1- -1),(1- -1),(1- -1),(1-1),(1- -1)]
--> [1, 2, 1, 1, 2, 2, 2, 2, 0, 2]
 ```

# Input/Output


 - `[input]` integer array a

    The initial array.

    Constraints: 

    `1 <= a.length <= 100`
    
    `-100 <= a[i] <= 100`


 - `[input]` integer `k`

    non-negative number of operations.

    Constraints: `0 <= k <= 100000`


 - [output] an integer array

    The array after `k` operations.
targets: def array_operations(a, n):
  li = []
  for i in range(n):
        m = max(a)
        a = [m-i for i in a] 
        if a in li:
            if not n & 1 : return li[-1]
            return a
        li.append(a)
  return a
inputs: Solve in Python:
Complete the function that determines the score of a hand in the card game [Blackjack](https://en.wikipedia.org/wiki/Blackjack) (aka 21).

The function receives an array of strings that represent each card in the hand (`"2"`, `"3",` ..., `"10"`, `"J"`, `"Q"`, `"K"` or `"A"`) and should return the score of the hand (integer).

~~~if:c
Note: in C the function receives a character array with the card `10` represented by the character `T`.
~~~


### Scoring rules:

Number cards count as their face value (2 through 10). Jack, Queen and King count as 10. An Ace can be counted as either 1 or 11.

Return the highest score of the cards that is less than or equal to 21. If there is no score less than or equal to 21 return the smallest score more than 21.


## Examples

```
["A"]                           ==>  11
["A", "J"]                      ==>  21
["A", "10", "A"]                ==>  12
["5", "3", "7"]                 ==>  15
["5", "4", "3", "2", "A", "K"]  ==>  25
```
targets: def score_hand(cards):
    aces = [i for i in cards if i == 'A']
    cards = list(filter(lambda x: x is not 'A', cards))
    cards.extend(aces)
    total = 0
    for i, card in enumerate(cards):
        if card in ['J', 'Q', 'K']:
            total += 10
        elif card is 'A':
            total += 11 if 11 <= (21 - total) and "".join(cards).rindex('A') == i else 1
        else:
            total += int(card)
    return total
inputs: Solve in Python:
## Decode the diagonal. 

Given a grid of characters. Output a decoded message as a string.

Input

```
  H Z R R Q
  D I F C A E A !
  G H T E L A E 
  L M N H P R F 
  X Z R P E
```
  
Output

`HITHERE!` (diagonally down right `↘` and diagonally up right `↗` if you can't go further).

The message ends when there is no space at the right up or down diagonal.

To make things even clearer: the same example, but in a simplified view

```
  H _ _ _ _
  _ I _ _ _ _ _ !
  _ _ T _ _ _ E 
  _ _ _ H _ R _
  _ _ _ _ E
```
targets: def get_diagonale_code(grid: str) -> str:
    flag=True
    temp=grid.split("\n")
    for i,j in enumerate(temp):
        temp[i]=j.split()
    res=""
    x=0
    y=0
    while True:
        try:
            res+=temp[y][x]
            if y==len(temp)-1:
                flag=False
            elif y==0 and not flag:
                flag=True
            y+=1 if flag else -1
            x+=1
        except:
            return res
inputs: Solve in Python:
Navnit is a college student and there are $N$ students in his college .Students are numbered from $1$ to $N$.
You are given $M$ facts that "Student $A_i$ and $B_i$".The same fact can be given multiple times .If $A_i$ is a friend of $B_i$ ,then $B_i$ is also a friend of $A_i$ . If $A_i$ is a friend of $B_i$ and $B_i$ is a friend of $C_i$ then $A_i$ is also a friend of $C_i$.
Find number of ways in which two students can be selected in such a way that they are not friends. 

-----Input:-----
- First line will contain two integers $N$ and $M$. 
- Then $M$ lines follow. Each line contains two integers $A_i$ and $B_i$ denoting the students who are friends.

-----Output:-----
For each testcase, output the number of ways in which  two students can be selected in such a way that they are friends.

-----Constraints-----
- $2 \leq N \leq 200000$
- $0 \leq M \leq 200000$
- $1 \leq A_i,B_i \leq N$

-----Sample Input:-----
5 3
1 2                                                   
3 4
1 5

-----Sample Output:-----
6

-----EXPLANATION:-----
Groups of friend are $[1,2,5]$ and $[3,4]$.Hence the answer is  3 X 2 =6.
targets: # cook your dish here
from collections import defaultdict
d=defaultdict(list)
def dfs(i):
    p=0
    nonlocal v
    e=[i]
    while(e!=[]):
        p+=1
        x=e.pop(0)
        v[x]=1
        for i in d[x]:
            if v[i]==-1:
                v[i]=1
                e.append(i)
    return p

n,m=list(map(int,input().split()))
for i in range(n+1):
    d[i]=[]
for _ in range(m):
	a,b=list(map(int,input().split()))
	d[a].append(b)
	d[b].append(a)
v=[]
for i in range(n+1):
    v.append(-1)
c=0
p=[]
for i in range(1,n+1):
    if v[i]==-1:
        c+=1
        p.append(dfs(i))
an=0
s=0
for i in range(c):
    s+=p[i]
    an+=p[i]*(n-s)
print(an)
inputs: I found an interesting problem on https://www.codechef.com/problems/UWCOI20B:
Using his tip-top physique, Kim has now climbed up the mountain where the base is located. Kim has found the door to the (supposedly) super secret base. Well, it is super secret, but obviously no match for Kim's talents. 
The door is guarded by a row of $N$ buttons. Every button has a single number $A_i$ written on it. Surprisingly, more than one button can have the same number on it. Kim recognises this as Soum's VerySafe door, for which you need to press two buttons to enter the password. More importantly, the sum of the two numbers on the buttons you press must be odd. Kim can obviously break through this door easily, but he also wants to know how many different pairs of buttons he can pick in order to break through the door.
Can you help Kim find the number of different pairs of buttons he can press to break through the door? 
Note: Two pairs are considered different if any of the buttons pressed in the pair is different (by position of the button pressed). Two pairs are not considered different if they're the same position of buttons, pressed in a different order. 
Please refer to the samples for more details.

-----Input:-----
- The first line contains a single integer $T$, representing the number of testcases. $2T$ lines follow, 2 for each testcase.
- For each testcase, the first line contains a single integer $N$, the number of buttons.
- The second line of each testcase contains $N$ space-separated integers, $A_1, A_2, \ldots, A_N$, representing the numbers written on each button.

-----Output:-----
Print a single number, $K$, representing the number of pairs of buttons in $A$ which have an odd sum.

-----Subtasks-----
For all subtasks,  $1 \leq T \leq 10$, $1 \leq N \leq 100000$, and $1 \leq A_i \leq 100000$ for all $A_i$.
Subtask 1 [15 points] : $N \leq 2$, There are at most 2 buttons
Subtask 2 [45 points] : $N \leq 1000$, There are at most 1000 buttons
Subtask 3 [40 points] : No additional constraints.

-----Sample Input:-----
3
4
3 5 3 4
2
5 7
1
4

-----Sample...

I tried it in Python, but could not do it. Can you solve it?
targets: # cook your dish here
t = int(input())
while t>0:
 n = int(input())
 a = list(map(int, input().split()))
 cnt = 0
 for i in range(n):
  if a[i]%2!=0:
   cnt = cnt + 1
 ans = n - cnt
 print(ans*cnt)
 t = t-1
inputs: Solve in Python:
Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them. 

```a``` and ```b``` will both be positive integers, and ```a``` will always be the first number in the operation, and ```b``` always the second.

The four operators are "add", "subtract", "divide", "multiply". 

A few examples: 

``` javascript
ArithmeticFunction.arithmetic(5, 2, "add")      => returns 7
ArithmeticFunction.arithmetic(5, 2, "subtract") => returns 3
ArithmeticFunction.arithmetic(5, 2, "multiply") => returns 10
ArithmeticFunction.arithmetic(5, 2, "divide")   => returns 2
```

Try to do it without using if statements!
targets: def arithmetic(a, b, operator):
    opd = {'add': a+b,'subtract': a-b,'multiply': a*b,'divide': a/b}
    return opd[operator]
inputs: I found an interesting problem on https://codeforces.com/problemset/problem/776/E:
The Holmes children are fighting over who amongst them is the cleverest.

Mycroft asked Sherlock and Eurus to find value of f(n), where f(1) = 1 and for n ≥ 2, f(n) is the number of distinct ordered positive integer pairs (x, y) that satisfy x + y = n and gcd(x, y) = 1. The integer gcd(a, b) is the greatest common divisor of a and b.

Sherlock said that solving this was child's play and asked Mycroft to instead get the value of $g(n) = \sum_{d|n} f(n / d)$. Summation is done over all positive integers d that divide n.

Eurus was quietly observing all this and finally came up with her problem to astonish both Sherlock and Mycroft.

She defined a k-composite function F_{k}(n) recursively as follows:

$F_{k}(n) = \left\{\begin{array}{ll}{f(g(n)),} & {\text{for} k = 1} \\{g(F_{k - 1}(n)),} & {\text{for} k > 1 \text{and} k \operatorname{mod} 2 = 0} \\{f(F_{k - 1}(n)),} & {\text{for} k > 1 \text{and} k \operatorname{mod} 2 = 1} \end{array} \right.$

She wants them to tell the value of F_{k}(n) modulo 1000000007.


-----Input-----

A single line of input contains two space separated integers n (1 ≤ n ≤ 10^12) and k (1 ≤ k ≤ 10^12) indicating that Eurus asks Sherlock and Mycroft to find the value of F_{k}(n) modulo 1000000007.


-----Output-----

Output a single integer — the value of F_{k}(n) modulo 1000000007.


-----Examples-----
Input
7 1

Output
6
Input
10 2

Output
4


-----Note-----

In the first case, there are 6 distinct ordered pairs (1, 6), (2, 5), (3, 4), (4, 3), (5, 2) and (6, 1) satisfying x + y = 7 and gcd(x, y) = 1. Hence, f(7) = 6. So, F_1(7) = f(g(7)) = f(f(7) + f(1)) = f(6 + 1) = f(7) = 6.

I tried it in Python, but could not do it. Can you solve it?
targets: MOD = 1000000007
def phi(n):
    res = n
    for i in range(2,int(n**(0.5)+1)):
        if n % i == 0:
            while n % i == 0:
                n = n//i
            res -= res//i
    if n > 1:
        res -= res//n
    return res

n,k = list(map(int,input().split()))
k = (k+1)//2
ans = n
for _ in range(k):
    if ans > 1:
        ans = phi(ans)
    else:
        break
print(ans % MOD)
inputs: Solve in Python:
In this simple exercise, you will build a program that takes a value, `integer `, and returns a list of its multiples up to another value, `limit `. If `limit` is a multiple of ```integer```, it should be included as well. There will only ever be positive integers passed into the function, not consisting of 0. The limit will always be higher than the base.

For example, if the parameters passed are `(2, 6)`, the function should return `[2, 4, 6]` as 2, 4, and 6 are the multiples of 2 up to 6.

If you can, try writing it in only one line of code.
targets: find_multiples = lambda a, b: list(range(a, b + 1, a))
inputs: Solve in Python:
Consider the following numbers (where `n!` is `factorial(n)`):
```
u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
...
un = (1 / n!) * (1! + 2! + 3! + ... + n!)
```

Which will win: `1 / n!` or `(1! + 2! + 3! + ... + n!)`?

Are these numbers going to `0` because of `1/n!` or to infinity due
to the sum of factorials or to another number?

## Task
Calculate `(1 / n!) * (1! + 2! + 3! + ... + n!)` 
for a given `n`, where `n` is an integer greater or equal to `1`.

To avoid discussions about rounding, return the result **truncated** to 6 decimal places, for example:
```
1.0000989217538616 will be truncated to 1.000098
1.2125000000000001 will be truncated to 1.2125
```

## Remark
Keep in mind that factorials grow rather rapidly, and you need to handle large inputs.

## Hint
You could try to simplify the expression.
targets: # truncate to 6 decimals
def trunc(n):
    return float(str(n)[:8])

def going(n):
    sum = 1
    fact = 1.0
    for i in range(1,n):
        fact = fact/(n-i+1)
        sum += fact
    return trunc(sum)
inputs: Solve in Python:
You get a new job working for Eggman Movers.  Your first task is to write a method that will allow the admin staff to enter a person’s name and return what that person's role is in the company.

You will be given an array of object literals holding the current employees of the company.  You code must find the employee with the matching firstName and lastName and then return the role for that employee or if no employee is not found it should return "Does not work here!"

The array is preloaded and can be referenced using the variable `employees` (`$employees` in Ruby). It uses the following structure.

```python
employees = [ {'first_name': "Dipper", 'last_name': "Pines", 'role': "Boss"}, ...... ]
```

There are no duplicate names in the array and the name passed in will be a single string with a space between the first and last name i.e. Jane Doe or just a name.
targets: employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]
def find_employees_role(name):
    return next(
        (d['role'] for d in employees if '{0[first_name]} {0[last_name]}'.format(d) == name),
        'Does not work here!'
    )
inputs: I found an interesting problem on https://www.hackerrank.com/challenges/list-comprehensions/problem:
=====Problem Statement=====
Let's learn about list comprehensions! You are given three integers x, y and z representing the dimensions of a cuboid along with an integer n. Print a list of all possible coordinates given by (i,j,k) on a 3D grid where the sum of i+j+k is not equal to n. Here, 0≤i≤x;0≤j≤y;0≤k≤z. Please use list comprehensions rather than multiple loops, as a learning exercise.

=====Example=====
x = 1
y = 1
z = 2
n = 3
All permutations of [i,j,k] are:
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2]]
Print an array of the elements that do not sum to n = 3
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,2]]

=====Input Format=====
Four integers x, y, z and n, each on a separate line.

=====Constraints=====
Print the list in lexographic increasing order

I tried it in Python, but could not do it. Can you solve it?
targets: def __starting_point():
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    
    print([ [ i, j, k] for i in range(x + 1) for j in range(y + 1) for k in range(z + 1) if ( (i + j + k) != n )])

__starting_point()
inputs: Solve in Python:
Given a positive integer `n`, return first n dgits of Thue-Morse sequence, as a string (see examples).

Thue-Morse sequence is a binary sequence with 0 as the first element. The rest of the sequece is obtained by adding the Boolean (binary) complement of a group obtained so far.

```
For example:

0
01
0110
01101001
and so on...
```

![alt](https://upload.wikimedia.org/wikipedia/commons/f/f1/Morse-Thue_sequence.gif)

Ex.:
```python
thue_morse(1);  #"0"
thue_morse(2);  #"01"
thue_morse(5);  #"01101"
thue_morse(10): #"0110100110"
```

- You don't need to test if n is valid - it will always be a positive integer.
- `n` will be between 1 and 10000

[Thue-Morse on Wikipedia](https://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence)

[Another kata on Thue-Morse](https://www.codewars.com/kata/simple-fun-number-106-is-thue-morse) by @myjinxin2015
targets: from codecs import decode

tm=b'QlpoOTFBWSZTWYSVjQkACcGIAGAAIACQEAUjUFRlVFsRLBUYVGKjKjVGJo01tbMxratRqjKjFRhU\nYJbQSyFRpCo4u5IpwoSEJKxoSA=='
for c in ('base64','bz2','utf8'): tm=decode(tm,c)

def thue_morse(n):
    return tm[:n]