Solve in Python:
The first input array is the key to the correct answers to an exam, like ["a", "a", "b", "d"]. The second one contains a student's submitted answers.

The two arrays are not empty and are the same length. Return the score for this array of answers, giving +4 for each correct answer, -1 for each incorrect answer, and +0 for each blank answer, represented as an empty string (in C the space character is used).

If the score < 0, return 0.

For example:
```
checkExam(["a", "a", "b", "b"], ["a", "c", "b", "d"]) → 6
checkExam(["a", "a", "c", "b"], ["a", "a", "b",  ""]) → 7
checkExam(["a", "a", "b", "c"], ["a", "a", "b", "c"]) → 16
checkExam(["b", "c", "b", "a"], ["",  "a", "a", "c"]) → 0
```

def check_exam(arr1,arr2):
    x = sum([4 if arr1[i] == arr2[i] else 0 if arr2[i] == '' else -1 for i in range(len(arr1))])
    return 0 if x < 0 else x


Solve in Python:
The first positive integer, `n`, with its value `4n² + 1`, being divisible by `5` and `13` is `4`. (condition 1)

It can be demonstrated that we have infinite numbers that may satisfy the above condition.

If we name **ai**, the different terms of the sequence of numbers with this property, we define `S(n)` as:

We are interested in working with numbers of this sequence from 10 to 15 digits. Could you elaborate a solution for these results?

You will be given an integer value `m`(always valid an positive) and you should output the closest value of the sequence to `m`.

If the given value `m` is in the sequence, your solution should return the same value.

In the case that there are two possible solutions: `s1` and `s2`, (`s1 < s2`), because `|m - s1| = |m - s2|`, output the highest solution `s2`

No hardcoded solutions are allowed.

No misterious formulae are required, just good observation to discover hidden patterns.

See the example tests to see output format and useful examples, edge cases are included.

Features of the random tests
`1000 <= m <= 5.2 e14`

**Note** Sierpinsky presented the numbers that satisfy condition (1)

def sierpinski():
    x = s = 0
    while 1:
        for a in 4, 9, 56, 61:
            s += x + a
            yield s
        x += 65

s = sierpinski()
S = [next(s)]

from bisect import bisect_left
def find_closest_value(m):
    while S[-1] < m: S.append(next(s))
    i = bisect_left(S, m)
    return min(S[i:i-2:-1], key=lambda n: abs(m - n))


Solve in Python:
The four bases found in DNA are adenine (A), cytosine (C), guanine (G) and thymine (T).

In genetics, GC-content is the percentage of Guanine (G) and Cytosine (C) bases on a DNA molecule that are either guanine or cytosine.

Given a DNA sequence (a string) return the GC-content in percent, rounded up to 2 decimal digits for Python, not rounded in all other languages.

