Solve in Python:
Cherry has a string S$S$ consisting of lowercase English letters. Using this string, he formed a pyramid of infinite length with certain rules:
- N$N$-th row of pyramid contains N$N$ characters.
- Each row of pyramid begins with the first character of the string.
- The subsequent characters of the row are appended to the string in cyclic fashion, until the size of string for that Row is reached (See example pyramid for better understanding).
He has another string T$T$ of smaller (or equal) size.
You are asked Q$Q$ queries. Each query is provided with a row number N$N$. The answer to the query is number of occurrences of string T$T$ in that particular row of pyramid. No of occurrences of String T$T$ in a string V$V$ would mean that you'd need to find number of substrings Vi,Vi+1...Vj$V_i, V_{i+1} ... V_j$ which are equal to String T$T$, where i≤j$i \leq j$.
For eg: If the string is code, then the pyramid will be of the form:
c
co
cod
code
codec
codeco
codecod
codecode
codecodec
codecodeco
...

-----Input:-----
- The first line contains string S$S$ — consisting of lowercase English letters.
- The second line contains string T$T$ — consisting of lowercase English letters.
- Next line contains an integer Q$Q$ — the number of queries.
- Then follow Q$Q$ lines with queries descriptions. Each of them contains a single integer N$N$ denoting the row number of pyramid.

-----Output:-----
- Print Q$Q$ lines. The i$i$-th of them should contain a integer denoting occurrences of string T$T$ in that particular row.

-----Constraints-----
- 1≤|S|≤105$1 \leq |S| \leq 10^5$
- 1≤|T|≤|S|$1 \leq |T| \leq |S|$
- 1≤Q≤105$1 \leq Q \leq 10^5$
- 1≤N≤109$1 \leq N \leq 10^9$

-----Sample Input:-----
codechef
chefcode
3
4
12
1455

-----Sample Output:-----
0
1
181

-----Explanation:-----
Pyramid will be formed as explained in the statement.
Query 1: Row number 4 of the pyramid is code. The number of occurrences of chefcode in code is 0.
Query 2: Row number 12 of the pyramid is codechefcode. The number of occurrences of chefcode in...

def kmp(s,t,lps):

    n=len(s)
    m=len(t)
    count=[0 for x in range(n)]
    i=0
    j=0
    while i<n:
        count[i]=count[i-1]
        if t[j]==s[i]:
            i+=1
            j+=1
        if j==m:
            count[i-1]+=1
            j=lps[j-1]
        elif  i<n and t[j]!=s[i]:
            if j!=0:
                j=lps[j-1]
            else:
                i+=1
    return count

def lpsa(t,m):
    l=0
    lps= [0 for i in range(m)]
    i=1
    while i<m:
        if t[i] ==t[l]:
            l+=1
            lps[i]=l
            i+=1
        else:
            if l!=0:
                l=lps[l-1]
            else:
                lps[i]=0
                i+=1
    return lps
s=input()
t=input()
n=len(s)
m=len(t)
lps=lpsa(t,m)
one=kmp(s,t,lps)[-1]
count=kmp(s+s,t,lps)
two=count[-1]
three=two-(2*one)
for _ in range(int(input())):
    q=int(input())
    v=q//n
    if v:
        ans=v*one +(v-1)*three
        e=q%n
        ans+=count[n-1+e]-count[n-1]
    else:
        e=q%n
        ans=count[e-1]
    print(ans)
    # if one:
    #     if q>n:
    #         hh=q//n
    #         i=0
    #         for i in range(hh):
    #             ans+=one
    #     print(ans)
    # elif two:
    #     hh=q//(n+n)
    #     i=0
    #     for i in range(hh):
    #         ans+=two
    #     print(ans)
    # elif three:
    #     hh=q//(n+n+n)
    #     i=0
    #     for i in range(hh):
    #         ans+=three
    #     print(ans)
    # else:
    #     print(0)
    # S=''
    # if q<n:
    #     for i in range(q):
    #         S+=s[i]
    #     kmp(S,t,lps)

    # elif q==n:
    #     kmp(s,t,lps)

    # elif q%n==0:
    #     tt=q//n
    #     for i in range(tt):
    #         S+=s
    #     kmp(S,t,lps)

    # elif q%n!=0:
    #     temp=0
    #     while temp<q:
    #         temp+=n
    #     temp=temp-n
    #     tem=temp//n
    #     for i in range(tem):
    #         S+=s

    #     h=q-temp
    #     for i in range(h):
    #         S+=s[i]
   ...


Solve in Python:
Chingel is practicing for a rowing competition to be held on this saturday. He is trying his best to win this tournament for which he needs to figure out how much time it takes to cover a certain distance.

**Input**

You will be provided with the total distance of the journey, speed of the boat and whether he is going downstream or upstream. The speed of the stream and direction of rowing will be given as a string. Check example test cases!

**Output**

The output returned should be the time taken to cover the distance. If the result has decimal places, round them to 2 fixed positions.

`Show some love ;) Rank and Upvote!`

def time(distance, boat_speed, stream):
    speed = boat_speed + (int(stream[11:]) if stream[0] == 'D' else -int(stream[9:]))
    return round(distance/speed, 2)


Solve in Python:
Christmas is coming, and Santa has a long list to go through, to find who deserves presents for the big day. Go through a list of children, and return a list containing every child who appeared on Santa's list. Do not add any child more than once. Output should be sorted.
~~~if:java
For java, use Lists.
~~~

Comparison should be case sensitive and the returned list should contain only one copy of each name: `"Sam"` and `"sam"` are different, but `"sAm"` and `"sAm"` are not.

def find_children(santas_list, children):
    return sorted({child for child in children if child in santas_list})


Solve in Python:
Chuck Norris just created a universe. He has already started the space-time continuum. Now he needs to fill the universe with matter and antimatter for the avatar cycle to start.
He created $N$ distinct pairs of elementary matter and their corresponding antimatter particles. Annihilations happen only when a matter particle is placed adjacent to its corresponding antimatter particle and not when it is placed adjacent to any other matter or antimatter particle. Thus for every distinct particle of matter in the universe there exist one and only one antimatter particle that can cause its annihilation.
Chuck Norris wants to arrange all the particles in a 2-D circular pattern such that a matter particle is placed adjacent only to antimatter particles and vice versa. In how many distinct ways can he arrange them, regardless of the orientation of the arrangement, such that total annihilation of ALL particles doesn't take place i.e., $at least$ $one$ pair remain unannihilated after he arranges them in a circular pattern.
Since the total number of distinct ways can be very large, print the result modulo $1000000007$.

-----Input:-----
- First line has single integer $T$, i.e., the number of test cases
- The first and only line of each test case has a single integer $N$ i.e., number of distinct pairs of matter-antimatter particles.

-----Output:-----
- For of each test case print a single line, i.e., total number of distinct ways.

-----Constraints :-----
- $1 \leq T \leq 1000$
- $0 \leq N \leq 10^7$

-----Subtasks-----
-
Subtask 1 : 10 pts
- $1 \leq T \leq 100$
- $0 \leq N \leq 100$
-
Subtask 2 : 90 pts
- Original Constraints

-----Sample input :-----
1
3

-----Sample output :-----
8

-----Explanation:-----
For 3 pairs of elementary matter and their corresponding  antimatter particles, Chuck Norris can arrange them in 8 ways such that at least one pair of matter antimatter particles survive annihilation.


Solve in Python:
Chuck has lost count of how many asses he has kicked...

Chuck stopped counting at 100,000 because he prefers to kick things in the face instead of counting. That's just who he is.

To stop having to count like a mere mortal chuck developed his own special code using the hairs on his beard. You do not need to know the details of how it works, you simply need to know that the format is as follows: 'A8A8A8A8A8.-A%8.88.'

In Chuck's code, 'A' can be any capital letter and '8' can be any number 0-9 and any %, - or . symbols must not be changed.

Your task, to stop Chuck beating your ass with his little finger, is to use regex to verify if the number is a genuine Chuck score. If not it's probably some crap made up by his nemesis Bruce Lee. Return true if the provided count passes, and false if it does not.

```Javascript
Example:
     'A8A8A8A8A8.-A%8.88.' <- don't forget final full stop :D\n
Tests:
     'A2B8T1Q9W4.-F%5.34.' == true;
     'a2B8T1Q9W4.-F%5.34.' == false; (small letter)
     'A2B8T1Q9W4.-F%5.3B.' == false; (last char should be number)
     'A2B8T1Q9W4.£F&5.34.' == false; (symbol changed from - and %)
 ```

The pattern only needs to appear within the text. The full input can be longer, i.e. the pattern can be surrounded by other characters... Chuck loves to be surrounded!

Ready, steady, VERIFY!!

import re

pattern = re.compile('A8A8A8A8A8.-A%8.88.'.replace('A', '[A-Z]').replace('8', '[0-9]').replace('.', r'\.'))

def body_count(code):
    return bool(pattern.search(code))


Solve in Python:
Classy Extensions
Classy Extensions, this kata is mainly aimed at the new JS ES6 Update introducing extends keyword. You will be preloaded with the Animal class, so you should only edit the Cat class.

Task
Your task is to complete the Cat class which Extends Animal and replace the speak method to return the cats name + meows.
e.g. 'Mr Whiskers meows.'

The name attribute is passed with this.name (JS), @name (Ruby) or self.name (Python).

