Solve in Python:
Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note i2 = -1 according to the definition.

Example 1:

Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.

Example 2:

Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.

Note:

The input strings will not have extra blank.
The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.

class Solution:
     def complexNumberMultiply(self, a, b):
         """
         :type a: str
         :type b: str
         :rtype: str
         """

         a1 = int(a.split('+')[0])
         a2 = int(a.split('+')[1].replace('i',''))
         b1 = int(b.split('+')[0])
         b2 = int(b.split('+')[1].replace('i',''))

         m1 = a1 * b1 - a2 * b2
         m2 = a1 * b2 + a2 * b1

         return str(m1) + '+' + str(m2) + 'i'


Solve in Python:
Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

class Solution:
     def findTheDifference(self, s, t):
         """
         :type s: str
         :type t: str
         :rtype: str
         """
         sums=sum([ord(i) for i in s]), sum([ord(i) for i in t])
         return chr(sum([ord(i) for i in t])-sum([ord(i) for i in s]))


Solve in Python:
Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

Example 1:

Input: s = "egg", t = "add"
Output: true

Example 2:

Input: s = "foo", t = "bar"
Output: false

Example 3:

Input: s = "paper", t = "title"
Output: true

Note:
You may assume both s and t have the same length.

class Solution:
     def isIsomorphic(self, s1, s2):
         # encode strings
         enc1, enc2 = [], []
         count1, count2 = 0, 0
         dict1, dict2 = dict(), dict()
         for i in range(len(s1)):
             char1, char2 = s1[i], s2[i]
             if char1 in dict1:
                 enc1.append(dict1[char1])
             else:
                 count1 += 1
                 dict1[char1] = count1
                 enc1.append(dict1[char1])
             if char2 in dict2:
                 enc2.append(dict2[char2])
             else:
                 count2 += 1
                 dict2[char2] = count2
                 enc2.append(dict2[char2])
         return enc1 == enc2  # compare encodings


Solve in Python:
Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

class Solution:
     def isAnagram(self, s, t):
         """
         :type s: str
         :type t: str
         :rtype: bool
         """
         def cnt(S):
             c={}
             for i in S:
                 if i in c:
                     c[i] += 1
                 else:
                     c[i] = 1
             return c
         c1 = cnt(s)
         c2 = cnt(t)
         return c2 == c1


Solve in Python:
Given two strings s1 and s2, we want to visualize how different the two strings are.
We will only take into account the *lowercase* letters (a to z).
First let us count the frequency of each *lowercase* letters in s1 and s2.

`s1 = "A aaaa bb c"`

`s2 = "& aaa bbb c d"`

`s1 has 4 'a', 2 'b', 1 'c'`

`s2 has 3 'a', 3 'b', 1 'c', 1 'd'`

So the maximum for 'a' in s1 and s2 is 4 from s1; the maximum for 'b' is 3 from s2.
In the following we will not consider letters when the maximum of their occurrences
is less than or equal to 1.

We can resume the differences between s1 and s2 in the following string:
`"1:aaaa/2:bbb"`
where `1` in `1:aaaa` stands for string s1 and `aaaa` because the maximum for `a` is 4.
In the same manner `2:bbb` stands for string s2 and `bbb` because the maximum for `b` is 3.

The task is to produce a string in which each *lowercase* letters of s1 or s2 appears as many times as
its maximum if this maximum is *strictly greater than 1*; these letters will be prefixed by the
number of the string where they appear with their maximum value and `:`.
If the maximum is in s1 as well as in s2 the prefix is `=:`.

In the result, substrings (a substring is for example 2:nnnnn or 1:hhh; it contains the prefix) will be in decreasing order of their length and when they have the same length sorted in ascending lexicographic order (letters and digits - more precisely sorted by codepoint); the different groups will be separated by '/'. See examples and "Example Tests".

Hopefully other examples can make this clearer.

```
s1 = "my&friend&Paul has heavy hats! &"
s2 = "my friend John has many many friends &"
mix(s1, s2) --> "2:nnnnn/1:aaaa/1:hhh/2:mmm/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss"

s1 = "mmmmm m nnnnn y&friend&Paul has heavy hats! &"
s2 = "my frie n d Joh n has ma n y ma n y frie n ds n&"
mix(s1, s2) --> "1:mmmmmm/=:nnnnnn/1:aaaa/1:hhh/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss"

s1="Are the kids at home? aaaaa fffff"
s2="Yes they are here! aaaaa fffff"
mix(s1, s2) -->...

from collections import Counter

def mix(s1, s2):
    res = []
    c1 = Counter([c for c in s1 if c.islower()])
    c2 = Counter([c for c in s2 if c.islower()])
    for c in c1 | c2:
        if c1[c] > 1 and c1[c] > c2[c]: res += ['1:' + c * c1[c]]
        if c2[c] > 1 and c2[c] > c1[c]: res += ['2:' + c * c2[c]]
        if c1[c] > 1 and c1[c] == c2[c]: res += ['=:' + c * c1[c]]
    return '/'.join(sorted(res, key = lambda a : [-len(a), a]))


Solve in Python:
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.

Example 1:

Input:s1 = "ab" s2 = "eidbaooo"
Output:True
Explanation: s2 contains one permutation of s1 ("ba").

Example 2:

Input:s1= "ab" s2 = "eidboaoo"
Output: False

Note:

The input strings only contain lower case letters.
The length of both given strings is in range [1, 10,000].

class Solution:
     def checkInclusion(self, s1, s2):
         """
         :type s1: str
         :type s2: str
         :rtype: bool
         """
         if len(s2) < len(s1):
             return False
         c1 = [0] * 128
         n = 0
         for i in s1:
             c = ord(i)
             if c1[c] == 0: n += 1
             c1[c] += 1
         for i in range(len(s1)):
             c = ord(s2[i])
             c1[c] -= 1
             if not c1[c]: n -= 1
         if not n: return True
         for i in range(len(s2) - len(s1)):
             c = ord(s2[i])
             if not c1[c]: n += 1
             c1[c] += 1
             c = ord(s2[i + len(s1)])
             c1[c] -= 1
             if not c1[c]:
                 n -= 1
                 if not n: return True
         return False


Solve in Python:
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences.  If multiple answers exist, you may return any of them.
(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)

Example 1:
Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation:
str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.

Note:

1 <= str1.length, str2.length <= 1000
str1 and str2 consist of lowercase English letters.

class Solution:
    def shortestCommonSupersequence(self, s1: str, s2: str) -> str:
        m, n = len(s1), len(s2)
        dp = [[''] * n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if s1[i] == s2[j]:
                    dp[i][j] = dp[i-1][j-1] + s1[i] if i > 0 and j > 0 else s1[i]
                else:
                    if i > 0 and j > 0:
                        dp[i][j] = max(dp[i-1][j], dp[i][j-1], key=lambda x:len(x))
                    elif i > 0:
                        dp[i][j] = dp[i-1][j]
                    elif j > 0:
                        dp[i][j] = dp[i][j-1]
        res, i, j = '', 0, 0
        for ch in dp[-1][-1]:
            while s1[i] != ch:
                res += s1[i]
                i += 1
            while s2[j] != ch:
                res += s2[j]
                j += 1
            res, i, j = res + ch, i + 1, j + 1
        res += s1[i:] + s2[j:]
        return res


Solve in Python:
Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.

If there is no common subsequence, return 0.

Example 1:
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.

Example 2:
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:
Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.

Constraints:

1 <= text1.length <= 1000
1 <= text2.length <= 1000
The input strings consist of lowercase English characters only.

class Solution:
    def lcs(self, s1, s2, m, n):
        if m == 0 or n == 0:
            return 0
        if self.dp[m][n] != -1: return self.dp[m][n]
        if s1[m - 1] == s2[n - 1]:
            self.dp[m][n] = 1 + self.lcs(s1, s2, m - 1, n - 1)
        else:
            self.dp[m][n] = max(self.lcs(s1, s2, m - 1, n), self.lcs(s1, s2, m, n - 1))
        return self.dp[m][n]

    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m = len(text1)
        n = len(text2)
        self.dp = [[-1 for _ in range(n + 1)] for __ in range(m + 1)]
        return self.lcs(text1, text2, m, n)


Solve in Python:
Given two strings, the first being a random string and the second being the same as the first, but with three added characters somewhere in the string (three same characters),

Write a function that returns the added character

### E.g

```
string1 = "hello"
string2 = "aaahello"

// => 'a'
```

The above is just an example; the characters could be anywhere in the string and string2 is actually **shuffled**.

### Another example

```
string1 = "abcde"
string2 = "2db2a2ec"

// => '2'
```

Note that the added character could also exist in the original string

```
string1 = "aabbcc"
string2 = "aacccbbcc"

