Solve in Python:
In the State of Takahashi in AtCoderian Federation, there are N cities, numbered 1, 2, ..., N.
M bidirectional roads connect these cities.
The i-th road connects City A_i and City B_i.
Every road connects two distinct cities.
Also, for any two cities, there is at most one road that directly connects them.
One day, it was decided that the State of Takahashi would be divided into two states, Taka and Hashi.
After the division, each city in Takahashi would belong to either Taka or Hashi.
It is acceptable for all the cities to belong Taka, or for all the cities to belong Hashi.
Here, the following condition should be satisfied:
 - Any two cities in the same state, Taka or Hashi, are directly connected by a road.
Find the minimum possible number of roads whose endpoint cities belong to the same state.
If it is impossible to divide the cities into Taka and Hashi so that the condition is satisfied, print -1.

-----Constraints-----
 - 2 \leq N \leq 700
 - 0 \leq M \leq N(N-1)/2
 - 1 \leq A_i \leq N
 - 1 \leq B_i \leq N
 - A_i \neq B_i
 - If i \neq j, at least one of the following holds: A_i \neq A_j and B_i \neq B_j.
 - If i \neq j, at least one of the following holds: A_i \neq B_j and B_i \neq A_j.

-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 B_1
A_2 B_2
:
A_M B_M

-----Output-----
Print the answer.

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

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

For example, if the cities 1, 2 belong to Taka and the cities 3, 4, 5 belong to Hashi, the condition is satisfied.
Here, the number of roads whose endpoint cities belong to the same state, is 4.

import sys
input = sys.stdin.readline
from itertools import combinations
n,m = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(m)]
g2d = [[1 for i in range(n+1)] for j in range(n+1)]
for i in range(1,n+1):
  g2d[i][i] = 0
for a,b in ab:
  g2d[a][b] = 0
  g2d[b][a] = 0
graph = [[] for i in range(n+1)]
for i in range(1,n+1):
  for j in range(1,n+1):
    if g2d[i][j]:
      graph[i].append(j)
      graph[j].append(i)
vis = [-1]*(n+1)
oddeven = []
for i in range(1,n+1):
  if vis[i] == -1:
    stack = [i]
    vis[i] = 0
    odd = 0
    even = 1
    while stack:
      x = stack.pop()
      for y in graph[x]:
        if vis[y] == -1:
          vis[y] = vis[x]+1
          if vis[y]%2:
            odd += 1
          else:
            even += 1
          stack.append(y)
        elif (vis[y]-vis[x])%2 == 0:
          print(-1)
          return
    oddeven.append(abs(odd-even))
t = len(oddeven)
s = sum(oddeven)
dp = 1<<s
for x in oddeven:
  dp = (dp<<abs(x)) | (dp>>abs(x))
for i in range(s+1):
  if (dp&1<<(s-i))|(dp&1<<(s+i)):
    ex = i
    break