Reference: [JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), [Ruby](http://rubylearning.com/satishtalim/ruby_inheritance.html), [Python](https://docs.python.org/2/tutorial/classes.html#inheritance).

class Cat:

    def __init__(self, name):
        super().__init__()
        self.name = name

    def speak(self):
        return f"{self.name} meows."


Solve in Python:
Clock shows 'h' hours, 'm' minutes and 's' seconds after midnight.

Your task is to make 'Past' function which returns time converted to milliseconds.

## Example:

```python
past(0, 1, 1) == 61000
```

Input constraints: `0 <= h <= 23`, `0 <= m <= 59`, `0 <= s <= 59`

def past(h, m, s):
    h_to_milli = h * 60 * 60 * 1000
    m_to_milli = m * 60 * 1000
    s_to_milli = s * 1000
    millis = h_to_milli + m_to_milli + s_to_milli
    return millis


Solve in Python:
Cluster analysis - Unweighted pair-group average

Clustering is a task of grouping a set of objects in such a way that the objects in the same class are similar to each other and the objects in different classes are distinct. Cluster analysis is employed in many fields such as machine learning, pattern recognition, image analysis, etc.

In this kata, your task is to implement a simple clustering technique called 'Unweighted pair-group average'. This method takes a set of 2D points and the desired number of final clusters. Initially, each point forms its own cluster. The most similar (least distant) clusters are iteratively merged until the target number of clusters is reached.

The distance metric between two clusters is defined as the average distance between all pairs of points from the two clusters. For example:
```
Cluster 1: (0, 0), (0, 1)
Cluster 2: (4, 3)
Distance = (sqrt((0-4)^2 + (0-3)^2) + sqrt((0-4)^2 + (1-2)^2)) / 2
```

Input:
- ```points``` - a list of 2D points ```[(1, 1), (3, 5), (4, 4), (8, 2), (0, 1)]```
- ```n``` - the desired number of clusters

Output:
- list of clusters, each cluster is a list of points
- points in each cluster should be sorted in ascending order
- the list of clusters should also be sorted in ascending order

Example:
- ```cluster(3, [(1, 1), (3, 5), (4, 4), (8, 2), (0, 1)])```
- should return
```[ [(0, 1), (1, 1)],
     [(3, 5), (4, 4)],
     [(8, 2)]
   ]
```

Notes:
- the coordinates ```(x, y)``` are chosen from interval ```<0, 1000>```
- ```0 < len(points) <= 100```
- ```0 < n <= len(points)```
- there is always only one unique solution
- there are no duplicate points in the input

from math import hypot
from statistics import mean

def cluster(points, n):
    cs = [[p] for p in points]
    def key(ij):
        return mean(dist(p1, p2) for p1 in cs[ij[0]] for p2 in cs[ij[1]])
    while len(cs) > n:
        i, j = min(((i, j) for i in range(len(cs)) for j in range(i)), key=key)
        cs[i] += cs[j]
        del cs[j]
    return sorted(map(sorted, cs))

def dist(a, b):
    return hypot(a[0] - b[0], a[1] - b[1])


Solve in Python:
Coach Khaled is a swag teacher in HIT (Hag Institute of Technology). However, he has some obsession problems.
Recently, coach Khaled was teaching a course in building 8G networks using TV antennas and programming them with assembly. There are $N$ students (numbered $1$ through $N$) in his class; for some reason, this number is always a multiple of $4$. The final exam has finished and Khaled has all the scores of his $N$ students. For each valid $i$, the score of the $i$-th student is $A_i$; each score is an integer between $0$ and $100$. Currently, the score-grade distribution is as follows:
- grade D for score smaller than $60$
- grade C for score greater or equal to $60$, but smaller than $75$
- grade B for score greater or equal to $75$, but smaller than $90$
- grade A for score greater or equal to $90$
However, coach Khaled is not satisfied with this. He wants exactly $N/4$ students to receive each grade (A, B, C and D), so that the grades are perfectly balanced. The scores cannot be changed, but the boundaries between grades can. Therefore, he wants to choose three integers $x$, $y$ and $z$ and change the grade distribution to the following (note that initially, $x = 60$, $y = 75$ and $z = 90$):
- grade D for score smaller than $x$
- grade C for score greater or equal to $x$, but smaller than $y$
- grade B for score greater or equal to $y$, but smaller than $z$
- grade A for score greater or equal to $z$
Your task is to find thresholds $x$, $y$ and $z$ that result in a perfect balance of grades. If there are multiple solutions, choose the one with the maximum value of $x+y+z$ (because coach Khaled wants seem smarter than his students); it can be proved that there is at most one such solution. Sometimes, there is no way to choose the thresholds and coach Khaled would resign because his exam questions were low-quality.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case...

# cook your dish here
t= int(input())
for _ in range(t):
 n=int(input())
 l = list(map(int,input().split()))
 a = n//4
 l.sort()
 if(l[a] == l[a-1] or l[2*a]==l[2*a-1] or l[3*a]==l[3*a-1]):
  print(-1)
 else:
  print(l[a],l[2*a],l[3*a])


Solve in Python:
Coach Moony wants the best team to represent their college in ICPC. He has $N$ students standing in a circle with certain rating $X_i$ on a competitive coding platform. It is an established fact that any coder with more rating on the platform is a better coder.
Moony  wants to send his best $3$ coders based upon their rating. But all coders only want to have their friends in their team and every coder is friends with four other coders, adjacent two on left side in the circle, and adjacent two on right. So Moony comes up with a solution that team with maximum cumulative rating of all three members in a team shall be representing their college.
You need to give the cumulative score of the team that will be representing the college.

-----Input:-----
- First line will contain $T$, number of testcases.
- First line of each test case contains a single integer $N$.
- Second  line of each test case takes $N$ integers, denoting rating of $ith$ coder.

-----Output:-----
For each testcase, output a single integer denoting cumulative rating  of the team.

-----Constraints-----
- $1 \leq T \leq 10$
- $7 \leq N \leq 10^5$
- $0 \leq X_i \leq 10^9$

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

7

10 40 30 30 20 0 0

-----Sample Output:-----
100

m=int(input())
for i in range(0,m):
    n=int(input())
    a=list(map(int,input().strip().split()))
    l=len(a)
    j=0
    max=-999999
    while(j<l):
        sum=0
        if(j==(l-1)):
            sum=a[j]+a[0]+a[1]
        elif(j==(l-2)):
            sum=a[j]+a[j+1]+a[0]
        else:
            sum=a[j]+a[j+1]+a[j+2]
        if(sum>max):
            max=sum
        j=j+1
    print(max)


Solve in Python:
Codefortia is a small island country located somewhere in the West Pacific. It consists of $n$ settlements connected by $m$ bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to be equal either to $a$ or $b$ seconds. It's guaranteed that one can go between any pair of settlements by following a sequence of roads.

Codefortia was recently struck by the financial crisis. Therefore, the king decided to abandon some of the roads so that:

  it will be possible to travel between each pair of cities using the remaining roads only,  the sum of times required to pass each remaining road will be minimum possible (in other words, remaining roads must form minimum spanning tree, using the time to pass the road as its weight),  among all the plans minimizing the sum of times above, the time required to travel between the king's residence (in settlement $1$) and the parliament house (in settlement $p$) using the remaining roads only will be minimum possible.

The king, however, forgot where the parliament house was. For each settlement $p = 1, 2, \dots, n$, can you tell what is the minimum time required to travel between the king's residence and the parliament house (located in settlement $p$) after some roads are abandoned?

-----Input-----

The first line of the input contains four integers $n$, $m$, $a$ and $b$ ($2 \leq n \leq 70$, $n - 1 \leq m \leq 200$, $1 \leq a < b \leq 10^7$) — the number of settlements and gravel roads in Codefortia, and two possible travel times. Each of the following lines contains three integers $u, v, c$ ($1 \leq u, v \leq n$, $u \neq v$, $c \in \{a, b\}$) denoting a single gravel road between the settlements $u$ and $v$, which requires $c$ minutes to travel.

You can assume that the road network is connected and has no loops or multiedges.

-----Output-----

Output a single line containing $n$ integers. The $p$-th of them should denote the minimum possible time required to travel from $1$ to $p$ after the selected roads...

import heapq
n,m,a,b=map(int,input().split())
graph={i:[] for i in range(n)}
for i in range(m):
    u,v,w=map(int,input().split())
    graph[u-1].append((v-1,w))
    graph[v-1].append((u-1,w))
components=[-1]*n
comp=-1
for i in range(n):
    if components[i]==-1:
        comp+=1
        components[i]=comp
        prev=[]
        layer=[i]
        while layer!=[]:
            newlayer=[]
            for guy in layer:
                for guy1 in graph[guy]:
                    if guy1[1]==a and components[guy1[0]]==-1:
                        newlayer.append(guy1[0])
                        components[guy1[0]]=comp
            prev=layer[:]
            layer=newlayer[:]
useless=[]
for guy in graph:
    for neigh in graph[guy]:
        if components[guy]==components[neigh[0]] and neigh[1]==b:
            useless.append((guy,neigh))
for guy in useless:
    graph[guy[0]].remove(guy[1])
counts=[0]*(comp+1)
for i in range(n):
    counts[components[i]]+=1
bad=[]
for i in range(comp+1):
    if counts[i]<=3:
        bad.append(i)
        for j in range(n):
            if components[j]==i:
                components[j]=-1
for guy in bad[::-1]:
    for i in range(n):
        if components[i]>guy:
            components[i]-=1
comp-=len(bad)
comp+=1
dists=[[float("inf") for i in range(2**comp)] for j in range(n)]
dists[0][0]=0
pq=[]
heapq.heappush(pq,[0,0,0])
remaining=n
visited=[0]*n
while len(pq)>0 and remaining>0:
    dist,vert,mask=heapq.heappop(pq)
    if visited[vert]==0:
        visited[vert]=1
        remaining-=1
    for neigh in graph[vert]:
        if neigh[1]==b:
            if components[vert]==components[neigh[0]] and components[vert]!=-1:
                continue
            if components[neigh[0]]!=-1:
                if mask & (2**components[neigh[0]])>0:
                    continue
            if components[vert]!=-1:
                maskn=mask+2**(components[vert])
            else:
                maskn=mask
        else:
            maskn=mask
        if dist+neigh[1]<dists[neigh[0]][maskn]:
         ...


Solve in Python:
Coding decimal numbers with factorials is a way of writing out numbers
in a base system that depends on factorials, rather than powers of numbers.

In this system, the last digit is always `0` and is in base 0!. The digit before that is either `0 or 1` and is in base 1!.  The digit before that is either `0, 1, or 2` and is in base 2!, etc.
More generally, the nth-to-last digit is always `0, 1, 2, ..., n` and is in base n!.

Read more about it at: http://en.wikipedia.org/wiki/Factorial_number_system

## Example

The decimal number `463` is encoded as `"341010"`, because:

463 = 3×5! + 4×4! + 1×3! + 0×2! + 1×1! + 0×0!

If we are limited to digits `0..9`, the biggest number we can encode is 10!-1 (= 3628799). So we extend `0..9` with letters `A..Z`. With these 36 digits we can now encode numbers up to 36!-1 (= 3.72 × 10^(41))

## Task

We will need two functions. The first one will receive a decimal number and return a string with the factorial representation.

~~~if:java
**Note:** the input number is at most a long.
~~~

The second one will receive a string with a factorial representation and produce the decimal representation.

Given numbers will always be positive.

import itertools
import math

digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def dec2FactString(nb):
    result = []
    i = itertools.count(1)
    while nb:
        nb, rem = divmod(nb, next(i))
        result.append(digits[rem])
    return "".join(i for i in result[::-1])

def factString2Dec(string):
    return sum(
        digits.index(d) * math.factorial(i)
        for d, i in zip(
            string[::-1],
            itertools.count()))


Solve in Python:
Coffee Vending Machine Problems [Part 1]

You have a vending machine, but it can not give the change back. You decide to implement this functionality. First of all, you need to know the minimum number of coins for this operation (i'm sure you don't want to return 100 pennys instead of 1$ coin).
So, find an optimal number of coins required, if you have unlimited set of coins with given denominations.

Assume all inputs are valid positive integers, and every set of coin denominations has len 4 for simplicity;

Examples:

optimal_number_of_coins(1, [1, 2, 5, 10])
(1 penny) so returns 1
optimal_number_of_coins(5, [1, 2, 5, 10])
(5) so returns 1
optimal_number_of_coins(6, [1, 3, 5, 10])
(3+3 or 5+1) = 6 so returns 2
optimal_number_of_coins(10, [1, 2, 5, 10])
(10) so returns 1
optimal_number_of_coins(12, [1, 3, 5, 10])
(10+1+1) = 12 so returns 3
optimal_number_of_coins(53, [1, 2, 5, 25])
(25+25+2+1) = 53 so returns 4
optimal_number_of_coins(7, [1, 1, 1, 25])
(1+1+1+1+1+1+1) = 7 so returns 7
etc..

Have fun =)

def optimal_number_of_coins(n, a):
    q = [float('inf')] * (n+1)
    q[0] = 0
    for i in range(1, n+1):
        q[i] = min(q[i-x]+1 for x in a if x <= i)
    return q[n]


Solve in Python:
Colour plays an important role in our lifes. Most of us like this colour better then another. User experience specialists believe that certain colours have certain psychological meanings for us.

You are given a 2D array, composed of a colour and its 'common' association in each array element. The function you will write needs to return the colour as 'key' and association as its 'value'.

For example:
```python
var array = [["white", "goodness"], ...] returns [{'white': 'goodness'}, ...]
```

def colour_association(arr):
    dict1 = []
    for item in arr:
        dicts = {}
        dicts.update({item[0] : item[1]})
        dict1.append(dicts)

    print(dict1)
    return dict1

    #your code here


Solve in Python:
Compare two strings by comparing the sum of their values (ASCII character code).

* For comparing treat all letters as UpperCase
* `null/NULL/Nil/None` should be treated as empty strings
* If the string contains other characters than letters, treat the whole string as it would be empty

Your method should return `true`, if the strings are equal and `false` if they are not equal.

## Examples:
```
"AD", "BC"  -> equal
"AD", "DD"  -> not equal
"gf", "FG"  -> equal
"zz1", ""   -> equal (both are considered empty)
"ZzZz", "ffPFF" -> equal
"kl", "lz"  -> not equal
null, ""    -> equal
```