For more information about GC-content you can take a look to [wikipedia GC-content](https://en.wikipedia.org/wiki/GC-content).

**For example**: the GC-content of the following DNA sequence is 50%:
"AAATTTCCCGGG".

**Note**: You can take a look to my others bio-info kata [here](http://www.codewars.com/users/nbeck/authored)

def gc_content(seq):
    return round(100 * (seq.count("G") + seq.count("C")) / len(seq), 2) if seq else 0


Solve in Python:
The function is not returning the correct values. Can you figure out why?

```python
get_planet_name(3) # should return 'Earth'
```

def get_planet_name(id):
    planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
    return planets[id-1]


Solve in Python:
The function must return the sequence of titles that match the string passed as an argument.

```if:javascript
TITLES is a preloaded sequence of strings.
```

```python
titles = ['Rocky 1', 'Rocky 2', 'My Little Poney']
search(titles, 'ock') --> ['Rocky 1', 'Rocky 2']
```

But the function return some weird result and skip some of the matching results.

Does the function have special movie taste?

Let's figure out !

def search(a, s):
    s = s.lower()
    return [x for x in a if s in x.lower()]


Solve in Python:
The function sigma 1, σ1 in mathematics, is known as the one that gives the sum of the divisors of an integer number.

For example for the number 10,
```python
σ1(10) = 18 # because the divisors of 10 are: 1, 2, 5, 10

σ1(10) = 1 + 2 + 5 + 10 = 18
```
You can see the graph of this important function up to 250:

The number 528 and its reversed, 825 have equal value for the function σ1.
```python
σ1(528) = σ1(825)

divisors of 528 are: 1, 2, 3, 4, 6, 8, 11, 12, 16, 22, 24, 33, 44, 48, 66, 88, 132, 176, 264 and 528

the sum of the divisors of 528 is 1488

divisors of 825 are: 1, 3, 5, 11, 15, 25, 33, 55, 75, 165, 275 and 825

the sum of the divisors of 825 is 1488
```
In fact 528 is the smallest non palindromic integer that has this property.

We need a function, ```equal_sigma1()```, that may collect all the positive integers that fulfill the property described above.

The function receives an upper limit, ```nMax```, will output the total sum of these numbers and its reversed while are less or equal nMax.

Let's see some cases:
```python
equal_sigma1(100) = 0 # There are no numbers.

equal_sigma1(1000) = 1353 # 528 and its revesed 825 were found, 528 +  825 = 1353

equal_sigma1(2000) = 4565 # There are four numbers_: 528 + 825 + 1561 + 1651 = 4565

equal_sigma1(1600) = 2914 # Now we have three numbers: 528 + 825 + 1561 = 2914

equal_sigma1(1561) = 2914
```
The palindromic numbers (like 88, 808, 929), numbers that are equal to its reversed should be discarded.

Happy coding!!

(For more information about the general sigma function see at: https://en.wikipedia.org/wiki/Divisor_function)

def sigma1(n):
    ans = 0
    for i in xrange(1,int(n**0.5) + 1):
        if n % i == 0:
            ans += i + n / i
    return ans if n ** 0.5 % 1 != 0 else ans - int(n ** 0.5)

def equal_sigma1(n_max):
    ans = 0
    for i in xrange(528,n_max+1):
        j = int(str(i)[::-1])
        if i != j and sigma1(i) == sigma1(j):ans += i
    return ans


Solve in Python:
The fusc function is defined recursively as follows:

    1. fusc(0) = 0
    2. fusc(1) = 1
    3. fusc(2 * n) = fusc(n)
    4. fusc(2 * n + 1) = fusc(n) + fusc(n + 1)

The 4 rules above are sufficient to determine the value of `fusc` for any non-negative input `n`. For example, let's say you want to compute `fusc(10)`.

1. `fusc(10) = fusc(5)`, by rule 3.
2. `fusc(5) = fusc(2) + fusc(3)`, by rule 4.
3. `fusc(2) = fusc(1)`, by rule 3.
4. `fusc(1) = 1`, by rule 2.
5. `fusc(3) = fusc(1) + fusc(2)` by rule 4.
6. `fusc(1)` and `fusc(2)` have already been computed are both equal to `1`.

Putting these results together `fusc(10) = fusc(5) = fusc(2) + fusc(3) = 1 + 2 = 3`

Your job is to produce the code for the `fusc` function. In this kata, your function will be tested with small values of `n`, so you should not need to be concerned about stack overflow or timeouts.

Hint: Use recursion.

When done, move on to [Part 2](http://www.codewars.com/kata/the-fusc-function-part-2).

def fusc(n):
    a, b = 1, 0
    while n > 0:
        if n & 1: b = a + b
        else: a = a + b
        n >>= 1
    return b


Solve in Python:
The game of billiards involves two players knocking 3 balls around
on a green baize table. Well, there is more to it, but for our
purposes this is sufficient.
The game consists of several rounds and in each round both players
obtain a score, based on how well they played. Once all the rounds
have been played, the total score of each player is determined by
adding up the scores in all the rounds and the player with the higher
total score is declared the winner.
The Siruseri Sports Club organises an annual billiards game where
the top two players of Siruseri play against each other. The Manager
of Siruseri Sports Club decided to add his own twist to the game by
changing the rules for determining the winner. In his version, at the
end of each round, the cumulative score for each player is calculated, and the leader and her current lead are found. Once
all the rounds are over the player who had the maximum lead at the
end of any round in the game is declared the winner.

Consider the following score sheet for a game with 5 rounds:
RoundPlayer 1Player 2114082289134390110411210658890

The total scores of both players, the leader and the lead after
each round for this game is given below:RoundPlayer 1Player 2LeaderLead114082Player 1582229216Player 1133319326Player 274431432Player 215519522Player 23
Note that the above table contains the cumulative scores.
The winner of this game is Player 1 as he had the maximum lead (58
at the end of round 1) during the game.
Your task is to help the Manager find the winner and the winning
lead. You may assume that the scores will be such that there will
always be a single winner.  That is, there are no ties.
Input
The first line of the input will contain a single integer N (N
≤ 10000) indicating the number of rounds in the game.  Lines
2,3,...,N+1 describe the scores of the two players in the N rounds.
Line i+1 contains two integer Si and Ti, the scores of the Player 1
and 2 respectively, in round i.  You may assume that 1 ≤ Si ≤
1000 and 1 ≤ Ti ≤ 1000.
Output
Your output must...

t=int(input())
l1=[]
l2=[]
n1=0
n2=0
for i in range(t):
    x,y=list(map(int,input().split()))
    n1+=x
    n2+=y
    if n1>n2:
        l1.append(n1-n2)
        l2.append(0)
    else:
        l1.append(0)
        l2.append(n2-n1)
m1=max(l1)
m2=max(l2)
if m1>m2:
    print(1,m1)
else:
    print(2,m2)


Solve in Python:
The garden has a tree with too many leaves on it and gardner wants to cut the unwanted leaves. This is a rooted tree, where a node $v$ is called parent of another node $u$, if there exists a directed edge from $v$ to $u$. Leaf node is a node with no outgoing edges.
Gardner cuts the tree in a peculiar way:
- For each parent node(which has a valid leaf node attached to it), he cuts $x$ leaf nodes, such that $x$ is a multiple of 3.
Example : If a parent node has 7 leaf nodes, 6 leaf nodes will be cut and 1 will be left.
- If a parent has all its leaf nodes cut, only then the parent node itself becomes a new leaf node. If new leaf nodes are created, Gardner repeats step 1 until he can cut no more leaf nodes.
After completing all operations, gardner wants to know the minimum number of nodes left on the tree.

It is guaranteed that the given input is a rooted tree.
The root of the tree is vertex 1.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains an integer $n$, the number of vertices in the tree.
- Second line of each testcase contains array $A$ of size $n-1$, where $A_{i}(1≤i≤n-1)$, is the index of the parent of the $(i+1)^{th}$ vertex.

-----Output:-----
For each testcase, output single integer, the number of nodes finally left on the tree.

-----Constraints-----
- $1 \leq T \leq 10$
- $2 \leq n \leq 10^5$
- $1 \leq A_i \leq i$

-----Sample Input:-----
1

13

1 1 1 1 1 4 3 4 4 3 4 3

-----Sample Output:-----
4

-----EXPLANATION:-----

from collections import defaultdict
import sys
sys.setrecursionlimit(10**6)

def dfs(node):
 visited[node]=True
 n0[node]+=1
 for x in d[node]:
  if visited[x]==False:
   dfs(x)
   n0[node]+=n0[x]
def dfs1(node):
 nonlocal ans
 visited[node]=True
 co=0
 for x in d[node]:
  if visited[x]==False:

   dfs1(x)
   if n0[x]==1:
    co+=1

 ans1=co//3
 ##print(ans1,node)
 if 3*ans1==len(d[node]):
  n0[node]=1
  ##print(n0[node],node)
 ans-=3*ans1

for _ in range(int(input())):
 n=int(input())
 a=list(map(int,input().split()))
 d=defaultdict(list)
 ans=n
 for i in range(len(a)):
  d[a[i]].append(i+2)
 ##print(d)
 visited = [False] * (n + 1)
 n0 = [0] * (n + 1)
 ##print(n0)
 dfs(1)
 ## print(n0)
 visited=[False]*(n+1)
 dfs1(1)
 print(ans)


Solve in Python:
The goal is to write a pair of functions the first of which will take a string of binary along with a specification of bits, which will return a numeric, signed complement in two's complement format. The second will do the reverse. It will take in an integer along with a number of bits, and return a binary string.

https://en.wikipedia.org/wiki/Two's_complement

Thus, to_twos_complement should take the parameters binary = "0000 0001", bits = 8 should return 1. And, binary = "11111111", bits = 8 should return -1 . While, from_twos_complement should return "00000000" from the parameters n = 0, bits = 8 . And, "11111111" from n = -1, bits = 8.

You should account for some edge cases.

def to_twos_complement(binary, bits):
    return int(binary.replace(' ', ''), 2) - 2 ** bits * int(binary[0])

def from_twos_complement(n, bits):
    return '{:0{}b}'.format(n & 2 ** bits - 1, bits)


Solve in Python:
The goal of this Kata is to reduce the passed integer to a single digit (if not already) by converting the number to binary, taking the sum of the binary digits, and if that sum is not a single digit then repeat the process.

- n will be an integer such that 0 < n < 10^20
- If the passed integer is already a single digit there is no need to reduce

For example given 5665 the function should return 5:

```
5665 --> (binary) 1011000100001
1011000100001 --> (sum of binary digits) 5
```

Given 123456789 the function should return 1:

```
123456789 --> (binary) 111010110111100110100010101
111010110111100110100010101 --> (sum of binary digits) 16
16 --> (binary) 10000
10000 --> (sum of binary digits) 1
```

def single_digit(n):
    while n > 9:
        n = sum(1 if i == "1" else 0 for i in bin(n))
    return n


Solve in Python:
The goal of this Kata is to remind/show you, how Z-algorithm works and test your implementation.

For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is meaning less as complete string is always prefix of itself.

Example:

Index:            0   1   2   3   4   5   6   7   8   9  10  11

Text:             "a   a   b   c   a   a   b   x   a   a   a   z"

Z values:         [11,   1,   0,   0,   3,   1,   0,   0,   2,   2,   1,   0]

Your task will be to implement Z algorithm in your code and return Z-array.

For empty string algorithm should return [].

Input: string str

Output: Z array

For example:

print zfunc('ababcaba')

[8, 0, 2, 0, 0, 3, 0, 1]

Note, that an important part of this kata is that you have to use
efficient way to get Z-array (O(n))

def getZarr(string):
    n = len(string)
    z = [0] * n

    # [L,R] make a window which matches
    # with prefix of s
    l, r, k = 0, 0, 0
    for i in range(1, n):

        # if i>R nothing matches so we will calculate.
        # Z[i] using naive way.
        if i > r:
            l, r = i, i

            # R-L = 0 in starting, so it will start
            # checking from 0'th index. For example,
            # for "ababab" and i = 1, the value of R
            # remains 0 and Z[i] becomes 0. For string
            # "aaaaaa" and i = 1, Z[i] and R become 5
            while r < n and string[r - l] == string[r]:
                r += 1
            z[i] = r - l
            r -= 1
        else:

            # k = i-L so k corresponds to number which
            # matches in [L,R] interval.
            k = i - l

            # if Z[k] is less than remaining interval
            # then Z[i] will be equal to Z[k].
            # For example, str = "ababab", i = 3, R = 5
            # and L = 2
            if z[k] < r - i + 1:
                z[i] = z[k]

            # For example str = "aaaaaa" and i = 2,
            # R is 5, L is 0
            else:

                # else start from R and check manually
                l = i
                while r < n and string[r - l] == string[r]:
                    r += 1
                z[i] = r - l
                r -= 1
    return z

def zfunc(str_):
    #your code goes here
    solution = getZarr(str_)
    if (len(solution) > 1):
        solution[0] = len(solution)
    return solution


Solve in Python:
The goal of this Kata is to return the greatest distance of index positions between matching number values in an array or 0 if there are no matching values.

Example:
In an array with the values [0, 2, 1, 2, 4, 1] the greatest index distance is between the matching '1' values at index 2 and 5.  Executing greatestDistance against this array would return 3. (i.e. 5 - 2)

Here's the previous example in test form:
```python
test.assert_equals(greatest_distance([0, 2, 1, 2, 4, 1]), 3)
```

This is based on a Kata I had completed only to realize I has misread the instructions.  I enjoyed solving the problem I thought it was asking me to complete so I thought I'd add a new Kata for others to enjoy.  There are no tricks in this one, good luck!

def greatest_distance(data):
    i = 0; d = 0
    while (i < len(data)):
        j = i + 1
        while (j < len(data)):
            if (data[j] == data[i]):
                if (j - i > d): d = j - i
            j += 1
        i += 1
    return d;


Solve in Python:
The goal of this exercise is to convert a string to a new string where each character in the new string is `"("` if that character appears only once in the original string, or `")"` if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.

## Examples
```
"din"      =>  "((("
"recede"   =>  "()()()"
"Success"  =>  ")())())"
"(( @"     =>  "))(("
```

**Notes**

Assertion messages may be unclear about what they display in some languages. If you read `"...It Should encode XXX"`, the `"XXX"` is the expected result, not the input!

from collections import Counter

def duplicate_encode(word):
    word = word.lower()
    counter = Counter(word)
    return ''.join(('(' if counter[c] == 1 else ')') for c in word)


Solve in Python:
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where:

1. the dictionary keys are the prefixes
2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java.
3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map) and `[:]` in Groovy.

**Examples:**

```python
>>> build_trie()
{}
>>> build_trie("")
{}
>>> build_trie("trie")
{'t': {'tr': {'tri': {'trie': None}}}}
>>> build_trie("tree")
{'t': {'tr': {'tre': {'tree': None}}}}
>>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn")
{'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}}
>>> build_trie("true", "trust")
{'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}}
```

Happy coding! :)

def build_trie(*words):
    trie = {}
    for word in words:
        node = trie
        for i in range(1, len(word)+1):
            prefix = word[:i]
            if prefix not in node:
                node[prefix] = None
            if i < len(word) and node[prefix] is None:
                node[prefix] = {}
            node = node[prefix]
    return trie


Solve in Python:
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive.

For example:

```python
count_char("fizzbuzz","z") => 4
count_char("Fancy fifth fly aloof","f") => 5
```

The character can be any alphanumeric character.

Good luck.

def count_char(strng, c):
    return strng.lower().count(c.lower())


Solve in Python:
The government has invited bids from contractors to run canteens at all railway stations. Contractors will be allowed to bid for the catering contract at more than one station. However, to avoid monopolistic price-fixing, the government has declared that no contractor may bid for a pair of neighbouring stations.
The railway network has exactly one route between any pair of stations. Each station is directly connected by a railway line to at most $50$ neighbouring stations.
To help contractors plan their bids, the government has provided data on the number of passengers who pass through each station each year. Contractors would like to bid for stations with a higher volume of passenger traffic to increase their turnover.
For instance, suppose the railway network is as follows, where the volume of passenger traffic is indicated by the side of each station.

In this network, the best option for the contractor is to bid for stations $1, 2, 5$ and $6$, for a total passenger volume of $90$.
Your task is to choose a set of stations that the contractor should bid for so that the total volume of traffic across all the stations in the bid is maximized.

-----Input:-----
The first line of the input contains one integer $N$ indicating the number of railways stations in the network. The stations are numbered $1,2,...,N$. This is followed by $N$ lines of input, lines $2, 3,..., N+1$, indicating the volume of traffic at each station. The volume of traffic at station $i, 1 \leq i \leq N$, is given by a single integer in line $i+1$. The next $N-1$ lines of input, lines $N+2, N+3, ..., 2N$, describe the railway network. Each of these lines contains two integers, denoting a pair of stations that are neighbours.

-----Output:-----
The output should be a single integer, corresponding to the total volume of traffic across the set of stations in the optimal bid made by the contractor.

-----Constraints:-----
- $1 \leq N \leq 100000$.
- Each railway station has at most $50$ neighbours.

-----Sample Input-----
6
10
20
25
40
30
30
4...

n=int(input())
l=[]
dp=[]
d={}
for i in range(n):
	l.append(int(input()))
	d[i]=[]
	dp.append([0,0])

for i in range(n-1):
	a,b=list(map(int,input().split()))
	d[a-1].append(b-1)
	d[b-1].append(a-1)
#print(l)
#print(d)

def dfs(ch,pa,visited):
	dp[ch][1]=l[ch]
	#print(dp[ch],ch+1)
	for i in range(len(d[ch])):
		if d[ch][i] not in visited:
			visited.add(d[ch][i])
			dfs(d[ch][i],ch,visited)
			dp[ch][0]+=max(dp[d[ch][i]][0],dp[d[ch][i]][1])
			dp[ch][1]+=dp[d[ch][i]][0]
			#print(ch+1,dp[ch])
v=set()
v.add(0)
dfs(0,-1,v)

#print(dp)
print(max(dp[0][0],dp[0][1]))


Solve in Python:
The government of Siruseri has just commissioned one of the longest and most modern railway routes in the world. This route runs the entire length of Siruseri and passes through many of the big cities and a large number of small towns and villages in Siruseri.
The railway stations along this route have all been constructed keeping in mind the comfort of the travellers. Every station has big parking lots, comfortable waiting rooms and plenty of space for eateries. The railway authorities would like to contract out the catering services of these eateries.
The Siruseri Economic Survey has done a through feasibility study of the different stations and documented the expected profits (or losses) for the eateries in all the railway stations on this route. The authorities would like to ensure that every station is catered to. To prevent caterers from bidding only for profitable stations, the authorities have decided to give out catering contracts for contiguous segments of stations.
The minister in charge realises that one of the bidders is his bitter adversary and he has decided to hand out as useless a segment as possible to him. On the other hand, he does not want to be seen to be blatantly unfair by handing out a large loss-making section to the adversary. Instead he wants to find the largest segment whose sum is closest to $0$, so that his adversary spends all his time running a large number of canteens and makes either a small loss or a small profit or, even better, nothing at all!
In other words, if the profits/losses at the stations are $p_1, p_2, ..., p_N$ the minister would like to handover a sequence $i, i+1, ..., j$ such that the absolute value of $p_i + p_{i+1} + ... + p_j$ is minimized. If there is more than one sequence with this minimum absolute value then he would like to hand over the longest one.
For example, suppose there are $8$ stations along the line and their profitability is as follows:
$ $
Station              1    2    3    4    5    6    7    8
Expected Profits   -20   90  -30  -20   80 ...

#for _ in range(int(input())):
#n,m = map(int,input().split())
#n = int(input())
#x = [int(w) for w in input().split()]
#x = [int(input()) for _ in range(n)]
#for i in range(n):
#dt = {} for i in x:dt[i] = dt.get(i,0)+1
#dt = {k:v for k,v in sorted(x.items(), key=lambda i: i[1])}

from bisect import bisect_left as bs
n = int(input())
x = [int(input()) for _ in range(n)]
dp = []
mn = float('inf')
idx = []
mlen = float('-inf')
si,sj = 0,0
sm = 0
def check(_sm,ind1,ind2,f):
    nonlocal mn,si,sj,mlen
    if _sm<abs(mn) or (_sm==abs(mn) and (idx[ind2]-idx[ind1])>mlen):
        si,sj = idx[ind1]+1,idx[ind2]
        mn = _sm*f
        mlen = sj-si+1

for k,v in enumerate(x,1):
    sm += v
    ind = bs(dp,sm)
    dp.insert(ind,sm)
    idx.insert(ind,k)
    check(abs(sm),0,ind,1)

    if ind>0:
        prev = ind-1
        diff = dp[ind]-dp[prev]
        while prev>0 and (dp[ind]-dp[prev-1])==diff:
            prev -= 1
        check(diff,prev,ind,1)
    if ind < len(dp)-1:
        nxt = ind+1
        diff = dp[nxt]-dp[ind]
        while nxt<len(dp)-1 and (dp[nxt+1]-dp[ind])==diff:
            nxt += 1
        check(diff,nxt,ind,-1)
print(mn)
print(si,sj)


Solve in Python:
The hamming distance of two equal-length strings is the number of positions, in which the two string differ. In other words, the number of character substitutions required to transform one string into the other.

For this first Kata, you will write a function ```hamming_distance(a, b)``` with two equal-length strings containing only 0s and 1s as parameters. There is no need to test the parameters for validity (but you can, if you want).The function's output should be the hamming distance of the two strings as an integer.

Example:

```python
hamming_distance('100101', '101001') == 2
hamming_distance('1010', '0101') == 4
```

def hamming_distance(a, b):
    return sum(c != d for c, d in zip(a, b))


Solve in Python:
The i-th person has weight people[i], and each boat can carry a maximum weight of limit.
Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats to carry every given person.  (It is guaranteed each person can be carried by a boat.)

Example 1:
Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)

Example 2:
Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)