// => 'c'
```

You can assume that string2 will aways be larger than string1, and there will always be three added characters in string2.

```if:c
Write the function `added_char()` that takes two strings and return the added character as described above.
```

```if:javascript
Write the function `addedChar()` that takes two strings and return the added character as described above.
```

from collections import Counter

def added_char(s1, s2):
    return next((Counter(s2) - Counter(s1)).elements())


Solve in Python:
Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa (in other words s2 can break s1).
A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.

Example 1:
Input: s1 = "abc", s2 = "xya"
Output: true
Explanation: "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc".

Example 2:
Input: s1 = "abe", s2 = "acd"
Output: false
Explanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.

Example 3:
Input: s1 = "leetcodee", s2 = "interview"
Output: true

Constraints:

s1.length == n
s2.length == n
1 <= n <= 10^5
All strings consist of lowercase English letters.

class Solution:
    def checkIfCanBreak(self, s1: str, s2: str) -> bool:
        s1=sorted(s1)
        s2=sorted(s2)

        def check(s1,s2):
            c=0
            n=len(s1)
            for i in range(n):
                if s1[i]>=s2[i]:
                    c=c+1
            return c==n

        return  check(s2,s1)  or check(s1,s2)


Solve in Python:
Given two strings s and t, your goal is to convert s into t in k moves or less.
During the ith (1 <= i <= k) move you can:

Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.
Do nothing.

Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times.
Remember that any index j can be picked at most once.
Return true if it's possible to convert s into t in no more than k moves, otherwise return false.

Example 1:
Input: s = "input", t = "ouput", k = 9
Output: true
Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.

Example 2:
Input: s = "abc", t = "bcd", k = 10
Output: false
Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.

Example 3:
Input: s = "aab", t = "bbb", k = 27
Output: true
Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.

Constraints:

1 <= s.length, t.length <= 10^5
0 <= k <= 10^9
s, t contain only lowercase English letters.

class Solution:
    def canConvertString(self, s: str, t: str, k: int) -> bool:
        if(s==t):
            return True
        if(len(s)!=len(t)):
            return False
        has={}
        for i in range(1,27):
            num=26+i
            if(i<=k):
                has[i]=1
                x=(k-i)//26
                has[i]+=x
        n=len(s)
        print(has)

        count=0
        for i in range(n):
            if(s[i]==t[i]):
                count+=1
                continue
            diff=(ord(t[i])-ord(s[i]))%26

            if(diff in has):
                count+=1
                has[diff]-=1
                if(has[diff]==0):
                    del has[diff]
            else:
                return False
        # print(has2)
        if(count==n):
            return True
        return False


Solve in Python:
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

       Only one letter can be changed at a time
       Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

       Return an empty list if there is no such transformation sequence.
       All words have the same length.
       All words contain only lowercase alphabetic characters.
       You may assume no duplicates in the word list.
       You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output:
[
  ["hit","hot","dot","dog","cog"],
  ["hit","hot","lot","log","cog"]
]

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: []

Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

class Solution:
     def findLadders(self, beginWord, endWord, wordList):
         wordDict = set(wordList)
         if endWord not in wordDict: return []
         wordDict.discard(beginWord)
         front, back = set([beginWord]), set([endWord])
         length = 2
         direction = 1
         parents = collections.defaultdict(set)

         while front:
             next_level = set()
             for word in front:
                 for index in range(len(beginWord)):
                     p1, p2 = word[:index], word[index+1:]
                     for ch in 'abcdefghijklmnopqrstuvwxyz':
                         if word[index] != ch:
                             next_word = p1 + ch + p2
                             if next_word in wordDict:
                                 next_level.add(next_word)
                                 if direction == 1:
                                     parents[next_word].add(word)
                                 else:
                                     parents[word].add(next_word)

             if next_level & back:
                 res = [[endWord]]
                 while res and res[0][0] !=beginWord:
                     res = [[p]+r for r in res for p in parents[r[0]]]
                 return res

             length += 1
             front = next_level
             if len(front) > len(back):
                 direction *= -1
                 front, back = back, front
             wordDict -= front
         return []

         """
         :type beginWord: str
         :type endWord: str
         :type wordList: List[str]
         :rtype: List[List[str]]
         """


Solve in Python:
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

       Only one letter can be changed at a time.
       Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

       Return 0 if there is no such transformation sequence.
       All words have the same length.
       All words contain only lowercase alphabetic characters.
       You may assume no duplicates in the word list.
       You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: 0

Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

class Solution:
     def ladderLength(self, beginWord, endWord, wordList):
         """
         :type beginWord: str
         :type endWord: str
         :type wordList: List[str]
         :rtype: int
         """

         words = set(wordList)
         if endWord not in words:
             return 0

         beginQ, endQ = {beginWord}, {endWord}
         dist = 2
         while beginQ:
             print(('beginQ', beginQ, 'endQ', endQ))
             newq = set()
             for u in beginQ:
                 for i in range(len(u)):
                     for c in 'abcdefghijklmnopqrstuvwxyz':
                         v = u[:i] + c + u[i+1:]
                         if v in words:
                             if v in endQ:
                                 return dist
                             newq.add(v)

             dist += 1
             beginQ = newq
             if len(beginQ) > len(endQ):
                 beginQ, endQ = endQ, beginQ

             words -= beginQ

         return 0


Solve in Python:
Given two words and a letter, return a single word that's a combination of both words, merged at the point where the given letter first appears in each word. The returned word should have the beginning of the first word and the ending of the second, with the dividing letter in the middle. You can assume both words will contain the dividing letter.

## Examples

```python
string_merge("hello", "world", "l")      ==>  "held"
string_merge("coding", "anywhere", "n")  ==>  "codinywhere"
string_merge("jason", "samson", "s")     ==>  "jasamson"
string_merge("wonderful", "people", "e") ==>  "wondeople"
```

def string_merge(str1, str2, l):
    i = str1.find(l)
    j = str2.find(l)
    return str1[:i] + str2[j:]


Solve in Python:
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.

Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".

Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".

Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".

Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".

Note:

1 <= S.length <= 200
1 <= T.length <= 200
S and T only contain lowercase letters and '#' characters.

Follow up:

Can you solve it in O(N) time and O(1) space?

class Solution:
    def backspaceCompare(self, S: str, T: str) -> bool:
        i = len(S) - 1
        j = len(T) - 1

        skip_S = 0
        skip_T = 0

        while i >=0 or j >= 0:
            while i >=0 and (S[i] == '#' or skip_S > 0):
                if S[i] == '#':
                    skip_S += 1
                else:
                    skip_S -= 1
                i -= 1

            while j >=0 and (T[j] == '#' or skip_T > 0):
                if T[j] == '#':
                    skip_T += 1
                else:
                    skip_T -= 1
                j -= 1

            if i < 0 and j < 0:
                return True
            elif i >= 0 and j >= 0:
                if S[i] == T[j]:
                    i -= 1
                    j -= 1
                else:
                    return False
            elif i >=0 or j >=0:
                return False
        return True


Solve in Python:
Given: an array containing hashes of names

Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.

Example:

``` ruby
list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'

list([ {name: 'Bart'}, {name: 'Lisa'} ])
# returns 'Bart & Lisa'

list([ {name: 'Bart'} ])
# returns 'Bart'

list([])
# returns ''
```
``` elixir
list([ %{name: "Bart"}, %{name: "Lisa"}, %{name: "Maggie"} ])
# returns 'Bart, Lisa & Maggie'

list([ %{name: "Bart"}, %{name: "Lisa"} ])
# returns 'Bart & Lisa'

list([ %{name: "Bart"} ])
# returns 'Bart'

list([])
# returns ''
```
``` javascript
list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
// returns 'Bart, Lisa & Maggie'

list([ {name: 'Bart'}, {name: 'Lisa'} ])
// returns 'Bart & Lisa'

list([ {name: 'Bart'} ])
// returns 'Bart'

list([])
// returns ''
```
```python
namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'

namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ])
# returns 'Bart & Lisa'

namelist([ {'name': 'Bart'} ])
# returns 'Bart'