from typing import Union

def compare(s1: Union[str, None], s2: Union[str, None]) -> bool:
    def value(s: Union[str, None]):
        return sum(map(ord, s.upper())) if s and all(c.isalpha() for c in s) else 0

    return value(s1) == value(s2)


Solve in Python:
Complete the  function `scramble(str1, str2)` that returns `true` if a portion of ```str1``` characters can be rearranged to match ```str2```, otherwise returns ```false```.

**Notes:**
* Only lower case letters will be used (a-z). No punctuation or digits will be included.
* Performance needs to be considered

## Examples

```python
scramble('rkqodlw', 'world') ==> True
scramble('cedewaraaossoqqyt', 'codewars') ==> True
scramble('katas', 'steak') ==> False
```

def scramble(s1, s2):
    if len(s1) < len(s2):
        return False
    s1_dict = {}
    s2_dict = {}
    for char in s1:
        try:
            s1_dict[char] += 1
        except KeyError:
            s1_dict[char] = 1
    for char in s2:
        try:
            s2_dict[char] += 1
        except KeyError:
            s2_dict[char] = 1
    for key in s2_dict:
        try:
            if s1_dict[key] < s2_dict[key]:
                return False
        except KeyError:
            return False
    return True


Solve in Python:
Complete the `greatestProduct` method so that it'll find the greatest product of five consecutive digits in the given string of digits.

For example:

The input string always has more than five digits.

Adapted from Project Euler.

from functools import reduce
def greatest_product(n):
    l=list(map(int,list(n)))
    return max([reduce(lambda x,y:x*y,l[i:i+5]) for i in range(len(l)) if len(l[i:i+5])==5])


Solve in Python:
Complete the code which should return `true` if the given object is a single ASCII letter (lower or upper case), `false` otherwise.

import re
def is_letter(s):
    return re.match(r'(?i)[a-z]\Z', s) is not None


Solve in Python:
Complete the function ```caffeineBuzz```, which takes a non-zero integer as it's one argument.

If the integer is divisible by 3, return the string ```"Java"```.

If the integer is divisible by 3 and divisible by 4, return the string ```"Coffee"```

If the integer is one of the above and is even, add ```"Script"``` to the end of the string.

Otherwise, return the string ```"mocha_missing!"```

```python
caffeineBuzz(1)   => "mocha_missing!"
caffeineBuzz(3)   => "Java"
caffeineBuzz(6)   => "JavaScript"
caffeineBuzz(12)  => "CoffeeScript"
```

import unittest

JAVA = 'Java'
COFFEE = 'Coffee'
SCRIPT = 'Script'
MOCHA_MISSING = 'mocha_missing!'

def caffeineBuzz(n):
    if n % 3 == 0:
        language = JAVA
        if n % 4 == 0:
            language = COFFEE
            if n % 2 == 0:
                language += SCRIPT
        elif n % 2 == 0:
            language += SCRIPT
        return language
    else:
        return MOCHA_MISSING

class TestCaffeineBuzz(unittest.TestCase):
    def test_should_return_java_when_given_n_is_divisible_by_3(self):
        n = 3
        actual = caffeineBuzz(n)
        self.assertEqual(actual, 'Java')

    def test_should_return_coffee_script_when_given_n_is_divisible_by_3_or_divisible_by_and_divisible_by_4_and_divisible_by_2(self):
        n = 12
        actual = caffeineBuzz(n)
        self.assertEqual(actual, 'CoffeeScript')

    def test_should_return_coffee_script_when_given_n_is_divisible_by_3_or_divisible_by_and_not_divisible_by_4_and_divisible_by_2(self):
        n = 6
        actual = caffeineBuzz(n)
        self.assertEqual(actual, 'JavaScript')

    def test_should_return_moch_missing_when_given_n_is_1(self):
        n = 1
        actual = caffeineBuzz(n)
        self.assertEqual(actual, 'mocha_missing!')


Solve in Python:
Complete the function ```circleArea``` so that it will return the area of a circle with the given ```radius```. Round the returned number to two decimal places (except for Haskell). If the radius is not positive or not a number, return ```false```.

Example:

```python
circleArea(-1485.86)     #returns false
circleArea(0)            #returns false
circleArea(43.2673)      #returns 5881.25
circleArea(68)           #returns 14526.72
circleArea("number")     #returns false
```

import math

def circleArea(r):
    return type(r) in (int, float) and r > 0 and round(math.pi * r**2, 2)