Example 3:
Input: people = [3,5,3,4], limit = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)
Note:

1 <= people.length <= 50000
1 <= people[i] <= limit <= 30000

class Solution:
    def numRescueBoats(self, people: List[int], limit: int) -> int:
        if not people or limit == 0:
            return 0

        ans = 0
        people.sort()
        left, right = 0, len(people) - 1
        while left <= right:
            if people[left] + people[right] <= limit:
                left += 1
                right -= 1
            else:
                right -= 1
            ans += 1
        return ans


Solve in Python:
The idea for this Kata came from 9gag today.[here](http://9gag.com/gag/amrb4r9)

[screen]:("http://img-9gag-fun.9cache.com/photo/amrb4r9_700b.jpg")

You'll have to translate a string to Pilot's alphabet (NATO phonetic alphabet) [wiki](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet).

Like this:

**Input:**

`If, you can read?`

**Output:**

`India Foxtrot , Yankee Oscar Uniform Charlie Alfa November Romeo Echo Alfa Delta ?`

**Notes**

* The set of used punctuation is `.!?`.
* Punctuation should be kept in your return string, but spaces should not.
* __Xray__ should not have a dash within.
* Every word and punctuation mark should be seperated by a space ' '.
* There should be no trailing whitespace

~~~if:php
Although the proper alphabet for j is `Juliett` you have to use `Juliet` here
~~~

def to_nato(words):
    dictionary = {'A':'Alfa', 'B':'Bravo','C':'Charlie', 'D':'Delta', 'E':'Echo', 'F':'Foxtrot', 'G':'Golf', 'H':'Hotel', 'I':'India', 'J':'Juliett', 'K':'Kilo', 'L':'Lima', 'M':'Mike', 'N':'November', 'O':'Oscar', 'P':'Papa', 'Q':'Quebec', 'R':'Romeo', 'S':'Sierra', 'T':'Tango', 'U':'Uniform', 'V':'Victor', 'W':'Whiskey', 'X':'Xray', 'Y':'Yankee', 'Z':'Zulu'}
    return ' '.join([dictionary.get(l, l) for l in words.upper().replace(' ','')]).strip()


Solve in Python:
The image shows how we can obtain the Harmonic Conjugated Point of three aligned points A, B, C.

- We choose any point L, that is not in the line with A, B and C. We form the triangle ABL

- Then we draw a line from point C that intersects the sides of this triangle at points M and N respectively.

- We draw the diagonals of the quadrilateral ABNM; they are AN and BM and they intersect at point K

- We unit, with a line L and K, and this line intersects the line of points A, B and C at point D

The point D is named the Conjugated Harmonic Point of the points A, B, C.
You can get more knowledge related with this point at: (https://en.wikipedia.org/wiki/Projective_harmonic_conjugate)

If we apply the theorems of Ceva (https://en.wikipedia.org/wiki/Ceva%27s_theorem)
and Menelaus (https://en.wikipedia.org/wiki/Menelaus%27_theorem) we will have this formula:

AC, in the above formula is the length of the segment of points A to C in this direction and its value is:

```AC = xA - xC```

Transform the above formula using the coordinates ```xA, xB, xC and xD```

The task is to create a function ```harmon_pointTrip()```, that receives three arguments, the coordinates of points xA, xB and xC, with values such that : ```xA < xB < xC```, this function should output the coordinates of point D for each given triplet, such that

`xA < xD < xB < xC`, or to be clearer

let's see some cases:
```python
harmon_pointTrip(xA, xB, xC) ------> xD # the result should be expressed up to four decimals (rounded result)
harmon_pointTrip(2, 10, 20) -----> 7.1429 # (2 < 7.1429 < 10 < 20, satisfies the constraint)
harmon_pointTrip(3, 9, 18) -----> 6.75
```

Enjoy it and happy coding!!

def harmon_pointTrip(xA, xB, xC):
    return round((xA * xC + xB * xC - 2 * xA * xB) / float(2 * xC - xA - xB), 4)


Solve in Python:
The integer ```64``` is the first integer that has all of its digits even and furthermore, is a perfect square.

The second one is ```400``` and the third one ```484```.

Give the numbers of this sequence that are in the range ```[a,b] ```(both values inclusive)

Examples:
``` python
even_digit_squares(100, 1000) == [400, 484] # the output should be sorted.
even_digit_squares(1000, 4000) == []
```

Features of the random tests for ```even_digit_squares(a, b)```
```
number of Tests = 167
maximum value for a = 1e10
maximum value for b = 1e12
```
You do not have to check the entries, ```a``` and ```b``` always positive integers and ```a < b```

Happy coding!!

even_digit_squares=lambda a,b:[n*n for n in range(1-int(-a**.5//1)&-2,int(b**.5)+1,2)if set(str(n*n))<=set('02468')]


Solve in Python:
The integers 14 and 15, are contiguous (1 the difference between them, obvious) and have the same number of divisors.
```python
14 ----> 1, 2, 7, 14 (4 divisors)
15 ----> 1, 3, 5, 15 (4 divisors)
```
The next pair of contiguous integers with this property is 21 and 22.
```python
21 -----> 1, 3, 7, 21 (4 divisors)
22 -----> 1, 2, 11, 22 (4 divisors)
```
We have 8 pairs of integers below 50 having this property, they are:
```python
[[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]]
```
Let's see now the integers that have a difference of 3 between them. There are seven pairs below 100:
```python
[[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]]
```
Let's name, diff, the difference between two integers, next and prev, (diff = next - prev) and nMax, an upper bound of the range.

We need a special function, count_pairsInt(), that receives two arguments, diff and nMax and outputs the amount of pairs of integers that fulfill this property, all of them being smaller (not smaller or equal) than nMax.

Let's see it more clearly with examples.
```python
count_pairsInt(1, 50) -----> 8 (See case above)
count_pairsInt(3, 100) -----> 7 (See case above)
```

Happy coding!!!

def count_pairs_int(dif, n_max):
    _c=((range(1,n_max)[i],range(1,n_max)[i+dif]) for i in range(0,len(range(1,n_max))-dif))
    def v(x):
        _s=[]
        for k in range(1,int(x**0.5)+1):
            if x%k==0:
                _s.append(k)
                _s.append(x/k)
        return len(set(_s))
    return len([i for i in _c if v(i[0])==v(i[1])])


Solve in Python:
The internet is a very confounding place for some adults. Tom has just joined an online forum and is trying to fit in with all the teens and tweens. It seems like they're speaking in another language! Help Tom fit in by translating his well-formatted English into n00b language.

The following rules should be observed:

- "to" and "too" should be replaced by the number 2, even if they are only part of a word (E.g. today = 2day)
- Likewise, "for" and "fore" should be replaced by the number 4
- Any remaining double o's should be replaced with zeros (E.g. noob = n00b)
- "be", "are", "you", "please", "people", "really", "have", and "know" should be changed to "b", "r", "u", "plz", "ppl", "rly", "haz", and "no" respectively (even if they are only part of the word)
- When replacing words, always maintain case of the first letter unless another rule forces the word to all caps.
- The letter "s" should always be replaced by a "z", maintaining case
- "LOL" must be added to the beginning of any input string starting with a "w" or "W"
- "OMG" must be added to the beginning (after LOL, if applicable,) of a string 32 characters^(1) or longer
- All evenly numbered words^(2) must be in ALL CAPS (Example: ```Cake is very delicious.``` becomes ```Cake IZ very DELICIOUZ```)
- If the input string starts with "h" or "H", the entire output string should be in ALL CAPS
- Periods ( . ), commas ( , ), and apostrophes ( ' ) are to be removed
- ^(3)A question mark ( ? ) should have more question marks added to it, equal to the number of words^(2) in the sentence (Example: ```Are you a foo?``` has 4 words, so it would be converted to ```r U a F00????```)
- ^(3)Similarly, exclamation points ( ! ) should be replaced by a series of alternating exclamation points and the number 1, equal to the number of words^(2) in the sentence (Example: ```You are a foo!``` becomes ```u R a F00!1!1```)

^(1) Characters should be counted After: any word conversions, adding additional words, and removing punctuation. Excluding: All punctuation and any 1's...

def remove_punc(words):
    if "'" in words:
        temp_2 = words.partition("'")
        words = temp_2[0] + temp_2[-1]

        words = remove_punc(words)

    if "." in words:
        temp_2 = words.partition(".")
        words = temp_2[0] + temp_2[-1]

        words = remove_punc(words)

    if "," in words:
        temp_2 = words.partition(",")
        words = temp_2[0] + temp_2[-1]

        words = remove_punc(words)

    return words

def transw(words, old, new):
    temp_words = words.lower().replace(old, " "*len(old))
    result = ""
    threshold = 0
    for i in range(0, len(temp_words)):
        if temp_words[i] != " ":
            result = result + words[i]
        else:
            threshold += 1
            if threshold == len(old):
                result = result + new
                threshold = 0
    return result

def n00bify(text):
    temp = text.split()
    result = ""
    for i in temp:

        i = transw(i, 'too', '2')
        i = transw(i, 'to', '2')
        i = transw(i, 'fore','4')
        i = transw(i, 'for', '4')
        i = transw(i, 'oo', '00')
        i = transw(i, 'be', 'b')
        i = transw(i, 'you', 'u')
        i = transw(i, 'are', 'r')
        i = transw(i, 'please', 'plz')
        i = transw(i, 'people', 'ppl')
        i = transw(i, 'really', 'rly')
        i = transw(i, 'have', 'haz')
        i = transw(i, 'know', 'no')
        i = transw(i, 's', 'z')

        i = remove_punc(i)

        if len(result) == 0:
            result = result + i
        else:
            result = result + " " + i

    if result[0] == "w" or result[0] == "W":
        result = "LOL" + " " + result
    if result[0] == "h" or result[0] == "H":
        result = result.upper()

    t_result = result.split()

    count = 0
    for m in t_result:
        for n in m:
            if n == "!":
                break

            elif n.isalnum():
                count +=...


Solve in Python:
The kingdom of the snakes is an NxN grid. Their most-valued possession is a huge collection of poison, which is stored in the central KxK grid. It is guaranteed that both N and K are odd. What we mean by 'central' is this: suppose in the NxN grid, (i, j) refers to the cell in the i-th row and j-th column and (1,1) refers to the top-left corner and (N,N) refers to the bottom-right corner. Then the poison is stored in the KxK square whose top-left corner is ( (N - K)/2 + 1, (N - K)/2 + 1 ).

But there are thieves who want to steal the poison. They cannot enter the NxN grid, but they can shoot arrows from outside. These arrows travel across a row (from left to right, or right to left), or across a column (top to bottom or bottom to top) in a straight line. If the arrow enters the KxK grid, some of the poison will stick to the arrow, and if it exits the NxN grid after that, the thieves will have successfully stolen some of the poison.
As the King of the snakes, you want to thwart these attempts. You know that the arrows will break and stop if they hit a snake's scaly skin, but won't hurt the snakes. There are some snakes already guarding the poison. Each snake occupies some consecutive cells in a straight line inside the NxN grid. That is, they are either part of a row, or part of a column. Note that there can be intersections between the snakes.  A configuration of snakes is 'safe', if the thieves cannot steal poison. That is, no matter which row or column they shoot arrows from, either the arrow should hit a snake and stop (this can happen even after it has entered and exited the KxK grid), or it shouldn't ever enter the KxK grid.
The King has other duties for the snakes, and hence wants to remove as many snakes as possible from this configuration, such that the remaining configuration is still 'safe'. Help him find the minimum number of snakes he needs to leave behind to protect the poison.

-----Input-----
- The first line contains a single integer, T, the number of testcases.
- The first line of each...

'''input
2
7 3 5
5 2 5 2
2 4 2 6
6 2 6 4
5 6 5 7
7 1 7 4
7 3 7
1 1 6 1
1 2 3 2
5 2 5 2
2 6 2 6
6 2 6 4
5 6 5 7
7 1 7 4
'''

for _ in range(int(input())):
 n, k, m = list(map(int, input().split()))
 row_s = []
 col_s = []
 for _ in range(m):
  h_x, h_y, t_x, t_y = list(map(int, input().split()))
  if h_x == t_x:
   if (h_x < (((n - k) // 2) + 1)) or (h_x > (((n - k) // 2) + k)):
    col_s.append([min(h_y, t_y), max(h_y, t_y)])
   else:
    row_s.append([h_x, h_x])
  if h_y == t_y:
   if (h_y < (((n - k) // 2) + 1)) or (h_y > (((n - k) // 2) + k)):
    row_s.append([min(h_x, t_x), max(h_x, t_x)])
   else:
    col_s.append([h_y, h_y])
 row_s.sort()
 col_s.sort()

 poss = True

 if len(col_s) == 0 or len(row_s) == 0:
  print(-1)
  continue

 # print(row_s, col_s)

 next_row = ((n - k) // 2) + 1
 i = 0
 count_row = 0
 while i < len(row_s):
  max_next = next_row
  if next_row < row_s[i][0]:
   poss = False
   break
  while i < len(row_s) and row_s[i][0] <= next_row:
   # print(max_next, row_s[i], next_row)
   max_next = max(max_next, row_s[i][1] + 1)
   # print(max_next, row_s[i], next_row)
   i += 1
  next_row = max_next
  count_row += 1
  if next_row > (((n - k) // 2) + k):
   break
  if next_row < (((n - k) // 2) + k) and i >= len(row_s) :
   poss = False
   break

 # print(count_row)

 next_col = ((n - k) // 2) + 1
 i = 0
 count_col = 0
 while i < len(col_s):
  max_next = next_col
  if next_col < col_s[i][0]:
   poss = False
   break
  while i < len(col_s) and col_s[i][0] <= next_col:
   # print(max_next, col_s[i], next_col)
   max_next = max(max_next, col_s[i][1] + 1)
   # print(max_next, col_s[i], next_col)
   i += 1
  next_col = max_next
  count_col += 1
  if next_col > (((n - k) // 2) + k):
   break
  if next_col < (((n - k) // 2) + k) and i >= len(col_s) :
   poss = False
   break

 # print(count_col)
 print(count_col + count_row if poss else -1)

 # print(row_s, col_s)


Solve in Python:
The land of Programmers Army is surrounded by many islands. A unique number is associated with each island. The king of the islands is a very generous person, he donates a certain amount of gold coins to travelers for visiting each island that they visited to.
Now, you are appointed as a traveler, who will travel to all these(or some) islands as many times as the Army wants, and you will collect gold coins from the king of the island.
In each trip, you will be asked to give the total sum of gold coins you have collected.

-----Input:-----
- The first line of the input contains a single integer $T$. $T$ denoting the number of test cases. The description of $T$ test cases is as follows.
- The next line of the input contains a single integer $N$. $N$ denotes the total number of Islands.
- The next line of the input contains $N$ space-separated integers $A1, A2, A3...An$ where $ith$ number denotes the maximum number of coins that the king of $ith$ island can donate.
- Next line contains a single integer $Q$. $Q$ denotes the total number of times traveler have to go for the trip.
- Next $Q$ lines contains, two space-separated integers $Q1,Q2$ denoting the start and end number of islands, i.e. traveler will start the trip from $Q1th$ island and will go till $Q2th$ island, in each trip.
Note: islands are numbered from $1$ to $N$.

-----Output:-----
- For each trip print the total number of gold coins, traveler will collect(each on a new line).

-----Constraints:-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 10^4$
- $1 \leq A1, A2, A3...An \leq 10^5$
- $1 \leq Q \leq 10^3$
- $1 \leq Q1,Q2 \leq N$

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

-----Sample Output:-----
17
57

-----Explanation:-----
-
In 1st Trip, traveler will go from 1st Island to 3rd Island, hence the total number of coins traveler can collect is 10+2+5 = 17
-
In 2 d Trip, traveler will go from 2nd Island to 4th Island, hence the total number of coins traveler can collect is 2+5+50 = 57

for _ in range(int(input())):
    a=input()
    l=list(map(int,input().split()))
    q=int(input())
    r=[]
    for i in range(q):
        a,b=list(map(int,input().split()))
        print(sum(l[a-1:b]))


Solve in Python:
The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!

There are $n$ snacks flavors, numbered with integers $1, 2, \ldots, n$. Bessie has $n$ snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows:  First, Bessie will line up the guests in some way.  Then in this order, guests will approach the snacks one by one.  Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad.

Help Bessie to minimize the number of sad guests by lining the guests in an optimal way.

-----Input-----

The first line contains integers $n$ and $k$ ($2 \le n \le 10^5$, $1 \le k \le 10^5$), the number of snacks and the number of guests.

The $i$-th of the following $k$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$), favorite snack flavors of the $i$-th guest.

-----Output-----

Output one integer, the smallest possible number of sad guests.

-----Examples-----
Input
5 4
1 2
4 3
1 4
3 4

Output
1

Input
6 5
2 3
2 1
3 4
6 5
4 5

Output
0

-----Note-----

In the first example, Bessie can order the guests like this: $3, 1, 2, 4$. Guest $3$ goes first and eats snacks $1$ and $4$. Then the guest $1$ goes and eats the snack $2$ only, because the snack $1$ has already been eaten. Similarly, the guest $2$ goes up and eats the snack $3$ only. All the snacks are gone, so the guest $4$ will be sad.

In the second example, one optimal ordering is $2, 1, 3, 5, 4$. All the guests will be satisfied.

n,k=list(map(int,input().split()))
parent=[i for i in range(n)]
rank=[1 for i in range(n)]
def find_parent(u):
    if parent[u]!=u:
        parent[u]=find_parent(parent[u])
    return parent[u]
for i in range(k):
    u,v=list(map(int,input().split()))
    u=find_parent(u-1)
    v=find_parent(v-1)
    if u!=v:
        parent[u]=v;
        rank[v]+=rank[u];
sat=0;
for i in range(n):
    if parent[i]==i:
        sat+=(rank[i]-1)
print(k-sat)


Solve in Python:
The life goes up and down, just like nice sequences. Sequence t_1, t_2, ..., t_{n} is called nice if the following two conditions are satisfied:   t_{i} < t_{i} + 1 for each odd i < n;  t_{i} > t_{i} + 1 for each even i < n.

For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.

Bear Limak has a sequence of positive integers t_1, t_2, ..., t_{n}. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements t_{i} and t_{j} in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.

-----Input-----

The first line of the input contains one integer n (2 ≤ n ≤ 150 000) — the length of the sequence.

The second line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 150 000) — the initial sequence. It's guaranteed that the given sequence is not nice.

-----Output-----

Print the number of ways to swap two elements exactly once in order to get a nice sequence.

-----Examples-----
Input
5
2 8 4 7 7

Output
2

Input
4
200 150 100 50

Output
1

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

Output
8

Input
9
1 2 3 4 5 6 7 8 9

Output
0

-----Note-----

In the first sample, there are two ways to get a nice sequence with one swap:   Swap t_2 = 8 with t_4 = 7.  Swap t_1 = 2 with t_5 = 7.

In the second sample, there is only one way — Limak should swap t_1 = 200 with t_4 = 50.

def main():
    n, l = int(input()), list(map(int, input().split()))
    if not (n & 1):
        l.append(0)
    l.append(150001)
    a, b, fails, res = 0, 150001, [], 0
    for i, c in enumerate(l, -1):
        if i & 1:
            if a >= b or b <= c:
                if len(fails) > 5:
                    print(0)
                    return
                fails.append(i)
        else:
            if a <= b or b >= c:
                if len(fails) > 5:
                    print(0)
                    return
                fails.append(i)
        a, b = b, c
    check = compile("and".join(
        "(l[{:n}]{:s}l[{:n}]{:s}l[{:n}])".format(i - 1, "><"[i & 1], i, "<>"[i & 1], i + 1) for i in fails),
                   "<string>", "eval")
    for i in fails:
        a = l[i]
        for j in range(n):
            l[i], l[j] = l[j], a
            if eval(check) and ((l[j - 1] < l[j] > l[j + 1]) if j & 1 else (l[j - 1] > l[j] < l[j + 1])):
                res += 1 if j in fails else 2
            l[j] = l[i]
        l[i] = a
    print(res // 2)

def __starting_point():
    main()
__starting_point()


Solve in Python:
The local transport authority is organizing an online picture contest.
Participants must take pictures of transport means in an original way, and then post the picture on Instagram using a specific ```hashtag```.

The local transport authority needs your help. They want you to take out the ```hashtag``` from the posted message. Your task is to implement the function

```python
def omit_hashtag(message, hashtag):
```

## Examples

```
* ("Sunny day! #lta #vvv", "#lta") -> "Sunny day!  #vvv" (notice the double space)
* ("#lta #picture_contest", "#lta") -> " #picture_contest"
```

## Notes

* When multiple occurences of the hashtag are found, delete only the first one.

* In C, you should modify the ```message```, as the function returns a void type. In Python, you should return the answer.

* There can be erroneous messages where the hashtag isn't present. The message should in this case stay untouched.

* The hashtag only consists of alphanumeric characters.

# Return the message, but with the first occurrence (if any) of the
# specified hashtag removed from the message
def omit_hashtag(message, hashtag):
    if hashtag in message:
        found_at = message.index(hashtag)
        return message[0:found_at] + message[found_at + len(hashtag):]
    else:
        return message


Solve in Python:
The look and say sequence is a sequence in which each number is the result of a "look and say" operation on the previous element.

Considering for example the classical version startin with `"1"`: `["1", "11", "21, "1211", "111221", ...]`. You can see that the second element describes the first as `"1(times number)1"`, the third is `"2(times number)1"` describing the second, the fourth is `"1(times number)2(and)1(times number)1"` and so on.

Your goal is to create a function which takes a starting string (not necessarily the classical `"1"`, much less a single character start) and return the nth element of the series.

## Examples

```python
look_and_say_sequence("1", 1)   == "1"
look_and_say_sequence("1", 3)   == "21"
look_and_say_sequence("1", 5)   == "111221"
look_and_say_sequence("22", 10) == "22"
look_and_say_sequence("14", 2)  == "1114"
```
Trivia: `"22"` is the only element that can keep the series constant.

look_and_say_sequence=l=lambda s,n:n>1and l(''.join(str(len(list(g)))+k for k,g in __import__('itertools').groupby(s)),n-1)or s


Solve in Python:
The magic sum of 3s is calculated on an array by summing up odd numbers which include the digit `3`. Write a function `magic_sum` which accepts an array of integers and returns the sum.

*Example:* `[3, 12, 5, 8, 30, 13]` results in `16` (`3` + `13`)

If the sum cannot be calculated, `0` should be returned.

def magic_sum(arr):
    return sum(v for v in arr if "3" in set(str(v)) and v%2) if arr else 0


Solve in Python:
The male gametes or sperm cells in humans and other mammals are heterogametic and contain one of two types of sex chromosomes. They are either X or Y. The female gametes or eggs however, contain only the X sex chromosome and are homogametic.

The sperm cell determines the sex of an individual in this case. If a sperm cell containing an X chromosome fertilizes an egg, the resulting zygote will be XX or female. If the sperm cell contains a Y chromosome, then the resulting zygote will be XY or male.

Determine if the sex of the offspring will be male or female based on the X or Y chromosome present in the male's sperm.

If the sperm contains the X chromosome, return "Congratulations! You're going to have a daughter.";
If the sperm contains the Y chromosome, return "Congratulations! You're going to have a son.";

def chromosome_check(sperm):
    gender = "son" if sperm[-1] == "Y" else "daughter"
    return f"Congratulations! You're going to have a {gender}."


Solve in Python:
The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!

Here's the deal:

- It must start with a hashtag (`#`).
- All words must have their first letter capitalized.
- If the final result is longer than 140 chars it must return `false`.
- If the input or the result is an empty string it must return `false`.

## Examples

```
" Hello there thanks for trying my Kata"  =>  "#HelloThereThanksForTryingMyKata"
"    Hello     World   "                  =>  "#HelloWorld"
""                                        =>  false
```

def generate_hashtag(s):
    solution = '#' + ''.join([word.strip().capitalize() for word in s.split(' ')])

    if len(solution) > 1 and len(solution) < 140:
        return solution
    return False


Solve in Python:
The mean and standard deviation of a sample of data can be thrown off if the sample contains one or many outlier(s) :

(image source)

For this reason, it is usually a good idea to check for and remove outliers before computing the mean or the standard deviation of a sample. To this aim, your function will receive a list of numbers representing a sample of data. Your function must remove any outliers and return the mean of the sample, rounded to two decimal places (round only at the end).

Since there is no objective definition of "outlier" in statistics, your function will also receive a cutoff, in standard deviation units. So for example if the cutoff is 3, then any value that is more than 3 standard deviations above or below the mean must be removed. Notice that, once outlying values are removed in a first "sweep", other less extreme values may then "become" outliers, that you'll have to remove as well!
Example :
```python
sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100]
cutoff = 3
clean_mean(sample, cutoff) → 5.5
```

Formula for the mean :

(where n is the sample size)

Formula for the standard deviation :

(where N is the sample size, xi is observation i and x̄ is the sample mean)

Note : since we are not computing the sample standard deviation for inferential purposes, the denominator is n, not n - 1.

from numpy import mean, std

def clean_mean(sample, cutoff):
    m, newMean = 1j, mean(sample)
    while m != newMean:
        m, sd = newMean, std(sample)
        sample = [s for s in sample if abs(s-m) < sd * cutoff]
        newMean = mean(sample)
    return round(newMean, 2)


Solve in Python:
The median of a sequence is the element in the middle of the sequence after it is sorted. For a sequence with even size, the median is the average of the two middle elements of the sequence after sorting. For example, for a sequence $A = [1, 3, 3, 5, 4, 7, 11]$, the median is equal to $4$, and for $A = [2, 3, 4, 5]$, the median is equal to $(3+4)/2 = 3.5$.
Fulu is a famous programmer in his country. He wrote the following program (given in pseudocode) for finding the median in a sequence $A$ with length $N$:
read(N)
read(A[0], A[1], ..., A[N-1])
sort(A)
# simultaneously remove elements A[K] and A[N mod K] from the array A
# the order of the remaining N-2 elements is unchanged
remove(A[K], A[N mod K])
return A[(N-2)/2] # integer division

The program takes an integer $K$ as a parameter. Fulu can choose this integer arbitrarily between $1$ and $N-1$ inclusive.
Little Lima, Fulu's friend, thinks Fulu's program is wrong (as always). As finding one counterexample would be an easy task for Lima (he has already found the sequence $A = [34, 23, 35, 514]$, which is a counterexample for any $K \le 3$), Lima decided to make hacking more interesting. Fulu should give him four parameters $S, K, m, M$ (in addition to $N$) and Lima should find the lexicographically smallest proper sequence $A$ with length $N$ as a counterexample.
We say that a sequence $A$ with length $N$ ($0$-indexed) is proper if it satisfies the following conditions:
- it contains only positive integers
- $A_0 + A_1 +A_2 + \dots + A_{N-1} = S$
- $m \le A_i \le M$ for each $0 \le i < N$
- the number returned by Fulu's program, ran with the given parameter $K$, is different from the correct median of the sequence $A$
Can you help Lima find the lexicographically smallest counterexample or determine that Fulu's program works perfectly for the given parameters?

-----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...

import numpy as np
import sys

def findSeq(n, s, k, m, M):
    midInd = n // 2
    seqs = []
    for ind in range(midInd + 2, midInd - 3, -1):
        if ind >= n or ind < 0:
            continue
        seq = genBestSeq(n, ind, m, M, s)
        if seq is not -1 and testSeq(k, seq):
            seqs.append(list(seq))
    if len(seqs) == 0:
        return -1
    return min(seqs)

#def findSeq(n, s, k, m, M):
#    midInd = n // 2
#    if k <= midInd: #and (n % 2 == 1 or s < m * midInd + M * (n - midInd)):
#        return genBestSeq(n, midInd + 1, m, M, s)
#    elif k > midInd + 1 and n % 2 == 1:
#        return -1
#    return genBestSeq(n, midInd, m, M, s)

def genBestSeq(n, diffInd, m, M, s):
    #inc = M - m - 1
    arr = np.full((n,), m)
    arr[diffInd:] += 1
    #remainder = s - np.sum(arr)
    #if remainder < 0:
    #    return -1

    #nFull, remainder = divmod(remainder, inc)
    #if nFull > n or (nFull == n and remainder > 0):
    #    return -1

    #addingInd = n - nFull -1
    #arr[addingInd + 1:] += inc
    #arr[addingInd] += remainder
    #return arr
    s = s - np.sum(arr)
    if s < 0:
        return -1
    inc = M - m - 1
    ind = n - 1
    while (ind >= 0):
        z = min(inc, s)
        arr[ind] += z
        s -= z
        ind -= 1
    if s != 0:
        return -1
    return arr

def testSeq(k, seq):
    seq = sorted(seq)
    n = len(seq)
    if n % 2 == 1:
        median = seq[n // 2]
    else:
        median = (seq[n // 2 - 1] + seq[n // 2]) / 2
    seq.pop(n % k)
    seq.pop(k - 1)
    return (median != seq[(n - 2) // 2])

def __starting_point():
    nCases = int(input())
    answers = []
    #ks = []
    for i in range(nCases):
        #nums = [int(val) for val in input().split()]
        #ks.append(nums[2])
        #answers.append(findSeq(*nums))
        answers.append(findSeq(*(int(val) for val in input().split())))
        ans = answers[-1]
        if not isinstance(ans, int):
           ...


Solve in Python:
The medians of a triangle are the segments that unit the vertices with the midpoint of their opposite sides.
The three medians of a triangle intersect at the same point, called the barycenter or the centroid.
Given a triangle, defined by the cartesian coordinates of its vertices we need to localize its barycenter or centroid.

The function ```bar_triang() or barTriang or bar-triang```, receives the coordinates of the three vertices ```A, B and C ``` as three different arguments and outputs the coordinates of the barycenter ```O``` in an array ```[xO, yO]```

This is how our asked function should work:
the result of the coordinates should be expressed up to four decimals, (rounded result).

You know that the coordinates of the barycenter are given by the following formulas.

For additional information about this important point of a triangle see at: (https://en.wikipedia.org/wiki/Centroid)

Let's see some cases:
```python
bar_triang([4, 6], [12, 4], [10, 10]) ------> [8.6667, 6.6667]

bar_triang([4, 2], [12, 2], [6, 10] ------> [7.3333, 4.6667]
```
The given points form a real or a degenerate triangle but in each case the above formulas can be used.

Enjoy it and happy coding!!

def bar_triang(A, B, C): # points A, B and C will never be aligned
    return [round((A[0]+B[0]+C[0])/3,4),round((A[-1]+B[-1]+C[-1])/3,4)]


Solve in Python:
The mobile application store has a new game called "Subway Roller".

The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.

All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.

Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column.

 [Image]

-----Input-----

Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 ≤ t ≤ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) — the number of sets.

Then follows the description of t sets of the input data.

The first line of the description of each set contains two integers n, k (2 ≤ n ≤ 100, 1 ≤ k ≤ 26) — the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in...

from queue import Queue
from collections import defaultdict

class PhilipTrains():
    def __init__(self, n, k, state):
        self.n = n
        self.k = k
        self.state = state
        self.graph = [[[0 for i in range(n+1)] for j in range(n)] for k in range(3)]
        for i in range(len(state)):
            for j in range(len(state[i])):
                if 'A' <= state[i][j] <= 'Z':
                    for k in range(n):
                        nj = j-(2*k)
                        if nj >= 0:
                            self.graph[i][nj][k] = -1
                        else:
                            break
        for i in range(len(state)):
            if state[i][0] == 's':
                self.r = i
                self.c = 0

    def check_reach(self):
        q = Queue()
        check = defaultdict(int)

        changes = [(1,1,1),(-1,1,1), (0,1,1)]

        q.put((self.r, self.c, 0))
        check[(self.r, self.c, 0)] = 1

        while not q.empty():
            pr, pc, pt = q.get()
            if self.graph[pr][pc][pt] == -1:
                continue
            if pc == self.n-1:
                return 'YES'
            if self.graph[pr][pc+1][pt] != -1:
                if check[(pr, pc+1,pt+1)] != 1:
                    q.put((pr, pc+1,pt+1))
                    check[(pr, pc+1, pt+1)] = 1
                for ch in [1,-1]:
                    if 0 <= pr+ch <= 2 and check[(pr+ch, pc+1,pt+1)] != 1 and self.graph[pr+ch][pc+1][pt] != -1:
                        q.put((pr+ch, pc+1,pt+1))
                        check[(pr+ch, pc+1, pt+1)] = 1
        return 'NO'

t = int(input())

for i in range(t):
    n, k = list(map(int,input().strip(' ').split(' ')))
    arr = []
    for i in range(3):
        arr.append(input().strip(' '))
    graph = PhilipTrains(n, k, arr)
    print(graph.check_reach())


Solve in Python:
The most basic encryption method is to map a char to another char by a certain math rule.
Because every char has an ASCII value, we can manipulate this value with a simple math expression.
For example 'a' + 1 would give us 'b', because 'a' value is 97 and 'b' value is 98.

You will need to write a method which does exactly that -

get a string as text and an int as the rule of manipulation, and should return encrypted text.
for example:

encrypt("a",1) = "b"

 *Full ascii table is used on our question (256 chars) - so 0-255 are the valid values.*

Good luck.

def encrypt(text, rule):
    encrypted_text = list(text)
    for i in range(len(encrypted_text)):
        encrypted_text[i] = chr((ord(encrypted_text[i]) + rule) % 256 )
    return "".join(encrypted_text)


Solve in Python:
The most dangerous cyborg Jenish is finally entrapped on a narrow bridge over a valley. The bridge is $N$ meters long. For convenience, position $i$ represents a portion of bridge between whose left border is at distance $i-1$ meters from left end and right border is at distance $i$ meters from left end.
There are $N$ batteries placed at positions $1,2...N$. The $i^{th}$ one has energy $a[i]$.
There are two tanks of strength $X$ at positions $0$ and $N+1$. Initially Jenish has $0$ energy.
From now at any second $t$ starting from $1$,
first, Jenish can select any battery placed at position $i$ such that $(t \leq i \leq N-t+1)$ and add $a[i]$ to his energy (every battery can be used atmost once).
Then both the tanks move one meter towards each other. If there are still any batteries present at positions where the tanks are heading, the battery gets destroyed.
At any moment if Jenish's total energy is greater than or equal to $X$, he destroys both the tanks and he escapes the cops. If by the end of $\lfloor \frac {(n+1)}{2}\rfloor^{th}$ second, he can't destroy the tanks, he himself gets destroyed. Find out if he can escape.

-----Input:-----
- The first line consists of a single integer $T$, the number of test cases.
- The first line of each test case contains two space separated integers which represents $N$ and $X$ for that test case respectively.
- The second line of each test case contains $N$ space separated integers, $i^{th}$ of which represents $a[i]$.

-----Output:-----
For each test case, print in a single line, $YES$ if Jenish can escape or $NO$ if he gets destroyed.

-----Constraints:-----
- $1 \leq  X \leq 10^9$
- $0 \leq a[i] \leq 10^6$
- $ 1 \leq N \leq 10^5$
- $\Sigma$ $N$ over all the test cases does not exceed $10^5$

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

-----Sample Output:-----
YES
YES
NO

-----Explanation-----
For test $1$, in the 1st second, first Jenish will select battery at index $1$ and then the tanks from either side will move one meter closer, thus destroying the...

# cook your dish here
import heapq
for _ in range(int(input())):

 n,x=list(map(int,input().split()))

 l=list(map(int,input().split()))
 battery=[]

 heapq.heapify(battery)
 power=0
 i=0
 t=(n+1)//2
 while power<x and i<t:

  if i==n-i-1:
   temp=[-1,l[i]]
  else:
   temp=sorted([ l[i], l[n-i-1] ])

  power+=temp[1]
  heapq.heappush(battery,temp[1])

  y=heapq.heappop(battery)
  heapq.heappush(battery,y)
  if temp[0]>y:

   power-=heapq.heappop(battery)
   power+=temp[0]
   heapq.heappush(battery,temp[0])

  i+=1

 if power>=x:
  print('YES')
 else:
  print('NO')


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 __init__(self):
         self.result = []
         self.visited = None

     def solveNQueens(self, n):
         """
         :type n: int
         :rtype: List[List[str]]
         """
         self.visited = [0 for i in range(n)]
         self.__solve_n_queues(n, 0, [])
         return self.result

     @staticmethod
     def __not_diagonal(x, y, curr_answer):
         for c_x, c_y in enumerate(curr_answer):
             if abs(c_x - x) == abs(c_y - y):
                 return False
         return True

     @staticmethod
     def visualize(curr_answer, n):
         answer = []
         for pos in curr_answer:
             answer.append('.' * pos + 'Q' + '.' * (n - pos - 1))
         return answer

     def __solve_n_queues(self, n, level, curr_answer):
         if level == n:
             self.result.append(Solution.visualize(curr_answer, n))
             return

         for i in range(n):
             if not self.visited[i] and Solution.__not_diagonal(level, i, curr_answer):
                 self.visited[i] = 1
                 curr_answer.append(i)
                 self.__solve_n_queues(n, level + 1, curr_answer)
                 curr_answer.pop()
                 self.visited[i] = 0


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 the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

class Solution:
     def totalNQueens(self, n):
         """
         :type n: int
         :rtype: int
         """
         if n <= 0:
             return 0
         diag_lr = [True] * (2*n-1)
         diag_rl = [True] * (2*n-1)
         vert = [True] * n
         res = []

         def _check_board(x, y):
             return vert[y] and diag_lr[y-x+n-1] and diag_rl[x+y]

         def _helper(x):
             if x == n:
                 res.append(1)
                 return
             for y in range(n):
                 if _check_board(x, y):
                     vert[y] = False
                     diag_lr[y-x+n-1] = False
                     diag_rl[x+y] = False
                     _helper(x+1)
                     vert[y] = True
                     diag_lr[y-x+n-1] = True
                     diag_rl[x+y] = True

         _helper(0)
         return len(res)


Solve in Python:
The name of our college is "Government College of Engineering and Textile Technology Berhampore". There is another college named "Government College of Engineering and Textile Technology Serampore". As the names are quite similar, those who are unaware of existence of both the colleges, often get confused. And mistake one with other.

Given a string, if it contains the word berhampore (case insensitive), print GCETTB or if it contains serampore(case-insensitive), print GCETTS . If the string contains neither print Others. If it contains both Berhampore and Serampore print Both
Input
- First line contains single integer T, No. of test case
- Next line for every test contain case a string S
Output

Print GCETTB or GCETTS or Others or Both on a new line
Constraints
- 1 <= T <= 10
- 0 <= len(S) <= 100
- S contain a-z and A-Z and space only
Sample Input
3
Government clg Berhampore
SeRaMporE textile college
Girls college Kolkata

Sample Output

GCETTB

GCETTS

Others
Explanation

Self-Explanatory

for _ in range(int(input())):
    s = input()
    check1 = 'berhampore'
    check2 = 'serampore'
    if check1 in s.casefold() and check2 in s.casefold():
        print("Both")
    else:
        if check1 in s.casefold():
            print("GCETTB")
        elif check2 in s.casefold():
            print("GCETTS")
        else:
            print("Others")


Solve in Python:
The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single `100`, `50` or `25` dollar bill. An "Avengers" ticket costs `25 dollars`.

Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.

Can Vasya sell a ticket to every person and give change if he initially has no money and sells the tickets strictly in the order people queue?

Return `YES`, if Vasya can sell a ticket to every person and give change with the bills he has at hand at that moment. Otherwise return `NO`.

### Examples:

```csharp
Line.Tickets(new int[] {25, 25, 50}) // => YES
Line.Tickets(new int[] {25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
Line.Tickets(new int[] {25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```python
tickets([25, 25, 50]) # => YES
tickets([25, 100]) # => NO. Vasya will not have enough money to give change to 100 dollars
tickets([25, 25, 50, 50, 100]) # => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```cpp
tickets({25, 25, 50}) // => YES
tickets({25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
tickets({25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```

def tickets(people):
  till = {100.0:0, 50.0:0, 25.0:0}

  for paid in people:
    till[paid] += 1
    change = paid-25.0

    for bill in (50,25):
      while (bill <= change and till[bill] > 0):
        till[bill] -= 1
        change -= bill

    if change != 0:
      return 'NO'

  return 'YES'


Solve in Python:
The new Formula 1 season is about to begin and Chef has got the chance to work with the Formula 1 technical team.
Recently, the pre-season testing ended and the technical team found out that their timing system for qualifying was a little bit buggy. So, they asked Chef to fix it before the season begins.
His task is to write a program to find the starting lineup of the race by taking the timings of the drivers in qualifying.
(If you don’t know the rules that make the starting grid in Formula 1, consider that the driver with the least time will start at the front).
Note:
- Two or more drivers can have the same name.
- Every driver will have a distinct time.

-----Input:-----
- The first line of the input consists of a single integer $T$ denoting the number of test cases.
- First line of each test case consists of a single integer $N$ denoting the number of drivers to set a time.
- The following $2*N$ lines consists of the driver’s name $S$ in one line and its timing details  $X$ (in milliseconds) in the next line.

-----Output:-----
- For each test case output the starting lineup of the race i.e., name of each driver in the order they will start the race. Print each name in a new line.

-----Constraints-----
- 1 <= $T$ <= 10
- 1 <= $N$ <= 105
- 1 <= $|S|$ <= 20
- 1 <= $X$ <= 109

-----Subtasks-----
Subtask #1 (20 points):
- 1 <= $N$ <= 100
Subtask #2 (80 points):
- Original Constraints

-----Sample Input:-----
2

3

Hamilton

75000

Vettel

76000

Bottas

75500

2

Leclerc

666666

Verstappen

666777

-----Sample Output:-----
Hamilton

Bottas

Vettel

Leclerc

Verstappen

-----EXPLANATION:-----
The drivers with the least time are ahead in the lineup.

# cook your dish here
t=int(input())
for i in range(t):
 n=int(input())
 l1=[]
 l2=[]
 d=dict()
 for i in range(1,2*n+1):
  if i%2==0:
   l1.append(int(input()))
  else:
   l2.append(str(input()))
 r1=[]
 for i in l1:
  r1.append(i)
 l1.sort()
 ind=[]
 for i in l1:
  a=r1.index(i)
  ind.append(a)
 for i in ind:
  print(l2[i])


Solve in Python:
The new football league season is coming and the Football Association need some help resetting the league standings. Normally the initial league standing is done in alphabetical order (from A to Z) but this year the FA have decided to freshen it up.

It has been decided that team who finished first last season will begin the next season in first place. Regardless of what letter their club begins with. e.g. if Manchester City were in first place last year, they will begin the season in position one. All other teams should be in alphabetical order.

The teams will be fed in as an object ({}). The key will be will be their position from last season and the value is the club's name e.g. Arsenal.

The output should be an object ({}) with the key as the club's starting position for the new season and the value should be club's name e.g. Arsenal.

For example. If in the previous season the standings were:

1:'Leeds United'
2:'Liverpool'
3:'Manchester City'
4:'Coventry'
5:'Arsenal'

Then the new season standings should

1:'Leeds United' (first last season)
2:'Arsenal' (alphabetical)
3:'Coventry' (alphabetical)
4:'Liverpool' (alphabetical)
5:'Manchester City' (alphabetical)

def premier_league_standings(teams):
    return {c : n for c, (_, n) in enumerate(sorted(teams.items(), key = lambda t: (t[0] > 1, t[1])), 1)}


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)), 0) // 5


Solve in Python:
The notorious hacker group "Sed" managed to obtain a string $S$ from their secret sources. The string contains only lowercase English letters along with the character '?'.
A substring of $S$ is a contiguous subsequence of that string. For example, the string "chef" is a substring of the string "codechef", but the string "codeh" is not a substring of "codechef".
A substring of $S$ is good if it is possible to choose a lowercase English letter $C$ such that the following process succeeds:
- Create a string $R$, which is a copy of the substring, but with each '?' replaced by the letter $c$. Note that all occurrences of '?' must be replaced by the same letter.
- For each lowercase English letter:
- Compute the number of times it occurs in $S$ and the number of times it occurs in $R$; let's denote them by $A$ and $B$ respectively. The '?' characters in the original string $S$ are ignored when computing $A$.
- Check the parity of $A$ and $B$. If they do not have the same parity, i.e. one of them is even while the other is odd, then this process fails.
- If the parities of the number of occurrences in $S$ and $R$ are the same for each letter, the process succeeds.
For different substrings, we may choose different values of $C$.
Help Sed find the number of good substrings in the string $S$.

-----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 string $S$.

-----Output-----
For each test case, print a single line containing one integer ― the number of good substrings.

-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le S \le 10^5$
- $S$ contains only lowercase English letters ('a' through 'z') and '?'
- the sum of $|S|$ over all test cases does not exceed $10^5$

-----Example Input-----
5
aa?
a???
????
asfhaslskfak
af??avvnfed?fav?faf????

-----Example Output-----
2
6
4
2
27

-----Explanation-----
Example case 1: All letters occur an even number of times in...

def to_bit(c):
    if c == "?":
        bit = 26
    else:
        bit = (ord(c)-ord('a'))
    return bit

T = int(input())
for _ in range(T):
    s = input()

    mask = 0
    for c in s:
        if c != "?":
            mask ^= 1 << to_bit(c)

    good_prefixes = []
    good_prefixes.append(mask & ((1 << to_bit("?")) - 1))
    for i in range(26):
        good_prefixes.append((mask ^ (1<<i)) | (1 << to_bit("?")))

    prefixes = { 0: 1}

    res = 0
    current = 0
    for c in s:
        current ^= 1 << to_bit(c)
        for prefix in good_prefixes:
            res += prefixes.get(prefix ^ current, 0)
        prefixes[current] = prefixes.get(current, 0) + 1

    print(res)


Solve in Python:
The number 45 is the first integer in having this interesting property:
the sum of the number with its reversed is divisible by the difference between them(absolute Value).
```
45 + 54 = 99
abs(45 - 54) = 9
99 is divisible by 9.
```
The first terms of this special sequence are :
```
n               a(n)
1               45
2               54
3               495
4               594
```
Make the function ```sum_dif_rev()```(`sumDivRef` in JavaScript and CoffeeScript), that receives ```n```, the ordinal number of the term and may give us, the value of the term of the sequence.
```python
sum_dif_rev(n) -----> a(n)
```
Let's see some cases:
```python
sum_dif_rev(1) -----> 45
sum_dif_rev(3) -----> 495
```
"Important: Do not include numbers which, when reversed, have a leading zero, e.g.: 1890 reversed is 0981, so 1890 should not be included."

Your code will be tested up to the first 65 terms, so you should think to optimize it as much as you can.

(Hint: I memoize, you memoize, he memoizes, ......they (of course) memoize)

Happy coding!!

def memoize_sum_dif(f):
    memory = {}

    def inner(n):
        if n not in memory:
            memory[n] = f(n)
        return memory[n]
    return inner

@memoize_sum_dif
def sum_dif_rev(n):

    if n == 1: return 45

    num = sum_dif_rev(n-1)

    while True:
        num = num+1
        if str(num)[::-1][0] == "0" or abs(num - int(str(num)[::-1])) == 0 :
            continue
        if (num + int(str(num)[::-1]))%abs(num - int(str(num)[::-1])) == 0:
            break
    return num


Solve in Python:
The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit).
The next one, is 512.
Let's see both cases with the details

8 + 1 = 9 and 9^(2) = 81

512 = 5 + 1 + 2 = 8 and 8^(3) = 512

We need to make a function, ```power_sumDigTerm()```, that receives a number ```n``` and may output the ```n-th term``` of this sequence of numbers.
The cases we presented above means that

power_sumDigTerm(1) == 81

power_sumDigTerm(2) == 512

Happy coding!

def power_sumDigTerm(n):

    def sum_d(x):
        L = [int(d) for d in str(x)]
        res = 0
        for l in L:
            res = res + l
        return res

    r_list = []

    for j in range(2, 50):
        for i in range(7, 100):
            a = i**j
            if sum_d(a) == i:
                r_list.append(a)
                r_list = list(set(r_list))

    r_list = sorted((r_list))
    return r_list[n-1]


Solve in Python:
The number `1035` is the smallest integer that exhibits a non frequent property: one its multiples, `3105 = 1035 * 3`, has its same digits but in different order, in other words, `3105`, is one of the permutations of `1035`.

The number `125874` is the first integer that has this property when the multiplier is `2`, thus: `125874 * 2 = 251748`

Make the function `search_permMult()`, that receives an upper bound, nMax and a factor k and will output the amount of pairs bellow nMax that are permuted when an integer of this range is multiplied by `k`. The pair will be counted if the multiple is less than `nMax`, too

Let'see some cases:
```python
search_permMult(10000, 7) === 1 # because we have the pair 1359, 9513
search_permMult(5000, 7) === 0 # no pairs found, as 9513 > 5000

search_permMult(10000, 4) === 2 # we have two pairs (1782, 7128) and (2178, 8712)
search_permMult(8000, 4) === 1 # only the pair (1782, 7128)

search_permMult(5000, 3) === 1 # only the pair (1035, 3105)
search_permMult(10000, 3) === 2 # found pairs (1035, 3105) and (2475, 7425)
```
Features of the random Tests:
```
10000 <= nMax <= 100000
3 <= k <= 7
```
Enjoy it and happy coding!!

def search_permMult(nMax, k):
    def tod(n):
        return "".join(sorted([d for d in str(n)]))
    i = 1; cnt = 0
    while i <= nMax // k:
        if tod(i) == tod(i * k):
            cnt += 1
        i += 1
    return cnt


Solve in Python:
The number `198` has the property that `198 = 11 + 99 + 88, i.e., if each of its digits is concatenated twice and then summed, the result will be the original number`. It turns out that `198` is the only number with this property. However, the property can be generalized so that each digit is concatenated `n` times and then summed.

eg:-
```
original number =2997 , n=3
2997 = 222+999+999+777 and here each digit is concatenated three times.

original number=-2997 , n=3

-2997 = -222-999-999-777 and here each digit is concatenated three times.

```
Write afunction named `check_concatenated_sum` that tests if a number has this generalized property.

def check_concatenated_sum(number, k):
    return sum(int(d * k) for d in str(abs(number))) == abs(number) if k else False


Solve in Python:
The number ```12``` is the first number in having six divisors, they are: ```1, 2, 3, 4, 6 and 12.```
Your challenge for this kata is to find the minimum number that has a certain number of divisors.
For this purpose we have to create the function

```find_min_num() or findMinNum() or similar in the other languages```

that receives the wanted number of divisors ```num_div```, and outputs the smallest number having an amount of divisors equals to ```num_div```.

Let's see some cases:
```
find_min_num(10) = 48 # divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and  48
find_min_num(12) = 60
```
In this kata all the tests will be with ```numDiv < 80```

(There will be a next kata with numDiv < 10000, Find the First Number Having a Certain Number of Divisors II, should have the help of number theory)

Enjoy it and happy coding!
(Memoization is advisable)

def n_div(n):
    result = 0
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            result += 1 + (i * i < n)
    return result

def find_min_num(num_div):
    for i in range(num_div, 1000000):
        if n_div(i) == num_div:
            return i


Solve in Python:
The number ```1331``` is the first positive perfect cube,  higher than ```1```, having all its digits odd (its cubic root is ```11```).

The next one is ```3375```.

In the interval [-5000, 5000] there are six pure odd digit perfect cubic numbers and are: ```[-3375,-1331, -1, 1, 1331, 3375]```

Give the numbers of this sequence that are in the range ```[a,b] ```(both values inclusive)

Examples:
``` python
odd_dig_cubic(-5000, 5000) == [-3375,-1331, -1, 1, 1331, 3375] # the output should be sorted.
odd_dig_cubic(0, 5000) == [1, 1331, 3375]
odd_dig_cubic(-1, 5000) == [-1, 1, 1331, 3375]
odd_dig_cubic(-5000, -2) == [-3375,-1331]

```
Features of the random tests for python:
```
number of Tests = 94
minimum value for a = -1e17
maximum value for b = 1e17
```
You do not have to check the entries, ```a``` and ```b``` always integers and ```a < b```

Working well in Python 2 and Python 3.
Translation into Ruby is coming soon.


Solve in Python:
The number ```89``` is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata.
What's the use of saying "Eureka"? Because this sum gives the same number.

In effect: ```89 = 8^1 + 9^2```

The next number in having this property is ```135```.

See this property again: ```135 = 1^1 + 3^2 + 5^3```

We need a function to collect these numbers, that may receive two integers ```a```, ```b``` that defines the range ```[a, b]``` (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.

Let's see some cases:
```python
sum_dig_pow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]

sum_dig_pow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
```
If there are no numbers of this kind in the range [a, b] the function should output an empty list.
```python
sum_dig_pow(90, 100) == []
```
Enjoy it!!

def dig_pow(n):
    return sum(int(x)**y for y,x in enumerate(str(n), 1))

def sum_dig_pow(a, b):
    return [x for x in range(a,b + 1) if x == dig_pow(x)]


Solve in Python:
The number ```89``` is the first positive integer that has a particular, curious property:

The square of ```89``` is ```7921```; ```89² = 7921```

The reverse of ```7921``` is ```1297```, and ```1297``` is a prime number.

The cube of ```89``` is ```704969```; ```89³ = 704969```

The reverse of ```704969``` is ```969407```, and ```969407``` is a prime number.

The first four terms of this sequence having this special property are:
```
n-th term      term value
    1               89
    2              271
    3              325
    4              328
```

Create a function ```sq_cub_rev_prime()```, that receives the ordinal number of the sequence and outputs its correspoding value.

Use the above table to show how the function should work:
```python
sq_cub_rev_prime(1) == 89
sq_cub_rev_prime(2) == 271
sq_cub_rev_prime(3) == 325
sq_cub_rev_prime(4) == 328
```
Your code will be tested up to the 250th term

This is not a registered sequence of OESIS, so if you are one of the first ten people that solve this kata, you may have the privilege to register the sequence at https://oeis.org, with your name. If you do so, please, mention in your biography that you are a Codewarrior.

Memoize your results to pass the tests.

Enjoy it!


Solve in Python:
The number n is Evil if it has an even number of 1's in its binary representation.
The first few Evil numbers: 3, 5, 6, 9, 10, 12, 15, 17, 18, 20
The number n is Odious if it has an odd number of 1's in its binary representation.
The first few Odious numbers: 1, 2, 4, 7, 8, 11, 13, 14, 16, 19
You have to write a function that determine if a number is Evil of Odious, function should return "It's Evil!" in case of evil number and "It's Odious!" in case of odious number.

good luck :)

def evil(n):
    x = str(bin(n))[2:]
    t = 0
    for i in x:
        if i == "1":
            t+=1

    if t % 2 == 0 and t >= 1:
        return "It's Evil!"
    else:
        return "It's Odious!"


Solve in Python:
The numbers 12, 63 and 119 have something in common related with their divisors and their prime factors, let's see it.
```
Numbers PrimeFactorsSum(pfs)        DivisorsSum(ds)              Is ds divisible by pfs
12         2 + 2 + 3 = 7         1 + 2 + 3 + 4 + 6 + 12 = 28            28 / 7 = 4,  Yes
63         3 + 3 + 7 = 13        1 + 3 + 7 + 9 + 21 + 63 = 104         104 / 13 = 8, Yes
119        7 + 17 = 24           1 + 7 + 17 + 119 = 144                144 / 24 = 6, Yes
```
There is an obvius property you can see: the sum of the divisors of a number is divisible by the sum of its prime factors.

We need the function ```ds_multof_pfs()``` that receives two arguments: ```nMin``` and  ```nMax```, as a lower and upper limit (inclusives), respectively, and outputs a sorted list with the numbers that fulfill the property described above.

We represent the features of the described function:
```python
ds_multof_pfs(nMin, nMax) -----> [n1, n2, ....., nl] # nMin ≤ n1 < n2 < ..< nl ≤ nMax
```
Let's see some cases:
```python
ds_multof_pfs(10, 100) == [12, 15, 35, 42, 60, 63, 66, 68, 84, 90, 95]

ds_multof_pfs(20, 120) == [35, 42, 60, 63, 66, 68, 84, 90, 95, 110, 114, 119]
```
Enjoy it!!

from functools import lru_cache
FC = lambda n, li=[], j=2:(FC(n, li, j+1) if n%j else FC(n//j, li+[j], j)) if j*j<=n else sum(li + [[],[n]][n>1])
get_factors = lru_cache(None)(lambda n:FC(n))
get_divisors = lru_cache(None)(lambda n:sum(sum([[i,n//i] for i in range(1,int(n**.5)+1) if not n % i], [])))
ds_multof_pfs = lambda start, end:[i for i in range(start, end+1) if not get_divisors(i) % get_factors(i)]


Solve in Python:
The objective is to disambiguate two given names: the original with another

Let's start simple, and just work with plain ascii strings.

The function ```could_be``` is given the original name and another one to test
against.

```python
# should return True if the other name could be the same person
> could_be("Chuck Norris", "Chuck")
True

# should False otherwise (whatever you may personnaly think)
> could_be("Chuck Norris", "superman")
False
```

Let's say your name is *Carlos Ray Norris*, your objective is to return True if
the other given name matches any combinaison of the original fullname:

```python
could_be("Carlos Ray Norris", "Carlos Ray Norris") : True
could_be("Carlos Ray Norris", "Carlos Ray") : True
could_be("Carlos Ray Norris", "Norris") : True
could_be("Carlos Ray Norris", "Norris Carlos") : True
```

For the sake of simplicity:

 * the function is case sensitive and accent sensitive for now
 * it is also punctuation sensitive
 * an empty other name should not match any original
 * an empty orginal name should not be matchable
 * the function is not symmetrical

The following matches should therefore fail:

```python
could_be("Carlos Ray Norris", " ") : False
could_be("Carlos Ray Norris", "carlos") : False
could_be("Carlos Ray Norris", "Norris!") : False
could_be("Carlos Ray Norris", "Carlos-Ray Norris") : False
could_be("Ray Norris", "Carlos Ray Norris") : False
could_be("Carlos", "Carlos Ray Norris") : False
```

Too easy ? Try the next steps:

* [Author Disambiguation: a name is a Name!](https://www.codewars.com/kata/author-disambiguation-a-name-is-a-name)
* or even harder: [Author Disambiguation: Signatures worth it](https://www.codewars.com/kata/author-disambiguation-signatures-worth-it)

def could_be(original, another):
    a, b = original.split(), another.split()
    return bool(a and b and set(a) >= set(b))


Solve in Python:
The objective is to disambiguate two given names: the original with another

This kata is slightly more evolved than the previous one: [Author Disambiguation: to the point!](https://www.codewars.com/kata/580a429e1cb4028481000019).

The function ```could_be``` is still given the original name and another one to test
against.

```python
# should return True even with 'light' variations (more details in section below)
> could_be("Chuck Norris", u"chück!")
True

# should False otherwise (whatever you may personnaly think)
> could_be("Chuck Norris", "superman")
False
```

**Watch out**: When accents comes into the game, they will enter through **UTF-8 unicodes. **

The function should be tolerant with regards to:

 * upper and lower cases: ```could_be(A, a) : True```
 * accents: ```could_be(E, é) : True```
 * dots: ```could_be(E., E) : True```
 * same for other ending punctuations in [!,;:?]: ```could_be(A, A!) : True```

On the other hand, more consideration needs to be given to *composed names*...
Let's be bold about it: if you have any, they will be considered as a whole :

```python
# We still have:
> could_be("Carlos Ray Norris", "Carlos Ray Norris")
True
> could_be("Carlos-Ray Norris", "Carlos-Ray Norris")
True

# But:
> could_be("Carlos Ray Norris", "Carlos-Ray Norris")
False
> could_be("Carlos-Ray Norris", "Carlos Ray Norris")
False
> could_be("Carlos-Ray Norris", "Carlos Ray-Norris")
False
```

Among the valid combinaisons of the fullname "Carlos Ray Norris", you will find

```python
could_be("Carlos Ray Norris", "carlos ray") : True
could_be("Carlos Ray Norris", "Carlos. Ray, Norris;") : True
could_be("Carlos Ray Norris", u"Carlòs! Norris") : True
```

Too easy ? Try the next step: [Author Disambiguation: Signatures worth it](https://www.codewars.com/kata/author-disambiguation-signatures-worth-it)

import re
import string
dic1 = {224:97, 244:111, 252:117, 233:101, 239:105}
def could_be(original, another):
    if original == '' and another == '': return False
    p = "!,;:?"
    o, a = re.sub(r"[!,;:\?\.]", ' ', original.lower()), re.sub(r"[!,;:\?\.]", ' ', another.lower())
    if o == a: return True
    o = o.encode('unicode-escape').decode('unicode-escape')
    a = a.encode('unicode-escape').decode('unicode-escape')
    o1, a1 = o.split(), a.split()
    o2 = [i[:-1] if i[-1] in p else i for i in o1]
    ans1 = [''.join([chr(dic1[ord(j)]) if ord(j) in dic1 else j for j in i]) for i in o2]
    a2 = [i[:-1] if i[-1] in p else i for i in a1]
    ans2 = [''.join([chr(dic1[ord(j)]) if ord(j) in dic1 else j for j in i]) for i in a2]
    if ans1 != [] and ans2 == []:
        return False
    for i in ans2:
        for j in ans1:
            if i == j: break
        else: return False
    return True


Solve in Python:
The objective is to return all pairs of integers from a given array of integers that have a difference of 2.

The result array should be sorted in ascending order of values.

Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter.

## Examples
~~~if-not:python
```
[1, 2, 3, 4]  should return [[1, 3], [2, 4]]

[4, 1, 2, 3]  should also return [[1, 3], [2, 4]]

[1, 23, 3, 4, 7] should return [[1, 3]]

[4, 3, 1, 5, 6] should return [[1, 3], [3, 5], [4, 6]]
```
~~~
~~~if:python
```
[1, 2, 3, 4]  should return [(1, 3), (2, 4)]

[4, 1, 2, 3]  should also return [(1, 3), (2, 4)]

[1, 23, 3, 4, 7] should return [(1, 3)]

[4, 3, 1, 5, 6] should return [(1, 3), (3, 5), (4, 6)]
```
~~~

def twos_difference(arr):
    arr = sorted(arr)
    b = []
    for i in range(len(arr)):
        for j in range(len(arr)):
            if arr[j] - arr[i] == 2:
                b.append((arr[i],arr[j]))
    return b


Solve in Python:
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters.

Taken from Wikipedia:
"In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4."

For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4.

If both parameters are 0, the method should return 0.
The function must be able to handle negative input.

def binary_gcd(x, y):
    from fractions import gcd
    return bin(reduce(gcd, [x, y])).count("1")


Solve in Python:
The objective of this Kata is to write a function that creates a dictionary of factors for a range of numbers.

The key for each list in the dictionary should be the number. The list associated with each key should possess the factors for the number.

If a number possesses no factors (only 1 and the number itself), the list for the key should be `['None']`

The function possesses two arguments (`n` and `m`). Where `n` is the starting number and `m` is the ending number.

For example: All factors for 2 (`n`) through to 6 (`m`) with the number being the key in the dictionary:

```python
{2: ['None'], 3: ['None'], 4: [2], 5: ['None'], 6: [2, 3]}
```

def factorsRange(n, m):
    def factors(n):
        ret = [i for i in range(2, n) if n % i == 0]
        if not ret: return ['None']
        return ret
    return {i:factors(i) for i in range(n, m + 1)}