namelist([])
# returns ''
```

Note: all the hashes are pre-validated and will only contain A-Z, a-z, '-' and '.'.

def namelist(names):
    return ", ".join(person["name"] for person in (names if len(names)<2 else names[:-1])) + (" & " + names[-1]["name"] if len(names)>1 else "")


Solve in Python:
Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.
Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.

Example 1:
Input: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
Output: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]]
Explanation:
The displaying table looks like:
Table,Beef Burrito,Ceviche,Fried Chicken,Water
3    ,0           ,2      ,1            ,0
5    ,0           ,1      ,0            ,1
10   ,1           ,0      ,0            ,0
For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".
For the table 5: Carla orders "Water" and "Ceviche".
For the table 10: Corina orders "Beef Burrito".

Example 2:
Input: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]
Output: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]]
Explanation:
For the table 1: Adam and Brianna order "Canadian Waffles".
For the table 12: James, Ratesh and Amadeus order "Fried Chicken".

Example 3:
Input: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef...

class Solution:
    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:

        table = {}
        dishes = set()

        for order in orders:
            if order[1] not in table:
                table[order[1]] = {}

            if order[2] not in table[order[1]]:
                table[order[1]][order[2]] = 1
            else:
                table[order[1]][order[2]] += 1

            dishes.add(order[2])

        dishes = sorted(list(dishes))
        table_ints = [int(x) for x in table.keys()]
        table_nums = sorted(table_ints, reverse=False)

        template = [\"Table\"] + dishes
        display = [template]
        for num in table_nums:
            order = [str(num)]
            for dish in dishes:
                order.append(str(table.get(str(num), {}).get(dish, 0)))

            display.append(order)

        return display


Solve in Python:
Goal
Given a list of elements [a1, a2, ..., an], with each ai being a string, write a function **majority** that returns the value that appears the most in the list.

If there's no winner, the function should return None, NULL, nil, etc, based on the programming language.

Example
majority(["A", "B", "A"]) returns "A"
majority(["A", "B", "B", "A"]) returns None

from collections import Counter

def majority(arr):
  mc = Counter(arr).most_common(2)
  if arr and (len(mc) == 1 or mc[0][1] != mc[1][1]):
      return mc[0][0]


Solve in Python:
Goldbach's conjecture is one of the oldest and best-known unsolved problems in number theory and all of mathematics. It states:

Every even integer greater than 2 can be expressed as the sum of two primes.
For example:

`6 = 3 + 3`
`8 = 3 + 5`
`10 = 3 + 7 = 5 + 5`
`12 = 5 + 7`

Some rules for the conjecture:

- pairs should be descending like [3,5] not [5,3]

- all pairs should be in ascending order based on the first element of the pair:
`[[5, 13], [7, 11]]` is accepted
but `[[7, 11],[5, 13]]` is not accepted.

Write the a function that find all identical pairs of prime numbers:
```python
def goldbach(even_number)
```
You should return an array of containing pairs of primes, like:
```python
[[5, 13], [7, 11]]  # even_number = 18
```
or
```python
[[3, 31], [5, 29], [11, 23], [17, 17]] # even_number = 34
```

def goldbach(n):
    if n < 2:
        return []
    if n == 4:
        return [[2, 2]]
    l = n - 2
    sieve = [True] * (l // 2)
    for i in range(3, int(l**0.5) + 1, 2):
        if sieve[i // 2]:
            sieve[i * i // 2::i] = [False] * ((l - i * i - 1) // (2 * i) + 1)
    primes = [(2 * i + 1) for i in range(1, l // 2) if sieve[i]]
    return [[p, n - p] for p in primes if (n - p) in primes and p <= (n - p)]


Solve in Python:
Good job! Now that Heidi is able to distinguish between Poisson and uniform distributions, she is in a good position to actually estimate the populations.

Can you help Heidi estimate each village's population?

-----Input-----

Same as the easy version.

-----Output-----

Output one line per village, in the same order as provided in the input, containing your (integer) population estimate.

Your answer is considered correct if it is an integer that falls into the interval $[ \lfloor 0.95 \cdot P \rfloor, \lceil 1.05 \cdot P \rceil ]$, where P is the real population of the village, used to create the distribution (either Poisson or uniform) from which the marmots drew their answers.

def sampleVariance(V):
    X = sum(V) / len(V)
    S = 0.0
    for x in V:
        S += (X-x)**2

    S /= (len(V)-1)
    return (X, S)

#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
    V = list(map(int, input().split()))
    X, S = sampleVariance(V)
    v1 = X
    v2 = (2*X) ** 2 / 12

    if abs(v1-S) < abs(v2-S):
        print(int(X))
    else:
        print(max(V)+min(V) // 2)


Solve in Python:
Gordon Ramsay shouts. He shouts and swears. There may be something wrong with him.

Anyway, you will be given a string of four words. Your job is to turn them in to Gordon language.

Rules:

Obviously the words should be Caps,
Every word should end with '!!!!',
Any letter 'a' or 'A' should become '@',
Any other vowel should become '*'.

from functools import partial
from re import compile

REGEX1 = partial(compile(r"(?<=\w)(?=\b)").sub, "!!!!")
trans = str.maketrans("AEIOU", "@****")

def gordon(a):
    return REGEX1(a.upper()).translate(trans)


Solve in Python:
Gorodetskiy is a university student. He is really good at math and really likes solving engaging math problems. In the last exam, his professor gave him really hard math problems to solve, but Gorodetskiy could not solve them and failed the exam, so the professor told him: "These problems are a piece of cake, you should know them from school!" Here is one of the problems from the exam - you can decide if it really was an easy problem or not.
You are given a positive integer $M$. Let's call a positive integer $A$ an interesting number if there is at least one integer $B$ ($A \le B$) such that $A \cdot B$ is divisible by $M$ and $\frac{A \cdot B}{M} = A+B$.
Find all interesting numbers. Let's denote the number of such integers by $K$; it is guaranteed that $K \le 3*10^5$.

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

-----Output-----
For each test case:
- First, print a line containing a single integer $K$.
- Then, print $K$ lines. For each valid $i$, the $i$-th of these lines should contain a single integer ― the $i$-th interesting number in increasing order.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le M \le 10^{14}$

-----Subtasks-----
Subtask #1 (20 points): $1 \le M \le 100$
Subtask #2 (20 points): $1 \le M \le 10^7$
Subtask #3 (60 points): original constraints

-----Example Input-----
2
3
6

-----Example Output-----
2
4
6
5
7
8
9
10
12

-----Explanation-----
Example case 1: There are two interesting numbers, $4$ and $6$. For $A = 4$, we can choose $B = 12$ and for $A = 6$, we can choose $B = 6$.

from math import sqrt
def sol(p, m):
 if p == s:
  ans.append(m + N)
  return
 __pow = 1
 for i in range(ls[p][1] + 1):
  if m > N // __pow:break
  sol(p + 1, m * __pow)
  __pow *= ls[p][0]
for _ in range(int(input())):
 n = int(input())
 N, sq,ls,ans = n, int(sqrt(n)),list(),list()
 for i in range(2, sq+1):
  if n % i == 0:
   Count = 0
   while n % i == 0:
    Count += 2
    n //= i
   ls.append([i, Count])
 if n != 1:ls.append([n, 2])
 s = len(ls)
 sol(0, 1)
 ans.sort()
 print(len(ans))
 print(*ans, sep = '\n')


Solve in Python:
Gray code is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for Karnaugh maps.

Here is an exemple of what the code look like:

```
0:    0000
1:    0001
2:    0011
3:    0010
4:    0110
5:    0111
6:    0101
7:    0100
8:    1100
```

The goal of this kata is to build two function bin2gray and gray2bin wich will convert natural binary to Gray Code and vice-versa. We will use the "binary reflected Gray code". The input and output will be arrays of 0 and 1, MSB at index 0.

There are "simple" formula to implement these functions. It is a very interesting exercise to find them by yourself.

All input will be correct binary arrays.

def bitlist(func):
    def wrapper(bits):
        i = int(''.join([str(b) for b in bits]), 2)
        result = func(i)
        return [int(b) for b in bin(result)[2:]]
    return wrapper

@bitlist
def bin2gray(bits):
    return bits >> 1 ^ bits

@bitlist
def gray2bin(bits):
    mask = bits >> 1
    while(mask != 0):
         bits ^= mask
         mask >>= 1
    return bits


Solve in Python:
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game:  The game consists of n steps.  On the i-th step Greg removes vertex number x_{i} from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex.  Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex x_{i}, then Greg wants to know the value of the following sum: $\sum_{v, u, v \neq u} d(i, v, u)$.

Help Greg, print the value of the required sum before each step.

-----Input-----

The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph.

Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line a_{ij} (1 ≤ a_{ij} ≤ 10^5, a_{ii} = 0) represents the weight of the edge that goes from vertex i to vertex j.

The next line contains n distinct integers: x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ n) — the vertices that Greg deletes.

-----Output-----

Print n integers — the i-th number equals the required sum before the i-th step.

Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.

-----Examples-----
Input
1
0
1

Output
0
Input
2
0 5
4 0
1 2

Output
9 0
Input
4
0 3 1 1
6 0 400 1
2 4 0 1
1 1 1 0
4 1 2 3

Output
17 23 404 0

import sys
from array import array  # noqa: F401

n = int(input())
matrix = [array('i', list(map(int, input().split()))) for _ in range(n)]
aa = tuple([int(x) - 1 for x in input().split()])
ans = [''] * n

for i in range(n-1, -1, -1):
    x = aa[i]

    for a in range(n):
        for b in range(n):
            if matrix[a][b] > matrix[a][x] + matrix[x][b]:
                matrix[a][b] = matrix[a][x] + matrix[x][b]

    val, overflow = 0, 0
    for a in aa[i:]:
        for b in aa[i:]:
            val += matrix[a][b]
        if val > 10**9:
            overflow += 1
            val -= 10**9

    ans[i] = str(10**9 * overflow + val)

print(' '.join(ans))


Solve in Python:
Greg has an array a = a_1, a_2, ..., a_{n} and m operations. Each operation looks as: l_{i}, r_{i}, d_{i}, (1 ≤ l_{i} ≤ r_{i} ≤ n). To apply operation i to the array means to increase all array elements with numbers l_{i}, l_{i} + 1, ..., r_{i} by value d_{i}.

Greg wrote down k queries on a piece of paper. Each query has the following form: x_{i}, y_{i}, (1 ≤ x_{i} ≤ y_{i} ≤ m). That means that one should apply operations with numbers x_{i}, x_{i} + 1, ..., y_{i} to the array.

Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.

-----Input-----

The first line contains integers n, m, k (1 ≤ n, m, k ≤ 10^5). The second line contains n integers: a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^5) — the initial array.

Next m lines contain operations, the operation number i is written as three integers: l_{i}, r_{i}, d_{i}, (1 ≤ l_{i} ≤ r_{i} ≤ n), (0 ≤ d_{i} ≤ 10^5).

Next k lines contain the queries, the query number i is written as two integers: x_{i}, y_{i}, (1 ≤ x_{i} ≤ y_{i} ≤ m).

The numbers in the lines are separated by single spaces.

-----Output-----

On a single line print n integers a_1, a_2, ..., a_{n} — the array after executing all the queries. Separate the printed numbers by spaces.

Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.

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

Output
9 18 17

Input
1 1 1
1
1 1 1
1 1

Output
2

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

Output
5 18 31 20

def main():
    n, m, k = list(map(int, input().split()))
    aa = list(map(int, input().split()))
    lrd = list(tuple(map(int, input().split())) for _ in range(m))
    cnt = [0] * (m + 1)
    for _ in range(k):
        x, y = list(map(int, input().split()))
        cnt[x - 1] += 1
        cnt[y] -= 1
    delta, c = [0] * (n + 1), 0
    for (l, r, d), dc in zip(lrd, cnt):
        c += dc
        d *= c
        delta[l - 1] += d
        delta[r] -= d
    da = 0
    for i, a, d in zip(list(range(n)), aa, delta):
        da += d
        aa[i] = a + da
    print(" ".join(map(str, aa)))

def __starting_point():
    main()

__starting_point()


Solve in Python:
Gru has a string $S$ of length $N$, consisting of only characters $a$ and $b$ for banana and $P$ points to spend.
Now Gru wants to replace and/or re-arrange characters of this given string to get the lexicographically smallest string possible. For this, he can perform the following two operations any number of times.
1) Swap any two characters in the string. This operation costs $1$ $point$. (any two, need not be adjacent)
2) Replace a character in the string with any other lower case english letter. This operation costs $2$ $points$.
Help Gru in obtaining the lexicographically smallest string possible, by using at most $P$ points.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains two lines of input, first-line containing two integers $N$ , $P$.
- The second line contains a string $S$ consisting of $N$ characters.

-----Output:-----
For each testcase, output in a single containing the lexicographically smallest string obtained.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $0 \leq P \leq 2N$
- $S$ only consists of $'a'$ and $'b'$

-----Sample Input:-----
1
3 3
bba

-----Sample Output:-----
aab

-----Explanation:-----
We swap $S[0]$ and $S[2]$, to get $abb$. With the 2 remaining points, we replace $S[1]$ to obtain $aab$ which is the lexicographically smallest string possible for this case.

def __starting_point():
 t=int(input())
 for _ in range(t):
  n,p=input().split()
  n,p=int(n),int(p)
  s=input()
  a,b=0,0
  arr=[0]*n
  for i in range(n):
   arr[i]=s[i]
  for c in s:
   if c=='a':
    a+=1
   else:
    b+=1
  swap=0
  for i in range(a):
   if s[i]=='b':
    swap+=1
  tmpp=p
  if p<=swap:
   for i in range(n):
    if p==0:
     break
    if arr[i]=='b':
     arr[i]='a'
     p-=1
   p=tmpp
   for i in range(n-1,-1,-1):
    if p==0:
     break
    if arr[i]=='a':
     arr[i]='b'
     p-=1
   for c in arr:
    print(c,end="")
   print()
  else:
   for i in range(n):
    if i<a:
     arr[i]='a'
    else:
     arr[i]='b'
   p-=swap
   for i in range(n):
    if arr[i]=='b':
     if s[i]=='b' and p>=2:
      p-=2
      arr[i]='a'
     if s[i]=='a' and p>=1:
      p-=1
      arr[i]='a'
   for c in arr:
    print(c,end="")
   print()
__starting_point()


Solve in Python:
Gru has not been in the limelight for a long time and is, therefore, planning something particularly nefarious. Frustrated by his minions' incapability which has kept him away from the limelight, he has built a transmogrifier — a machine which mutates minions.

Each minion has an intrinsic characteristic value (similar to our DNA), which is an integer. The transmogrifier adds an integer K to each of the minions' characteristic value.

Gru knows that if the new characteristic value of a minion is divisible by 7, then it will have Wolverine-like mutations.

Given the initial characteristic integers of N minions, all of which are then transmogrified, find out how many of them become Wolverine-like.

-----Input Format:-----
The first line contains one integer, T, which is the number of test cases. Each test case is then described in two lines.
The first line contains two integers N and K, as described in the statement.
The next line contains N integers, which denote the initial characteristic values for the minions.

-----Output Format:-----
For each testcase, output one integer in a new line, which is the number of Wolverine-like minions after the transmogrification.

-----Constraints:-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 100
- 1 ≤ K ≤ 100
- All initial characteristic values lie between 1 and 105, both inclusive.

-----Example-----
Input:
1
5 10
2 4 1 35 1

Output:
1

-----Explanation:-----
After transmogrification, the characteristic values become {12,14,11,45,11}, out of which only 14 is divisible by 7. So only the second minion becomes Wolverine-like.

# cook your dish here
for _ in range(int(input())):
 n,k=[int(x) for x in input().split()]
 a=[int(x) for x in input().split()]
 c=0
 for i in a:
  aa=i+k
  if aa%7==0:
   c+=1
 print(c)


Solve in Python:
Gru wants to distribute $N$ bananas to $K$ minions on his birthday.
Gru does not like to just give everyone the same number of bananas, so instead, he wants to distribute bananas in such a way that each minion gets a $distinct$ amount of bananas. That is, no two minions should get the same number of bananas.
Gru also loves $gcd$. The higher the $gcd$, the happier Gru and the minions get. So help Gru in distributing the bananas in such a way that each Minion gets a distinct amount of bananas and gcd of this distribution is highest possible. Output this maximum gcd. If such a distribution is not possible output $-1$.
Note: You have to distribute $all$ $N$ bananas.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase consists of a single line of input, which has two integers: $N, K$.

-----Output:-----
For each testcase, output in a single line the maximum gcd or -1.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N, K \leq 10^9$

-----Sample Input:-----
1
6 3

-----Sample Output:-----
1

-----EXPLANATION:-----
The only possible distribution is $[1, 2, 3]$. So the answer is 1.

from math import sqrt

for _ in range(int(input())):

 n, k = map(int, input().split())
 fact,i = [],1

 while i<=sqrt(n):

  if n%i==0:
   if (n // i != i):
    fact.append(n//i)

   fact.append(i)

  i+=1

 tot = (k*(k+1))//2
 mx = -1

 for i in fact:
  if i>=tot:
   mx = max(mx,n//i)

 print(mx)


Solve in Python:
Guddu was participating in a programming contest. He only had one problem left when his mother called him for dinner. Guddu is well aware how angry his mother could get if he was late for dinner and he did not want to sleep on an empty stomach, so he had to leave that last problem to you. Can you solve it on his behalf?
For a given sequence of positive integers $A_1, A_2, \ldots, A_N$, you are supposed to find the number of triples $(i, j, k)$ such that $1 \le i < j \le k \le N$ and
Ai⊕Ai+1⊕…⊕Aj−1=Aj⊕Aj+1⊕…⊕Ak,Ai⊕Ai+1⊕…⊕Aj−1=Aj⊕Aj+1⊕…⊕Ak,A_i \oplus A_{i+1} \oplus \ldots \oplus A_{j-1} = A_j \oplus A_{j+1} \oplus \ldots \oplus A_k \,,
where $\oplus$ denotes bitwise XOR.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

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

-----Constraints-----
- $1 \le T \le 10$
- $2 \le N \le 10^5$
- $1 \le A_i \le 10^6$ for each valid $i$

-----Subtasks-----
Subtask #1 (20 points):
- $1 \le T \le 5$
- $1 \le N \le 100$
Subtask #2 (30 points):
- $1 \le T \le 5$
- $1 \le N \le 1,000$
Subtask #3 (50 points): original constraints

-----Example Input-----
1
3
5 2 7

-----Example Output-----
2

-----Explanation-----
Example case 1: The triples are $(1, 3, 3)$, since $5 \oplus 2 = 7$, and $(1, 2, 3)$, since $5 = 2 \oplus 7$.

t=int(input())
for _ in range(t):
 n=int(input())
 l=list(map(int,input().split()))
 ans=0

 m=[0]*n
 for i in range(n):
  if i==0:
   m[i]=l[i]
  else:
   m[i]=m[i-1]^l[i]
 d={}
 c=0
 for i in l:
  c=c^i

 for i in range(n-1,-1,-1):
  try:
   x=d[l[i]^c]
   ans+=x[0]-x[1]*i
  except:
   pass
  try:
   d[m[i]]=[d[m[i]][0]+i,d[m[i]][1]+1]
  except:
   d[m[i]]=[i,1]
  c=c^l[i]
 print(ans)


Solve in Python:
HELP! Jason can't find his textbook! It is two days before the test date, and Jason's textbooks are all out of order! Help him sort a list (ArrayList in java) full of textbooks by subject, so he can study before the test.

The sorting should **NOT** be case sensitive

def sorter(textbooks):
    textbooks = sorted(textbooks, key=lambda x:x[0:] if x[0:].islower() else x[0:].lower())
    return textbooks


Solve in Python:
HTML Element Generator
In this kata, you will be creating a python function that will take arguments and turn them into an HTML element.
An HTML tag has three parts:

The opening tag, which consists of a tag name and potentially attributes, all in between angle brackets.
The element content, which is the data that is shown on the webpage.  This is in between the opening and closing tags.
And the closing tag, which is an opening angle bracket, a forward slash, the name of the tag, and a closing angle bracket

If you were to have multiple attributes, they would each appear with a single space separating them

Some tags do not require a closing tag.  These are called self-closing tags.  For this kata, any tag passed into the function without 'element content' (keyword arguments) will be treated in this way:  after the tag name (and any attributes), there will be a space and then a forward slash.  See the picture to the right.

Data will be passed into the html function as such:

The first argument will be the tag name
Any other non-keyword arguments will be element content. If no element content is given, the return value will be expected to be a self-closing tag.  If more than one argument is given as element content, you will return multiple of the same element, just with different element content, separated by one or more newline characters.
Ex:

Hello World!
\n
This is HTML code!

IMPORTANT:  Because class is a python keyword, and class is a very important HTML attribute, you will also have to implement a keyword argument named cls, as opposed to class.  This attribute will appear as class="variable" in the return value of your function
Any other keyword arguments of the function will be treated as attributes of the element.  The keyword is the attribute name (left of the equals sign), and the keyword's value is the attribute's value (right of the equals sign).
Element attributes will appear in the return value of your...

def html(tag_name, *args, **kwargs):
    attributes = []
    for key, value in kwargs.items():
        if key == "cls":
            key = "class"
        attributes.append(f'{key}="{value}"')

    if len(args) == 0:
        return f"<{tag_name}{'' if len(attributes) == 0 else ' ' + ' '.join(attributes)} />"

    closing_tags = []
    for arg in args:
        closing_tags.append(f"<{tag_name}{'' if len(attributes) == 0 else ' ' + ' '.join(attributes)}>{arg}</{tag_name}>")
    return "\n".join(closing_tags)


Solve in Python:
Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.
Iroha is looking for X,Y,Z-Haiku (defined below) in integer sequences.
Consider all integer sequences of length N whose elements are between 1 and 10, inclusive. Out of those 10^N sequences, how many contain an X,Y,Z-Haiku?
Here, an integer sequence a_0, a_1, ..., a_{N-1} is said to contain an X,Y,Z-Haiku if and only if there exist four indices x, y, z, w (0 ≦ x < y < z < w ≦ N) such that all of the following are satisfied:
 - a_x + a_{x+1} + ... + a_{y-1} = X
 - a_y + a_{y+1} + ... + a_{z-1} = Y
 - a_z + a_{z+1} + ... + a_{w-1} = Z
Since the answer can be extremely large, print the number modulo 10^9+7.

-----Constraints-----
 - 3 ≦ N ≦ 40
 - 1 ≦ X ≦ 5
 - 1 ≦ Y ≦ 7
 - 1 ≦ Z ≦ 5

-----Input-----
The input is given from Standard Input in the following format:
N X Y Z

-----Output-----
Print the number of the sequences that contain an X,Y,Z-Haiku, modulo 10^9+7.

-----Sample Input-----
3 5 7 5

-----Sample Output-----
1

Here, the only sequence that contains a 5,7,5-Haiku is [5, 7, 5].

mod = 1000000007
eps = 10**-9

def main():
    import sys
    input = sys.stdin.readline

    N, x, y, z = list(map(int, input().split()))
    s = x + y + z
    m = max(x, y, z)
    mask_x = (1 << (x + 1)) - 1
    mask_y = (1 << y) - 1
    mask_z = (1 << z) - 1

    dp = [0] * (1 << s)
    dp[1] = 1
    for _ in range(N):
        dp_new = [0] * (1 << s)
        for state in range(1 << s):
            if dp[state] == 0:
                continue
            state_x = state & mask_x
            state_y = (state >> (x + 1)) & mask_y
            state_z = (state >> (x + y + 1)) & mask_z
            for w in range(1, m+1):
                if z - w - 1 >= 0:
                    if (state_z >> (z - w - 1)) & 1:
                        continue
                if w == z and (state_y >> (y - 1)) & 1:
                    continue
                state_new = ((state_x << w) & mask_x) | (((state_y << w) & mask_y) << (x + 1))\
                            | (((state_z << w) & mask_z) << (x + y + 1)) | 1
                if ((state_x >> x) & 1) and w <= y:
                    state_new |= (1 << (w + x))
                if ((state_y >> (y - 1)) & 1) and w <= z:
                    state_new |= (1 << (w + x + y))
                dp_new[state_new] = (dp_new[state_new] + dp[state])%mod
            dp_new[1] = (dp_new[1] + (dp[state] * (10 - m))%mod)%mod
        dp = dp_new
    ans = pow(10, N, mod)
    for a in dp:
        ans = (ans - a)%mod
    print(ans)

def __starting_point():
    main()

__starting_point()


Solve in Python:
Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract k ≥ 1 non-overlapping substrings from it such that each of them contains string t as a substring? More formally, you need to calculate the number of ways to choose two sequences a_1, a_2, ..., a_{k} and b_1, b_2, ..., b_{k} satisfying the following requirements:

  k ≥ 1  $\forall i(1 \leq i \leq k) 1 \leq a_{i}, b_{i} \leq|s|$  $\forall i(1 \leq i \leq k) b_{i} \geq a_{i}$  $\forall i(2 \leq i \leq k) a_{i} > b_{i - 1}$  $\forall i(1 \leq i \leq k)$  t is a substring of string s_{a}_{i}s_{a}_{i} + 1... s_{b}_{i} (string s is considered as 1-indexed).

As the number of ways can be rather large print it modulo 10^9 + 7.

-----Input-----

Input consists of two lines containing strings s and t (1 ≤ |s|, |t| ≤ 10^5). Each string consists of lowercase Latin letters.

-----Output-----

Print the answer in a single line.

-----Examples-----
Input
ababa
aba

Output
5

Input
welcometoroundtwohundredandeightytwo
d

Output
274201

Input
ddd
d

Output
12


Solve in Python:
Han Solo and Chewbacca start a space journey to planet Naboo on the Millennium Falcon. During the journey they land at a mysterious planet with high gravity where they find n diamond stones scattered all around. All the stones are of same weight. Each stone has a value according to its purity which can be detected by a special device. They choose to divide the stones fairly among themselves in two halves so that they carry almost equal weights such that the difference between the value of two halves is as small as possible. If n is even, then sizes of two halves must be strictly n/2 and if n is odd, then size of one half must be (n-1)/2 and size of the other half must be (n+1)/2. Given the value of stones, help them to divide the stones among themselves.

-----Input-----
First line consists of an integer n which denotes the number of stones.Second line consists of n space separated integers denoting the value of the stones.

-----Output-----
First line consists of the values of the stones assigned to Han Solo.Second line consists of the values of the stones assigned to Chewbacca.Assume that the set containing the first value in the input is always assigned to Han Solo.Also the values in the output sets must follow the same ordering as the input.

-----Constraints-----
The number of stones can range from 2 to 99.The values of the stones vary from 1 to 10^4.

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

Output:
1 2 4 7
3 5 6

-----Explanation-----
These 7 values must be separated into 2 sets of sizes 3 and 4.In this case, it is possible to form two sets (1,2,4,7) & (3,5,6) of equal size.The set containing the first value (i.e.) 1 must be assigned to Han Solo and the elements of the output sets have the same order as the input.

s,n,s1,lis,new1=[],[],[],[],[]
import itertools
q = int(input())
s.append(input().split(' '))
s1 = list([list(map(int,x)) for x in s])
sum1 = sum(s1[0])
if len(s1[0])%2!=0 :
 z = (len(s1[0])+1)//2
 n = list(itertools.combinations(s1[0],z))
 for j in range(len(n)) :
   x = sum(n[j])
   if x==sum1//2 :
    lis = n[j]
    break
 new1 = list(lis)
 sum2 = sum(new1)
 for j in range(len(lis)) :
    y = lis[j]
    s1[0].remove(y)
 sum3=sum(s1[0])
 if sum3>sum2 :
  print(' '.join(map(str,s1[0])))
  print(' '.join(map(str,new1)))
 else :
  print(' '.join(map(str,new1)))
  print(' '.join(map(str,s1[0])))
else :
 z = len(s1[0])//2
 n = list(itertools.combinations(s1[0],z))
 for j in range(len(n)) :
   x = sum(n[j])
   if x==sum1//2 :
    lis = n[j]
    break
   #print lis,len(lis)
 new1 = list(lis)
 sum2 = sum(new1)
 for j in range(len(lis)) :
    y = lis[j]
    s1[0].remove(y)
 sum3 = sum(s1[0])
 if sum3>sum2  :
  print(' '.join(map(str,s1[0])))
  print(' '.join(map(str,new1)))
 else :
  print(' '.join(map(str,new1)))
  print(' '.join(map(str,s1[0])))


Solve in Python:
Happy traveller [Part 1]

There is a play grid NxN; Always square!

   0  1  2  3
0 [o, o, o, X]
1 [o, o, o, o]
2 [o, o, o, o]
3 [o, o, o, o]

You start from a random point. I mean, you are given the coordinates of your start position in format (row, col).

And your TASK is to define the number of unique paths to reach position X (always in the top right corner).

From any point you can go only UP or RIGHT.

Implement a function count_paths(N, (row, col)) which returns int;
Assume input params are always valid.

Example:

count_paths(1, (0, 0))
grid 1x1:

[X]
 You are already in the target point, so return 0

count_paths(2, (1, 0))
grid 2x2:

[o, X]
[@, o]
 You are at point @; you can move UP-RIGHT or RIGHT-UP, and there are 2 possible unique paths here

count_paths(2, (1, 1))
grid 2x2:

[o, X]
[o, @]
 You are at point @; you can move only UP, so there is 1 possible unique path here

count_paths(3, (1, 0))
grid 3x3:

[o, o, X]
[@, o, o]
[o, o, o]
 You are at point @; you can move UP-RIGHT-RIGHT or RIGHT-UP-RIGHT, or RIGHT-RIGHT-UP, and there are 3 possible unique paths here

I think it's pretty clear =)

btw. you can use preloaded Grid class, which constructs 2d array for you. It's very very basic and simple. You can use numpy instead or any other way to produce the correct answer =)
 grid = Grid(2, 2, 0)
samegrid = Grid.square(2) will give you a grid[2][2], which you can print easily to console.

print(grid)

[0, 0]
[0, 0]

Enjoy!

You can continue adventures:
Happy traveller [Part 2]

from math import factorial as f
count_paths=lambda n,c:f(c[0]+abs(n-c[1]-1))//(f(abs(n-c[1]-1))*f(c[0])) if n!=1 else 0


Solve in Python:
Harish has decided to go to Arya's hotel this morning. We all know he is crazy for masala dosas. And as usual he is always hungry. He decided to order all the masala dosas at once. But then he realised that he did not have enough money to buy all of them. So he decided to share the amount with his friend Ozil. But both of them are fans of even numbers. Both of them says they want to eat even number of dosas. Ozil is ready to put the share if and only if , he is sure that he can get even number of dosas. So given N number of dosas can you please help Harish to decide, if he will be able to get all the dosas at once from the hotel.

-----Input-----
The first line of input contains an integer T which denotes the number of test files. Next T lines contains an integer N where N is the total number of dosas.

-----Output-----
Print "YES" if both can get even number of dosas. If it is not possible print "NO".

-----Constraints-----
- 1 ≤ T ≤ 10^6
- 1 ≤ N ≤ 10^18

-----Subtasks-----
Subtask #1 : (20 points)
- 1 ≤ T ≤ 10
- 1 ≤ N≤ 100

Subtask 2 : (80 points)

- 1 ≤ T ≤ 10^6
- 1 ≤ N≤ 10^18

-----Example-----
Input:
2
16
27
Output:
YES
NO

t=int(input())
while(t>0):
 n=int(input())
 if(n%2==0):
  print("YES")
 else:
  print("NO")
 t=t-1


Solve in Python:
Harrenhal is the largest castle in the Seven Kingdoms and is the seat of House Whent in the Riverlands, on the north shore of the Gods Eye lake. Since the War of Conquest, however, it has become a dark and ruinous place.
(c) A Wiki of Ice and Fire

Now Harrenhal is too dangerous since it's a nice place for bandits to hide, or even for rebels to start planning overthrowing of the king. So, the current Lord of the Seven Kingdoms has decided, that it's time to completely ruin the castle. For that puposes, he's planning to send some military troops.
In this problem we assume, that Harrenhal can be described as a string H, which consists only of symbols 'a' and 'b'. Harrenhal is completely ruined if and only if the length of H is equal to zero.
So, how to make H empty? Send a military troop! When a military troop of the king reach the castle, they delete some palindromic subsequence S of H. For example, let H = 'abbabaab'. Then the current military troop can choose S = 'ababa'(Let's make symbols of S bold in H: 'abbabaab'). After deleting S, H will be equal to 'bab'. Military troops are free to choose any possible palindromic subsequence of H.
Your task is pretty simple: determine the minimal number of military troops, that the Lord of the Seven Kingdoms has to send in order to ruin Harrenhal.

-----Note-----

Maybe, some of you aren't familiar with definitions from the statement. Here're some articles that could help you to understand the problem correctly:

- Subsequence: http://en.wikipedia.org/wiki/Subsequence
- Palindrome: http://en.wikipedia.org/wiki/Palindrome

-----Input-----
The first line of the input contains an integer T, denoting the number of test cases.
The next T lines contain a string H each, denoting the string, that describes the current state of Harrenhal for the corresponding test cases.
It's guaranteed, that each H consists only of symbols 'a' and 'b'.

-----Output-----
The output should contain exactly T lines. i'th line of the output should contain the only integer: the minimal number of...

# cook your dish here
def isPalindrome(s):
    return(s==s[::-1])
t=int(input())
for i in range(t):
    word=input()
    if(isPalindrome(word)):
        print(1)
    else:
        print(2)


Solve in Python:
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class.

Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each student’s laziness level is equal to their task’s difficulty level. Both sets of values are given by the sequence a, where a_{i} represents both the laziness level of the i-th student and the difficulty of his task.

The time a student needs to finish a task is equal to the product of their laziness level and the task’s difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.

-----Input-----

The first line of input contains integer n (1 ≤ n ≤ 100 000) — the number of tasks. The next n lines contain exactly one integer number a_{i} (1 ≤ a_{i} ≤ 100 000) — both the difficulty of the initial task and the laziness of the i-th students.

-----Output-----

Print the minimum total time to finish all tasks modulo 10 007.

-----Example-----
Input
2
1
3

Output
6

-----Note-----

In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.

n = int(input())
a = sorted([int(input()) for i in range(n)])

time = 0
for i in range(n):
    time += a[i] * a[n - 1 - i]

print(time % 10007)


Solve in Python:
Harry is a bright student. To prepare thoroughly for exams, he completes all the exercises in his book! Now that the exams are approaching fast, he is doing book exercises day and night. He writes down and keeps updating the remaining number of exercises on the back cover of each book.
Harry has a lot of books messed on the floor. Therefore, he wants to pile up the books that still have some remaining exercises into a single pile. He will grab the books one-by-one and add the books that still have remaining exercises to the top of the pile.
Whenever he wants to do a book exercise, he will pick the book with the minimum number of remaining exercises from the pile. In order to pick the book, he has to remove all the books above it. Therefore, if there are more than one books with the minimum number of remaining exercises, he will take the one which requires the least number of books to remove. The removed books are returned to the messy floor. After he picks the book, he will do all the remaining exercises and trash the book.
Since number of books is rather large, he needs your help to tell him the number of books he must remove, for picking the book with the minimum number of exercises.

Note that more than one book can have the same name.

-----Input-----
The first line contains a single integer N denoting the number of actions. Then N lines follow. Each line starts with an integer. If the integer is -1, that means Harry wants to do a book exercise. Otherwise, the integer is number of the remaining exercises in the book he grabs next. This is followed by a string denoting the name of the book.

-----Output-----
For each -1 in the input, output a single line containing the number of books Harry must remove, followed by the name of the book that Harry must pick.

-----Constraints-----

1 < N ≤ 1,000,000
0 ≤ (the number of remaining exercises of each book) < 100,000
The name of each book consists of between 1 and 15 characters 'a' - 'z'.
Whenever he wants to do a book exercise, there is at least one book in the...

t=eval(input())

a=[]
b=[]

top=-1

for __ in range(0,t):

 x=input().split()

 if(x[0]!="-1" and x[0]!="0"):

  add=int(x[0])

  if top!=-1 and add>a[top][0] :

    b[top]+=1

  else:
    a.append((add,x[1]))

    b.append(0)
    top+=1

 elif (x[0]=="-1"):

  #print("%s %s" %(b[top],a[top][1]))
  print((b[top]), end=' ')
  print(a[top][1])
  foo=a.pop()
  bar=b.pop()
  top-=1


Solve in Python:
Harsh, like usual, started studying 6 months before for his end semester examinations. He was going to complete his 8th revision of the whole syllabus, when suddenly Pranav showed up in his room with the last year's question paper for their algorithms course. This paper contains a problem which both of them couldn't solve. Frustrated he asked you for help. But you declined him and instead try to do this problem instead:
You are given an array $A_1,A_2,\dots,A_N$, a positive integer $K$, and a function $F(x)=\displaystyle\sum_{i=1}^{N}{\left|{\left({x-A_i}\right)^K}\right|}$. Find the smallest integer $x$ such that $F(x)$ is minimum.Input
- The first line contains two space-seperated integers , $N$ and $K$
- The second line contains $N$ space-seperated integers $A_1,A_2,\dots,A_N$. Output
In the first and only line print the smallest integer $x$ such that $F(x)$ is minimumConstraints
- $1 \leq N \leq {10}^{5}$
- $1 \leq K \leq {3}$
- $1 \leq A_i \leq {5}\times{10}^{4}$ for each valid $i$Sample Input 1
3 1
6 1 7
Sample Output 1
6
Explanation 1
$F(6) = \displaystyle\sum_{i=1}^{N}{\left|{\left({6-A_i}\right)^K}\right|} \\ F(6) = \left|{\left({6-6}\right)^1}\right| + \left|{\left({6-1}\right)^1}\right| + \left|{\left({6-7}\right)^1}\right| \\ F(6)  = 0 + 5+ 1 \\ F(6)  = 6 $
Here $6$ is the minumum value for $F(x)$ for any integer value of $x$.Sample Input 2
3 2
6 1 7
Sample Output 2
5
Explanation 2
$F(5) = \displaystyle\sum_{i=1}^{N}{\left|{\left({5-A_i}\right)^K}\right|} \\F(5) = \left|{\left({5-6}\right)^2}\right| + \left|{\left({5-1}\right)^2}\right| + \left|{\left({5-7}\right)^2}\right| \\F(5) = 1 + 16 + 4 \\F(5) = 21$
Here $21$ is the minumum value for $F(x)$ for any integer value of $x$.Sample Input 3
3 3
6 1 7
Sample Output 3
4
Explanation 3
$F(4) = \displaystyle\sum_{i=1}^{N}{\left|{\left({4-A_i}\right)^K}\right|} \\F(4) = \left|{\left({4-6}\right)^3}\right| + \left|{\left({4-1}\right)^3}\right| + \left|{\left({4-7}\right)^3}\right| \\F(4) = 8 + 27 + 27 \\F(4) = 62 $
Here $62$ is the minumum value for...

# cook your dish here
def f(x):
    sumi=0
    for i in li:
        sumi+=(abs((x-i)))**k
    return sumi
def binary_search(l,r):
    mid=(l+r)//2
    if(f(mid)<f(mid-1)):
        if(f(mid)<=f(mid+1)):
            return mid
        return binary_search(mid+1,r)
    return binary_search(l,mid-1)
l=input().split()
n=int(l[0])
k=int(l[1])
l=input().split()
li=[int(i) for i in l]
print(binary_search(0,5*(10**4)+5))


Solve in Python:
Have a look at the following numbers.

```
 n | score