A,B = (n+ex)//2,(n-ex)//2
print(A*(A-1)//2+B*(B-1)//2)


Solve in Python:
In the board game Talisman, when two players enter combat the outcome is decided by a combat score, equal to the players power plus any modifiers plus the roll of a standard 1-6 dice. The player with the highest combat score wins and the opposing player loses a life. In the case of a tie combat ends with neither player losing a life.

For example:
```
Player 1: 5 Power, 0 Modifier
Player 2: 3 Power, 2 Modifier

Player 1 rolls a 4, Player 2 rolls a 2.

(5 + 0 + 4) -> (3 + 2 + 2)
Player 1 wins (9 > 7)
```

Your task is to write a method that calculates the required roll for the player to win.

The player and enemy stats are given as an array in the format:
```python
[power, modifier]
```

For example for the examples used above the stats would be given as:
```python
get_required([5, 0], [3, 2]) # returns 'Random'
```

If the player has at least 6 more power (including modifiers) than the enemy they automatically wins the fight, as the enemy's combat score couldn't possibly exceed the player's. In this instance the method should return "Auto-win".

For example:
```python
get_required([9, 0], [2, 1]) # returns 'Auto-win' as the enemy can't possibly win
```

If the enemy has at least 6 more power (including modifiers) than the player they automatically wins the fight, as the player's combat score couldn't possibly exceed the enemy's. In this instance the method should return "Auto-lose".

For example:
```python
get_required([2, 1], [9, 0]) # returns 'Auto-lose' as the player can't possibly win
```

If the player and enemy have the same power (including modifiers) the outcome is purely down to the dice roll, and hence would be considered completely random. In this instance the method should return "Random".

For example (as above):
```python
get_required([5, 0], [3, 2]) # returns 'Random' as it is purely down to the dice roll
```

If the player has greater power than the enemy (including modifiers) the player could guarantee a win by rolling a high enough number on the dice. In this instance the method should...

def get_required(player,enemy):
    difference = player[0] + player[1] - enemy[0] - enemy[1]
    if difference >= 6:
        return 'Auto-win'
    elif difference <= -6:
        return 'Auto-lose'
    elif difference == -5:
        return 'Pray for a tie!'
    elif difference == 0:
        return 'Random'
    else:
        if difference > 0:
            return '(' + str(6-difference+1) + '..' + '6)'
        else:
            return '(1' + '..' + str(6-abs(difference-1)) + ')'


Solve in Python:
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.

Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.

Note:

The given numbers of 0s and 1s will both not exceed 100
The size of given string array won't exceed 600.

Example 1:

Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4

Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”

Example 2:

Input: Array = {"10", "0", "1"}, m = 1, n = 1
Output: 2

Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".

class Solution:
     def Greedy(self, counts, zeros, ones) :
         num = 0;
         for a, b in counts :
             if a <= zeros and b <= ones :
                 zeros -= a
                 ones -= b
                 num += 1
         return num

     def findMaxForm(self, strs, m, n):
         """
         :type strs: List[str]
         :type m: int
         :type n: int
         :rtype: int
         """
         counts = list(map(lambda x : [x.count('0'), x.count('1')], strs))
         return max(self.Greedy(sorted(counts, key = lambda c : min(c[0], c[1])), m, n),
                    self.Greedy(sorted(counts, key = lambda c : min(m - c[0], n - c[1]), reverse = True), m, n))


Solve in Python:
In the drawing below we have a part of the Pascal's triangle, lines are numbered from **zero** (top).
The left diagonal in pale blue with only numbers equal to 1 is diagonal **zero**, then in dark green
(1, 2, 3, 4, 5, 6, 7) is diagonal 1, then in pale green (1, 3, 6, 10, 15, 21) is
diagonal 2 and so on.

We want to calculate the sum of the binomial coefficients on a given diagonal.
The sum on diagonal 0 is 8 (we'll write it S(7, 0), 7 is the number of the line where we start,
0 is the number of the diagonal). In the same way S(7, 1) is 28, S(7, 2) is 56.

Can you write a program which calculate S(n, p) where n is the line where we start and p
is the number of the diagonal?

The function will take n and p (with: `n >= p >= 0`) as parameters and will return the sum.

## Examples:
```
diagonal(20, 3) => 5985
diagonal(20, 4) => 20349
```
## Hint:
When following a diagonal from top to bottom have a look at the numbers on the diagonal at its right.

## Ref:
http://mathworld.wolfram.com/BinomialCoefficient.html

![alternative text](http://i.imgur.com/eUGaNvIm.jpg)

from math import factorial
def diagonal(n, p):
    return factorial(n + 1) // (factorial(p + 1) * factorial(n - p))


Solve in Python:
In the evenings Donkey would join Shrek to look at the stars. They would sit on a log, sipping tea and they would watch the starry sky. The sky hung above the roof, right behind the chimney. Shrek's stars were to the right of the chimney and the Donkey's stars were to the left. Most days the Donkey would just count the stars, so he knew that they are exactly n. This time he wanted a challenge. He imagined a coordinate system: he put the origin of the coordinates at the intersection of the roof and the chimney, directed the OX axis to the left along the roof and the OY axis — up along the chimney (see figure). The Donkey imagined two rays emanating from he origin of axes at angles α_1 and α_2 to the OX axis.

 [Image]

Now he chooses any star that lies strictly between these rays. After that he imagines more rays that emanate from this star at the same angles α_1 and α_2 to the OX axis and chooses another star that lies strictly between the new rays. He repeats the operation as long as there still are stars he can choose between the rays that emanate from a star.

 [Image]

As a result, the Donkey gets a chain of stars. He can consecutively get to each star if he acts by the given rules.

Your task is to find the maximum number of stars m that the Donkey's chain can contain.

Note that the chain must necessarily start in the point of the origin of the axes, that isn't taken into consideration while counting the number m of stars in the chain.

-----Input-----

The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of stars. The second line contains simple fractions representing relationships "a/b c/d", such that $\frac{a}{b} = \frac{\operatorname{sin} \alpha_{1}}{\operatorname{cos} \alpha_{1}}$ and $\frac{c}{d} = \frac{\operatorname{sin} \alpha_{2}}{\operatorname{cos} \alpha}$ (0 ≤ a, b, c, d ≤ 10^5; $0^{\circ} \leq \alpha_{1} < \alpha_{2} \leq 90^{\circ}$; $\frac{a}{b} \neq \frac{0}{0}$; $\frac{c}{d} \neq \frac{0}{0}$). The given numbers a, b, c, d are integers.

Next n lines contain pairs of...

from bisect import *
from math import *

n = int(input())
a, b, c, d = list(map(int,input().replace('/',' ').split()))

alpha = atan2(c,d) - atan2(a,b)
tan_alpha = tan(alpha)

lis = []

for x,y in sorted((y/tan_alpha - x,y) for x,y in [ (x,y) for x,y in [(b*x + a*y,-a*x + b*y) for x, y in [list(map(int,input().split())) for _ in range(n)] if a*x - b*y <= 0 and d*y - c*x <= 0]]):
    pos = bisect_left(lis,-y)
    if pos == len(lis):
        lis.append(-y)
    else:
        lis[pos] = -y

print(len(lis))


Solve in Python:
In the following 6 digit number:

```
283910
```

`91` is the greatest sequence of 2 consecutive digits.

In the following 10 digit number:
```
1234567890
```

`67890` is the greatest sequence of 5 consecutive digits.

Complete the solution so that it returns the greatest sequence of five consecutive digits found within the number given. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits.

*Adapted from ProjectEuler.net*

def solution(digits):
    lst = list(map(int, digits))
    answ = []
    for i in range(0, len(lst) - 4):
        x = lst[i:i+5]
        z = ''
        for j in x:
            z += str(j)
        answ.append(int(z))
    return max(answ)


Solve in Python:
In the morning all the doors in the school are closed. The school is quite big: there are **N** doors. Then pupils start coming. It might be hard to believe, but all of them want to study! Also, there are exactly **N** children studying in this school, and they come one by one.

When these strange children pass by some doors they change their status (i.e. Open -> Closed, Closed -> Open). Each student has their number, and each i-th student alters the status of every i-th door. For example: when the first child comes to the schools, he changes every first door (he opens all of them). The second one changes the status of every second door (he closes some doors: the 2nd, the 4th and so on). Finally, when the last one – the n-th – comes to the school, he changes the status of each n-th door (there's only one such door, though).

You need to count how many doors are left opened after all the students have come.

Example:

![](http://i.imgur.com/IqlOi2q.png)

*Here you can see red squares – closed doors, green – opened ones.*

Input:

> n – the number of doors and students, n ∈ N, n ∈ [1, 100000]

Output:

> o – the number of opened doors, o ∈ N

---

```
doors(5)
```

Should return

```
2
```


Solve in Python:
In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.

Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible.

There are n (n is always even) possible starting positions for characters marked along the Ox axis. The positions are given by their distinct coordinates x_1, x_2, ..., x_{n}, two characters cannot end up at the same position.

Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be n - 2). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting.

Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally.

-----Input-----

The first line on the input contains a single integer n (2 ≤ n ≤ 200 000, n is...

from itertools import accumulate
m = int(input())//2
X = [int(x) for x in input().split()]
X.sort()
Z = [X[i+m] - X[i] for i in range(m)]
print(min(Z))


Solve in Python:
In the previous Kata we discussed the OR case.

We will now discuss the AND case, where rather than calculating the probablility for either of two (or more) possible results, we will calculate the probability of receiving all of the viewed outcomes.

For example, if we want to know the probability of receiving head OR tails in two tosses of a coin, as in the last Kata we add the two probabilities together. However if we want to know the probability of receiving head AND tails, in that order, we have to work differently.

The probability of an AND event is calculated by the following rule:

`P(A ∩ B) = P(A | B) * P(B)`

or

`P(B ∩ A) = P(B | A) * P(A)`

That is, the probability of A and B both occuring is equal to the probability of A given B occuring times the probability of B occuring or vice versa.
If the events are mutually exclusive like in the case of tossing a coin, the probability of A occuring if B has occured is equal to the probability of A occuring by itself. In this case, the probability can be written as the below:

`P(A ∩ B) = P(A) * P(B)`

or

`P(B ∩ A) = P(B) * P(A)`

Applying to the heads and tails case:

`P(H ∩ T) = P(0.5) * P(0.5)`

or

`P(H ∩ T) = P(0.5) * P(0.5)`

The task:

You are given a random bag of 10 balls containing 4 colours. `Red`, `Green`, `Yellow` and `Blue`. You will also be given a sequence of 2 balls of any colour e.g. `Green` and `Red` or `Yellow` and `Yellow`.

You have to return the probability of pulling a ball at random out of the bag and it matching the first colour and then pulling a ball at random out of the bag and it matching the second colour.

You will be given a boolean value of `true` or `false` which indicates whether the balls that is taken out in the first draw is replaced in to the bag for the second draw. Hint: this will determine whether the events are mutually exclusive or not.

You will receive two arrays and a boolean value. The first array contains the colours of the balls in the bag and the second contains the colour of the two balls you have to...

from collections import Counter as C
def ball_probability(b):
      d, n, p = C(b[0]), len(b[0]), 1
      for i in b[1]:
          p *= d.get(i,0)/n
          n -= b[2]^1
          d[i] -= b[2]^1
      return round(p,3)


Solve in Python:
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.

One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.

Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.

To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path.

One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.

Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.

Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their...

from time import time

opposite = {
    'N': 'S',
    'S': 'N',
    'E': 'W',
    'W': 'E'
}
otr = str.maketrans(opposite)

bits = {
    'N': 0,
    'S': 1,
    'E': 2,
    'W': 3,
}

Q = 4294967291

def combine(h, v, q):
    return (h<<2 | v) % q

def combinel(h, v, q, s):
    return (v*s + h) % q

def flip(s):
    return ''.join(reversed(s.translate(otr)))

def solvable(p1, p2):
    h1 = 0
    h2 = 0
    s = 1
    for i in reversed(list(range(len(p1)))):
        n1 = bits[p1[i]]
        n2 = bits[opposite[p2[i]]]
        h1 = combine(h1, n1, Q)
        h2 = combinel(h2, n2, Q, s)
        if h1 == h2 and p1[i:] == flip(p2[i:]):
            return False
        s = (s<<2) % Q
    return True

def __starting_point():
    n = int(input())
    p1 = input()
    p2 = input()
    print('YES' if solvable(p1, p2) else 'NO')

# Made By Mostafa_Khaled

__starting_point()


Solve in Python:
In the wake of the npm's `left-pad` debacle, you decide to write a new super padding method that superceds the functionality of `left-pad`. Your version will provide the same functionality, but will additionally add right, and justified padding of string -- the `super_pad`.

Your function `super_pad` should take three arguments: the string `string`, the width of the final string `width`, and a fill character `fill`. However, the fill character can be enriched with a format string resulting in different padding strategies. If `fill` begins with `'<'` the string is padded on the left with the remaining fill string and if `fill` begins with `'>'` the string is padded on the right. Finally, if `fill` begins with `'^'` the string is padded on the left and the right, where the left padding is always greater or equal to the right padding. The `fill` string can contain more than a single char, of course.

Some examples to clarify the inner workings:

- `super_pad("test", 10)` returns "      test"
- `super_pad("test", 10, "x")` returns `"xxxxxxtest"`
- `super_pad("test", 10, "xO")` returns `"xOxOxOtest"`
- `super_pad("test", 10, "xO-")` returns `"xO-xO-test"`
- `super_pad("some other test", 10, "nope")` returns `"other test"`
- `super_pad("some other test", 10, "> ")` returns `"some other"`
- `super_pad("test", 7, ">nope")` returns `"testnop"`
- `super_pad("test", 7, "^more complex")` returns `"motestm"`
- `super_pad("test", 7, "")` returns `"test"`

The `super_pad` method always returns a string of length `width` if possible. We expect the `width` to be positive (including 0) and the fill could be also an empty string.

def super_pad(string, width, fill=" "):
    if fill.startswith('>'):
        return (string + width * fill[1:])[:width]
    elif fill.startswith('^'):
        pad = (width * fill[1:])[:max(0, width - len(string) + 1) // 2]
        return (pad + string + pad)[:width]
    else:
        if fill.startswith('<'): fill = fill[1:]
        return (width * fill)[:max(0, width - len(string))] + string[max(0, len(string) - width):]


Solve in Python:
In the world of Dota2, there are two parties: the Radiant and the Dire.

The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:

Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.
Announce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and make the decision about the change in the game.

Given a string representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party respectively. Then if there are n senators, the size of the given string will be n.

The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.

Suppose every senator is smart enough and will play the best strategy for his own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire.

Example 1:

Input: "RD"
Output: "Radiant"
Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights any more since his right has been banned. And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.

Example 2:

Input: "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in the round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in the round 1. And...

class Solution:
     def predictPartyVictory(self, senate):
         """
         :type senate: str
         :rtype: str
         """
         queue = collections.deque()
         people, bans = [0, 0], [0, 0]

         for person in senate:
             x = person == 'R'
             people[x] += 1
             queue.append(x)

         while all(people):
             x = queue.popleft()
             if bans[x]:
                 bans[x] -= 1
                 people[x] -= 1
             else:
                 bans[x^1] += 1
                 queue.append(x)

         return 'Radiant' if people[1] else 'Dire'


Solve in Python:
In the world of DragonBool there are fierce warriors called Soints. Also there are even fiercer warriors called Sofloats – the mortal enemies of Soints.

The power of each warrior is determined by the amount of chakra he possesses which is some positive integer. Warriors with zero level of chakra are dead warriors :) When the fight between Soint with power CI and Sofloat with power CF occurs the warrior with lower power will die and the winner will lose the amount of chakra that his enemy have possessed before the fight. So three cases are possible:

- CI > CF. Then Sofloat will die while the new power of Soint will be CI – CF.
- CI < CF. Then Soint will die while the new power of Sofloat will be CF – CI.
- CI = CF. In this special case both warriors die.

Each warrior (Soint or Sofloat) has his level of skills which is denoted by some positive integer. The fight between two warriors can occur only when these warriors are Soint and Sofloat of the same level. In particual, friendly fights are not allowed, i.e., a Soint cannot fight with another Soint and the same holds for Sofloats.

Lets follow the following convention to denote the warriors. A Soint of level L and power C will be denoted as (I, C, L), while Sofloat of level L and power C will be denoted as (F, C, L). Consider some examples. If A = (I, 50, 1) fights with B = (F, 20, 1), B dies and A becomes (I, 30, 1). On the other hand, (I, 50, 1) cannot fight with (F, 20, 2) as they have different levels.

There is a battle between Soints and Sofloats. There are N Soints and M Sofloats in all. The battle will consist of series of fights. As was mentioned above in each fight one Soint and one Sofloat of the same level take part and after the fight the warrior with lower power will die (or both will die if they have the same power). The battle proceeds as long as there exists at least one pair of warriors who can fight. The distribution of warriors by levels satisfies the following condition: for every Soint of level L there exists at least one Sofloat of the...

# fierce battles - codechef oct 2012 - drgnbool.py

t = int(input())

for testCase in range(t):
    n,m = list(map(int, input().split()))
    chakra = [0]*101
    for i in range(n):
        c,l = list(map(int, input().split()))
        chakra[l] += c
    for i in range(m):
        p,l = list(map(int, input().split()))
        chakra[l] -= p
    boost = 0
    for c in chakra:
        boost += max(0, -c)
    print(boost)


Solve in Python:
In the world of birding there are four-letter codes for the common names of birds. These codes are created by some simple rules:

* If the bird's name has only one word, the code takes the first four letters of that word.
* If the name is made up of two words, the code takes the first two letters of each word.
* If the name is made up of three words, the code is created by taking the first letter from the first two words and the first two letters from the third word.
* If the name is four words long, the code uses the first letter from all the words.

*(There are other ways that codes are created, but this Kata will only use the four rules listed above)*

Complete the function that takes an array of strings of common bird names from North America, and create the codes for those names based on the rules above. The function should return an array of the codes in the same order in which the input names were presented.

Additional considertations:

* The four-letter codes  in the returned array should be in UPPER CASE.
* If a common name has a hyphen/dash, it should be considered a space.

## Example

If the input array is: `["Black-Capped Chickadee", "Common Tern"]`

The return array would be: `["BCCH", "COTE"]`

import re

def f(name):
    words = re.findall("[\w']+", name)
    if len(words) == 1:
        return words[0][:4]
    elif len(words) == 2:
        return words[0][:2] + words[1][:2]
    elif len(words) == 3:
        return words[0][:1] + words[1][:1] + words[2][:2]
    return ''.join(word[0] for word in words)

def bird_code(arr):
    return [f(name).upper() for name in arr]


Solve in Python:
In the year 4242, the language Haskell has evolved so much that it has become an AI. It can solve very challenging problems, in very little time. Humanity is worried that Haskell will take over the world. All hopes remain tied to the Competitive Programming community as they are the expert in shaving milliseconds off code runtime. Haskell creators have found one particular task that if solved faster than Haskell itself, can be used to hack into Haskell's codebase and thus defeat it. The exact details of the task are as follows,

" Calculate the sum, S(N, K) = , for Q queries. Here Fi is ith Fibonacci number defined as: Fi = i if i = 0 or 1 and Fi = Fi-1 + Fi-2 if i >= 2. "

You being a member of the Competitive Programming community are encouraged to make a submission to this task.

-----Input-----

The first line contains a single integer Q, the number of queries.

Each of the next Q lines contain two integers each, Ni and Ki.

-----Output-----

Output Q lines with one integer each. The ith line should contain the value S(Ni, Ki).

-----Constraints-----
- 1 <= Q <= 5*104
- 1 <= N <= 1018
- 1 <= K <= 1018

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

mod=10**9+7
def fibonacci(n):
 if n < 0:
  raise ValueError("Negative arguments not implemented")
 return (_fib(n)[0]%mod + mod)%mod;
def _fib(n):
 if n == 0:
  return (0, 1)
 else:
  a, b = _fib(n // 2)
  c = (a * (b * 2 - a))%mod
  d = (a * a + b * b)%mod
  if n % 2 == 0:
   return (c, d)
  else:
   return (d, c + d)
def inv(n):
 return pow(n,mod-2,mod)
def brute(n,k):
 ret = 0
 for i in range(0,n+1):
  ret+=fibonacci(i)*pow(k,i,mod)
 return ret%mod
def ans(n,k):
 k%=mod
 a = pow(k,n+1,mod)
 b=(a*k)%mod
 x = a*(fibonacci(n+1))+b*fibonacci(n)-k
 y = inv((k*k+k-1)%mod)
 return ((x*y)%mod+mod)%mod
for t in range(0,eval(input())):
 n,k = list(map(int,input().split()))
 print(ans(n,k))


Solve in Python:
In these quarantine days, Chef and Chefina are getting bored. So, Chef came up with a game for her. He gets a pack of cards with numbers written on them. Chef then asks her to remove cards from the pack in the following manner: Chefina can choose any 3 cards at a time, having unique values, and remove the smallest and largest of them, and put back the middle one. For example, say Chefina chooses 3 cards that have numbers $x$, $y$, $z$ on them, such that $x <= y <= z$. Then she can throw away cards with number $x$ and $z$, but has to put the card with number $y$ on it back into the pack. Chefina can repeat this process any number of times. As soon as the pack contains cards with unique numbers, the game ends. If Chefina can determine the count of cards that will remain in the end, and tell it to Chef beforehand, she wins the game. Chefina asks for your help to win this game. Given the number written on the cards, help her find the count of cards in the pack when she wins.
$Note:$ You need to maximize the array length or the number of unique elements

-----Input:-----
- The first line of the input consists of a single integer $T$, denoting the number of test cases. Description of $T$ test cases follow.
- The first line of each test case consists of a single integer $N$, denoting the number of cards in the pack
- The next line consists of $N$ space separated numbers $A1$, $A2$ … $An$. For each valid $i (1 <= i <= N)$, the $i$-th card has the number $Ai$ written on it.

-----Output:-----
- For each test case, print the count of the cards that remain in the end.

-----Constraints-----
- $1 \leq T \leq 500$
- $1 \leq N \leq 10^6$
- $1 \leq Ai \leq N$

-----Subtasks-----
- 30 points : $1 \leq T \leq 20$; $ 1 \leq N \leq 5*10^5$
- 70 points : Original constraints

-----Sample Input:-----
2
5
1 2 2 3 5
9
1 2 2 3 3 5 8 8 9

-----Sample Output:-----
3
5

-----EXPLANATION:-----
Test case 1:
Chefina chooses the cards with number: 2, 3, 5, throws away 2 & 5, and puts back 3. So, the pack now contains cards with numbers: 1,...

def ans(n,dic):
 count=0
 remain=0
 for i in dic:
  if dic[i]%2==1:
   count+=1
  else:
   remain+=1
 if remain%2==1:
  count+=remain-1
 else:
  count+=remain
 return count
t=int(input())
for w in range(t):
 n=int(input())
 arr=[int(x) for x in input().split()]
 dic={}
 for i in arr:
  try:
   dic[i]+=1
  except:
   dic[i]=1
 print(ans(n,dic))


Solve in Python:
In this Kata we are passing a number (n) into a function.

Your code will determine if the number passed is even (or not).

The function needs to return either a true or false.

Numbers may be positive or negative, integers or floats.

Floats are considered UNeven for this kata.

def is_even(n):
    output = False
    if n % 2 == 0:
        output = True
    return output


Solve in Python:
In this Kata we focus on finding a sum S(n) which is the total number of divisors taken for all natural numbers less or equal to n. More formally, we investigate the sum of n components denoted by d(1) + d(2) + ... + d(n) in which for any i starting from 1 up to n the value of d(i) tells us how many distinct numbers divide i without a remainder.

Your solution should work for possibly large values of n without a timeout.
Assume n to be greater than zero and not greater than 999 999 999 999 999.
Brute force approaches will not be feasible options in such cases. It is fairly simple to conclude that for every n>1 there holds a recurrence S(n) = S(n-1) + d(n) with initial case S(1) = 1.

For example:
S(1) = 1
S(2) = 3
S(3) = 5
S(4) = 8
S(5) = 10

But is the fact useful anyway? If you find it is rather not, maybe this will help:

Try to convince yourself that for any natural k, the number S(k) is the same as the number of pairs (m,n) that solve the inequality mn <= k in natural numbers.
Once it becomes clear, we can think of a partition of all the solutions into classes just by saying that a pair (m,n) belongs to the class indexed by n.
The question now arises if it is possible to count solutions of n-th class. If f(n) stands for the number of solutions that belong to n-th class, it means that S(k) = f(1) + f(2) + f(3) + ...

The reasoning presented above leads us to some kind of a formula for S(k), however not necessarily the most efficient one. Can you imagine that all the solutions to inequality mn <= k can be split using sqrt(k) as pivotal item?

def count_divisors(n):
    rt = int(n ** .5)
    su = 0

    for k in range(1, rt + 1): su += n // k

    return 2 * su - rt * rt


Solve in Python:
In this Kata you are a builder and you are assigned a job of building a wall with a specific size (God knows why...).

Create a function called `build_a_wall` (or `buildAWall` in JavaScript) that takes `x` and `y` as integer arguments (which represent the number of rows of bricks for the wall and the number of bricks in each row respectively) and outputs the wall as a string with the following symbols:

`■■` => One full brick (2 of `■`)

`■` => Half a brick

`|` => Mortar (between bricks on same row)

There has to be a `|` between every two bricks on the same row. For more stability each row's bricks cannot be aligned vertically with the bricks of the row above it or below it meaning at every 2 rows you will have to make the furthest brick on both sides of the row at the size of half a brick (`■`) while the first row from the bottom will only consist of full bricks. Starting from the top, every new row is to be represented with `\n` except from the bottom row. See the examples for a better understanding.

If one or both of the arguments aren't valid (less than 1, isn't integer, isn't given...etc) return `None` in Python.

If the number of bricks required to build the wall is greater than 10000 return `"Naah, too much...here's my resignation."`

Examples, based on Python:
```
build_a_wall(5,5) => '■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■'

build_a_wall(10,7) => '■|■■|■■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■|■■|■■'

build_a_wall("eight",[3]) => None  }
                                   }> Invalid input
build_a_wall(12,-4) => None        }

build_a_wall(123,987) => "Naah, too much...here's my resignation."
123 * 987 = 121401 > 10000
```

def generateBricks(isCut, y):
    return "{0}|{1}|{0}".format("■" * (1+isCut), '|'.join("■■" for _ in range(y-1-isCut)))

def build_a_wall(*args):
    if len(args) != 2 or any(type(z) != int or z <= 0 for z in args):
        return None

    x,y = args
    return ("Naah, too much...here\'s my resignation." if x*y > 10000
            else '\n'.join( generateBricks((x-nr)%2, y) for nr in range(x) ))


Solve in Python:
In this Kata you are a game developer and have programmed the #1 MMORPG(Massively Multiplayer Online Role Playing Game) worldwide!!! Many suggestions came across you to make the game better, one of which you are interested in and will start working on at once.

Players in the game have levels from 1 to 170, XP(short for experience) is required to increase the player's level and is obtained by doing all sorts of things in the game, a new player starts at level 1 with 0 XP. You want to add a feature that would enable the player to input a target level and the output would be how much XP the player must obtain in order for him/her to reach the target level...simple huh.

Create a function called ```xp_to_target_lvl``` that takes 2 arguments(```current_xp``` and ```target_lvl```, both as integer) and returns the remaining XP for the player to reach the ```target_lvl``` formatted as a rounded down integer.

Leveling up from level 1 to level 2 requires 314 XP, at first each level up requires 25% XP more than the previous level up, every 10 levels the percentage increase reduces by 1. See the examples for a better understanding.

Keep in mind that when players reach level 170 they stop leveling up but they continue gaining experience.

If one or both of the arguments are invalid(not given,  not in correct format, not in range...etc) return "Input is invalid.".

If the player has already reached the ```target_lvl``` return ```"You have already reached level target_lvl."```.

Examples:
```
xp_to_target_lvl(0,5) => XP from lvl1 to lvl2 = 314
                         XP from lvl2 to lvl3 = 314 + (314*0.25) = 392
                         XP from lvl3 to lvl4 = 392 + (392*0.25) = 490
                         XP from lvl4 to lvl5 = 490 + (490*0.25) = 612
                         XP from lvl1 to target_lvl = 314 + 392 + 490 + 612 = 1808
                         XP from current_xp to target_lvl = 1808 - 0 = 1808

xp_to_target_lvl(12345,17) => XP from lvl1 to lvl2 = 314
                               XP...

def xp_to_target_lvl(*args):
    if len(args) < 2:
        return 'Input is invalid.'

    current_xp, target_lvl = args

    if not isinstance(target_lvl, int):
        return 'Input is invalid.'

    if not (0 < target_lvl < 171):
        return 'Input is invalid.'

    if current_xp < 0:
        return 'Input is invalid.'

    level = 1
    xp = 314
    xp_bump = 25

    sum_ = 0
    while level < target_lvl:
        sum_ += xp
        level += 1
        xp_bump_reduction = level // 10
        xp += int(xp * (xp_bump - xp_bump_reduction) / 100)

    diff = sum_ - current_xp
    if diff <= 0:
        return 'You have already reached level {}.'.format(target_lvl)
    else:
        return diff


Solve in Python:
In this Kata you are expected to find the coefficients of quadratic equation of the given two roots (`x1` and `x2`).

Equation will be the form of ```ax^2 + bx + c = 0```

Return type is a Vector (tuple in Rust, Array in Ruby) containing coefficients of the equations in the order `(a, b, c)`.

Since there are infinitely many solutions to this problem, we fix `a = 1`.

Remember, the roots can be written like `(x-x1) * (x-x2) = 0`

### Example

    quadratic(1,2) = (1, -3, 2)

This means `(x-1) * (x-2) = 0`; when we do the multiplication this becomes `x^2 - 3x + 2 = 0`

### Example 2

    quadratic(0,1) = (1, -1, 0)

This means `(x-0) * (x-1) = 0`; when we do the multiplication this becomes `x^2 - x + 0 = 0`

### Notes

* Inputs will be integers.
* When `x1 == x2`, this means the root has the multiplicity of two


Solve in Python:
In this Kata you are to implement a function that parses a string which is composed from tokens of the form 'n1-n2,n3,n4-n5:n6' where 'nX' is a positive integer. Each token represent a different range:

'n1-n2' represents the range n1 to n2 (inclusive in both ends).
'n3' represents the single integer n3.
'n4-n5:n6' represents the range n4 to n5 (inclusive in both ends) but only includes every other n6 integer.

Notes:
1. The input string doesn't not have to include all the token types.
2. All integers are assumed to be positive.
3. Tokens may be separated by `','`, `', '` or ` , `.

Some examples:

'1-10,14, 20-25:2' -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 20, 22, 24]

'5-10' -> [5, 6, 7, 8, 9, 10]

'2' -> [2]

The output should be a list of integers.

def range_parser(string):
    res = []
    for range_ in string.split(','):
        first_last, _, step = range_.partition(':')
        first, _, last = first_last.partition('-')
        res += range(int(first), int(last or first) + 1, int(step or 1))
    return res


Solve in Python:
In this Kata you must convert integers numbers from and to a negative-base binary system.

Negative-base systems can accommodate all the same numbers as standard place-value systems, but both positive and negative numbers are represented without the use of a minus sign (or, in computer representation, a sign bit); this advantage is countered by an increased complexity of arithmetic operations.

To help understand, the first eight digits (in decimal) of the Base(-2) system is:

`[1, -2, 4, -8, 16, -32, 64, -128]`

Example conversions:

`Decimal, negabinary`
```
6,   '11010'
-6,  '1110'
4,   '100'
18,  '10110'
-11, '110101'
```

def int_to_negabinary(n):
    def do(n1):
        li = []
        while n1 != 0:
            li.append(str(abs(n1 % (-2)))) ; n1 //= -2
        return li[::-1]
    return "".join([do(abs(n)),do(-n)][n>0]) or '0'

negabinary_to_int=lambda n:sum([int(j)*((-2)**i)for i,j in enumerate(n[::-1])])


Solve in Python:
In this Kata you need to write the method SharedBits that returns true if 2 integers share at least two '1' bits. For simplicity assume that all numbers are positive

For example
int seven = 7;    //0111
int ten = 10;     //1010
int fifteen = 15; //1111
SharedBits(seven, ten);     //false
SharedBits(seven, fifteen); //true
SharedBits(ten, fifteen);   //true

- seven and ten share only a single '1' (at index 3)
- seven and fifteen share 3 bits (at indexes 1, 2, and 3)
- ten and fifteen  share 2 bits (at indexes 0 and 2)

Hint: you can do this with just string manipulation, but binary operators will make your life much easier.

shared_bits = lambda a, b: sum(f"{a:16b}"[i] == f"{b:16b}"[i] == "1" for i in range(16)) > 1


Solve in Python:
In this Kata your task will be to return the count of pairs that have consecutive numbers as follows:
```Haskell
pairs([1,2,5,8,-4,-3,7,6,5]) = 3
The pairs are selected as follows [(1,2),(5,8),(-4,-3),(7,6),5]
--the first pair is (1,2) and the numbers in the pair are consecutive; Count = 1
--the second pair is (5,8) and are not consecutive
--the third pair is (-4,-3), consecutive. Count = 2
--the fourth pair is (7,6), also consecutive. Count = 3.
--the last digit has no pair, so we ignore.
```

More examples in the test cases.

Good luck!

Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)

def pairs(ar):
    return sum(1 for n in range(0, len(ar)-1, 2) if abs(ar[n] - ar[n+1]) == 1)


Solve in Python:
In this Kata, two players, Alice and Bob, are playing a palindrome game. Alice starts with `string1`, Bob starts with `string2`, and the board starts out as an empty string. Alice and Bob take turns; during a turn, a player selects a letter from his or her string, removes it from the string, and appends it to the board; if the board becomes a palindrome (of length >= 2), the player wins. Alice makes the first move. Since Bob has the disadvantage of playing second, then he wins automatically if letters run out or the board is never a palindrome. Note also that each player can see the other player's letters.

The problem will be presented as `solve(string1,string2)`. Return 1 if Alice wins and 2 it Bob wins.

For example:
```Haskell
solve("abc","baxy") = 2 -- There is no way for Alice to win. If she starts with 'a', Bob wins by playing 'a'. The same case with 'b'. If Alice starts with 'c', Bob still wins because a palindrome is not possible. Return 2.
solve("eyfjy","ooigvo") = 1 -- Alice plays 'y' and whatever Bob plays, Alice wins by playing another 'y'. Return 1.
solve("abc","xyz") = 2 -- No palindrome is possible, so Bob wins; return 2
solve("gzyqsczkctutjves","hpaqrfwkdntfwnvgs") = 1 -- If Alice plays 'g', Bob wins by playing 'g'. Alice must be clever. She starts with 'z'. She knows that since she has two 'z', the win is guaranteed. Note that she also has two 's'. But she cannot play that. Can you see why?
solve("rmevmtw","uavtyft") = 1 -- Alice wins by playing 'm'. Can you see why?
```
Palindrome lengths should be at least `2` characters. More examples in the test cases.

Good luck!

def solve(str1,str2):
    a=set(str1)
    return 1 if any(str1.count(i)>1 and i not in str2 for i in a) else 2


Solve in Python:
In this Kata, we are going to determine if the count of each of the characters in a string can be equal if we remove a single character from that string.

For example:
```
solve('abba') = false -- if we remove any character, the count of each character will not be equal.
solve('abbba') = true -- if we remove one b, the count of each character becomes 2.
solve('aaaa') = true -- if we remove one character, the remaining characters have same count.
solve('wwwf') = true -- if we remove f, the remaining letters have same count.
```
More examples in the test cases. Empty string is not tested.

Good luck!

def solve(s):
    a = [s.replace(s[y], '', 1) for y,x in enumerate(s)]
    return any(len(sorted(set([x.count(c) for c in x]))) == 1 for x in a)


Solve in Python:
In this Kata, we are going to reverse a string while maintaining the spaces (if any) in their original place.

For example:
```
solve("our code") = "edo cruo"
-- Normal reversal without spaces is "edocruo".
-- However, there is a space at index 3, so the string becomes "edo cruo"

solve("your code rocks") = "skco redo cruoy".
solve("codewars") = "srawedoc"
```
More examples in the test cases. All input will be lower case letters and in some cases spaces.

Good luck!

Please also try:

[Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)

[Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)

def solve(s):
    spaces = [i for i, c in enumerate(s) if c == " "]
    string = list(s.replace(" ", "")[::-1])
    for space in spaces:
        string.insert(space, " ")
    return "".join(string)


Solve in Python:
In this Kata, we are going to see how a Hash (or Map or dict) can be used to keep track of characters in a string.

Consider two strings `"aabcdefg"` and `"fbd"`. How many characters do we have to remove from the first string to get the second string?  Although not the only way to solve this, we could create a Hash of counts for each string and see which character counts are different. That should get us close to the answer. I will leave the rest to you.

For this example, `solve("aabcdefg","fbd") = 5`. Also, `solve("xyz","yxxz") = 0`, because we cannot get second string from the first since the second string is longer.

More examples in the test cases.

Good luck!

from collections import Counter

def solve(a,b):
    aa=Counter(a)
    bb=Counter(b)

    for k,v in list(bb.items()):
        diff = aa[k]-v
        aa[k]-=v
        if diff<0: return 0

    return sum(aa.values())


Solve in Python:
In this Kata, we define an arithmetic progression as a series of integers in which the differences between adjacent numbers are the same. You will be given an array of ints of `length > 2` and your task will be to convert it into an arithmetic progression by the following rule:
```Haskell
For each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1
or it can be left unchanged.
```
Return the minimum number of changes needed to convert the array to an arithmetic progression. If not possible, return `-1`.
```Haskell
For example:
solve([1,1,3,5,6,5]) == 4 because [1,1,3,5,6,5] can be changed to [1,2,3,4,5,6] by making 4 changes.
solve([2,1,2]) == 1 because it can be changed to [2,2,2]
solve([1,2,3]) == 0  because it is already a progression, and no changes are needed.
solve([1,1,10) == -1 because it's impossible.
solve([5,6,5,3,1,1]) == 4. It becomes [6,5,4,3,2,1]
```

More examples in the test cases. Good luck!

def solve(a):
    r = []
    for i in range(-1, 2):
        for j in range(-1, 2):
            curr_diff = a[-1]-a[0]+j-i
            if curr_diff%(len(a)-1) == 0:
                curr_a = [a[0]+i] + a[1:-1] + [a[-1]+j]
                k = curr_diff//(len(a)-1)
                t = [abs(curr_a[0]+i*k-a[i]) for i in range(len(a))]
                if max(t) <= 1: r.append(sum(t))

    return min(r) if r else -1


Solve in Python:
In this Kata, we will calculate the **minumum positive number that is not a possible sum** from a list of positive integers.

```
solve([1,2,8,7]) = 4 => we can get 1, 2, 3 (from 1+2), but we cannot get 4. 4 is the minimum number not possible from the list.
solve([4,1,2,3,12]) = 11. We can get 1, 2, 3, 4, 4+1=5, 4+2=6,4+3=7,4+3+1=8,4+3+2=9,4+3+2+1=10. But not 11.
solve([2,3,2,3,4,2,12,3]) = 1. We cannot get 1.
```
More examples in test cases.

Good luck!

solve=s=lambda a,x=1:a and s(a,x|x<<a.pop())or len(bin(~x&x+1))-3


Solve in Python:
In this Kata, we will check if a string contains consecutive letters as they appear in the English alphabet and if each letter occurs only once.

```Haskell
Rules are: (1) the letters are adjacent in the English alphabet, and (2) each letter occurs only once.

For example:
solve("abc") = True, because it contains a,b,c
solve("abd") = False, because a, b, d are not consecutive/adjacent in the alphabet, and c is missing.
solve("dabc") = True, because it contains a, b, c, d
solve("abbc") = False, because b does not occur once.
solve("v") = True
```
All inputs will be lowercase letters.

More examples in test cases. Good luck!

def solve(s):
    return "".join(sorted(s)) in "abcdefghijklmnopqrstuvwxyz"


Solve in Python:
In this Kata, you will be given a ```number```, two indexes (```index1``` and ```index2```) and a ```digit``` to look for. Your task will be to check if the ```digit``` exists in the ```number```, within the ```indexes``` given.

Be careful, the ```index2``` is not necessarily more than the ```index1```.

```
  index1 == 2 and index2 == 5 -> snippet from 2 to 5 positons;
  index1 == 5 and index2 == 2 -> snippet from 2 to 5 positons;

  number.length = 14;

  0 <= index1 < 14;

  0 <= index2 < 14;

  index2 is inclusive in search snippet;

  0 <= digit <= 9;

```

Find more details below:

```

  checkDigit(12345678912345, 1, 0, 1) -> true, 1 exists in 12

  checkDigit(12345678912345, 0, 1, 2) -> true, 2 exists in 12

  checkDigit(67845123654000, 4, 2, 5) -> true, 4 exists in 845

  checkDigit(66688445364856, 0, 0, 6) -> true, 6 exists in 6

  checkDigit(87996599994565, 2, 5, 1) -> false, 1 doesn't exist in 9965

```

def check_digit(s,t,p,q):
    if t<p:

        return True if str(q) in str(s)[t:p+1]  else False
    return True if str(q) in str(s)[p:t+1]  else False


Solve in Python:
In this Kata, you will be given a list of strings and your task will be to find the strings that have the same characters and return the sum of their positions as follows:

```Haskell
solve(["abc","abbc", "ab", "xyz", "xy", "zzyx"]) = [1,8]
-- we see that the elements at indices 0 and 1 have the same characters, as do those at indices 3 and 5.
-- we therefore return [1,8] because [0+1,3+5] = [1,8]. This result is sorted.
-- ignore those that don't have at least one matching partner, such as "ab" and "xy".

Another example...
solve(["wkskkkkkk","fokoo","wkskk","uizzzz","fokooff","wkskkkk","uizzzzzzz"]),[5,7,9]);
--The element at index 0 is similar to those at indices 2 and 5; so 0 + 2 + 5 = 7.
--The element at index 1 is similar to that at index 4; so 1 + 4 = 5.
--The element at index 3 is similar to that at index 6; so 3 + 6 = 9.
--The result must be sorted. We get [5,7,9].
```
More examples in the test cases.

Good luck!

def solve(arr):
  arr = [''.join(sorted(list(set(x)))) for x in arr]
  return sorted(sum(i for i, y in enumerate(arr) if x == y) for x in set(arr) if arr.count(x) >= 2)


Solve in Python:
In this Kata, you will be given a lower case string and your task will be to remove `k` characters from that string using the following rule:
```Python
- first remove all letter 'a', followed by letter 'b', then 'c', etc...
- remove the leftmost character first.
```

```Python
For example:
solve('abracadabra', 1) = 'bracadabra' # remove the leftmost 'a'.
solve('abracadabra', 2) = 'brcadabra'  # remove 2 'a' from the left.
solve('abracadabra', 6) = 'rcdbr'      # remove 5 'a', remove 1 'b'
solve('abracadabra', 8) = 'rdr'
solve('abracadabra',50) = ''
```

More examples in the test cases. Good luck!

Please also try:

[Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)

[Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)

from collections import Counter

def solve(letters, removes):
  letter_counts = Counter(letters)
  unique_sorted_letters = sorted(letter_counts.keys())

  for letter in unique_sorted_letters:
    amount_to_remove = letter_counts[letter] if removes >= letter_counts[letter] else removes
    letters = letters.replace(letter, '', amount_to_remove)
    removes -= amount_to_remove

  return letters


Solve in Python:
In this Kata, you will be given a mathematical string and your task will be to remove all braces as follows:

```Haskell
solve("x-(y+z)") = "x-y-z"
solve("x-(y-z)") = "x-y+z"
solve("u-(v-w-(x+y))-z") = "u-v+w+x+y-z"
solve("x-(-y-z)") = "x+y+z"
```

There are no spaces in the expression. Only two operators are given: `"+" or "-"`.

More examples in test cases.

Good luck!

def clean(string,to_clean=[("+-","-"),("-+","-"),("++","+"),("--","+")]):
    cleaned_string=string
    for i,j in to_clean:
        while i in cleaned_string:cleaned_string=cleaned_string.replace(i,j)
    print((cleaned_string,string))
    return clean(cleaned_string) if cleaned_string!=string else string
def solve(string):
    while "(" in string:
        counter=int()
        while counter<len(string):
            if string[counter]=="(":
                for x in range(counter+1,len(string)):
                    if string[x]==")":string,counter=string[:counter]+"".join(["+-"["-+".index(y)] if y in "-+" and string[counter-1]=="-" and string[counter+ind] not in "(-+" else y for ind,y in enumerate(string[counter+1:x])])+string[x+1:],counter-1
                    elif string[x]=="(":pass
                    else:continue
                    break
            counter+=1
            print(string)
    to_return=clean(string)
    return to_return[1:] if to_return[int()]=="+" else to_return


Solve in Python:
In this Kata, you will be given a multi-dimensional array containing `2 or more` sub-arrays of integers. Your task is to find the maximum product that can be formed by taking any one element from each sub-array.

```
Examples:
solve( [[1, 2],[3, 4]] ) = 8. The max product is given by 2 * 4
solve( [[10,-15],[-1,-3]] ) = 45, given by (-15) * (-3)
solve( [[1,-1],[2,3],[10,-100]] ) = 300, given by (-1) * 3 * (-100)
```

More examples in test cases. Good luck!

def solve(a):
    r_min = r_max = 1
    for x in a:
        cur = [n * m for n in [min(x), max(x)] for m in [r_min, r_max]]
        r_min = min(cur)
        r_max = max(cur)
    return r_max


Solve in Python:
In this Kata, you will be given a number `n` (`n > 0`) and your task will be to return the smallest square number `N` (`N > 0`) such that `n + N` is also a perfect square. If there is no answer, return `-1` (`nil` in Clojure, `Nothing` in Haskell, `None` in Rust).

```clojure
solve 13 = 36
; because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49

solve 3 = 1 ; 3 + 1 = 4, a perfect square
solve 12 = 4 ; 12 + 4 = 16, a perfect square
solve 9 = 16
solve 4 = nil
```

```csharp
solve(13) = 36
//because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49

solve(3) = 1 // 3 + 1 = 4, a perfect square
solve(12) = 4 // 12 + 4 = 16, a perfect square
solve(9) = 16
solve(4) = -1
```

```haskell
solve 13 = Just 36
-- because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49

solve 3 = Just 1 -- 3 + 1 = 4, a perfect square
solve 12 = Just 4 -- 12 + 4 = 16, a perfect square
solve 9 = Just 16
solve 4 = Nothing
```

```python
solve(13) = 36
# because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49

solve(3) = 1 # 3 + 1 = 4, a perfect square
solve(12) = 4 # 12 + 4 = 16, a perfect square
solve(9) = 16
solve(4) = -1
```

More examples in test cases.

Good luck!


Solve in Python:
In this Kata, you will be given a number and your task will be to rearrange the number so that it is divisible by `25`, but without leading zeros. Return the minimum number of digit moves that are needed to make this possible. If impossible, return `-1` ( `Nothing` in Haskell ).

For example:

More examples in test cases.

Good luck!

from functools import partial

def check(s, tail):
    i = s.find(tail[1])
    if i == -1: return float('inf')
    s = s[:i] + s[i+1:]

    j = s.find(tail[0])
    if j == -1: return float('inf')
    s = s[:j] + s[j+1:]

    if not s: return i+j
    if s == '0'*len(s): return float('inf')
    return i + j + next(i for i,c in enumerate(reversed(s)) if c != '0')

def solve(n):
    result = min(map(partial(check, str(n)[::-1]), ('00', '25', '50', '75')))
    return -1 if result == float('inf') else result


Solve in Python:
In this Kata, you will be given a number and your task will be to return the nearest prime number.

```Haskell
solve(4) = 3. The nearest primes are 3 and 5. If difference is equal, pick the lower one.
solve(125) = 127
```

We'll be testing for numbers up to `1E10`. `500` tests.

More examples in test cases.

Good luck!

If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)

def isPrime(n):
    if n < 2:
        return False
    for i in range(2,int(n**.5)+1):
        if not n%i:
            return False
    return True

def solve(n):
    if isPrime(n):
        return n
    add = 1
    rem = 1

    ans = None
    while True:
        if isPrime(n+add):
            ans = n+add
        if isPrime(n-rem):
            ans = n-rem
        if ans != None:
            return ans
        add += 1
        rem += 1


Solve in Python:
In this Kata, you will be given a number in form of a string and an integer `k` and your task is to insert `k` commas into the string and determine which of the partitions is the largest.

```
For example:
solve('1234',1) = 234 because ('1','234') or ('12','34') or ('123','4').
solve('1234',2) = 34 because ('1','2','34') or ('1','23','4') or ('12','3','4').
solve('1234',3) = 4
solve('2020',1) = 202
```

More examples in test cases. Good luck!

Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)

def solve(s, k):
    n = len(s) - k
    return max(int(s[i:i+n]) for i in range(0, k + 1))


Solve in Python:
In this Kata, you will be given a series of times at which an alarm goes off. Your task will be to determine the maximum time interval between alarms. Each alarm starts ringing at the beginning of the corresponding minute and rings for exactly one minute. The times in the array are not in chronological order. Ignore duplicate times, if any.

```Haskell
For example:
solve(["14:51"]) = "23:59". If the alarm goes off now, it will not go off for another 23 hours and 59 minutes.
solve(["23:00","04:22","18:05","06:24"]) == "11:40". The max interval that the alarm will not go off is 11 hours and 40 minutes.
```
In the second example, the alarm goes off `4` times in a day.

More examples in test cases. Good luck!

def solve(arr):
    k = sorted(int(x[:2])*60 + int(x[3:]) for x in arr)
    z = [(k[i] - k[i-1])%1440 for i in range(len(k))]
    return len(k) > 1 and '{:02}:{:02}'.format(*divmod(max(z)-1,60)) or "23:59"


Solve in Python:
In this Kata, you will be given a string and two indexes (`a` and `b`). Your task is to reverse the portion of that string between those two indices inclusive.

~~~if-not:fortran
```
solve("codewars",1,5) = "cawedors" -- elements at index 1 to 5 inclusive are "odewa". So we reverse them.
solve("cODEWArs", 1,5) = "cAWEDOrs" -- to help visualize.
```
~~~
~~~if:fortran
```
solve("codewars",2,6) = "cawedors" -- elements at indices 2 to 6 inclusive are "odewa". So we reverse them.
solve("cODEWArs", 2,6) = "cAWEDOrs" -- to help visualize.
```
~~~

Input will be lowercase and uppercase letters only.

The first index `a` will always be lower that than the string length; the second index `b` can be greater than the string length. More examples in the test cases. Good luck!

Please also try:

[Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)

[Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)

~~~if:fortran
*NOTE: You may assume that all input strings will* **not** *contain any (redundant) trailing whitespace.  In return, your returned string is* **not** *permitted to contain any (redundant) trailing whitespace.*
~~~

def solve(st,a,b):
    str = st[a:b+1]
    st = st.replace(st[a:b+1], str[::-1])
    return st


Solve in Python:
In this Kata, you will be given a string and your task is to determine if that string can be a palindrome if we rotate one or more characters to the left.

```Haskell
solve("4455") = true, because after 1 rotation, we get "5445" which is a palindrome
solve("zazcbaabc") = true, because after 3 rotations, we get "abczazcba", a palindrome
```

More examples in test cases. Input will be strings of lowercase letters or numbers only.

Good luck!

is_pal = lambda s: all(s[i] == s[len(s)-i-1] for i in range(len(s)//2))
solve  = lambda s: any(is_pal(s[i:]+s[:i]) for i in range(len(s)))


Solve in Python:
In this Kata, you will be given a string and your task is to return the most valuable character. The value of a character is the difference between the index of its last occurrence and the index of its first occurrence. Return the character that has the highest value. If there is a tie, return the alphabetically lowest character. `[For Golang return rune]`

All inputs will be lower case.

```
For example:
solve('a') = 'a'
solve('ab') = 'a'. Last occurrence is equal to first occurrence of each character. Return lexicographically lowest.
solve("axyzxyz") = 'x'
```

More examples in test cases. Good luck!


Solve in Python:
In this Kata, you will be given a string and your task will be to return a list of ints detailing the count of uppercase letters, lowercase, numbers and special characters, as follows.

```Haskell
Solve("*'&ABCDabcde12345") = [4,5,5,3].
--the order is: uppercase letters, lowercase, numbers and special characters.
```

More examples in the test cases.

Good luck!

def solve(s):
    res = [0, 0, 0, 0]
    for c in s:
        i = 0 if c.isupper() else 1 if c.islower() else 2 if c.isdigit() else 3
        res[i] += 1
    return res


Solve in Python:
In this Kata, you will be given a string and your task will be to return the length of the longest prefix that is also a suffix. A prefix is the start of a string while the suffix is the end of a string.  For instance, the prefixes of the string `"abcd"` are `["a","ab","abc"]`. The suffixes are `["bcd", "cd", "d"]`. You should not overlap the prefix and suffix.

```Haskell
for example:
solve("abcd") = 0, because no prefix == suffix.
solve("abcda") = 1, because the longest prefix which == suffix is "a".
solve("abcdabc") = 3. Longest prefix which == suffix is "abc".
solve("aaaa") = 2. Longest prefix which == suffix is "aa". You should not overlap the prefix and suffix
solve("aa") = 1. You should not overlap the prefix and suffix.
solve("a") = 0. You should not overlap the prefix and suffix.
```

All strings will be lowercase and string lengths are `1 <= length <= 500`

More examples in test cases. Good luck!

def solve(st):
    return max((i for i in range(1, len(st)//2+1) if st[:i] == st[-i:]), default=0)


Solve in Python:
In this Kata, you will be given a string of numbers in sequence and your task will be to return the missing number. If there is no number
missing or there is an error in the sequence, return `-1`.

For example:
```Haskell
missing("123567") = 4
missing("899091939495") = 92
missing("9899101102") = 100
missing("599600601602") = -1 -- no number missing
missing("8990919395") = -1 -- error in sequence. Both 92 and 94 missing.
```
The sequence will always be in ascending order.

More examples in the test cases.

Good luck!

def missing(s):
    for i in range(1, len(s) // 2 + 1):
        n, missing = int(s[:i]), None
        while i < len(s):
            n += 1
            j = len(str(n))
            if s.startswith(str(n)[:len(s) - i], i):
                i += j
            elif missing:
                missing = None  # 2 missing numbers
                break
            else: missing = n
        else:
            if not missing: return -1  # No missing number
        if missing: return missing  # 1 missing number
    return -1  # Error in the sequence


Solve in Python:
In this Kata, you will be given a string that has lowercase letters and numbers. Your task is to compare the number groupings and return the largest number. Numbers will not have leading zeros.

For example, `solve("gh12cdy695m1") = 695`, because this is the largest of all number groupings.

Good luck!

Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)

def solve(s):
    import re
    return max([int(i) for i in re.split('(\d+)',s) if i.isnumeric()])


Solve in Python:
In this Kata, you will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on:

* make as few changes as possible.
* if the string contains equal number of uppercase and lowercase letters, convert the string to lowercase.

For example:
```Haskell
solve("coDe") = "code". Lowercase characters > uppercase. Change only the "D" to lowercase.
solve("CODe") = "CODE". Uppercase characters > lowecase. Change only the "e" to uppercase.
solve("coDE") = "code". Upper == lowercase. Change all to lowercase.
```

More examples in test cases. Good luck!

Please also try:

[Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)

[Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)

def solve(s):
    bcount=0
    i =0
    acount =0
    while i < len(s):
        if s[i].isupper():
            acount+=1
            i+=1

        elif s[i].islower():
            bcount+=1
            i +=1

    if bcount >= acount:
        print(bcount)
        return s.lower()

    if acount > bcount:

        return s.upper()
    else:
        return s.lower()


Solve in Python:
In this Kata, you will be given a string with brackets and an index of an opening bracket and your task will be to return the index of the matching closing bracket.  Both the input and returned index are 0-based **except in Fortran where it is 1-based**. An opening brace will always have a closing brace. Return `-1` if there is no answer (in Haskell, return `Nothing`; in Fortran, return `0`; in Go, return an error)

### Examples

```python
solve("((1)23(45))(aB)", 0) = 10 -- the opening brace at index 0 matches the closing brace at index 10
solve("((1)23(45))(aB)", 1) = 3
solve("((1)23(45))(aB)", 2) = -1 -- there is no opening bracket at index 2, so return -1
solve("((1)23(45))(aB)", 6) = 9
solve("((1)23(45))(aB)", 11) = 14
solve("((>)|?(*'))(yZ)", 11) = 14
```

Input will consist of letters, numbers and special characters, but no spaces. The only brackets will be `(` and `)`.

More examples in the test cases.

Good luck!

~~~if:fortran
*NOTE: In Fortran, you may assume that the input string will not contain any leading/trailing whitespace.*
~~~

def solve(st, idx):
    if st[idx] != '(':
        return -1
    open = 1
    for i in range(idx+1, len(st)):
        if st[i] == '(':
            open += 1
        elif st[i] == ')':
            open -= 1
        if open == 0:
            return i


Solve in Python:
In this Kata, you will be given an array and your task will be to determine if an array is in ascending or descending order and if it is rotated or not.

Consider the array `[1,2,3,4,5,7,12]`. This array is sorted in `Ascending` order. If we rotate this array once to the left, we get `[12,1,2,3,4,5,7]` and twice-rotated we get `[7,12,1,2,3,4,5]`. These two rotated arrays are in `Rotated Ascending` order.

Similarly, the array `[9,6,5,3,1]` is in `Descending` order, but we can rotate it to get an array in `Rotated Descending` order: `[1,9,6,5,3]` or `[3,1,9,6,5]` etc.

Arrays will never be unsorted, except for those that are rotated as shown above. Arrays will always have an answer, as shown in the examples below.

More examples:
```Haskell
solve([1,2,3,4,5,7]) = "A" -- Ascending
solve([7,1,2,3,4,5]) = "RA" -- Rotated ascending
solve([4,5,6,1,2,3]) = "RA" -- Rotated ascending
solve([9,8,7,6]) = "D" -- Descending
solve([5,9,8,7,6]) = "RD" -- Rotated Descending
```
More examples in the test cases.

Good luck!

solve=lambda a:(lambda i:'R'*((a[-1]>a[0])-(a[-1]<a[0])==i)+'UDA'[i])(__import__('collections').Counter((x>y)-(x<y)for x,y in zip(a[-1:]+a,a)).most_common(1)[0][0])


Solve in Python:
In this Kata, you will be given an array of arrays and your task will be to return the number of unique arrays that can be formed by picking exactly one element from each subarray.

For example: `solve([[1,2],[4],[5,6]]) = 4`, because it results in only `4` possiblites. They are `[1,4,5],[1,4,6],[2,4,5],[2,4,6]`.

```if:r
In R, we will use a list data structure.
So the argument for `solve` is a list of numeric vectors.
~~~
solve(list(c(1, 2), 4, c(5, 6)))
[1] 4
~~~
```

Make sure that you don't count duplicates; for example `solve([[1,2],[4,4],[5,6,6]]) = 4`, since the extra outcomes are just duplicates.

See test cases for more examples.

Good luck!

If you like this Kata, please try:

[Sum of integer combinations](https://www.codewars.com/kata/59f3178e3640cef6d90000d5)

[Sum of array singles](https://www.codewars.com/kata/59f11118a5e129e591000134)

def solve(arr):
    res = 1
    for a in arr: res *= len(set(a))
    return res


Solve in Python:
In this Kata, you will be given an array of integers and your task is to return the number of arithmetic progressions of size `3` that are possible from that list. In each progression, the differences between the elements must be the same.

```
[1, 2, 3, 5, 7, 9] ==> 5
// [1, 2, 3], [1, 3, 5], [1, 5, 9], [3, 5, 7], and [5, 7, 9]
```

All inputs will be sorted. More examples in test cases.

Good luck!

def solve(arr):
    return sum(num + i in arr and num + 2 * i in arr for i in range(1, arr[-2] + 1)\
        for num in arr[:-2])


Solve in Python:
In this Kata, you will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer.

Examples:

`[1, -1, 2, -2, 3] => 3`

`3` has no matching negative appearance

`[-3, 1, 2, 3, -1, -4, -2] => -4`

`-4` has no matching positive appearance

`[1, -1, 2, -2, 3, 3] => 3`

(the only-positive or only-negative integer may appear more than once)

Good luck!

def solve(arr):
    positive = sorted([x for x in arr if x>=0])
    negative = sorted([x for x in arr if x<0], reverse=True)
    longer_index = len(positive) <= len(negative)
    longer = [positive, negative][longer_index]
    for i in [positive, negative][not longer_index]:
        longer.remove(-i)
    return longer[0]


Solve in Python:
In this Kata, you will be given an array of numbers and a number `n`, and your task will be to determine if `any` array elements, when summed (or taken individually), are divisible by `n`.

For example:

  * `solve([1,3,4,7,6],9) == true`, because `3 + 6` is divisible by `9`
  * `solve([1,2,3,4,5],10) == true` for similar reasons.
  * `solve([8,5,3,9],7) == true`, because `7` evenly divides `5 + 9`
  * but `solve([8,5,3],7) == false`.

All numbers in the array will be greater than `0`.

More examples in the test cases.

Good luck!

If you like this Kata, please try:

[Simple division](https://www.codewars.com/kata/59ec2d112332430ce9000005)

[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)

solve=lambda a,n:any(sum(c)%n<1for r in range(len(a))for c in __import__('itertools').combinations(a,r+1))


Solve in Python:
In this Kata, you will be given an array of numbers in which two numbers occur once and the rest occur only twice. Your task will be to return the sum of the numbers that occur only once.

For example, `repeats([4,5,7,5,4,8]) = 15` because only the numbers `7` and `8` occur once, and their sum is `15`.

More examples in the test cases.

```if:csharp
Documentation:
Kata.Repeats Method (List<Int32>)

Takes a list where all ints are repeated twice, except two ints, and returns the sum of the ints of a list where those ints only occur once.

Syntax

public
static
int Repeats(
List<int> source
    )

Parameters

source

Type: System.Collections.Generic.List<Int32>
The list to process.

Return Value

Type: System.Int32
  The sum of the elements of the list where those elements have no duplicates.

```

Good luck!

If you like this Kata, please try:

[Sum of prime-indexed elements](https://www.codewars.com/kata/59f38b033640ce9fc700015b)

[Sum of integer combinations](https://www.codewars.com/kata/59f3178e3640cef6d90000d5)

def repeats(arr):
    return sum(i for i in arr if arr.count(i) == 1)


Solve in Python:
In this Kata, you will be given an array of strings and your task is to remove all consecutive duplicate letters from each string in the array.

For example:

  * `dup(["abracadabra","allottee","assessee"]) = ["abracadabra","alote","asese"]`.

  * `dup(["kelless","keenness"]) = ["keles","kenes"]`.

Strings will be lowercase only, no spaces. See test cases for more examples.

~~~if:rust
For the sake of simplicity you can use the macro 'vec_of_string' to create a Vec with an array of string literals.
~~~

Good luck!

If you like this Kata, please try:

[Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075)

[Vowel consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)

from itertools import groupby

def dup(strings):
    return [''.join(c for c, _ in groupby(s)) for s in strings]


Solve in Python:
In this Kata, you will be given an array of unique elements, and your task is to rerrange the values so that the first max value is followed by the first minimum, followed by second max value then second min value, etc.

For example:
The first max is `15` and the first min is `7`. The second max is `12` and the second min is `10` and so on.

More examples in the test cases.

Good luck!

def solve(arr):
    rarr = sorted(arr, reverse=True)
    farr = rarr[::-1]
    return [item for sublist in zip(rarr, farr) for item in sublist][:len(rarr)]


Solve in Python:
In this Kata, you will be given an integer `n` and your task will be to return `the largest integer that is <= n and has the highest digit sum`.

For example:
```
solve(100) = 99. Digit Sum for 99 = 9 + 9 = 18. No other number <= 100 has a higher digit sum.
solve(10) = 9
solve(48) = 48. Note that 39 is also an option, but 48 is larger.
```

Input range is `0 < n < 1e11`

More examples in the test cases.

Good luck!

from typing import List, Union
def digit_sum(n: Union[List[int], int]) -> int:
    """
    Finds the digit sum of the digits in an integer or list of positional integers
    """
    if isinstance(n, list):
        return sum(n)
    return sum(int(ch) for ch in str(n))

def to_int(arr: List[int]) -> int:
    """
    Converts an array of positional integers into a single integer
    """
    return int(''.join(str(n) for n in arr))

def bump(arr, i):
    """
    Takes the digits of an array and increments the digit at index i and decrements the digit at
    index i + 1.
    E.g. bump([1, 2, 8, 4], 1) -> [1, 2+1, 8-1, 4] -> [1, 3, 7, 4]
    """
    return arr[:i] + [arr[i] + 1] + [arr[i + 1] - 1] + arr[i+2:]

def solve(n: int) -> int:
    """
    Find the largest number <= n with the maximum digit sum
    """
    s = str(n)
    # Decrement the first digit and convert all others to 9 as a baseline
    option = [int(s[0]) - 1] + [9] * (len(s) - 1)
    if digit_sum(option) > digit_sum(n):
        for i in range(len(option) - 1):
            # Keep bumping digit i in option while still a single digit and the int value <= n
            while True:
                if option[i] == 9:
                    break
                b = bump(option, i)
                if to_int(b) > n:
                    break
                option = b
        return to_int(option)
    return n


Solve in Python:
In this Kata, you will be given an integer array and your task is to return the sum of elements occupying prime-numbered indices.

~~~if-not:fortran
The first element of the array is at index `0`.
~~~

~~~if:fortran
The first element of an array is at index `1`.
~~~

Good luck!

If you like this Kata, try:

[Dominant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed). It takes this idea a step further.

[Consonant value](https://www.codewars.com/kata/59c633e7dcc4053512000073)

def sieve(n):
    sieve, primes = [0]*(n+1), set()
    for i in range(2, n+1):
        if not sieve[i]:
            primes.add(i)
            for j in range(i**2, n+1, i): sieve[j] = 1
    return primes

PRIMES = sieve(5000)

def total(arr):
    return sum(arr[p] for p in set(range(len(arr))) & PRIMES)


Solve in Python:
In this Kata, you will be given directions and your task will be to find your way back.
```Perl
solve(["Begin on Road A","Right on Road B","Right on Road C","Left on Road D"]) = ['Begin on Road D', 'Right on Road C', 'Left on Road B', 'Left on Road A']
solve(['Begin on Lua Pkwy', 'Right on Sixth Alley', 'Right on 1st Cr']) =  ['Begin on 1st Cr', 'Left on Sixth Alley', 'Left on Lua Pkwy']
```

More examples in test cases.

Good luck!

Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)

solve = lambda arr: list(reversed([{'Right': 'Left', 'Left': 'Right'}[arr[i + 1].split(' ')[0]] + ' ' + ' '.join(arr[i].split(' ')[1:]) if i < len(arr)-1 else 'Begin ' + ' '.join(arr[i].split(' ')[1:]) for i in range(len(arr))]))


Solve in Python:
In this Kata, you will be given two integers `n` and `k` and your task is to remove `k-digits` from `n` and return the lowest number possible, without changing the order of the digits in `n`. Return the result as a string.

Let's take an example of `solve(123056,4)`. We need to remove `4` digits from `123056` and return the lowest possible number. The best digits to remove are `(1,2,3,6)` so that the remaining digits are `'05'`. Therefore, `solve(123056,4) = '05'`.

Note also that the order of the numbers in `n` does not change: `solve(1284569,2) = '12456',` because we have removed `8` and `9`.

More examples in the test cases.

Good luck!

def solve(n, k):
    s = str(n)
    result = ''
    for _ in range(len(s)-k):
        i = min(range(k+1), key=s.__getitem__)
        result += s[i]
        k -= i
        s = s[i+1:]
    return result


Solve in Python:
In this Kata, you will be given two numbers, `a` and `b`, and your task is to determine if the first number `a` is divisible by `all` the prime factors of the second number `b`. For example: `solve(15,12) = False` because `15` is not divisible by all the prime factors of `12` (which include`2`).

See test cases for more examples.

Good luck!

If you like this Kata, please try:

[Sub-array division](https://www.codewars.com/kata/59eb64cba954273cd4000099)

[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)

def solve(a,b):
    k = 2
    while k <= int(b**0.5):
        while b%k == 0:
            b //= k
            if a%k != 0: return False
        k += 1
    return a%b == 0


Solve in Python:
In this Kata, you will be given two numbers, n and k and your task will be to return the k-digit array that sums to n and has the maximum possible GCD.

For example, given `n = 12, k = 3`, there are a number of possible `3-digit` arrays that sum to `12`, such as `[1,2,9], [2,3,7], [2,4,6], ...` and so on. Of all the possibilities, the one with the highest GCD is `[2,4,6]`. Therefore, `solve(12,3) = [2,4,6]`.

Note also that digits cannot be repeated within the sub-array, so `[1,1,10]` is not a possibility. Lastly, if there is no such array, return an empty array.

More examples in the test cases.

Good luck!

def solve(n,k):
    psum = (k * (k+1)) / 2
    if n >= psum:
        min_int = n // psum
        while min_int > 0:
            if n % min_int == 0:
                return populate(n,min_int,k)
            min_int -= 1
    return []

def populate(n,s,k):
    output = []
    m = n
    for i in range(1, k):
        output.append(i*s)
        m -= i*s
    output.append(m)
    return output


Solve in Python:
In this Kata, you will be given two positive integers `a` and `b` and your task will be to apply the following operations:

```
i) If a = 0 or b = 0, return [a,b]. Otherwise, go to step (ii);
ii) If a ≥ 2*b, set a = a - 2*b, and repeat step (i). Otherwise, go to step (iii);
iii) If b ≥ 2*a, set b = b - 2*a, and repeat step (i). Otherwise, return [a,b].
```

`a` and `b` will both be lower than 10E8.

More examples in tests cases. Good luck!

Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)

def solve(a,b):
    return ([a,b]           if not a or not b else
            solve(a%(2*b),b)  if a>=2*b else
            solve(a,b%(2*a))  if b>=2*a else
            [a,b])


Solve in Python:
In this Kata, you will be given two strings `a` and `b` and your task will be to return the characters that are not common in the two strings.

For example:
```Haskell
solve("xyab","xzca") = "ybzc"
--The first string has 'yb' which is not in the second string.
--The second string has 'zc' which is not in the first string.
```
Notice also that you return the characters from the first string concatenated with those from the second string.

More examples in the tests cases.

Good luck!

Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)

def solve(a,b):
    return "".join([c for c in a if not c in b]+[c for c in b if not c in a])


Solve in Python:
In this Kata, you will check if it is possible to convert a string to a palindrome by changing one character.

For instance:
```Haskell
solve ("abbx") = True, because we can convert 'x' to 'a' and get a palindrome.
solve ("abba") = False, because we cannot get a palindrome by changing any character.
solve ("abcba") = True. We can change the middle character.
solve ("aa") = False
solve ("ab") = True
```

Good luck!

Please also try [Single Character Palindromes](https://www.codewars.com/kata/5a2c22271f7f709eaa0005d3)

def solve(s):
    r = sum(s[i] != s[-1-i] for i in range(len(s)//2))
    return r == 1 or (r == 0 and len(s) % 2)


Solve in Python:
In this Kata, you will count the number of times the first string occurs in the second.

```Haskell
solve("zaz","zazapulz") = 4 because they are ZAZapulz, ZAzapulZ, ZazApulZ, zaZApulZ
```

More examples in test cases.

Good luck!

Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)

from functools import lru_cache

def solve(a, b):
    l_a, l_b, rec = len(a), len(b), lru_cache(maxsize=None)(lambda x,y: (x == l_a) or sum(rec(x+1, i+1) for i in range(y, l_b) if b[i] == a[x]))
    return rec(0, 0)


Solve in Python:
In this Kata, you will create a function that converts a string with letters and numbers to the inverse of that string (with regards to Alpha and Numeric characters). So, e.g. the letter `a` will become `1` and number `1` will become `a`; `z` will become `26` and `26` will become `z`.

Example: `"a25bz"` would become `"1y226"`

Numbers representing letters (`n <= 26`) will always be separated by letters, for all test cases:

* `"a26b"` may be tested, but not `"a262b"`
* `"cjw9k"` may be tested, but not `"cjw99k"`

A list named `alphabet` is preloaded for you: `['a', 'b', 'c', ...]`

A dictionary of letters and their number equivalent is also preloaded for you called `alphabetnums = {'a': '1', 'b': '2', 'c': '3', ...}`

import re
from string import ascii_lowercase

def repl(m):
    x = m.group()
    if x.isdigit():
        return ascii_lowercase[int(x)-1]
    else:
        return str(ascii_lowercase.find(x) + 1)

def AlphaNum_NumAlpha(string):
    return re.sub(r'[a-z]|\d+', repl, string)


Solve in Python:
In this Kata, you will implement a function `count` that takes an integer and returns the number of digits in `factorial(n)`.

For example, `count(5) = 3`, because `5! = 120`, and `120` has `3` digits.

More examples in the test cases.

Brute force is not possible. A little research will go a long way, as this is a well known series.

Good luck!

Please also try:

from math import ceil, log, pi, e
count = lambda n: int(ceil(log(2*pi*n, 10)/2+n*log(n/e, 10)))


Solve in Python:
In this Kata, you will implement the [Luhn Algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm), which is used to help validate credit card numbers.

Given a positive integer of up to 16 digits, return ```true``` if it is a valid credit card number, and ```false``` if it is not.

Here is the algorithm:

* Double every other digit, scanning **from right to left**, starting from the second digit (from the right).

  Another way to think about it is: if there are an **even** number of digits, double every other digit starting with the **first**; if there are an **odd** number of digits, double every other digit starting with the **second**:

  ```
  1714 ==> [1*, 7, 1*, 4] ==> [2, 7, 2, 4]

  12345 ==> [1, 2*, 3, 4*, 5] ==> [1, 4, 3, 8, 5]

  891 ==> [8, 9*, 1] ==> [8, 18, 1]
  ```

*  If a resulting number is greater than `9`, replace it with the sum of its own digits (which is the same as subtracting `9` from it):

  ```
  [8, 18*, 1] ==> [8, (1+8), 1] ==> [8, 9, 1]

  or:

  [8, 18*, 1] ==> [8, (18-9), 1] ==> [8, 9, 1]
  ```

* Sum all of the final digits:

  ```
  [8, 9, 1] ==> 8 + 9 + 1 = 18
  ```

* Finally, take that sum and divide it by `10`.  If the remainder equals zero, the original credit card number is valid.
    ```
    18 (modulus) 10 ==> 8 , which is not equal to 0, so this is not a valid credit card number
    ```

```if:fsharp,csharp
For F# and C# users:

The input will be a string of spaces and digits `0..9`

```

def validate(n):
    digits = [int(x) for x in str(n)]
    even = [x*2 if x*2 <= 9 else x*2 - 9 for x in digits[-2::-2]]
    odd  = [x for x in digits[-1::-2]]
    return (sum(even + odd)%10) == 0


Solve in Python:
In this Kata, you will remove the left-most duplicates from a list of integers and return the result.

```python
# Remove the 3's at indices 0 and 3
# followed by removing a 4 at index 1
solve([3, 4, 4, 3, 6, 3]) # => [4, 6, 3]
```

More examples can be found in the test cases.

Good luck!

def solve(arr):
    ls = []
    for x in arr[::-1]:
        if ls.count(x) == 0:
            ls.append(x)
    return [i for i in ls[::-1]]


Solve in Python:
In this Kata, you will sort elements in an array by decreasing frequency of elements. If two elements have the same frequency, sort them by increasing value.

More examples in test cases.

Good luck!

Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)

def solve(array):
    return sorted(sorted(array), key=array.count, reverse=True)


Solve in Python:
In this Kata, you will write a function `doubles` that will remove double string characters that are adjacent to each other.

For example:

`doubles('abbcccdddda') = 'aca'`, because, from left to right:
```Haskell
a) There is only one 'a' on the left hand side, so it stays.
b) The 2 b's disappear because we are removing double characters that are adjacent.
c) Of the 3 c's, we remove two. We are only removing doubles.
d) The 4 d's all disappear, because we first remove the first double, and again we remove the second double.
e) There is only one 'a' at the end, so it stays.
```

Two more examples: `doubles('abbbzz') = 'ab'` and `doubles('abba') = ""`. In the second example, when we remove the b's in `'abba'`, the double `a` that results is then removed.

The strings will contain lowercase letters only. More examples in the test cases.

Good luck!

def doubles(s):
    for x in range(0,3):
        for a in "abcdefghijklmnopqrstuvwqxyz": s=s.replace(2*a,"")
    return s


Solve in Python:
In this Kata, you're to complete the function `sum_square_even_root_odd`.

You will be given a list of numbers, `nums`, as the only argument to the function. Take each number in the list and *square* it if it is even, or *square root* the number if it is odd. Take this new list and find the *sum*, rounding to two decimal places.

The list will never be empty and will only contain values that are greater than or equal to zero.

Good luck!

def sum_square_even_root_odd(nums):
    return round(sum(i**[2,0.5][i&1] for i in nums),2)


Solve in Python:
In this exercise, a string is passed to a method and a new string has to be returned with the first character of each word in the string.

For example:

```
"This Is A Test" ==> "TIAT"
```

from operator import itemgetter

def make_string(s):
    return ''.join(map(itemgetter(0), s.split()))


Solve in Python:
In this exercise, you will have to create a function named tiyFizzBuzz. This function will take on a string parameter and will return that string with some characters replaced, depending on the value:

- If a letter is a upper case consonants, replace that character with "Iron".
- If a letter is a lower case consonants or a non-alpha character, do nothing to that character
- If a letter is a upper case vowel, replace that character with "Iron Yard".
- If a letter is a lower case vowel, replace that character with "Yard".

Ready?

tiy_fizz_buzz=lambda x:''.join(('Iron'*e.isupper()+' '+'Yard'*(e.lower() in 'aiueo')).strip() or e for e in x)


Solve in Python:
In this kata the function returns an array/list like the one passed to it but with its nth element removed (with `0 <= n <= array/list.length - 1`). The function is already written for you and the basic tests pass, but random tests fail. Your task is to figure out why and fix it.

Good luck!

~~~if:javascript
Some good reading: [MDN Docs about arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
~~~
~~~if:python
Some good reading: [Python Docs about lists](https://docs.python.org/3/tutorial/datastructures.html)
~~~
~~~if:coffeescript
Some good reading: [CoffeeScript docs](http://coffeescript.org/)
~~~

def remove_nth_element(lst, n):
    lst_copy = lst[:] # That's a shallow copy
    del lst_copy[n]
    return lst_copy


Solve in Python:
In this kata the function returns an array/list of numbers without its last element. The function is already written for you and the basic tests pass, but random tests fail. Your task is to figure out why and fix it.

Good luck!

Hint: watch out for side effects.

~~~if:javascript
Some good reading: [MDN Docs about arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
~~~
~~~if:python
Some good reading: [Python Lists](http://www.compciv.org/guides/python/fundamentals/lists-mutability/)
~~~

def without_last(lst):
    print(lst)
    #print(lst.pop()) # removes the last element
    return lst[0:len(lst)-1]


Solve in Python:
In this kata we are focusing on the Numpy python package. You must write a function called `looper` which takes three integers `start, stop and number` as input and returns a list from `start` to `stop` with `number` total values in the list.  Five examples are shown below:

```
looper(1, 5, 1) = [1.0]
looper(1, 5, 2) = [1.0, 5.0]
looper(1, 5, 3) = [1.0, 3.0, 5.0]
looper(1, 5, 4) = [1.0, 2.333333333333333, 3.6666666666666665, 5.0]
looper(1, 5, 5) = [1.0, 2.0, 3.0, 4.0, 5.0]
```

looper = lambda a, z, n: [a] if n == 1 else [a] + [(z - a) / (n - 1) * i + a for i in range(1, n - 1)] + [z]


Solve in Python:
In this kata we want to convert a string into an integer. The strings simply represent the numbers in words.

Examples:

* "one" => 1
* "twenty" => 20
* "two hundred forty-six" => 246
* "seven hundred eighty-three thousand nine hundred and nineteen" => 783919

Additional Notes:

* The minimum number is "zero" (inclusively)
* The maximum number, which must be supported is 1 million (inclusively)
* The "and" in e.g. "one hundred and twenty-four" is optional, in some cases it's present and in others it's not
* All tested numbers are valid, you don't need to validate them

import re

SIMPLIFIER = re.compile(r'(\s|-|\band)+')
SPLITTER   = [re.compile(rf'\s*{what}\s*') for what in ('million', 'thousand', 'hundred', r'ty\b')]
COEFS      = [10**x for x in (6,3,2,1)]

vals       = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()
VALUES     = {name:v for name,v in zip(vals, range(len(vals)))}
VALUES.update({'twen': 2, 'thir': 3, 'for': 4, 'fif': 5, 'eigh':8})

def parse_int(s):
    return parse(0, SIMPLIFIER.sub(' ',s.lower()))

def parse(i, s):
    if i == len(SPLITTER): return VALUES.get(s,0)

    lst, coef, i = SPLITTER[i].split(s), COEFS[i], i+1

    return parse(i,lst[0]) if len(lst)==1 else coef * parse(i,lst[0]) + parse(i,lst[1])


Solve in Python:
In this kata you are expected to recover a scattered password in a (m x n) grid (you'll be given directions of all password pieces in the array)

The array will contain pieces of the password to be recovered, you'll get directions on how to get all the the pieces, your initial position in the array will be the character "x".

Heres what the array looks like

The given directions would consist of `[left, right, up, down]` and `[leftT, rightT, upT, downT]`, the former would be used to move around the grid while the latter would be used when you have a password to that direction of you.(
**E.g** if you are in a position and the move to make is `leftT` it means theres a password to the left of you, so take the value and move there)

So in the 2d array example above, you will be given the directions `["lefT", "downT", "rightT", "rightT"]`, making for the word `"pa$$"`.

Remember you initial position is the character "x".

So you write the function `getPassword(grid, directions)` that uses the directions to get a password in the grid.

Another example.

Once again, Your initial position is the character "x", so from the position of "x" you follow the directions given and get all pieces in the grid.

def get_password(grid, directions):
    r, c = [(r, c) for r in range(len(grid)) for c in range(len(grid[r])) if grid[r][c] == 'x'].pop()
    p = ''
    for d in directions:
        r, c = (r + {'d':1, 'u':-1}.get(d[0], 0), c + {'r':1, 'l':-1}.get(d[0], 0))
        if d[-1] == 'T': p += grid[r][c]
    return p


Solve in Python:
In this kata you are given an array to sort but you're expected to start sorting from a specific position of the array (in ascending order) and optionally you're given the number of items to sort.

#### Examples:

```python
sect_sort([1, 2, 5, 7, 4, 6, 3, 9, 8], 2) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
sect_sort([9, 7, 4, 2, 5, 3, 1, 8, 6], 2, 5) //=> [9, 7, 1, 2, 3, 4, 5, 8, 6]
```

#### Documentation:

```python
sect_sort(array, start, length);
```

- array - array to sort
- start - position to begin sorting
- length - number of items to sort (optional)

if the **length** argument is not passed or is zero, you sort all items to the right of the start postiton in the array

sect_sort=lambda arr,s,l=None: (lambda l: arr[:s]+sorted(arr[s:s+l])+arr[s+l:])(len(arr) if not l else l)


Solve in Python:
In this kata you have to correctly return who is the "survivor", ie: the last element of a Josephus permutation.

Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this:

```
josephus_survivor(7,3) => means 7 people in a circle;
one every 3 is eliminated until one remains
[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out
[1,2,4,5,7] => 6 is counted out
[1,4,5,7] => 2 is counted out
[1,4,5] => 7 is counted out
[1,4] => 5 is counted out
[4] => 1 counted out, 4 is the last element - the survivor!
```

The above link about the "base" kata description will give you a more thorough insight about the origin of this kind of permutation, but basically that's all that there is to know to solve this kata.

**Notes and tips:** using the solution to the other kata to check your function may be helpful, but as much larger numbers will be used, using an array/list to compute the number of the survivor may be too slow; you may assume that both n and k will always be >=1.

def josephus_survivor(n,k):
    arr = [i + 1 for i in range(n)]
    if len(arr) == 1:
        return arr[0]
    cur_pos = k - 1
    while len(arr) != 1:
        while cur_pos >= len(arr):
            cur_pos = cur_pos - len(arr)
        arr.pop(cur_pos)
        cur_pos += k - 1
    return arr[0]