Solve in Python:
Complete the function `power_of_two`/`powerOfTwo` (or equivalent, depending on your language) that determines if a given non-negative integer is a [power of two](https://en.wikipedia.org/wiki/Power_of_two).  From the corresponding Wikipedia entry:

> *a power of two is a number of the form 2^(n) where **n** is an integer, i.e. the result of exponentiation with number two as the base and integer **n** as the exponent.*

You may assume the input is always valid.

## Examples

~~~if-not:nasm
```python
power_of_two(1024) ==> True
power_of_two(4096) ==> True
power_of_two(333)  ==> False
```
~~~
~~~if:nasm
```
mov edi, 0
call power_of_two    ; returns false (zero)
mov edi, 16
call power_of_two    ; returns true (non-zero)
mov edi, 100
call power_of_two    ; returns false
mov edi, 1024
call power_of_two    ; returns true
mov edi, 20000
call power_of_two    ; returns false
```
~~~

Beware of certain edge cases - for example, `1` is a power of `2` since `2^0 = 1` and `0` is not a power of `2`.

def power_of_two(x):
  return bin(x).count('1')==1


Solve in Python:
Complete the function so that it returns the number of seconds that have elapsed between the start and end times given.

##### Tips:
- The start/end times are given as Date (JS/CoffeeScript), DateTime (C#), Time (Nim), datetime(Python) and Time (Ruby) instances.
- The start time will always be before the end time.

import datetime

def elapsed_seconds(start, end):
    a=end-start
    return a.total_seconds()


Solve in Python:
Complete the function so that it takes an array of keys and a default value and returns a hash (Ruby) / dictionary (Python) with all keys set to the default value.

## Example

```python
["draft", "completed"], 0   # should return {"draft": 0, "completed: 0}
```

from itertools import repeat
def populate_dict(keys, default):
    return {k: v for k, v in zip(keys, repeat(default))}


Solve in Python:
Complete the function that accepts a string parameter, and reverses each word in the string. **All** spaces in the string should be retained.

## Examples
```
"This is an example!" ==> "sihT si na !elpmaxe"
"double  spaces"      ==> "elbuod  secaps"
```

import re

def reverse_words(text):
    list = re.split(r'(\s+)', text)
    res = ""
    for w in list:
        for i in range(len(w), 0, -1):
            res += w[i - 1]
    return res


Solve in Python:
Complete the function that accepts a valid string and returns an integer.

Wait, that would be too easy! Every character of the string should be converted to the hex value of its ascii code, then the result should be the sum of the numbers in the hex strings (ignore letters).

## Examples
```
"Yo" ==> "59 6f" ==> 5 + 9 + 6 = 20
"Hello, World!"  ==> 91
"Forty4Three"    ==> 113
```

def hex_hash(code):
    res=''.join(list(map(hex, map(ord,code))))
    return sum(int(x) for x in res if x.isdigit())


Solve in Python:
Complete the function that calculates the derivative of a polynomial. A polynomial is an expression like: 3x^(4) - 2x^(2) + x - 10

### How to calculate the derivative:

* Take the exponent and multiply it with the coefficient
* Reduce the exponent by 1

For example: 3x^(4) --> (4*3)x^((4-1)) = 12x^(3)

### Good to know:

* The derivative of a constant is 0 (e.g. 100 --> 0)
* Anything to the 0th exponent equals 1 (e.g. x^(0) = 1)
* The derivative of the sum of two function is the sum of the derivatives

Notes:
* The exponentiation is marked with "^"
* Exponents are always integers and >= 0
* Exponents are written only if > 1
* There are no spaces around the operators
* Leading "+" signs are omitted

See the examples below.

## Examples
```python
derivative("-100")      = "0"
derivative("4x+1")      = "4"      # = 4x^0 + 0
derivative("-x^2+3x+4") = "-2x+3"  # = -2x^1 + 3x^0 + 0
```

import re

def derivative(eq):
    res = []

    # change bare "x"s to "1x" for easier processing
    eq = re.sub(r'\bx', '1x', eq)

    # extract constants, variables and exponents
    for const, var, exp in re.findall(r'([+-]?\d+)(x?)\^?(\d*)', eq):

        # if constant only, derivative = 0
        if not var:
            continue

        # if no exponent found (= 1), derivative = const
        if not exp:
            res.append(const)
            continue

        # if exponent > 1, calculate derivative
        const, exp = int(const), int(exp)
        const *= exp
        if exp == 2:
            res.append('%+dx' % const)
        else:
            res.append('%+dx^%d' % (const, exp - 1))

    # construct the final result and return it
    res = ''.join(res).strip('+')
    return res if res else '0'


Solve in Python:
Complete the function that counts the number of unique consonants in a string (made up of printable ascii characters).

Consonants are letters used in English other than `"a", "e", "i", "o", "u"`. We will count `"y"` as a consonant.

Remember, your function needs to return the number of unique consonants - disregarding duplicates. For example, if the string passed into the function reads `"add"`, the function should return `1` rather than `2`, since `"d"` is a duplicate.

Similarly, the function should also disregard duplicate consonants of differing cases. For example, `"Dad"` passed into the function should return `1` as `"d"` and `"D"` are duplicates.

## Examples

```
"add" ==> 1
"Dad" ==> 1
"aeiou" ==> 0
"sillystring" ==> 7
"abcdefghijklmnopqrstuvwxyz" ==> 21
"Count my unique consonants!!" ==> 7
```

def count_consonants(text):
    return len(set(filter(str.isalpha,text.lower())) - set("aeiou"))


Solve in Python:
Complete the function that determines the score of a hand in the card game [Blackjack](https://en.wikipedia.org/wiki/Blackjack) (aka 21).

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

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

### Scoring rules:

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

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

## Examples

```
["A"]                           ==>  11
["A", "J"]                      ==>  21
["A", "10", "A"]                ==>  12
["5", "3", "7"]                 ==>  15
["5", "4", "3", "2", "A", "K"]  ==>  25
```

def score_hand(cards):
    aces = [i for i in cards if i == 'A']
    cards = list(filter(lambda x: x is not 'A', cards))
    cards.extend(aces)
    total = 0
    for i, card in enumerate(cards):
        if card in ['J', 'Q', 'K']:
            total += 10
        elif card is 'A':
            total += 11 if 11 <= (21 - total) and "".join(cards).rindex('A') == i else 1
        else:
            total += int(card)
    return total


Solve in Python:
Complete the function that returns an array of length `n`, starting with the given number `x` and the squares of the previous number. If `n` is negative or zero, return an empty array/list.

## Examples

```
2, 5  -->  [2, 4, 16, 256, 65536]
3, 3  -->  [3, 9, 81]
```

def squares(x, n):
    mx = [x]
    while len(mx)<n:
        mx.append(mx[-1]**2)
    return mx if n>0 else []


Solve in Python:
Complete the function that takes 3 numbers `x, y and k` (where `x ≤ y`), and returns the number of integers within the range `[x..y]` (both ends included) that are divisible by `k`.

More scientifically:  `{ i : x ≤ i ≤ y, i mod k = 0 }`

## Example

Given ```x = 6, y = 11, k = 2``` the function should return `3`, because there are three numbers divisible by `2` between `6` and `11`: `6, 8, 10`

- **Note**: The test cases are very large. You will need a O(log n) solution or better to pass. (A constant time solution is possible.)

def divisible_count(x,y,k):
    upper = y//k
    lower = (x-1)//k
    return upper - lower


Solve in Python:
Complete the function that takes a non-negative integer `n` as input, and returns a list of all the powers of 2 with the exponent ranging from 0 to `n` (inclusive).

## Examples

```python
n = 0  ==> [1]        # [2^0]
n = 1  ==> [1, 2]     # [2^0, 2^1]
n = 2  ==> [1, 2, 4]  # [2^0, 2^1, 2^2]
```

def powers_of_two(n):
    power = n
    square_list = [1]
    for i in range(1,n+1):
        square_list.append(2 ** i)
    return square_list


Solve in Python:
Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.

In case of multiple appearances to choose from, take the last occurence of the unpaired character.

**Notes:**
* A wide range of characters is used, and some of them may not render properly in your browser.
* Your solution should be linear in terms of string length to pass the last test.

## Examples

```
"Hello World"   -->  ["H", "e", " ", "W", "r", "l", "d"]
"Codewars"      -->  ["C", "o", "d", "e", "w", "a", "r", "s"]
"woowee"        -->  []
"wwoooowweeee"  -->  []
"racecar"       -->  ["e"]
"Mamma"         -->  ["M"]
"Mama"          -->  ["M", "m"]
```

def odd_one_out(s):
    from collections import Counter
    c = Counter(s)
    ans = []
    for i in s[::-1]:
        try:
            if c[i] % 2 == 1:
                ans.append(i)
                del c[i]
        except:
            pass

    return ans[::-1]


Solve in Python:
Complete the function that takes an array of words.

You must concatenate the `n`th letter from each word to construct a new word which should be returned as a string, where `n` is the position of the word in the list.

For example:

```
["yoda", "best", "has"]  -->  "yes"
  ^        ^        ^
  n=0     n=1     n=2
```

**Note:** Test cases contain valid input only - i.e. a string array or an empty array; and each word will have enough letters.

def nth_char(words):
    return ''.join(w[i] for i,w in enumerate(words))


Solve in Python:
Complete the function that takes one argument, a list of words, and returns the length of the longest word in the list.

For example:

```python
['simple', 'is', 'better', 'than', 'complex'] ==> 7
```

Do not modify the input list.

longest = lambda w: len(max(w, key = len))


Solve in Python:
Complete the function that takes two integers (`a, b`, where `a < b`) and return an array of all integers between the input parameters, **including** them.

For example:
```
a = 1
b = 4
--> [1, 2, 3, 4]
```

def between(a,b):
    arr = []
    while (a < b+1):
            arr.append(a)
            a += 1
    return arr


Solve in Python:
Complete the function that takes two numbers as input, ```num``` and ```nth``` and return the `nth` digit of `num` (counting from right to left).

## Note
- If ```num``` is negative, ignore its sign and treat it as a positive value
- If ```nth``` is not positive, return `-1`
- Keep in mind that `42 = 00042`. This means that ```findDigit(42, 5)``` would return `0`

## Examples

```
findDigit(5673, 4)     returns 5
findDigit(129, 2)      returns 2
findDigit(-2825, 3)    returns 8
findDigit(-456, 4)     returns 0
findDigit(0, 20)       returns 0
findDigit(65, 0)       returns -1
findDigit(24, -8)      returns -1
```

def find_digit(num, nth):
    return int((f'{abs(num):0{nth}}'[::-1])[nth-1]) if nth > 0 else -1


Solve in Python:
Complete the function to determine the number of bits required to convert integer `A` to integer `B` (where `A` and `B` >= 0)

The upper limit for `A` and `B` is 2^(16), `int.MaxValue` or similar.

For example, you can change 31 to 14 by flipping the 4th and 0th bit:
```
 31  0 0 0 1 1 1 1 1
 14  0 0 0 0 1 1 1 0
---  ---------------
bit  7 6 5 4 3 2 1 0
```
Thus `31` and `14` should return `2`.

def countSetBits(n):
  count = 0
  while n:
      count += n & 1
      n >>= 1
  return count

def convert_bits(a, b):
  return countSetBits(a^b)


Solve in Python:
Complete the function to find the count of the most frequent item of an array. You can assume that input is an array of integers. For an empty array return `0`

## Example
```python
input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
ouptut: 5
```
The most frequent number in the array is `-1` and it occurs `5` times.

from collections import Counter

def most_frequent_item_count(collection):
    return Counter(collection).most_common(1)[0][1] if collection else 0


Solve in Python:
Complete the function which converts hex number (given as a string) to a decimal number.

def hex_to_dec(s):
    m = '0123456789ABCDEF'
    result = 0
    for i in range(0, len(s)):
        result += m.index(s[i].upper()) * 16 ** (len(s) - 1 - i)

    return result


Solve in Python:
Complete the function which returns the weekday according to the input number:

* `1` returns `"Sunday"`
* `2` returns `"Monday"`
* `3` returns `"Tuesday"`
* `4` returns `"Wednesday"`
* `5` returns `"Thursday"`
* `6` returns `"Friday"`
* `7` returns `"Saturday"`
* Otherwise returns `"Wrong, please enter a number between 1 and 7"`

def whatday(n):
    weekdays = {
        1: "Sunday",
        2: "Monday",
        3: "Tuesday",
        4: "Wednesday",
        5: "Thursday",
        6: "Friday",
        7: "Saturday"
    }
    return weekdays.get(n, "Wrong, please enter a number between 1 and 7")


Solve in Python:
Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of `numbers` and the second is the `divisor`.

## Example

```python
divisible_by([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6]
```

def divisible_by(numbers, divisor):
    return [ el for el in numbers if el % divisor == 0]


Solve in Python:
Complete the function, which calculates how much you need to tip based on the total amount of the bill and the service.

You need to consider the following ratings:

- Terrible: tip 0%
- Poor: tip 5%
- Good: tip 10%
- Great: tip 15%
- Excellent: tip 20%

The rating is **case insensitive** (so "great" = "GREAT"). If an unrecognised rating is received, then you need to return:

* `"Rating not recognised"` in Javascript, Python and Ruby...
* ...or `null` in Java
* ...or `-1` in C#

Because you're a nice person, you **always round up** the tip, regardless of the service.

import numpy as np
def calculate_tip(amount, rating):
    tips={'terrible': 0, 'poor':0.05, 'good': 0.1, 'great': 0.15, 'excellent':0.2}
    try:
        return np.ceil(tips[rating.lower()]*amount)
    except:
        return 'Rating not recognised'


Solve in Python:
Complete the function/method (depending on the language) to return `true`/`True` when its argument is an array that has the same nesting structures and same corresponding length of nested arrays as the first array.

For example:

```python
# should return True
same_structure_as([ 1, 1, 1 ], [ 2, 2, 2 ] )
same_structure_as([ 1, [ 1, 1 ] ], [ 2, [ 2, 2 ] ] )

# should return False
same_structure_as([ 1, [ 1, 1 ] ], [ [ 2, 2 ], 2 ] )
same_structure_as([ 1, [ 1, 1 ] ], [ [ 2 ], 2 ] )

# should return True
same_structure_as([ [ [ ], [ ] ] ], [ [ [ ], [ ] ] ] )

# should return False
same_structure_as([ [ [ ], [ ] ] ], [ [ 1, 1 ] ] )
```

~~~if:javascript
For your convenience, there is already a function 'isArray(o)' declared and defined that returns true if its argument is an array, false otherwise.
~~~

~~~if:php
You may assume that all arrays passed in will be non-associative.
~~~

def islist(A):
    return isinstance(A, list)
def same_structure_as(original,other):
    if islist(original) != islist(other):
        return False
    elif islist(original):
        if len(original) != len(other):
            return False
        for i in range(len(original)):
            if not same_structure_as(original[i], other[i]):
                return False
        return True
    else:
        return True


Solve in Python:
Complete the function/method so that it returns the url with anything after the anchor (`#`) removed.

## Examples

```python
# returns 'www.codewars.com'
remove_url_anchor('www.codewars.com#about')

# returns 'www.codewars.com?page=1'
remove_url_anchor('www.codewars.com?page=1')
```

def remove_url_anchor(url):
    c=""
    for ch in url:
        if ch== "#":
            break
        c+=ch
    return c


Solve in Python:
Complete the function/method so that it takes CamelCase string and returns the string in snake_case notation. Lowercase characters can be numbers. If method gets number, it should return string.

Examples:

``` javascript
//  returns test_controller
toUnderscore('TestController');

// returns movies_and_books
toUnderscore('MoviesAndBooks');

// returns app7_test
toUnderscore('App7Test');

// returns "1"
toUnderscore(1);
```

``` coffeescript
#  returns test_controller
toUnderscore 'TestController'

# returns movies_and_books
toUnderscore 'MoviesAndBooks'

# returns app7_test
toUnderscore 'App7Test'

# returns "1"
toUnderscore 1
```

def to_underscore(string):
    string = str(string)
    camel_case = string[0].lower()
    for c in string[1:]:
        camel_case += '_{}'.format(c.lower()) if c.isupper() else c
    return camel_case


Solve in Python:
Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted string. Empty string values should be ignored. Empty arrays or null/nil values being passed into the method should result in an empty string being returned.

```Python
format_words(['ninja', 'samurai', 'ronin']) # should return "ninja, samurai and ronin"
format_words(['ninja', '', 'ronin']) # should return "ninja and ronin"
format_words([]) # should return ""
```
```Haskell
formatWords ["ninja", "samurai", "ronin"] -- should return "ninja, samurai and ronin"
formatWords ["ninja", "", "ronin"] -- should return "ninja and ronin"
formatWords [] -- should return ""
```

def format_words(words):
    return ', '.join(word for word in words if word)[::-1].replace(',', 'dna ', 1)[::-1] if words else ''


Solve in Python:
Complete the method that takes a boolean value and return a `"Yes"` string for `true`, or a `"No"` string for `false`.

def bool_to_word(boolean):
    n = "No"
    if boolean == True:
        n = "Yes"
    return n


Solve in Python:
Complete the method that takes a sequence of objects with two keys each: country or state, and capital. Keys may be symbols or strings.

The method should return an array of sentences declaring the state or country and its capital.

## Examples

```python
[{'state': 'Maine', 'capital': 'Augusta'}] --> ["The capital of Maine is Augusta"]
[{'country' : 'Spain', 'capital' : 'Madrid'}] --> ["The capital of Spain is Madrid"]
[{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}] --> ["The capital of Maine is Augusta", "The capital of Spain is Madrid"]
```

def capital(capitals):
    output = []

    i = 0
    for key1, key2 in capitals:
        if key1 == "country":
            output.append(
                f"The capital of {capitals[i]['country']} is {capitals[i]['capital']}")
        if key1 == "state":
            output.append(
                f"The capital of {capitals[i]['state']} is {capitals[i]['capital']}")
        i += 1
    return output


Solve in Python:
Complete the method which accepts an array of integers, and returns one of the following:

* `"yes, ascending"` - if the numbers in the array are sorted in an ascending order
* `"yes, descending"` - if the numbers in the array are sorted in a descending order
* `"no"` - otherwise

You can assume the array will always be valid, and there will always be one correct answer.

def is_sorted_and_how(arr):
    if arr[0]>arr[1]:
        try:
            if arr[1]<arr[2]:
                return 'no'
        except:
            pass
        return "yes, descending"
    elif arr[0]<arr[1] :
        try:
            if arr[1]>arr[2]:
                return 'no'
        except:
            pass
        return "yes, ascending"
    return 'no'


Solve in Python:
Complete the method which returns the number which is most frequent in the given input array. If there is a tie for most frequent number, return the largest number among them.

Note: no empty arrays will be given.

## Examples

```
[12, 10, 8, 12, 7, 6, 4, 10, 12]              -->  12
[12, 10, 8, 12, 7, 6, 4, 10, 12, 10]          -->  12
[12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10]  -->   3
```

from collections import Counter

def highest_rank(arr):
    return max(Counter(arr).items(), key=lambda x: [x[1], x[0]])[0]


Solve in Python:
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized **only** if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).

## Examples

```python
to_camel_case("the-stealth-warrior") # returns "theStealthWarrior"

to_camel_case("The_Stealth_Warrior") # returns "TheStealthWarrior"
```

def to_camel_case(text):
    return text[0] + ''.join([w[0].upper() + w[1:] for w in text.replace("_", "-").split("-")])[1:] if text else ''


Solve in Python:
Complete the solution so that it returns a formatted string. The return value should equal "Value is VALUE"  where value is a 5 digit padded number.

Example:

```python
solution(5)  # should return "Value is 00005"
```

def solution(value):
    return "Value is %05d" % value


Solve in Python:
Complete the solution so that it returns the number of times the search_text is found within the full_text.

```python
search_substr( fullText, searchText, allowOverlap = true )
```

so that overlapping solutions are (not) counted. If the searchText is empty, it should return `0`. Usage examples:

```python
search_substr('aa_bb_cc_dd_bb_e', 'bb') # should return 2 since bb shows up twice
search_substr('aaabbbcccc', 'bbb') # should return 1
search_substr( 'aaa', 'aa' ) # should return 2
search_substr( 'aaa', '' ) # should return 0
search_substr( 'aaa', 'aa', false ) # should return 1
```

def search_substr(full_text, search_text, allow_overlap=True):
    if search_text == '':
        return 0
    if allow_overlap:
        return len([1 for i in range(len(full_text)) if full_text.startswith(search_text, i)])
    return full_text.count(search_text)


Solve in Python:
Complete the solution so that it returns the number of times the search_text is found within the full_text.

Usage example:


Solve in Python:
Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function.

The array values passed in will only be strings or numbers. The only valid return values are `true` and `false`.

Examples:
```
solution(1, 2, 3)             -->  false
solution(1, 2, 3, 2)          -->  true
solution('1', '2', '3', '2')  -->  true
```

def solution(*args):
    s = set()
    for x in args:
        if x in s:
            return 1
        s.add(x)
    return 0


Solve in Python:
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).

Examples:

```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```

def solution(string, ending):
    if string[-len(ending):] == ending:
        return True
    elif len(ending) == 0:
        return True
    return False


Solve in Python:
Complete the solution so that it reverses all of the words within the string passed in.

Example:

```python
reverseWords("The greatest victory is that which requires no battle")
// should return "battle no requires which that is victory greatest The"
```

def reverseWords(s):
    result = ""
    orded = s.split(" ")
    i = len(orded)
    while i > 0:
        result += orded[i-1]
        if i > 1:
            result += " "
        i-=1
    return result


Solve in Python:
Complete the solution so that it reverses the string passed into it.

```
'world'  =>  'dlrow'
```

def solution(string):
    word=''
    for letter in reversed(string):
        word+=letter
    return word


Solve in Python:
Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.

**Example:**

Given an input string of:
```
apples, pears # and bananas
grapes
bananas !apples
```

The output expected would be:
```
apples, pears
grapes
bananas
```

The code would be called like so:

```python
result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
# result should == "apples, pears\ngrapes\nbananas"

```

from re import sub
def solution(string,markers):
    return sub("(.*?) ?([\%s].*)" % "\\".join(markers),"\g<1>",string) if markers else string


Solve in Python:
Complete the solution so that it takes the object (JavaScript/CoffeeScript) or hash (ruby) passed in and generates a human readable string from its key/value pairs.

The format should be "KEY = VALUE". Each key/value pair should be separated by a comma except for the last pair.

**Example:**
```python
solution({"a": 1, "b": '2'}) # should return "a = 1,b = 2"
```

def solution(pairs):
    return ','.join('{} = {}'.format(k, v) for k,v in sorted(pairs.items()))


Solve in Python:
Complete the solution so that the function will break up camel casing, using a space between words.

### Example

```
solution("camelCasing")  ==  "camel Casing"
```

def solution(s):
    final_string = ""
    for i in range(len(s)):
        char = s[i]
        if char.isupper():
            final_string += " " + char
        else:
            final_string += char
    return final_string


Solve in Python:
Complete the solution. It should try to retrieve the value of the array at the index provided. If the index is out of the array's max bounds then it should return the default value instead.

Example:
```Haskell
solution [1..3] 1 1000 `shouldBe` 2
solution [1..5] (10) 1000 `shouldBe` 1000
-- negative values work as long as they are not out of the length bounds
solution [1..3] (-1) 1000 `shouldBe` 3
solution [1..3] (-5) 1000 `shouldBe` 1000
solution [1..3] (-3) 1000 `shouldBe` 1
solution [1..5] (-3) 1000 `shouldBe` 3
-- for Haskell default value will always be a (random) number, not a character.
```

```python
data = ['a', 'b', 'c']
solution(data, 1, 'd') # should == 'b'
solution(data, 5, 'd') # should == 'd'

# negative values work as long as they aren't out of the length bounds
solution(data, -1, 'd') # should == 'c'
solution(data, -5, 'd') # should == 'd'
```

def solution(items, index, default_value):
    try:
        return items[index]
    except IndexError:
        return default_value


Solve in Python:
Complete the square sum function so that it squares each number passed into it and then sums the results together.

For example, for `[1, 2, 2]` it should return `9` because `1^2 + 2^2 + 2^2 = 9`.

```if:racket
In Racket, use a list instead of an array, so '(1 2 3) should return 9.
```

def square_sum(x):
    L=[]
    for i in x:
        L.append(i**2)
    return sum(L)


Solve in Python:
Comprised of a team of five incredibly brilliant women, "The ladies of ENIAC" were the first “computors” working at the University of Pennsylvania’s Moore School of Engineering (1945). Through their contributions, we gained the first software application and the first programming classes! The ladies of ENIAC were inducted into the WITI Hall of Fame in 1997!

Write a function which reveals "The ladies of ENIAC" names, so that you too can add them to your own hall of tech fame!

To keep: only alpha characters, space characters and exclamation marks.
To remove: numbers and these characters: ```%$&/£?@```

Result should be all in uppercase.

from string import ascii_uppercase

VALID = set(ascii_uppercase + ' !')

def rad_ladies(name):
    return ''.join(a for a in name.upper() if a in VALID)


Solve in Python:
Computation of the date either previous or forthcoming dates is quiet easy. But it is quiet difficult to calculate the day from a particular given date.
You are required to find a day from a particular date given to you.

-----Input-----
It consists of a single line entry consisting of date in format dd mm yyyy.
i.e. the input line consists of the three numbers written in order followed by spaces.
Eg. Input for 18-12-1990 is be written as 18 12 1990

-----Output-----
It consists of single line output showing the day for that particular date.

-----Example-----
Input:
14 3 2012

Output:
Wednesday

import sys
from datetime import date

def main():
 s = sys.stdin.readline
 dateis = list(map(int, s().strip().split()))
 day = dateis[0]
 month = dateis[1]
 year = dateis[2]
 ans = date(year, month, day).weekday()
 if ans == 0:
  print("Monday")
 elif ans == 1:
  print("Tuesday")
 elif ans == 2:
  print("Wednesday")
 elif ans == 3:
  print("Thursday")
 elif ans == 4:
  print("Friday")
 elif ans == 5:
  print("Saturday")
 else:
  print("Sunday")

def __starting_point():
 main()

__starting_point()


Solve in Python:
Congratulations !!! You have successfully completed the heist by looting all the gifts in Santa's locker. Now it's time to decide who gets to take all the gifts, you or the Grinch, there will be no splitting. So you and Grinch decide to play a game.
To start the game, an Integer N will be given. The game is played in turns and for each turn, the player can make any one of the following moves:
- Divide N by any of it's odd divisors greater than 1.
- Subtract 1 from N if N is greater than 1.
Divisor of a number includes the number itself.
The player who is unable to make a move loses the game.
Since you are the mastermind of the heist, you get to play the first move.

-----Input-----
The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The description of the test cases follows.
The only line of each test case contains a single integer — N (1 ≤ N ≤ 109).

-----Output-----
For each test case, print " Me" if you win, and " Grinch" if otherwise (without quotes).

-----Sample Input-----
7
1
2
3
4
5
6
12

-----Sample Output-----
Grinch
Me
Me
Grinch
Me
Grinch
Me

def isprime(n):
    for i in range(2,int(n**(0.5))+1):
        if n%i==0:
            return False
    return True

t=int(input())
while t>0:
    n=int(input())
    x=n & -n

    if n==2:
        print("Me")
    elif (x==2 and isprime(n//x)) or n==1 or x==n :
        print("Grinch")
    else:
        print("Me")
    t-=1


Solve in Python:
Congratulations! That Special Someone has given you their phone number.

But WAIT, is it a valid number?

Your task is to write a function that verifies whether a given string contains a valid British mobile (cell) phone number or not.

If valid, return 'In with a chance'.

If invalid, or if you're given an empty string, return 'Plenty more fish in the sea'.

A number can be valid in the following ways:

Here in the UK mobile numbers begin with '07' followed by 9 other digits, e.g. '07454876120'.

Sometimes the number is preceded by the country code, the prefix '+44', which replaces the '0' in ‘07’, e.g. '+447454876120'.

And sometimes you will find numbers with dashes in-between digits or on either side, e.g. '+44--745---487-6120' or '-074-54-87-61-20-'. As you can see, dashes may be consecutive.

Good Luck Romeo/Juliette!

import re

def validate_number(s):
    for c in '-+': s = s.replace(c, '')
    return 'In with a chance' if re.match(r'^(07|447)\d{9}$', s) else 'Plenty more fish in the sea'


Solve in Python:
Consider X as the  aleatory  variable that count the number of letters in a word. Write a function that, give in input an array of words (strings), calculate the  variance  of X.
Max decimal of the variance : 4.

Some wiki: Variance ,
 Aleatory variable

Example:

Consider "Hello" and "World":

X is { 5 } with P(X = 5) = 1 beacuse the two words has the same length.
So E[X] = 5 x 1 = 5 and the standard formula for variance is E[(X - u)^2] so  1 x (5-5)^2 = 0
or you can calculate with the other formula E[X^2] - E[X]^2 = 5^2 x 1 - 5^2 = 0

Consider "Hi" and "World":

X is { 2, 5 } with P(X = 5) = 1/2 and P(X = 2) = 1/2.
So E[X] = 5 x 1/2 + 2 x 1/2 = 3.5 and the standard formula for variance is E[(X - u)^2] so  1/2 x (2-3.5)^2 + 1/2 x (5 - 3.5)^2 = 2.25
or you can calculate with the other formula E[X^2] - E[X]^2 = (5^2 x 1/2 + 2^2 x 1/2) - 3.5^2 = 2.25

def variance(array):
    nums = list(map(len, array))
    length = float(len(nums))
    average = sum(nums) / length
    return round(sum((average - a) ** 2 for a in nums) / length, 4)


Solve in Python:
Consider a 2d-grid. That is, each cell is identified by (i,j). You have received reports of two snake-sightings on this grid. You want to check whether they could be partial sightings of the same snake or not.
Each of the snake sightings correspond to a straight, axis-parallel line segment in the grid, and the starting and ending cells for each are given to you. Now consider a graph, where each cell in the 2d-grid is a vertex. And there is an edge between 2 vertices if and only if the cells corresponding to these two vertices are consecutive cells in at least one of the two snakes. That is, at least in one of the snakes, when you go from one end point to the other end point, these two cells should occur consecutively.
The two sightings/snakes are said to be same, if both these conditions are satisfied:
- The union of the set of cells in the first snake and the set of cells in the second snake, should form a connected component in this graph.
- No vertex should have degree more than 2 in the graph.
In other words, the induced subgraph on the union set must be a path graph.

-----Input-----
- The first line contains a single integer, T, which is the number of testcases. The description of each testcase follows.
- The first line of each testcase contains four integers: X11, Y11, X12, Y12. This represents the fact that the first snake's end points are (X11, Y11) and (X12, Y12).
- The second line of each testcase contains four integers: X21, Y21, X22, Y22. This represents the fact that the second snake's end points are (X21, Y21) and (X22, Y22).

-----Output-----
- For each testcase, output "yes" if the snakes are the same, as per the definition given above. Output "no" otherwise.

-----Constraints-----
- 1 ≤ T ≤ 105
- -109 ≤ Xij,Yij ≤ 109
- The two end points of every snake is guaranteed to be either on the same row or on the same column. Thus, the snake occupies all the cells between these cells, including the end points.

-----Example-----
Input:
4
2 1 8 1
11 1 7 1
2 1 8 1
11 1 9 1
2 1 8 1
3 1 3 -2
2 1 8 1
2 1...

# cook your dish here
t=int(input())
for _ in range(t):
 x1,y1,x2,y2=map(int,input().split())
 x3,y3,x4,y4=map(int,input().split())
 if (x1==x3 and y1==y3)or(x2==x4 and y2==y4):
  print("yes")
 elif (x1==x4 and y1==y4)or(x2==x3 and y2==y3):
  print("yes")
 else:
  if(y1==y2)and(y1==y3)and(y1==y4):
   a1=max(x1,x2);a2=min(x1,x2)
   b1=max(x3,x4);b2=min(x3,x4)
   if a1>=b2 and a2<=b1:
    print("yes")
   else:
    print("no")
  elif (x1==x2)and(x1==x3)and(x1==x4):
   a1=max(y1,y2);a2=min(y1,y2)
   b1=max(y3,y4);b2=min(y3,y4)
   if a1>=b2 and a2<=b1:
    print("yes")
   else:
    print("no")
  else:
   print("no")


Solve in Python:
Consider a currency system in which there are notes of six denominations, namely, Rs. 1, Rs. 2, Rs. 5, Rs. 10, Rs. 50, Rs. 100.
If the sum of Rs. N is input, write a program to computer smallest number of notes that will combine to give Rs. N.

-----Input-----

The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N.

-----Output-----
For each test case, display the smallest number of notes that will combine to give N, in a new line.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 1000000

-----Example-----
Input
3
1200
500
242

Output
12
5
7

for _ in range(int(input())):
    l=[100,50,10,5,2,1]
    n=int(input())
    c=0
    for i in l:
        if(n>=i):
            r=n/i
            if(type(r)==int):
                print(r)
                break
            else:
                r=int(r)
                c+=r
                n=n-(i*r)
        if(n==0):
            break
    print(c)


Solve in Python:
Consider a directed graph, with nodes labelled 0, 1, ..., n-1.  In this graph, each edge is either red or blue, and there could be self-edges or parallel edges.
Each [i, j] in red_edges denotes a red directed edge from node i to node j.  Similarly, each [i, j] in blue_edges denotes a blue directed edge from node i to node j.
Return an array answer of length n, where each answer[X] is the length of the shortest path from node 0 to node X such that the edge colors alternate along the path (or -1 if such a path doesn't exist).

Example 1:
Input: n = 3, red_edges = [[0,1],[1,2]], blue_edges = []
Output: [0,1,-1]
Example 2:
Input: n = 3, red_edges = [[0,1]], blue_edges = [[2,1]]
Output: [0,1,-1]
Example 3:
Input: n = 3, red_edges = [[1,0]], blue_edges = [[2,1]]
Output: [0,-1,-1]
Example 4:
Input: n = 3, red_edges = [[0,1]], blue_edges = [[1,2]]
Output: [0,1,2]
Example 5:
Input: n = 3, red_edges = [[0,1],[0,2]], blue_edges = [[1,0]]
Output: [0,1,1]

Constraints:

1 <= n <= 100
red_edges.length <= 400
blue_edges.length <= 400
red_edges[i].length == blue_edges[i].length == 2
0 <= red_edges[i][j], blue_edges[i][j] < n

from collections import defaultdict, deque
class Solution:
    def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:
        # we can create a directed graph with 1 as red and 0 as blue
        graph = defaultdict(list)
        for to, frm in red_edges:
            graph[to] += [[frm,1]]
        for to, frm in blue_edges:
            graph[to] += [[frm,0]]

        # bfs to find shortest path to each node
        paths = [-1]*n
        visited = set()
        queue = deque()
        queue.append((0, None, 0))

        while queue:
            curr, color, path = queue.popleft()
            if paths[curr] == -1:
                paths[curr] = path

            for v, c in graph[curr]:
                # if we havent visited a specific weighted edge and color is alternating allow it
                if (v, c) not in visited and (color==None or c != color):
                    queue.append((v, c, path+1))
                    visited.add((v, c))
        return paths


Solve in Python:
Consider a game, wherein the player has to guess a target word. All the player knows is the length of the target word.

To help them in their goal, the game will accept guesses, and return the number of letters that are in the correct position.

Write a method that, given the correct word and the player's guess, returns this number.

For example, here's a possible thought process for someone trying to guess the word "dog":

```cs
CountCorrectCharacters("dog", "car"); //0 (No letters are in the correct position)
CountCorrectCharacters("dog", "god"); //1 ("o")
CountCorrectCharacters("dog", "cog"); //2 ("o" and "g")
CountCorrectCharacters("dog", "cod"); //1 ("o")
CountCorrectCharacters("dog", "bog"); //2 ("o" and "g")
CountCorrectCharacters("dog", "dog"); //3 (Correct!)
```
```python
count_correct_characters("dog", "car"); #0 (No letters are in the correct position)
count_correct_characters("dog", "god"); #1 ("o")
count_correct_characters("dog", "cog"); #2 ("o" and "g")
count_correct_characters("dog", "cod"); #1 ("o")
count_correct_characters("dog", "bog"); #2 ("o" and "g")
count_correct_characters("dog", "dog"); #3 (Correct!)
```

The caller should ensure that the guessed word is always the same length as the correct word, but since it could cause problems if this were not the case, you need to check for this eventuality:

```cs
//Throw an InvalidOperationException if the two parameters are of different lengths.
```
```python
#Raise an exception if the two parameters are of different lengths.
```

You may assume, however, that the two parameters will always be in the same case.

def count_correct_characters(a, b):
    return len([i for i in range(len(a)) if a[i]==b[i]]) if len(a)==len(b) else error


Solve in Python:
Consider a number X on which K Mag-Inc operations are to be performed. In a Mag-Inc operation, the number X undergoes an increment of A/B times of X where A and B are two integers.

There is a numerator and a denominator array of size K which contain the ith values of A and B. After K Mag-Inc operations, the number X turns to M.

Now your job is to find what percentage of M is to be decremented from M if it has to be converted back to X. Let this percentage be denoted by Z.

Print the integral part of Z.

-----Input:-----

First line contains an integer T denoting the number of test cases.

First line of every test case contains two space separated integers X and K.

The second and third line of every test case will contain K space separated integers

denoting the Numerator and Denominator array.

-----Output:-----

For each test case, print the required result in a single line.

-----Constraints:-----
1 ≤ T ≤ 100
1 ≤ K, A, B ≤ 40000
1≤X≤10^100

-----Example:-----Input:
2
100 1
1
4
100 2
1 1
2 3Output:
20
50

-----Explanation:-----

Case 2: 100 undergoes an increment of (1/2)*100. Therefore M = 100 + 50.

Now M = 150.

Now again,

M undergoes an increment of (1/3)*150. Therefore, M = 150 + 50.

Now as we want to revert back M = 200 to X i.e. 100, we need to decrement it by a value

of 100 and we know that 100 is 50% of 200.

Hence, we print 50.

import sys
import math

def solution():
 T = int(input().strip())
 for _ in range(T):
  x, k = list(map(float, input().strip().split(' ')))
  original_x = x
  if k == 1:
   a = [float(input().strip())]
   b = [float(input().strip())]
  else:
   a = list(map(float, input().strip().split(' ')))
   b = list(map(float, input().strip().split(' ')))
  for i in range(int(k)):
   x = x + (a[i]/b[i])*(x)
  percentage = ((x - original_x) / x)*100
  print("%d"%(int(percentage)))

solution()


Solve in Python:
Consider a pyramid made up of blocks. Each layer of the pyramid is a rectangle of blocks, and the dimensions of these rectangles increment as you descend the pyramid. So, if a layer is a `3x6` rectangle of blocks, then the next layer will be a `4x7` rectangle of blocks. A `1x10` layer will be on top of a `2x11` layer on top of a `3x12` layer, and so on.

## Task

Given the dimensions of a pyramid's topmost layer `w,l`, and its height `h` (aka the number of layers), return the total number of blocks in the pyramid.

## Examples

`num_blocks(1, 1, 2)` will return `5`. This pyramid starts with a `1x1` layer and has 2 layers total. So, there is 1 block in the first layer, and `2x2=4` blocks in the second. Thus, 5 is the total number of blocks.

`num_blocks(2, 4, 3)` will return `47`. This pyramid has 3 layers: `2x4`, `3x5`, and `4x6`. So, there are `47` blocks total.

## Notes

All parameters will always be postive nonzero integers.

Efficiency is important. There will be:

* 100 'small' cases with `w`, `l`, and `h` below `20`.
* 100 'big' cases with `w`, `l`, and `h` between `1e9` and `1e10`.


Solve in Python:
Consider a sequence [a_1, a_2, ... , a_{n}]. Define its prefix product sequence $[ a_{1} \operatorname{mod} n,(a_{1} a_{2}) \operatorname{mod} n, \cdots,(a_{1} a_{2} \cdots a_{n}) \operatorname{mod} n ]$.

Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].

-----Input-----

The only input line contains an integer n (1 ≤ n ≤ 10^5).

-----Output-----

In the first output line, print "YES" if such sequence exists, or print "NO" if no such sequence exists.

If any solution exists, you should output n more lines. i-th line contains only an integer a_{i}. The elements of the sequence should be different positive integers no larger than n.

If there are multiple solutions, you are allowed to print any of them.

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

Output
YES
1
4
3
6
5
2
7

Input
6

Output
NO

-----Note-----

For the second sample, there are no valid sequences.

def comp(x):
    for i in range(2, x):
        if x % i == 0:
            return True
    return False

N = int(input())

if N == 4:
    print('YES', '1', '3', '2', '4', sep = '\n')
elif comp(N):
    print('NO')
else:
    print('YES', '1', sep = '\n')
    if N > 1:
        for i in range(2, N):
            print((i - 1) * pow(i, N - 2, N) % N)
        print(N)


Solve in Python:
Consider a sequence `u` where u is defined as follows:

1. The number `u(0) = 1` is the first one in `u`.
2. For each `x` in `u`, then `y = 2 * x + 1` and `z = 3 * x + 1` must be in `u` too.
3. There are no other numbers in `u`.

Ex:
`u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]`

1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on...

## Task:
Given parameter `n` the function `dbl_linear` (or dblLinear...) returns the element `u(n)` of
the ordered (with <) sequence `u` (so, there are no duplicates).

## Example:
`dbl_linear(10) should return 22`

## Note:
Focus attention on efficiency

# This is a Python implementation of the excellent algorithm user g964 wrote in C. Credit goes to him/her.

def dbl_linear(n):
    arr = [1]
    xi = yi = 0

    for i in range(n):
        x,y = arr[xi]*2+1, arr[yi]*3+1
        arr.append( min(x,y) )
        if min(x,y) == x:
            xi += 1
        if min(x,y) == y:
            yi += 1
    return arr[n]


Solve in Python:
Consider a sequence generation that follows the following steps. We will store removed values in variable `res`. Assume `n = 25`:
```Haskell
-> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] Let's remove the first number => res = [1]. We get..
-> [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]. Let's remove 2 (so res = [1,2]) and every 2-indexed number. We get..
-> [3,5,7,9,11,13,15,17,19,21,23,25]. Now remove 3, then every 3-indexed number. res = [1,2,3].
-> [5,7,11,13,17,19,23,25]. Now remove 5, and every 5-indexed number. res = [1,2,3,5]. We get..
-> [7,11,13,17,23,25]. Now remove 7 and every 7-indexed. res = [1,2,3,5,7].
But we know that there are no other 7-indexed elements, so we include all remaining numbers in res. So res = [1,2,3,5,7,11,13,17,23,25] and sum(res) = 107.

Note that when we remove every n-indexed number, we must remember that indices start at 0. So for every 3-indexed number above:
[3,5,7,9,11,13,15,17,19,21,23], we remove index0=3, index3= 9, index6=15,index9=21, etc.

Note also that if the length of sequence is greater than x, where x is the first element of the sequence, you should continue the remove step: remove x, and every x-indexed number until the length of sequence is shorter than x. In our example above, we stopped at 7 because the the length of the remaining sequence [7,11,13,17,23,25] is shorter than 7.
```
You will be given a number `n` and your task will be to return the sum of the elements in res, where the maximum element in res is `<= n`.

For example:

```Python
Solve(7) = 18, because this is the sum of res = [1,2,3,5,7].
Solve(25) = 107
```

More examples in the test cases.

Good luck!

def solve(n):
    arr = [i+1 for i in range(n)]
    arr2 = list()

    while len(arr) >= 1 :
        arr2.append(arr[0])
        del arr[0]
        for j in range(1, n) :
            if arr2[-1] == 1 or (arr2[-1]*j)-j >= len(arr) :
                break
            else :
                del arr[(arr2[-1]*j)-j]
    sum = 0
    for i in arr2 :
        sum += int(i)
    return sum


Solve in Python:
Consider a sequence made up of the consecutive prime numbers. This infinite sequence would start with:
```python
"2357111317192329313741434753596167717379..."
```

You will be given two numbers: `a` and `b`, and your task will be to return `b` elements starting from index `a` in this sequence.
```
For example:
solve(10,5) == `19232` Because these are 5 elements from index 10 in the sequence.
```

Tests go up to about index `20000`.

More examples in test cases. Good luck!

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

def solve(a, b):
    """creates sequence of prime numbers
    up to at least a + b
    returns string of b elements from index a
    """
    prime_seq = ''
    for prime in gen_primes():
        if len(prime_seq) > (a + b):
            break
        prime_seq += str(prime)
    print(prime_seq)
    return prime_seq[a:a+b]

def gen_primes():
    """
    generate indefinite sequence of prime numbers
    implementing Erastothenes' Sieve
    returns generator object
    """
    D = {}
    p = 2  # running integer
    while True:
        if p not in D:
            yield p
            D[p * p] = [p]
        else:
            for q in D[p]:
                D.setdefault(p + q, []).append(q)
            del D[p]
        p += 1


Solve in Python:
Consider a sequence, which is formed by the following rule: next term is taken as the smallest possible non-negative integer, which is not yet in the sequence, so that `no 3` terms of sequence form an arithmetic progression.

## Example

`f(0) = 0` -- smallest non-negative
`f(1) = 1` -- smallest non-negative, which is not yet in the sequence
`f(2) = 3` -- since `0, 1, 2` form an arithmetic progression
`f(3) = 4` -- neither of `0, 1, 4`, `0, 3, 4`, `1, 3, 4` form an arithmetic progression, so we can take smallest non-negative, which is larger than `3`
`f(4) = 9` --  `5, 6, 7, 8` are not good, since `1, 3, 5`, `0, 3, 6`, `1, 4, 7`, `0, 4, 8` are all valid arithmetic progressions.

etc...

## The task

Write a function `f(n)`, which returns the `n-th` member of sequence.

## Limitations

There are `1000` random tests with `0 <= n <= 10^9`, so you should consider algorithmic complexity of your solution.


Solve in Python:
Consider a tree $T$ (that is, a connected graph without cycles) with $n$ vertices labelled $1$ through $n$. We start the following process with $T$: while $T$ has more than one vertex, do the following:

 choose a random edge of $T$ equiprobably;

 shrink the chosen edge: if the edge was connecting vertices $v$ and $u$, erase both $v$ and $u$ and create a new vertex adjacent to all vertices previously adjacent to either $v$ or $u$. The new vertex is labelled either $v$ or $u$ equiprobably.

At the end of the process, $T$ consists of a single vertex labelled with one of the numbers $1, \ldots, n$. For each of the numbers, what is the probability of this number becoming the label of the final vertex?

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 50$).

The following $n - 1$ lines describe the tree edges. Each of these lines contains two integers $u_i, v_i$ — labels of vertices connected by the respective edge ($1 \leq u_i, v_i \leq n$, $u_i \neq v_i$). It is guaranteed that the given graph is a tree.

-----Output-----

Print $n$ floating numbers — the desired probabilities for labels $1, \ldots, n$ respectively. All numbers should be correct up to $10^{-6}$ relative or absolute precision.

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

Output
0.1250000000
0.2916666667
0.2916666667
0.2916666667

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

Output
0.0850694444
0.0664062500
0.0664062500
0.1955295139
0.1955295139
0.1955295139
0.1955295139

-----Note-----

In the first sample, the resulting vertex has label 1 if and only if for all three edges the label 1 survives, hence the probability is $1/2^3 = 1/8$. All other labels have equal probability due to symmetry, hence each of them has probability $(1 - 1/8) / 3 = 7/24$.

maxn=50+10
g=[None]*maxn
dp=[None]*maxn
c=[None]*maxn
size=[0]*maxn

for i in range(0,maxn):
    c[i]=[0]*maxn
    c[i][0]=1
    for j in range(1,i+1):
        c[i][j]=c[i-1][j-1]+c[i-1][j]

n=int(input())
for i in range(1,n+1):
    g[i]=[]
for i in range(1,n):
    u,v=input().split()
    u=int(u)
    v=int(v)
    g[u].append(v)
    g[v].append(u)

def mul(a,b,x,y):
    tmp=[0]*(x+y+1)
    for i in range(0,x+1):
        for j in range(0,y+1):
            tmp[i+j]+=a[i]*b[j]*c[i+j][i]*c[x+y-i-j][x-i]
    return tmp
def dfs(pos,fa):
    nonlocal dp
    nonlocal size
    dp[pos]=[1]
    size[pos]=0
    for ch in g[pos]:
        if ch != fa:
            dfs(pos=ch,fa=pos)
            dp[pos]=mul(dp[pos],dp[ch],size[pos],size[ch])
            size[pos]+=size[ch]
    if fa:
        size[pos]+=1
        tmp=[0]*(size[pos]+1)
        for i in range(0,size[pos]+1):
            for j in range(0,size[pos]):
                if j<i:
                    tmp[i]+=dp[pos][i-1]
                else:
                    tmp[i]+=dp[pos][j]*0.5
        dp[pos]=tmp

for i in range(1,n+1):
    dfs(pos=i,fa=0)
    tmp=dp[i][0]
    for j in range(1,n):
        tmp/=j
    print(tmp)


Solve in Python:
Consider all binary strings of length $m$ ($1 \le m \le 60$). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly $2^m$ such strings in total.

The string $s$ is lexicographically smaller than the string $t$ (both have the same length $m$) if in the first position $i$ from the left in which they differ, we have $s[i] < t[i]$. This is exactly the way strings are compared in dictionaries and in most modern programming languages when comparing them in a standard way. For example, the string 01011 is lexicographically smaller than the string 01100, because the first two characters are the same, and the third character in the first string is less than that in the second.

We remove from this set $n$ ($1 \le n \le \min(2^m-1, 100)$) distinct binary strings $a_1, a_2, \ldots, a_n$, each of length $m$. Thus, the set will have $k=2^m-n$ strings. Sort all strings of the resulting set in lexicographical ascending order (as in the dictionary).

We number all the strings after sorting from $0$ to $k-1$. Print the string whose index is $\lfloor \frac{k-1}{2} \rfloor$ (such an element is called median), where $\lfloor x \rfloor$ is the rounding of the number down to the nearest integer.

For example, if $n=3$, $m=3$ and $a=[$010, 111, 001$]$, then after removing the strings $a_i$ and sorting, the result will take the form: $[$000, 011, 100, 101, 110$]$. Thus, the desired median is 100.

-----Input-----

The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases. Then, $t$ test cases follow.

The first line of each test case contains integers $n$ ($1 \le n \le \min(2^m-1, 100)$) and $m$ ($1 \le m \le 60$), where $n$ is the number of strings to remove, and $m$ is the length of binary strings. The next $n$ lines contain $a_1, a_2, \ldots, a_n$ — distinct binary strings of length $m$.

The total length of all given binary strings in all test cases in one test does not exceed...

def main():
    for t in range(int(input())):
        n, m = map(int, input().split())
        l = []
        for i in range(n):
            l.append((int(input(), 2)))

        l.sort()
        median = (2 ** m - n - 1) // 2
        # print(l)
        # print(median)
        for i in l:
            if i <= median:
                median += 1
            # print(median)
        while median in l:
            median += 1

        ans = bin(median)[2:]
        temp = ''
        for i in range(len(ans), m):
            temp += '0'
        print(temp + ans)

main()


Solve in Python:
Consider an array containing cats and dogs. Each dog can catch only one cat, but cannot catch a cat that is more than `n` elements away. Your task will be to return the maximum number of cats that can be caught.

For example:
```Haskell
solve(['D','C','C','D','C'], 2) = 2, because the dog at index 0 (D0) catches C1 and D3 catches C4.
solve(['C','C','D','D','C','D'], 2) = 3, because D2 catches C0, D3 catches C1 and D5 catches C4.
solve(['C','C','D','D','C','D'], 1) = 2, because D2 catches C1, D3 catches C4. C0 cannot be caught because n == 1.
solve(['D','C','D','D','C'], 1) = 2, too many dogs, so all cats get caught!
```

Do not modify the input array.

More examples in the test cases. Good luck!

def solve(arr,n):
    c,l = 0,len(arr)
    for i in range(l):
        if arr[i] == 'C':
            a = max(0,i-n)
            b = min(l-1,i+n)
            for j in range(a,b+1):
                if arr[j] == 'D':
                    arr[j] = 'd'
                    c += 1
                    break
    return c


Solve in Python:
Consider an array that has no prime numbers, and none of its elements has any prime digit. It would start with: `[1,4,6,8,9,10,14,16,18,..]`.

`12` and `15` are not in the list because `2` and `5` are primes.

You will be given an integer `n` and your task will be return the number at that index in the array.
For example:
```
solve(0) = 1
solve(2) = 6
```

More examples in the test cases.

Good luck!

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

from itertools import compress
def sieve(n):
    n += 1
    r = [False,True] * (n//2) + [True]
    r[1] = False
    r[2] = True
    for i in range(3,int(n**.5)+1,2):
        if r[i]:
            r[i*i::2*i] = [False] * ((n+2*i-1-i*i)//(2*i))
    r = list(compress(range(len(r)),r))
    if r[-1] %2 == 0:
        return r[:-1]
    return r

primes = set(sieve(10**6))
res = []
factors = {'2','3','5','7'}
for i in range(1,10**6):
    if i not in primes and set(str(i)).isdisjoint(factors):
        res.append(i)

def solve(n):
    return res[n]


Solve in Python:
Consider an infinite full binary tree (each node has two children except the leaf nodes) defined as follows. For a node labelled v its left child will be labelled 2*v and its right child will be labelled 2*v+1. The root is labelled as 1.
You are given N queries of the form i j. For each query, you have to print the length of the shortest path between node labelled i and  node labelled j.

-----Input-----
First line contains N, the number of queries. Each query consists of two space separated integers i and j in one line.

-----Output-----
For each query, print the required answer in one line.

-----Constraints-----
- 1 ≤ N ≤ 105
- 1 ≤ i,j ≤ 109

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

Output:
1
2
3

-----Explanation-----
For first query, 1 is directly connected to 2 by an edge. Hence distance 1.

n = int(input())
for j in range(n):
 a,b = list(map(int, input().split()))
 d = 0
 while a!=b:
  if a>b:
   a/=2
   d+=1
  else:
   b/=2
   d+=1
 print(d)


Solve in Python:
Consider having a cow that gives a child every year from her fourth year of life on and all her subsequent children do the same.

After n years how many cows will you have?
Return null if n is not an integer.

Note: Assume all the cows are alive after n years.

from functools import lru_cache

@lru_cache(maxsize=None)
def f(n):
    if n < 3:
        return 1
    return f(n-3) + f(n-1)

def count_cows(n):
    if not isinstance(n, int):
        return None
    return f(n)


Solve in Python:
Consider integer coordinates x, y in the Cartesian plan and three functions f, g, h
defined by:
```
f: 1 <= x <= n, 1 <= y <= n --> f(x, y) = min(x, y)
g: 1 <= x <= n, 1 <= y <= n --> g(x, y) = max(x, y)
h: 1 <= x <= n, 1 <= y <= n --> h(x, y) = x + y
```
where n is a given integer (n >= 1, guaranteed) and x, y are integers.

In the table below you can see the value of the function f with n = 6.

  ---|*0* |*1*|*2*|*3*|*4*|*5*|*6*|
  -- |--|--|--|--|--|--|--|
  *6*|- |1 |2 |3 |4 |5 |6 |
  *5*|- |1 |2 |3 |4 |5 |5 |
  *4*|- |1 |2 |3 |4 |4 |4 |
  *3*|- |1 |2 |3 |3 |3 |3 |
  *2*|- |1 |2 |2 |2 |2 |2 |
  *1*|- |1 |1 |1 |1 |1 |1 |
  *0*|- |- |- |- |- |- |- |

The task is to calculate the sum of f(x, y), g(x, y) and h(x, y) for all integers x and y such that (1 <= x <= n, 1 <= y <= n).

The function sumin (sum of f) will take n as a parameter and return the sum of min(x, y) in the domain 1 <= x <= n, 1 <= y <= n.
The function sumax (sum of g) will take n as a parameter and return the sum of max(x, y) in the same domain.
The function sumsum (sum of h) will take n as a parameter and return the sum of x + y in the same domain.

#Examples:
```
sumin(6) --> 91
sumin(45) --> 31395
sumin(999) --> 332833500
sumin(5000) --> 41679167500

sumax(6) --> 161
sumax(45) --> 61755
sumax(999) --> 665167500
sumax(5000) --> 83345832500

sumsum(6) --> 252
sumsum(45) --> 93150
sumsum(999) --> 998001000
sumsum(5000) --> 125025000000
```

#Hint:
1. Try to avoid nested loops
2. Note that h = f + g

def sumin(n):

    lst = [i for i in range(1,n+1)]
    summa = sum(lst)
    delta = summa
    for x in lst:
        delta -=x
        summa+=delta
    return summa

def sumax(n):
    lst = [i for i in range(1,n+1)]
    summa = 0
    delta = sum(lst)
    for x in lst:
        summa+=delta
        delta +=x

    return summa

def sumsum(n):
    return sumin(n)+sumax(n)


Solve in Python:
Consider the array `[3,6,9,12]`. If we generate all the combinations with repetition that sum to `12`, we get `5` combinations: `[12], [6,6], [3,9], [3,3,6], [3,3,3,3]`. The length of the sub-arrays (such as `[3,3,3,3]` should be less than or equal to the length of the initial array (`[3,6,9,12]`).

Given an array of positive integers and a number `n`, count all combinations with repetition of integers that sum to `n`. For example:
```Haskell
find([3,6,9,12],12) = 5.
```

More examples in the test cases.

Good luck!

If you like this Kata, please try:

[Array combinations](https://www.codewars.com/kata/59e66e48fc3c499ec5000103)

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

from itertools import combinations_with_replacement as c

def find(arr, n):
    return sum(
        sum(xs) == n
        for i in range(len(arr))
        for xs in c(arr, i + 1)
    )


Solve in Python:
Consider the following $4 \times 4$ pattern:
1  2  4  7
3  5  8 11
6  9 12 14
10 13 15 16

You are given an integer $N$. Print the $N \times N$ pattern of the same kind (containing integers $1$ through $N^2$).

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single integer $N$.

-----Output-----
For each test case, print $N$ lines; each of them should contain $N$ space-separated integers.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 100$

-----Subtasks-----
Subtask #1 (100 points): Original constraints

-----Example Input-----
1
4

-----Example Output-----
1 2 4 7
3 5 8 11
6 9 12 14
10 13 15 16

-----Explanation-----

# cook your dish here
try:
 for i in range(int(input())):
  n=int(input())
  a=[[0 for i in range(n)] for j in range(n)]
  p=1
  for k in range(n):
   j=k
   i=0
   while(j>=0):
    a[i][j]=p
    p=p+1
    i=i+1
    j=j-1
  for k in range(1,n,1):
   i=k
   j=n-1
   f=k
   while(j>=f):
    a[i][j]=p
    p=p+1
    i=i+1
    j=j-1
  for i in range(n):
   for j in range(n):
    print(a[i][j],end=" ")
   print("\n")
except:
 pass


Solve in Python:
Consider the following algorithm
order(arr, i) {
if length(arr) <= 1 {
return arr
}
l = []
r = []
n = length(arr) - 1
for j in 0, 1, ..., n {
if ( (arr[j] modulo power(2,i+1))  < power(2,i) ) {
append arr[j] to l
}else{
append arr[j] to r
}
}
l = order(l, i + 1)
r = order(r, i + 1)
c = concatenate(l, r)
return c
}

Note that $concatenate(l, r)$ returns an array which is the array $l$, followed by the array $r$. Similarly $power(x,y)$ returns $x^y$.
Let $a$ be the array $a_0,a_1,a_2,a_3, \ldots,a_n$ where $a_j = j$ for each index $j$ and the last index $n = (2^p-1)$ for a fixed integer parameter $p$.  Given an integer $p$ and an index $idx$, your task is calculate the element at index $idx$ in the array returned by executing $order(a, 0)$.
For example, suppose $ p = 3$ and $idx = 3$.
- The initial array is $a = [0, 1, 2, 3, 4, 5, 6, 7]$.
- Executing $order(a, 0)$ first creates two new arrays $l == [0, 2, 4, 6]$ and $r == [1, 3, 5, 7]$.
- Next, $order(l, 1)$ and $order(r, 1)$ are executed.
- $order(l, 1)$, in turn, executes $order([0, 4], 2)$ and $order([2, 6], 2)$ which return $[0, 4]$ and $[2, 6]$, respectively. These are then concatenated, so $order(l, 1)$ returns $[0, 4, 2, 6]$.
- Similarly, $order(r, 1)$ returns $[1, 5, 3, 7]$.
- These two are concatenated as the final result, so the array returned by $order(a, 0)$ is $[0, 4, 2, 6, 1, 5, 3, 7]$.
So, if the input is $p = 3$, and $idx = 3$, the answer is $6$. If $p = 3$ and $idx = 7$, the answer should be $7$.

-----Input Format:-----
- The first line contains a single integer, $T$, which is the number of testcases. The description of each testcase follows.
- Each testcase is described by a single line with two integers: $p$ and $idx$, where $p$ is the parameter that determines the length of the array $a$ and $idx$ is the index at which you have to report the value in the output of $order(a, 0)$.

-----Output Format:-----
- You should print the answer in a new line for each testcase, which should be a single integer, the element at index $idx$ after...

# cook your dish here
for _ in range(int(input())):
 p, i = map(int, input().split())
 p = 1 << (p-1)
 j = 0
 ans = 0
 while p > 0:
  if i >= p:
   ans += 1 << j
   i -= p
  p >>= 1
  j += 1
 print(ans)


Solve in Python:
Consider the following array:

```
[1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 12345678910, 1234567891011...]
```

If we join these blocks of numbers, we come up with an infinite sequence which starts with `112123123412345123456...`. The list is infinite.

You will be given an number (`n`) and your task will be to return the element at that index in the sequence, where `1 ≤ n ≤ 10^18`. Assume the indexes start with `1`, not `0`.  For example:

```
solve(1) = 1, because the first character in the sequence is 1. There is no index 0.
solve(2) = 1, because the second character is also 1.
solve(3) = 2, because the third character is 2.
```

More examples in the test cases. Good luck!

from math import sqrt, ceil, log10
import numpy as np

def getGreatest(n, d, prefix):
    rows = 9 * 10**(d - 1)
    triangle = rows * (d + rows * d) // 2
    l = 0
    r = triangle

    while l < r:
        mid = l + ((r - l) >> 1)
        triangle = mid * prefix + mid * (d + mid * d) // 2
        prevTriangle = (mid-1) * prefix + (mid-1) * (d + (mid-1) * d) // 2
        nextTriangle = (mid+1) * prefix + (mid+1) * (d + (mid+1) * d) // 2

        if triangle >= n:
            if prevTriangle < n:
                return prevTriangle
            else:
                r = mid - 1
        else:
            if nextTriangle >= n:
                return triangle
            else:
                l = mid
    return l * prefix + l * (d + l * d) // 2

def findDiff(n, x):
#print("Xdiff=", x)
    mult = 1
    temp=x/10
    while temp >= 1:
        temp /= 10
        mult *= 10
  #  print("sectionMATT=", calcSeq(mult-1))
    #print("rowMATT=", calcSeq(x-(mult-1)) )
    sLen = x-(mult-1)
    d = round(log10(mult))
   # print("WOW, slen is", sLen)
    prefixes = 0
    for z in range(1,round(d)+1):
        prefixes += (9*z*10**(z-1))
    #    print('PROIFFIXES=',prefixes)
    #print('now N IS THIS ONE? WRONG YET??: NOPE!!!!', n)
    #print("PREFIXED", prefixes)
    d+=1
    #print('D',d)
   # totEX = int((d + d*(sLen)))
  #  ort = d*sLen/2*(1+sLen)
    n -= calcSeq(mult-1)
   # print('ave Len=', int(d + d*(sLen)), d, sLen )
    #print("pewpewpew, totEXSHOULDNT BE TOO BIG=",int(totEX*sLen/2), calcSeq(mult-1))
    temp = getGreatest(n, d, prefixes)
    #print("temp=", temp)
    #print("DDDD=",d)
    #print('theN=', n)

    #print('theN=', n)
   # n -= totC
    #n = int(n/2  + (n - totEX*sLen)/2)#int((int(totEX)*sLen)/2)
    #for _ in range(sLen+1):
    #    n -= int(d*sLen/2)
#    print('theN=', n)
    return n-temp

def calcSeq(current):
    x = np.int64(current*(current+1)/2)
    mult = 10
    temp=np.int64(current)
    while temp > 0:
        temp=current
        temp -= mult-1
        mult *= 10
        if...


Solve in Python:
Consider the following expansion:
```Haskell
solve("3(ab)") = "ababab" -- "ab" repeats 3 times
solve("2(a3(b))" = "abbbabbb" -- "a3(b)" == "abbb" repeats twice.
```

Given a string, return the expansion of that string.

Input will consist of only lowercase letters and numbers (1 to 9) in valid parenthesis. There will be no letters or numbers after the last closing parenthesis.

More examples in test cases.

Good luck!

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

def solve(st):
    st = st.replace('(','').replace(')','')
    i  = len(st)
    while i:
        i -=1
        if st[i].isdigit():
            dg = int(st[i])
            ex = st[i+1:] * dg
            st = st[:i] + ex
            i += dg
    return st


Solve in Python:
Consider the following numbers (where `n!` is `factorial(n)`):
```
u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
...
un = (1 / n!) * (1! + 2! + 3! + ... + n!)
```

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

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

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

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

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

## Hint
You could try to simplify the expression.

def going(n):
    s = 1.0
    for i in range(2, n + 1):
        s = s/i + 1
    return int(s * 1e6) / 1e6