---+-------
 1 |  50
 2 |  150
 3 |  300
 4 |  500
 5 |  750
```

Can you find a pattern in it? If so, then write a function `getScore(n)`/`get_score(n)`/`GetScore(n)` which returns the score for any positive number `n`:

```c++
int getScore(1) = return 50;
int getScore(2) = return 150;
int getScore(3) = return 300;
int getScore(4) = return 500;
int getScore(5) = return 750;
```


Solve in Python:
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.

In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.

Du will chat in the group for $n$ days. On the $i$-th day:  If Du can speak, he'll make fun of Boboniu with fun factor $a_i$. But after that, he may be muzzled depending on Boboniu's mood.  Otherwise, Du won't do anything.

Boboniu's mood is a constant $m$. On the $i$-th day:  If Du can speak and $a_i>m$, then Boboniu will be angry and muzzle him for $d$ days, which means that Du won't be able to speak on the $i+1, i+2, \cdots, \min(i+d,n)$-th days.  Otherwise, Boboniu won't do anything.

The total fun factor is the sum of the fun factors on the days when Du can speak.

Du asked you to find the maximum total fun factor among all possible permutations of $a$.

-----Input-----

The first line contains three integers $n$, $d$ and $m$ ($1\le d\le n\le 10^5,0\le m\le 10^9$).

The next line contains $n$ integers $a_1, a_2, \ldots,a_n$ ($0\le a_i\le 10^9$).

-----Output-----

Print one integer: the maximum total fun factor among all permutations of $a$.

-----Examples-----
Input
5 2 11
8 10 15 23 5

Output
48

Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7

Output
195

-----Note-----

In the first example, you can set $a'=[15, 5, 8, 10, 23]$. Then Du's chatting record will be:  Make fun of Boboniu with fun factor $15$.  Be muzzled.  Be muzzled.  Make fun of Boboniu with fun factor $10$.  Make fun of Boboniu with fun factor $23$.

Thus the total fun factor is $48$.

n, d, m = list(map(int, input().split()))
a = list(map(int, input().split()))
p = []
q = []
for x in a:
    if x > m:
        p.append(x)
    else:
        q.append(x)
p = [0] + sorted(p, reverse=True)
q = [0] + sorted(q, reverse=True)
for i in range(len(p) - 1):
    p[i + 1] += p[i]
for i in range(len(q) - 1):
    q[i + 1] += q[i]
ans = 0
for t in range(len(p)):
    v = n + d - t * d - t
    if 0 <= v < len(q) + d:
        ans = max(ans, p[t] + q[min(v, len(q) - 1)])
print(ans)


Solve in Python:
Have you heard about Megamind? Megamind and Metro Man are two aliens who came to earth. Megamind wanted to destroy the earth, while Metro Man wanted to stop him and protect mankind. After a lot of fighting, Megamind finally threw Metro Man up into the sky. Metro Man was defeated and was never seen again. Megamind wanted to be a super villain. He believed that the difference between a villain and a super villain is nothing but presentation. Megamind became bored, as he had nobody or nothing to fight against since Metro Man was gone. So, he wanted to create another hero against whom he would fight for recreation. But accidentally, another villain named Hal Stewart was created in the process, who also wanted to destroy the earth. Also, at some point Megamind had fallen in love with a pretty girl named Roxanne Ritchi. This changed him into a new man. Now he wants to stop Hal Stewart for the sake of his love. So, the ultimate fight starts now.

* Megamind has unlimited supply of guns named Magic-48. Each of these guns has `shots` rounds of magic spells.
* Megamind has perfect aim. If he shoots a magic spell it will definitely hit Hal Stewart. Once hit, it decreases the energy level of Hal Stewart by `dps` units.
* However, since there are exactly `shots` rounds of magic spells in each of these guns, he may need to swap an old gun with a fully loaded one. This takes some time. Let’s call it swapping period.
* Since Hal Stewart is a mutant, he has regeneration power. His energy level increases by `regen` unit during a swapping period.
* Hal Stewart will be defeated immediately once his energy level becomes zero or negative.
* Hal Stewart initially has the energy level of `hp` and Megamind has a fully loaded gun in his hand.
* Given the values of `hp`, `dps`, `shots` and `regen`, find the minimum number of times Megamind needs to shoot to defeat Hal Stewart. If it is not possible to defeat him,  return `-1` instead.

# Example
Suppose, `hp` = 13, `dps` = 4, `shots` = 3 and `regen` = 1. There are 3 rounds of spells...

def mega_mind(hp, dps, shots, regen):
    if regen < dps*shots or hp <= shots*dps:
        cnt = 0
        while hp > shots*dps:
            hp = hp - shots*dps + regen
            cnt += shots

        for i in range(hp):
            hp = hp - dps
            cnt+= 1
            if hp <= 0:
                return cnt
    return -1


Solve in Python:
Have you heard about the myth that [if you fold a paper enough times, you can reach the moon with it](http://scienceblogs.com/startswithabang/2009/08/31/paper-folding-to-the-moon/)? Sure you have, but exactly how many? Maybe it's time to write a program to figure it out.

You know that a piece of paper has a thickness of `0.0001m`. Given `distance` in units of meters, calculate how many times you have to fold the paper to make the paper reach this distance.
(If you're not familiar with the concept of folding a paper: Each fold doubles its total thickness.)

Note: Of course you can't do half a fold. You should know what this means ;P

Also, if somebody is giving you a negative distance, it's clearly bogus and you should yell at them by returning `null` (or whatever equivalent in your language. In Shell please return `None`).

def fold_to(distance):
    if distance < 0:
        return None

    thiccness = .0001
    folds = 0

    while thiccness < distance:
        thiccness = thiccness * 2
        folds = folds + 1

    return folds


Solve in Python:
Having two standards for a keypad layout is inconvenient!
Computer keypad's layout:

Cell phone keypad's layout:

Solve the horror of unstandartized keypads by providing a function that converts computer input to a number as if it was typed by a phone.

Example:
"789" -> "123"

Notes:
You get a string with numbers only

def computer_to_phone(numbers):
    return numbers.translate(str.maketrans('123789', '789123'))


Solve in Python:
Hector the hacker has stolen some information, but it is encrypted. In order to decrypt it, he needs to write a function that will generate a decryption key from the encryption key which he stole (it is in hexadecimal). To do this, he has to determine the two prime factors `P` and `Q` of the encyption key, and return the product `(P-1) * (Q-1)`.

**Note:** the primes used are < 10^(5)

## Examples

For example if the encryption key is `"47b"`, it is 1147 in decimal. This factors to 31\*37, so the key Hector needs is 1080 (= 30\*36).

More examples:
* input: `"2533"`, result: 9328 (primes: 89, 107)
* input: `"1ba9"`, result: 6912 (primes: 73, 97)

def find_key(key):
    n = int(key, 16)
    a, b = factor(n)
    return (a - 1) * (b - 1)

def factor(n):
    for i in range(2, n):
        if n % i == 0:
            return i, int(n/i)


Solve in Python:
Heidi is a statistician to the core, and she likes to study the evolution of marmot populations in each of V (1 ≤ V ≤ 100) villages! So it comes that every spring, when Heidi sees the first snowdrops sprout in the meadows around her barn, she impatiently dons her snowshoes and sets out to the Alps, to welcome her friends the marmots to a new season of thrilling adventures.

Arriving in a village, Heidi asks each and every marmot she comes across for the number of inhabitants of that village. This year, the marmots decide to play an April Fools' joke on Heidi. Instead of consistently providing the exact number of inhabitants P (10 ≤ P ≤ 1000) of the village, they respond with a random non-negative integer k, drawn from one of two types of probability distributions:

  Poisson (d'avril) distribution: the probability of getting an answer k is $\frac{p^{k} e^{-P}}{k !}$ for k = 0, 1, 2, 3, ...,  Uniform distribution: the probability of getting an answer k is $\frac{1}{2 P + 1}$ for k = 0, 1, 2, ..., 2P.

Heidi collects exactly 250 answers per village. Every village follows either the Poisson or the uniform distribution. Heidi cannot tell marmots apart, so she may query some marmots several times, and each time the marmot will answer with a new number drawn from the village's distribution.

Can you help Heidi to find out whether a village follows a Poisson or a uniform distribution?

-----Input-----

The first line of input will contain the number of villages V (1 ≤ V ≤ 100). The following V lines each describe one village. The description of each village consists of 250 space-separated integers k, drawn from one of the above distributions.

-----Output-----

Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answer came from a uniform distribution.

-----Example-----
Input
2
92 100 99 109 93 105 103 106 101 99 ... (input is truncated)
28 180 147 53 84 80 180 85 8 16 ... (input...

v = int(input())
eps = 130

def ans(a):
    a.sort()
    if len(a) % 2 == 0:
        med = a[len(a)//2]
    else:
        med = (a[len(a)//2] + a[len(a)//2 - 1]) // 2

    l = med - med // 2
    r = med + med // 2

    c1 = c2 = 0

    for i in a:
        if i >= l and i <= r:
            c1 += 1
        else:
            c2 += 1

    if abs(c1 - c2) <= eps:
        return "uniform"
    else:
        return "poisson"

for i in range(v):
    cur = [int(i) for i in input().split()]
    print(ans(cur))


Solve in Python:
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.

Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.

All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.

Helen knows that each minute of delay of the i-th flight costs airport c_{i} burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.

-----Input-----

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.

The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^7), here c_{i} is the cost of delaying the i-th flight for one minute.

-----Output-----

The first line must contain the minimum possible total cost of delaying the flights.

The second line must contain n different integers t_1, t_2, ..., t_{n} (k + 1 ≤ t_{i} ≤ k + n), here t_{i} is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.

-----Example-----
Input
5 2
4 2 1 10 2

Output
20
3 6 7 4 5

-----Note-----

Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 +...

from heapq import heappush, heappop, heapify
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
q = [(-a[i], i) for i in range(k)]
heapify(q)
res, s = [0] * n, 0
for i in range(k, n):
    heappush(q, (-a[i], i))
    x, j = heappop(q)
    s -= x * (i-j)
    res[j] = i+1
for i in range(n, n+k):
    x, j = heappop(q)
    s -= x * (i-j)
    res[j] = i+1
print(s)
print(*res)


Solve in Python:
Hello everyone.

I have a simple challenge for you today. In mathematics, the formula for finding the sum to infinity of a geometric sequence is:

**ONLY IF** `-1 < r < 1`

where:

* `a` is the first term of the sequence
* `r` is the common ratio of the sequence (calculated by dividing one term in the sequence by the previous term)

For example: `1 + 0.5 + 0.25 + 0.125 + ... = 2`

Your challenge is to calculate the sum to infinity of the given sequence. The solution must be rounded to 3 decimal places.

If there are no solutions, for example if `r` is out of the above boundaries, return `"No Solutions"`.

Hope you enjoy, let me know of any issues or improvements!

def sum_to_infinity(arr):
    a, b = arr[:2]
    c = b / a
    return round(a / (1 - c), 3) if -1 < c < 1 else "No Solutions"


Solve in Python:
Hello! Your are given x and y and 2D array size tuple (width, height) and you have to:
Calculate the according index in 1D space (zero-based).
Do reverse operation.

Implement:
to_1D(x, y, size):
  --returns index in 1D space
to_2D(n, size)
  --returns x and y in 2D space

1D array: [0, 1, 2, 3, 4, 5, 6, 7, 8]
2D array: [[0 -> (0,0), 1 -> (1,0), 2 -> (2,0)],
           [3 -> (0,1), 4 -> (1,1), 5 -> (2,1)],
           [6 -> (0,2), 7 -> (1,2), 8 -> (2,2)]]

to_1D(0, 0, (3,3)) returns 0
to_1D(1, 1, (3,3)) returns 4
to_1D(2, 2, (3,3)) returns 8
to_2D(5, (3,3)) returns (2,1)
to_2D(3, (3,3)) returns (0,1)

Assume all input are valid:

1 < width  < 500;
1 < height < 500

def to_1D(x, y, size):
    return y * size[0] + x

def to_2D(n, size):
    return (n % size[0], n // size[0])


Solve in Python:
Help Johnny!
He can't make his code work!
Easy Code
Johnny is trying to make a function that adds the sum of two encoded strings, but he can't find the error in his code! Help him!

def add(s1, s2):
    return sum([ord(i) for i in s1+s2])


Solve in Python:
Help Saurabh with his Chemistry Assignment.

Saurabh has been given a chemistry assignment by Ruby Mam. Though the assignment is simple but

Saurabh has to watch India vs Pakistan Match and he has no time to do the assignment by himself.

So Saurabh wants you to do his assignment so that he doesn’t get scolded by Ruby Mam . The assignment

is as follows , Suppose there are X particles initially at time t=0 in a box. At a time t the number of particles in

box becomes t times the number of particles at time t-1 . You will be given N and X where N is time at which the

number of particles in box is to be calculated and X is the number of particles at time t=0.

-----Input-----
The first line will contain the integer T, the number of test cases. Each test case consists of two space

separated integers N and X .

-----Output-----
For each test case, output the answer to the query. Since the output can be very large, output the answer modulo

10^6+3

-----Constraints-----
- 1 ≤ T ≤ 100000
- 1 ≤ N,X ≤ 10^18

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

Output:
2
2

-----Explanation-----
Example case 2.At t=0 particles are 1 ,so at t=1 ,particles are 1*1 = 1 particles. At t=2, particles are 2*1 = 2 particles.

a = [1]
M = 10**6 + 3
for ii in range(1, 1000005):
 a.append((a[-1]*ii)%M)
for __ in range(eval(input())):
 n, x = list(map(int, input().split()))
 if n>=M: print(0)
 else: print((a[n]*x)%M)


Solve in Python:
Help Suzuki rake his garden!

The monastery has a magnificent Zen garden made of white gravel and rocks and it is raked diligently everyday by the monks. Suzuki having a keen eye is always on the lookout for anything creeping into the garden that must be removed during the daily raking such as insects or moss.

You will be given a string representing the garden such as:

```
garden = 'gravel gravel gravel gravel gravel gravel gravel gravel gravel rock slug ant gravel gravel snail rock gravel gravel gravel gravel gravel gravel gravel slug gravel ant gravel gravel gravel gravel rock slug gravel gravel gravel gravel gravel snail gravel gravel rock gravel snail slug gravel gravel spider gravel gravel gravel gravel gravel gravel gravel gravel moss gravel gravel gravel snail gravel gravel gravel ant gravel gravel moss gravel gravel gravel gravel snail gravel gravel gravel gravel slug gravel rock gravel gravel rock gravel gravel gravel gravel snail gravel gravel rock gravel gravel gravel gravel gravel spider gravel rock gravel gravel'
```

Rake out any items that are not a rock or gravel and replace them with gravel such that:

```
garden = 'slug spider rock gravel gravel gravel gravel gravel gravel gravel'
```

Returns a string with all items except a rock or gravel replaced with gravel:

```
garden = 'gravel gravel rock gravel gravel gravel gravel gravel gravel gravel'
```

Please also try the other Kata in this series..

* [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b)
* [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c)
* [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255)
* [Suzuki needs help lining up his students!](https://www.codewars.com/kata/5701800886306a876a001031)
* [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)

def rake_garden(garden):
    garden = garden.split(" ")
    for i in range(len(garden)):
        if garden[i] != "gravel" and garden[i]!= "rock":
            garden[i] = "gravel"
    return " ".join(garden)


Solve in Python:
Help a fruit packer sort out the bad apples.

There are 7 varieties of apples, all packaged as pairs and stacked in a fruit box. Some of the apples are spoiled. The fruit packer will have to make sure the spoiled apples are either removed from the fruit box or replaced. Below is the breakdown:

Apple varieties are represented with numbers, `1 to 7`

A fruit package is represented with a 2 element array `[4,3]`

A fruit package with one bad apple, or a bad package, is represented with `[2,0]` or `[0,2]`

A fruit package with two bad apples, or a rotten package, is represented with `[0,0]`

A fruit box is represented with:

```
[ [ 1, 3 ],
  [ 7, 6 ],
  [ 7, 2 ],
  [ 1, 3 ],
  [ 0, 2 ],
  [ 4, 5 ],
  [ 0, 3 ],
  [ 7, 6 ] ]

```

Write a program to clear the fruit box off bad apples.

The INPUT will be a fruit box represented with a 2D array: `[[1,3],[7,6],[7,2],[1,3],[0,2],[4,5],[0,3],[7,6]]`

The OUTPUT should be the fruit box void of bad apples: `[[1,3],[7,6],[7,2],[1,3],[2,3],[4,5],[7,6]]`

Conditions to be met:

1.A bad package should have the bad apple replaced if there is another bad package with a good apple to spare. Else, the bad package should be discarded.

2.The order of the packages in the fruit box should be preserved. Repackaging happens from the top of the fruit box `index = 0` to the bottom `nth index`. Also note how fruits in a package are ordered when repacking. Example shown in INPUT/OUPUT above.

3.Rotten packages should be discarded.

4.There can be packages with the same variety of apples, e.g `[1,1]`, this is not a problem.

def bad_apples(apples):
    lst, notFull = [], []
    for a,b in apples:
        if (bool(a) ^ bool(b)) and notFull:  lst[notFull.pop()].append(a or b)                  # One bad and partially full box already present: fill it (as second element)
        elif a and b:                        lst.append([a,b])                                  # 2 good ones: keep as they are
        elif a or b:                         notFull.append(len(lst)) ; lst.append([a or b])    # 1 good but no partial box: archive
    if notFull: lst.pop(notFull.pop())                                                          # If 1 not full box remains: remove it
    return lst


Solve in Python:
Henry and Derek are waiting on a room, eager to join the Snackdown 2016 Qualifier Round. They decide to pass the time by playing a game.
In this game's setup, they write N positive integers on a blackboard. Then the players take turns, starting with Henry. In a turn, a player selects one of the integers, divides it by 2, 3, 4, 5 or 6, and then takes the floor to make it an integer again. If the integer becomes 0, it is erased from the board. The player who makes the last move wins.

Henry and Derek are very competitive, so aside from wanting to win Snackdown, they also want to win this game. Assuming they play with the optimal strategy, your task is to predict who wins the game.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the number of integers they wrote on the board. The second line contains N space-separated integers A1, A2, ..., AN denoting the integers themselves.

-----Output-----
For each test case, output a single line containing either “Henry” or “Derek” (without quotes), denoting the winner of the game.

-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 100
- 1 ≤ Ai ≤ 1018

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

Output:Henry
Derek

-----Explanation-----
Example case 1. In this test case, the numbers on the board are [3,4]. Henry can win by selecting 4 and then dividing it by 2. The integers on the board are now [3,2]. Derek now has a couple of choices:
- Derek can divide 2 by 3, 4, 5 or 6, making it 0 and removing it. Now only one integer remains on the board, 3, and Henry can just divide it by 6 to finish, and win, the game.
- Derek can divide 3 by 4, 5 or 6, making it 0 and removing it. Now only one integer remains on the board, 2, and Henry can just divide it by 6 to finish, and win, the game.
- Derek can divide 2 by 2. Now the integers are [1,3]. Henry can respond by dividing 3 by 3. The integers are now [1,1]. Now Derek has...

for _ in range(int(input())):
 n=int(input())
 a=[int(x) for x in input().split()]

 def nimber(game):
  if game<=2:
   return game
  mx=2
  nim=2
  while True:
   if nim==3:
    mx*=3
    mx/=2
   else:
    mx*=2
   if game<mx:
    return nim
   nim+=1
   nim%=4

 x=0
 for aa in a:
  x^=nimber(aa)
 if x!=0:
  print("Henry")
 else:
  print("Derek")


Solve in Python:
Here we have a function that help us spam our hearty laughter. But is not working! I need you to find out why...

Expected results:

```python
spam(1)  ==> "hue"
spam(6)  ==> "huehuehuehuehuehue"
spam(14) ==> "huehuehuehuehuehuehuehuehuehuehuehuehuehue"
```

def spam(number):
    return number * 'hue'


Solve in Python:
Here you have to do some mathematical operations on a "dirty string". This kata checks some basics, it's not too difficult.

__So what to do?__

Input: String which consists of two positive numbers (doubles) and exactly one operator like `+, -, * or /` always between these numbers. The string is dirty, which means that there are different characters inside too, not only numbers and the operator. You have to combine all digits left and right, perhaps with "." inside (doubles), and to calculate the result which has to be rounded to an integer and converted to a string at the end.

### Easy example:

```
Input: "gdfgdf234dg54gf*23oP42"
Output: "54929268" (because 23454*2342=54929268)
```

First there are some static tests, later on random tests too...

### Hope you have fun! :-)

import re

def calculate_string(st):
    st = re.sub(r'[^-+*/\d.]', '', st)
    result = eval(st)
    return str(int(round(result)))


Solve in Python:
Here you will create the classic [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle).
Your function will be passed the depth of the triangle and you code has to return the corresponding pascal triangle up to that depth.

The triangle should be returned as a nested array.

for example:
```python
pascal(5) # should return [[1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]
```

To build the triangle, start with a single 1 at the top, for each number in the next row you just take the two numbers above it and add them together (except for the edges, which are all `1`), e.g.:
```
              [1]
            [1   1]
          [1   2   1]
        [1   3   3   1]
```

def pascal(p):
    row, res = [1], []
    for x in range(max(p, 0)):
        res.append(row)
        row = [l + r for l, r in zip(row + [0], [0] + row)]
    return res


Solve in Python:
Here your task is to Create a (nice) Christmas Tree.
You don't have to check errors or incorrect input values, every thing is ok without bad tricks, only one int parameter as input and a string to return;-)...
So what to do?First three easy examples:

````
Input: 3 and Output:
  *
 ***
*****
 ###

 Input 9 and Output:
    *
   ***
  *****
   ***
  *****
 *******
  *****
 *******
*********
   ###

 Input 17 and Output:
      *
     ***
    *****
     ***
    *****
   *******
    *****
   *******
  *********
   *******
  *********
 ***********
  *********
 ***********
*************
     ###

Really nice trees, or what???! So merry Christmas;-)
````

You can see, always a root, always steps of hight 3, tree never smaller than 3 (return "") and no difference for input values like 15 or 17 (because (int) 15/3 = (int) 17/3). That's valid for every input and every tree.
I think there's nothing more to say - perhaps look at the testcases too;-)!

There are some static tests at the beginning and many random tests if you submit your solution.
Hope you have fun:-)!

def christmas_tree(height):
    if height < 3:
        return ''
    res = [1, 3, 5]
    for _ in range((height-3)//3):
        res.extend(res[-2:] + [res[-1]+2])
    w = max(res)
    ans = [('*' * r).center(w).rstrip() for r in res] + ['###'.center(w).rstrip()]
    return '\r\n'.join(ans)


Solve in Python:
Here's a way to construct a list containing every positive rational number:

Build a binary tree where each node is a rational and the root is `1/1`, with the following rules for creating the nodes below:
* The value of the left-hand node below `a/b` is `a/a+b`
* The value of the right-hand node below `a/b` is `a+b/b`

So the tree will look like this:

```
                       1/1
                  /           \
            1/2                  2/1
           /    \              /     \
       1/3        3/2        2/3       3/1
      /   \      /   \      /   \     /   \
   1/4    4/3  3/5   5/2  2/5   5/3  3/4   4/1

 ...
```

Now traverse the tree, breadth first, to get a list of rationals.

```
[ 1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, .. ]
```

Every positive rational will occur, in its reduced form, exactly once in the list, at a finite index.

```if:haskell
In the kata, we will use tuples of type `(Integer, Integer)` to represent rationals, where `(a, b)` represents `a / b`
```
```if:javascript
In the kata, we will use tuples of type `[ Number, Number ]` to represent rationals, where `[a,b]` represents `a / b`
```

Using this method you could create an infinite list of tuples:

matching the list described above:

However, constructing the actual list is too slow for our purposes. Instead, study the tree above, and write two functions:

For example:

from math import ceil
def rat_at(n):
    if n==0:return (1,1)
    a,b=rat_at(max(ceil(n/2)-1,0))
    return (a,b+a) if n%2 else (a+b,b)

def index_of(a,b):
    if a==b==1:return 0
    elif a<b:return index_of(a,b-a)*2+1
    else: return (index_of(a-b,b)+1)*2


Solve in Python:
Hey CodeWarrior,

we've got a lot to code today!

I hope you know the basic string manipulation methods, because this kata will be all about them.

Here we go...

## Background

We've got a very long string, containing a bunch of User IDs. This string is a listing, which seperates each user ID with a comma and a whitespace ("' "). Sometimes there are more than only one whitespace. Keep this in mind! Futhermore, some user Ids are written only in lowercase, others are mixed lowercase and uppercase characters. Each user ID starts with the same 3 letter "uid", e.g. "uid345edj". But that's not all! Some stupid student edited the string and added some hashtags (#). User IDs containing hashtags are invalid, so these hashtags should be removed!

## Task

1.  Remove all hashtags
2.  Remove the leading "uid" from each user ID
3.  Return an array of strings --> split the string
4.  Each user ID should be written in only lowercase characters
5.  Remove leading and trailing whitespaces

---

## Note

Even if this kata can be solved by using Regex or Linq, please try to find a solution by using only C#'s string class.

Some references for C#:

- [Microsoft MDSN: Trim](https://msdn.microsoft.com/de-de/library/t97s7bs3%28v=vs.110%29.aspx)
- [Microsoft MSDN: Split](https://msdn.microsoft.com/de-de/library/tabh47cf%28v=vs.110%29.aspx)
- [Microsoft MSDN: ToLower](https://msdn.microsoft.com/en-us/library/system.string.tolower%28v=vs.110%29.aspx)
- [Microsoft MSDN: Replace](https://msdn.microsoft.com/de-de/library/fk49wtc1%28v=vs.110%29.aspx)
- [Microsoft MSDN: Substring](https://msdn.microsoft.com/de-de/library/aka44szs%28v=vs.110%29.aspx)

get_users_ids = lambda string: [x.strip()[3:].strip() for x in string.lower().replace('#','').split(', ')]


Solve in Python:
Hey, Path Finder, where are you?

## Path Finder Series:
-       [#1: can you reach the exit?](https://www.codewars.com/kata/5765870e190b1472ec0022a2)
-       [#2: shortest path](https://www.codewars.com/kata/57658bfa28ed87ecfa00058a)
-       [#3: the Alpinist](https://www.codewars.com/kata/576986639772456f6f00030c)
-       [#4: where are you?](https://www.codewars.com/kata/5a0573c446d8435b8e00009f)
-       [#5: there's someone here](https://www.codewars.com/kata/5a05969cba2a14e541000129)

x = 0
y = 0
heading = 0

def plus(cpl1, cpl2, factor):
    return [cpl1[0] + cpl2[0] * factor, cpl1[1] + cpl2[1] * factor]

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

def change_heading(heading, character):
    if character == "l":
        return (heading + 1) % 4
    if character == "r":
        return (heading - 1) % 4
    if character == "L":
        return (heading - 2) % 4
    if character == "R":
        return (heading - 2) % 4
def i_am_here(path):
    nonlocal x
    nonlocal y
    nonlocal heading
    buffnum = ""
    i = 0
    while i < len(path):
        character = path[i]
        if '0' <= character <= '9':
            buffnum += character
        else:
            if buffnum != "":
                [x, y] = plus([x, y], headings[heading], int(buffnum))
                buffnum = ""
            heading = change_heading(heading, character)
        i += 1
    if buffnum != "":
        [x, y] = plus([x, y], headings[heading], int(buffnum))
    return [x, y]