Solve in Python:
In this kata you have to create all permutations of an input string and remove duplicates, if present. This means, you have to shuffle all letters from the input in all possible orders.

Examples:

```python
permutations('a'); # ['a']
permutations('ab'); # ['ab', 'ba']
permutations('aabb'); # ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa']
```

The order of the permutations doesn't matter.

from itertools import permutations as pm
permutations=lambda s: map(''.join, set(pm(s)))


Solve in Python:
In this kata you must determine the lowest floor in a building from which you cannot drop an egg without it breaking. You may assume that all eggs are the same; if one egg breaks when dropped from floor `n`, all eggs will. If an egg survives a drop from some floor, it will survive a drop from any floor below too.

You are given `num_eggs` eggs and are allowed to make a maximum of `num_drops` drops. If an egg does not break when dropped, it may be reused. You may assume that it is feasible to determine the floor with the given number of eggs and drops.

Example 1:
You are given 1 egg and 10 drops. You start by dropping the egg from the first floor (floor numbering starts at 1). If it breaks, the answer is 1. If it does not break, you drop it from the second floor. If it breaks, the answer is 2. Otherwise you continue in the same manner until you reach a floor where the egg breaks. You may assume that you will reach that floor before you have exhausted your drops (i.e., in this example, the egg will break when dropped from floor 10 or lower).

Example 2: You are given 2 eggs and 10 drops. The highest floor for which this problem has a solution is floor 55, so you may assume that the answer is floor 55 or a lower floor. You will have to determine how the number 55 is derived and generalize it for any number of eggs and drops.

To solve this problem, you need to write a function `solve` that takes an argument `emulator` and returns the lowest floor from which an egg will break if dropped. The `emulator` object has the following properties and method which you may invoke:

  1. `emulator.eggs` returns the number of eggs you have left. You may use this property to detemine the number of eggs you are given initially.
  2. `emulator.drops` returns the the number of drops you have left. You may use this property to detemine the number of drops you are given initially.
  3. `emulator.drop(n)` returns `True` if an egg dropped from floor `n` breaks and `False` if it does not break. The number of times that you may...

#THanks to easter eggs kata ;*

def height(n, m):
    if n >= m:
        return (2 ** (min(n, m)) - 1)
    f = 1
    res = 0
    for i in range(n):
        f = f * (m - i) // (i + 1)
        res += f
    return res

def solve(emulator):
    m = emulator.drops
    n = emulator.eggs
    h = 0
    tryh = 0
    while n and m:
        tryh = height(n - 1, m - 1) + 1
        if emulator.drop(h + tryh):
            n -= 1
        else:
            h += tryh
        m -= 1
    return(h + 1)
    # continue here


Solve in Python:
In this kata you must take an input string, reverse the order of the words, and reverse the order of the letters within the words.

But, as a bonus, every test input will end with a punctuation mark (! ? .) and the output should be returned with the mark at the end.

A few examples should help clarify:

```python
esrever("hello world.") == "dlrow olleh."

esrever("Much l33t?") == "t33l hcuM?"

esrever("tacocat!") == "tacocat!"
```

Quick Note: A string will always be passed in (though it may be empty) so no need for error-checking other types.

def esrever(string):
    return string[-2::-1] + string[-1] if string else ""


Solve in Python:
In this kata you need to build a function to return either `true/True` or `false/False` if a string can be seen as the repetition of a simpler/shorter subpattern or not.

For example:

```cpp,java
hasSubpattern("a") == false; //no repeated pattern
hasSubpattern("aaaa") == true; //created repeating "a"
hasSubpattern("abcd") == false; //no repeated pattern
hasSubpattern("abababab") == true; //created repeating "ab"
hasSubpattern("ababababa") == false; //cannot be entirely reproduced repeating a pattern
```
```python
has_subpattern("a") == False #no repeated pattern
has_subpattern("aaaa") == True #created repeating "a"
has_subpattern("abcd") == False #no repeated pattern
has_subpattern("abababab") == True #created repeating "ab"
has_subpattern("ababababa") == False #cannot be entirely reproduced repeating a pattern
```
Strings will never be empty and can be composed of any character (just consider upper- and lowercase letters as different entities) and can be pretty long (keep an eye on performances!).

If you liked it, go for the [next kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/) of the series!

def has_subpattern(string):
    s = len(string)
    for i in range(1,s//2+1):
        if s % i == 0:
            q = s//i
            if string[:i] * q == string:
                return True
    return False


Solve in Python:
In this kata you need to create a function that takes a 2D array/list of non-negative integer pairs and returns the sum of all the "saving" that you can have getting the [LCM](https://en.wikipedia.org/wiki/Least_common_multiple) of each couple of number compared to their simple product.

For example, if you are given:
```
[[15,18], [4,5], [12,60]]
```
Their product would be:
```
[270, 20, 720]
```
While their respective LCM would be:
```
[90, 20, 60]
```
Thus the result should be:
```
(270-90)+(20-20)+(720-60)==840
```
This is a kata that I made, among other things, to let some of my trainees familiarize with the [euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm), a really neat tool to have on your belt ;)

from math import gcd

def sum_differences_between_products_and_LCMs(pairs):
    return sum((x[0]*x[1]-(x[0]*x[1]/(gcd(x[0],x[1])if x[1]!=0 else 1))) for x in pairs)


Solve in Python:
In this kata you need to write a function that will receive two strings (```n1``` and ```n2```), each representing an integer as a binary number. A third parameter will be provided (```o```) as a string representing one of the following operators: add, subtract, multiply.

Your task is to write the calculate function so that it will perform the arithmetic and the result returned should be a string representing the binary result.

Examples:
```
1 + 1 === 10
10 + 10 === 100
```

Negative binary numbers are usually preceded by several 1's. For this kata, negative numbers can be represented with the negative symbol at the beginning of the string.

Examples of negatives:
```
1 - 10 === -1
10 - 100 === -10
```

def calculate(n1, n2, o):
    return bin(int(n1, 2) + int(n2, 2) if o == 'add' else int(n1, 2) - int(n2, 2) if o == 'subtract' else int(n1, 2) * int(n2, 2)).replace('0b', '')


Solve in Python:
In this kata you should simply determine, whether a given year is a leap year or not. In case you don't know the rules, here they are:

* years divisible by 4 are leap years
* but years divisible by 100 are **not** leap years
* but years divisible by 400 are leap years

Additional Notes:

* Only valid years (positive integers) will be tested, so you don't have to validate them

Examples can be found in the test fixture.

import calendar

def isLeapYear(year):
    # if calendar is not available:
    # return year % 4 == 0 and year and (year % 400 == 0 or year % 100 != 0)
    return calendar.isleap(year)


Solve in Python:
In this kata you will be given a random string of letters and tasked with returning them as a string of comma-separated sequences sorted alphabetically, with each sequence starting with an uppercase character followed by `n-1` lowercase characters, where `n` is the letter's alphabet position `1-26`.

## Example

```python
alpha_seq("ZpglnRxqenU") -> "Eeeee,Ggggggg,Llllllllllll,Nnnnnnnnnnnnnn,Nnnnnnnnnnnnnn,Pppppppppppppppp,Qqqqqqqqqqqqqqqqq,Rrrrrrrrrrrrrrrrrr,Uuuuuuuuuuuuuuuuuuuuu,Xxxxxxxxxxxxxxxxxxxxxxxx,Zzzzzzzzzzzzzzzzzzzzzzzzzz"
```

## Technical Details

- The string will include only letters.
- The first letter of each sequence is uppercase followed by `n-1` lowercase.
- Each sequence is separated with a comma.
- Return value needs to be a string.

alpha_seq=lambda s:','.join((c.upper()+c*(ord(c)-97))for c in sorted(s.lower()))


Solve in Python:
In this kata you will be given a sequence of the dimensions of rectangles ( sequence with width and length ) and circles ( radius - just a number ).
Your task is to return a new sequence of dimensions, sorted ascending by area.

For example,

```python
seq = [ (4.23, 6.43), 1.23, 3.444, (1.342, 3.212) ] # [ rectangle, circle, circle, rectangle ]
sort_by_area(seq) => [ ( 1.342, 3.212 ), 1.23, ( 4.23, 6.43 ), 3.444 ]
```

This kata inspired by [Sort rectangles and circles by area](https://www.codewars.com/kata/sort-rectangles-and-circles-by-area/).

from math import pi as PI

def sort_by_area(lst):
    return sorted(lst, key=lambda d: d[0] * d[1] if isinstance(d, tuple) else PI * d * d)


Solve in Python:
In this kata you will be given an **integer n**, which is the number of times that is thown a coin. You will have to return an array of string for all the possibilities (heads[H] and tails[T]). Examples:
```coin(1) should return {"H", "T"}```
```coin(2) should return {"HH", "HT", "TH", "TT"}```
```coin(3) should return {"HHH", "HHT", "HTH", "HTT", "THH", "THT", "TTH", "TTT"}```
When finished sort them alphabetically.

In C and C++ just return a ```char*``` with all elements separated by```,``` (without space):
```coin(2) should return "HH,HT,TH,TT"```
INPUT:
```0 < n < 18```
Careful with performance!! You'll have to pass 3 basic test (n = 1, n = 2, n = 3), many medium tests (3 < n <= 10) and many large tests (10 < n < 18)

from itertools import product

def coin(n):
    return list(map(''.join, product(*(["HT"]*n))))


Solve in Python:
In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.

### Example

```python
filter_list([1,2,'a','b']) == [1,2]
filter_list([1,'a','b',0,15]) == [1,0,15]
filter_list([1,2,'aasf','1','123',123]) == [1,2,123]
```

def filter_list(l):
  'return a new list with the strings filtered out'
  return [e for e in l if isinstance(e, int)]


Solve in Python:
In this kata you will create a function that takes in a list and returns a list with the reverse order.

### Examples

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

def reverse_list(l):
  'return a list with the reverse order of l'
  c = [0] * len(l)
  for i in range(len(l)):
      c[i] = l[len(l) - i - 1]
  return c


Solve in Python:
In this kata you will create a function to check a non-negative input to see if it is a prime number.

The function will take in a number and will return True if it is a prime number and False if it is not.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

### Examples

def is_prime(n):
    'Return True if n is a prime number otherwise return False'
    # 0 and 1 are not primes
    if n < 2:
        return False

    # 2 is only even prime so reject all others
    if n == 2:
        return True

    if not n & 1:
        return False

    # test other possiblities
    for i in range(3, n):
        if (n % i) == 0 and n != i:
            return False

    return True


Solve in Python:
In this kata you will have to change every letter in a given string to the next letter in the alphabet. You will write a function `nextLetter` to do this. The function will take a single parameter `s` (string).

Examples:

```
"Hello" --> "Ifmmp"

"What is your name?" --> "Xibu jt zpvs obnf?"

"zoo" --> "app"

"zzZAaa" --> "aaABbb"
```

Note: spaces and special characters should remain the same. Capital letters should transfer in the same way but remain capitilized.

def next_letter(string):
    return "".join(chr(ord(c)+(-25 if c in 'zZ' else 1)) if c.isalpha() else c for c in string)


Solve in Python:
In this kata you will have to modify a sentence so it meets the following rules:

convert every word backwards that is:

    longer than 6 characters

  OR

    has 2 or more 'T' or 't' in it

convert every word uppercase that is:

    exactly 2 characters long

  OR

    before a comma

convert every word to a "0" that is:

    exactly one character long

 NOTES:

      Punctuation must not be touched. if a word is 6 characters long, and a "." is behind it,
      it counts as 6 characters so it must not be flipped, but if a word is 7 characters long,
      it must be flipped but the "." must stay at the end of the word.
      -----------------------------------------------------------------------------------------
      Only the first transformation applies to a given word, for example 'companions,'
      will be 'snoinapmoc,' and not 'SNOINAPMOC,'.
      -----------------------------------------------------------------------------------------
      As for special characters like apostrophes or dashes, they count as normal characters,
      so e.g 'sand-colored' must be transformed to 'deroloc-dnas'.


Solve in Python:
In this kata you're expected to sort an array of 32-bit integers in ascending order of the number of **on** bits they have.

E.g Given the array **[7, 6, 15, 8]**

- 7 has **3 on** bits  (000...0**111**)
- 6 has **2 on** bits  (000...00**11**)
- 15 has **4 on** bits (000...**1111**)
- 8 has **1 on** bit   (000...**1**000)

So the array in sorted order would be **[8, 6, 7, 15]**.

In cases where two numbers have the same number of bits, compare their real values instead.

E.g between 10 **(...1010)** and 12 **(...1100)**, they both have the same number of **on** bits '**2**' but the integer 10 is less than 12 so it comes first in sorted order.

Your task is to write the function `sortBybit()` that takes an array of integers and sort them as described above.

```if-not:haskell
Note: Your function should modify the input rather than creating a new array.
```

def sort_by_bit(lst):
    return sorted(lst, key=lambda n: (f"{n:b}".count("1"), n))


Solve in Python:
In this kata your mission is to rotate matrix counter - clockwise N-times.

So, you will have 2 inputs:

    1)matrix

    2)a number, how many times to turn it

And an output is turned matrix.
Example:

    matrix = [[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]]

    times_to_turn = 1

It should return this:

    [[4, 8, 12, 16],
     [3, 7, 11, 15],
     [2, 6, 10, 14],
     [1, 5, 9, 13]])

Note: all matrixes will be square. Also random tests will have big numbers in input (times to turn)

Happy coding!

import numpy as np

def rotate_against_clockwise(matrix, times):
    return np.rot90(matrix, times).tolist()


Solve in Python:
In this kata, the number 0 is infected. You are given a list. Every turn, any item in the list that is adjacent to a 0 becomes infected and transforms into a 0. How many turns will it take for the whole list to become infected?

```
[0,1,1,0] ==> [0,0,0,0]
All infected in 1 turn.

[1,1,0,1,1] --> [1,0,0,0,1] --> [0,0,0,0,0]
All infected in 2 turns

[0,1,1,1] --> [0,0,1,1] --> [0,0,0,1] --> [0,0,0,0]
All infected in 3 turns.
```

All lists will contain at least one item, and at least one zero, and the only items will be 0s and 1s. Lists may be very very long, so pure brute force approach will not work.

def infected_zeroes(a):
    zeros = [i for i, n in enumerate(a) if not n]
    return len(zeros) and max((y - x) // 2 for x, y in
            zip([-1 - zeros[0]] + zeros, zeros + [2*len(a) -1 - zeros[-1]]))


Solve in Python:
In this kata, we want to discover a small property of numbers.
We say that a number is a **dd** number if it contains d occurences of a digit d, (d is in [1,9]).

## Examples

* 664444309 is a **dd** number, as it contains 4 occurences of the number 4
* 30313, 122 are **dd** numbers as they respectively contain 3 occurences of the number 3, and (1 occurence of the number 1 AND 2 occurences of the number 2)
* 123109, 0, 56542 are not **dd** numbers

## Task

Your task is to implement a function called `is_dd` (`isDd` in javascript) that takes a **positive** number (type depends on the language) and returns a boolean corresponding to whether the number is a **dd** number or not.

def is_dd(n):
    n = str(n)
    return any(n.count(d) == int(d) for d in set(n))


Solve in Python:
In this kata, we will check is an array is (hyper)rectangular.
A rectangular array is an N-dimensional array with fixed sized within one dimension. Its sizes can be repsented like A1xA2xA3...xAN. That means a N-dimensional array has N sizes. The 'As' are the hyperrectangular properties of an array.

You should implement a functions that returns a N-tuple with the arrays hyperrectangular properties or None if the array is not hyperrectangular.
```
hyperrectangularity_properties(arr)
```
## Note
An empty array IS rectagular and has one dimension of length 0
```
hyperrectangularity_properties([]) == (0,)
```
## Example
```
1D array
hyperrectangularity_properties([1,2,3]) == (3,)

2D arrays

hyperrectangularity_properties(
                                [[0,1,2],
                                 [3,4,5],
                                 [6,7,8]] ) == (3,3)
hyperrectangularity_properties(
                                [[0,1,2],
                                 [3,4,5]] ) == (2,3)
hyperrectangularity_properties(
                                [[0,1,2],
                                 [3,4]  ] ) == None
3D arrays
hyperrectangularity_properties(
                                [
                                 [ [0], [2] ],
                                 [ [0], [2] ],
                                 [ [0], [2] ]
                                              ] ) == (3,2,1)
hyperrectangularity_properties(
                                [
                                   [[0],[2]],
                                   [[0],[2,2]],
                                   [[0],[2]]
                                              ] )  ==  None
hyperrectangularity_properties(
                                [[ [], [], [] ]]
                                                ) ==  (1,3,0)
```
### Heterogeneous Arrays can appear too
```
hyperrectangularity_properties(
                                [[0,1,2],
                                 3,
          ...

def hp(arr):
    if not isinstance(arr, list):
        return ()
    elif not arr:
        return (0,)
    xs = list(map(hp, arr))
    if None not in xs and all(x == xs[0] for x in xs):
        return (len(arr),) + xs[0]
hyperrectangularity_properties = hp


Solve in Python:
In this kata, we're going to create the function `nato` that takes a `word` and returns a string that spells the word using the [NATO phonetic alphabet](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet).

There should be a space between each word in the returned string, and the first letter of each word should be capitalized.

For those of you that don't want your fingers to bleed, this kata already has a dictionary typed out for you.

``` python
nato("Banana") # == "Bravo Alpha November Alpha November Alpha"
```
``` ruby
nato("Banana") # == "Bravo Alpha November Alpha November Alpha"
```

letters =  {
    "A": "Alpha",  "B": "Bravo",   "C": "Charlie",
    "D": "Delta",  "E": "Echo",    "F": "Foxtrot",
    "G": "Golf",   "H": "Hotel",   "I": "India",
    "J": "Juliett","K": "Kilo",    "L": "Lima",
    "M": "Mike",   "N": "November","O": "Oscar",
    "P": "Papa",   "Q": "Quebec",  "R": "Romeo",
    "S": "Sierra", "T": "Tango",   "U": "Uniform",
    "V": "Victor", "W": "Whiskey", "X": "X-ray",
    "Y": "Yankee", "Z": "Zulu"
  }

def nato(word):
    stringlist = []
    for ch in word.upper():
        stringlist.append(letters[ch])
    string = " ".join(stringlist)

    return string


Solve in Python:
In this kata, you have to define a function named **func** that will take a list as input.

You must try and guess the pattern how we get the output number and return list - **[output number,binary representation,octal representation,hexadecimal representation]**, but **you must convert that specific number without built-in : bin,oct and hex functions.**

Examples :

```python
func([12,13,6,3,6,45,123]) returns - [29,'11101','35','1d']

func([1,9,23,43,65,31,63,99]) returns - [41,'101001','51','29']

func([2,4,6,8,10,12,14,16,18,19]) returns - [10,'1010','12','a']
```

def func(l):
    n = sum(l) // len(l)
    return [n] + '{:b} {:o} {:x}'.format(n, n, n).split()


Solve in Python:
In this kata, you need to make a (simplified) LZ78 encoder and decoder.
[LZ78](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ78) is a dictionary-based compression method created in 1978. You will find a  detailed explanation about how it works below.

The input parameter will always be a non-empty string of upper case alphabetical characters. The maximum decoded string length is 1000 characters.

# Instructions

*If anyone has any ideas on how to make the instructions shorter / clearer, that would be greatly appreciated.*

If the below explanation is too confusing, just leave a comment and I'll be happy to help.

---

The input is looked at letter by letter.
Each letter wants to be matched with the longest dictionary substring at that current time.

The output is made up of tokens.
Each token is in the format ``
where `index` is the index of the longest dictionary value that matches the current substring
and `letter` is the current letter being looked at.

Here is how the string `'ABAABABAABAB'` is encoded:

* First, a dictionary is initialised with the 0th item pointing to an empty string:

```md
Dictionary      Input             Output
0  |  ''        ABAABABAABAB
```

* The first letter is `A`. As it doesn't appear in the dictionary, we add `A` to the next avaliable index.
The token `<0, A>` is added to the output:

```md
Dictionary      Input             Output

0  |  ''        ABAABABAABAB      <0, A>
1  |  A         ^
```

* The second letter is `B`. It doesn't appear in the dictionary, so we add `B` to the next avaliable index.
The token `<0, B>` is added to the output:

```md
Dictionary      Input             Output

0  |  ''        ABAABABAABAB      <0, A> <0, B>
1  |  A          ^
2  |  B
```

* The third letter is `A` again: it already appears in the dictionary at position `1`. We add the next letter which is also `A`. `AA` doesn't appear in the dictionary, so we add it to the next avaliable index.
The token `<1, A>` is added to the output:

```md
Dictionary      Input             Output

0  | ...

def encoder(data):
    d,c,o=[''],'',''
    for i in data: d,c,o=(d,c+i,o)if c+i in d else(d+[c+i],'',o+str(d.index(c))+i)
    return o+(str(d.index(c)) if c else '')

def decoder(data):
    d,c,o=[''],'',''
    for i in data: d,c,o=(d,c+i,o)if i in '0123456789' else(d+[d[int(c)]+i],'',o+d[int(c)]+i)
    return o+(d[int(c)] if c else '')


Solve in Python:
In this kata, you should calculate type of triangle with three given sides ``a``, ``b`` and ``c`` (given in any order).

If all angles are less than ``90°``, this triangle is ``acute`` and function should return ``1``.

If one angle is strictly ``90°``, this triangle is ``right`` and function should return ``2``.

If one angle more than ``90°``, this triangle is ``obtuse`` and function should return ``3``.

If three sides cannot form triangle, or one angle is ``180°`` (which turns triangle into segment) - function should return ``0``.

Input parameters are ``sides`` of given triangle. All input values are non-negative floating point or integer numbers (or both).

Acute

Right

Obtuse

### Examples:
```python
triangle_type(2, 4, 6) # return 0 (Not triangle)
triangle_type(8, 5, 7) # return 1 (Acute, angles are approx. 82°, 38° and 60°)
triangle_type(3, 4, 5) # return 2 (Right, angles are approx. 37°, 53° and exactly 90°)
triangle_type(7, 12, 8) # return 3 (Obtuse, angles are approx. 34°, 106° and 40°)
```

If you stuck, this can help you: http://en.wikipedia.org/wiki/Law_of_cosines. But you can solve this kata even without angle calculation.

There is very small chance of random test to fail due to round-off error, in such case resubmit your solution.

def triangle_type(a, b, c):
  x,y,z = sorted([a,b,c])
  if z >= x + y: return 0
  if z*z == x*x + y*y: return 2
  return 1 if z*z < x*x + y*y else 3


Solve in Python:
In this kata, you will be given a string of text and valid parentheses, such as `"h(el)lo"`. You must return the string, with only the text inside parentheses reversed, so `"h(el)lo"` becomes `"h(le)lo"`. However, if said parenthesized text contains parenthesized text itself, then that too must reversed back, so it faces the original direction. When parentheses are reversed, they should switch directions, so they remain syntactically correct (i.e. `"h((el)l)o"` becomes `"h(l(el))o"`). This pattern should repeat for however many layers of parentheses. There may be multiple groups of parentheses at any level (i.e. `"(1) (2 (3) (4))"`), so be sure to account for these.

For example:
```python
reverse_in_parentheses("h(el)lo") == "h(le)lo"
reverse_in_parentheses("a ((d e) c b)") == "a (b c (d e))"
reverse_in_parentheses("one (two (three) four)") == "one (ruof (three) owt)"
reverse_in_parentheses("one (ruof ((rht)ee) owt)") == "one (two ((thr)ee) four)"
```

Input parentheses will always be valid (i.e. you will never get "(()").

def pairs(s):
    stack, pairs = [], {}
    for i, c in enumerate(s):
        if c == '(': stack.append(i)
        elif c == ')': pairs[stack.pop()] = i
    return pairs

swap_parentheses = str.maketrans('()', ')(')

def reverse_in_parentheses(s):
    res = list(s)
    for i, j in pairs(s).items():
        res[i + 1:j] = ''.join(res[j - 1:i:-1]).translate(swap_parentheses)
    return ''.join(res)


Solve in Python:
In this kata, you will do addition and subtraction on a given string. The return value must be also a string.

**Note:** the input will not be empty.

## Examples

```
"1plus2plus3plus4"  --> "10"
"1plus2plus3minus4" -->  "2"
```

import re

def calculate(s):
    xs = re.split(r'(plus|minus)', s)
    xs[::2] = map(int, xs[::2])
    return str(xs[0] + sum(
        xs[i+1] * (1 if xs[i] == 'plus' else -1)
        for i in range(1, len(xs), 2)
    ))


Solve in Python:
In this kata, you will make a function that converts between `camelCase`, `snake_case`, and `kebab-case`.

You must write a function that changes to a given case. It must be able to handle all three case types:

```python
py> change_case("snakeCase", "snake")
"snake_case"
py> change_case("some-lisp-name", "camel")
"someLispName"
py> change_case("map_to_all", "kebab")
"map-to-all"
py> change_case("doHTMLRequest", "kebab")
"do-h-t-m-l-request"
py> change_case("invalid-inPut_bad", "kebab")
None
py> change_case("valid-input", "huh???")
None
py> change_case("", "camel")
""
```

Your function must deal with invalid input as shown, though it will only be passed strings. Furthermore, all valid identifiers will be lowercase except when necessary, in other words on word boundaries in `camelCase`.

_**(Any translations would be greatly appreciated!)**_

import re

def change_case(label, target):
    if ('_' in label) + ('-' in label) + (label != label.lower()) > 1:
        return

    if target == 'snake':
        return re.sub('([A-Z])', r'_\1', label.replace('-', '_')).lower()

    if target == 'kebab':
        return re.sub('([A-Z])', r'-\1', label.replace('_', '-')).lower()

    if target == 'camel':
        return re.sub('([_-])([a-z])', lambda m: m.group(2).upper(), label)


Solve in Python:
In this kata, you will write a function that returns the positions and the values of the "peaks" (or local maxima) of a numeric array.

For example, the array `arr = [0, 1, 2, 5, 1, 0]` has a peak at position `3` with a value of `5` (since `arr[3]` equals `5`).

~~~if-not:php,cpp,java,csharp
The output will be returned as an object with two properties: pos and peaks. Both of these properties should be arrays. If there is no peak in the given array, then the output should be `{pos: [], peaks: []}`.
~~~
~~~if:php
The output will be returned as an associative array with two key-value pairs: `'pos'` and `'peaks'`.  Both of them should be (non-associative) arrays.  If there is no peak in the given array, simply return `['pos' => [], 'peaks' => []]`.
~~~
~~~if:cpp
The output will be returned as an object of type `PeakData` which has two members: `pos` and `peaks`.  Both of these members should be `vector`s.  If there is no peak in the given array then the output should be a `PeakData` with an empty vector for both the `pos` and `peaks` members.

`PeakData` is defined in Preloaded as follows:

~~~
~~~if:java
The output will be returned as a ``Map>` with two key-value pairs: `"pos"` and `"peaks"`. If there is no peak in the given array, simply return `{"pos" => [], "peaks" => []}`.
~~~
~~~if:csharp
The output will be returned as a `Dictionary>` with two key-value pairs: `"pos"` and `"peaks"`.
If there is no peak in the given array, simply return `{"pos" => new List(), "peaks" => new List()}`.
~~~

Example: `pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3])` should return `{pos: [3, 7], peaks: [6, 3]}` (or equivalent in other languages)

All input arrays will be valid integer arrays (although it could still be empty), so you won't need to validate the input.

The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don't know what is after and before and therefore, we don't know if it is a peak or not).

Also, beware of plateaus !!! `[1, 2, 2, 2, 1]` has a...

def pick_peaks(arr):
    results = {'pos': [], 'peaks': []}

    for i in range(1, len(arr)-1):
        if is_peak(arr, i):
            results['pos'].append(i)
            results['peaks'].append(arr[i])

    return results

def get_direction(last, i):
    if i > last:
        return 1
    elif i == last:
        return 0
    else:
        return -1

def is_peak(arr, index):
    result = False
    cur_val = arr[index]

    if get_direction(cur_val, arr[index -1]) < 0:
        for i in range(index, len(arr)):
            dir = get_direction(cur_val, arr[i])
            if dir < 0:
                result = True
                break
            elif dir > 0:
                result = False
                break

    return result


Solve in Python:
In this kata, you'll be given an integer of range `0 <= x <= 99` and have to return that number spelt out in English. A few examples:

```python
name_that_number(4)   # returns "four"
name_that_number(19)  # returns "nineteen"
name_that_number(99)  # returns "ninety nine"
```

Words should be separated by only spaces and not hyphens. No need to validate parameters, they will always be in the range [0, 99]. Make sure that the returned String has no leading of trailing spaces. Good luck!

lessThan20 = ["","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"]
tens = ["","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"]

def name_that_number(n):
    if n==0: return "zero"
    return helper(n).strip()

def helper(n):
    if n<20: return lessThan20[n]+" "
    return tens[n//10]+" "+helper(n%10)


Solve in Python:
In this kata, you've to count lowercase letters in a given string and return the letter count in a hash with 'letter' as key and count as 'value'. The key must be 'symbol' instead of string in Ruby and 'char' instead of string in Crystal.

Example:

```python
letter_count('arithmetics') #=> {"a": 1, "c": 1, "e": 1, "h": 1, "i": 2, "m": 1, "r": 1, "s": 1, "t": 2}
```

import collections

def letter_count(s):
    result = {}
    for i, d in enumerate(s):
        count = 1
        if d not in result:
            for j in range(i+1, len(s)):
                if d == s[j]:
                    count += 1
            result[d] = count
    return collections.OrderedDict(sorted(result.items()))


Solve in Python:
In this kata, your job is to return the two distinct highest values in a list. If there're less than 2 unique values, return as many of them, as possible.

The result should also be ordered from highest to lowest.

Examples:

```
[4, 10, 10, 9]  =>  [10, 9]
[1, 1, 1]  =>  [1]
[]  =>  []
```

def two_highest(arg1):
    arg2 = list(set(arg1))
    arg2 = sorted(arg2)

    if len(arg2) == 0:
        return []
    if len(arg2) == 1:
        return arg2
    else:
        return [arg2[-1], arg2[-2]]
    pass


Solve in Python:
In this kata, your task is to create a function that takes a single list as an argument and returns a flattened list. The input list will have a maximum of one level of nesting (list(s) inside of a list).

```python
# no nesting
[1, 2, 3]

# one level of nesting
[1, [2, 3]]
```
---

# Examples

```python
>>> flatten_me(['!', '?'])
['!', '?']

>>> flatten_me([1, [2, 3], 4])
[1, 2, 3, 4]

>>> flatten_me([['a', 'b'], 'c', ['d']])
['a', 'b', 'c', 'd']

>>> flatten_me([[True, False], ['!'], ['?'], [71, '@']])
[True, False, '!', '?', 71, '@']
```

Good luck!

def flatten_me(lst):
    res = []
    for l in lst:
        if isinstance(l, list):
            res.extend(l)
        else:
            res.append(l)
    return res


Solve in Python:
In this kata, your task is to find the maximum sum of any straight "beam" on a hexagonal grid, where its cell values are determined by a finite integer sequence seq.
In this context, a beam is a linear sequence of cells in any of the 3 pairs of opposing sides of a hexagon. We'll refer to the sum of a beam's integer values as the "beam value".Refer to the example below for further clarification.
Input
Your function will receive two arguments:

n : the length of each side of the hexagonal grid, where 2 <= n < 100
seq : a finite sequence of (positive and/or nonpositive) integers with a length >= 1The sequence is used to populate the cells of the grid and should be repeated as necessary.The sequence type will be dependent on the language (e.g. array for JavaScript, tuple for Python, etc.).

Output
Your function should return the largest beam value as an integer.
Test Example

In our test example, we have the following arguments:
n = 4
seq = [2, 4, 6, 8]

Below is the hexagonal grid determined by our example arguments;
the sequence repeats itself from left to right, then top to bottom.

   2 4 6 8
  2 4 6 8 2
 4 6 8 2 4 6
8 2 4 6 8 2 4
 6 8 2 4 6 8
  2 4 6 8 2
   4 6 8 2

The three diagrams below illustrate the "beams" in the hexagonal grid above.
In the grid on the left, the horizontal beams are highlighted by their likewise colors,
and the value of each beam is given to its right.
In the center grid, the beams highlighted go from upper-right to bottom-left (and vice-versa).
In the grid on the right, the beams highlighted go from upper-left to bottom-right (and vice-versa).

   2 4 6 8 -> 20           2 4 6 8           2 4 6 8
  2 4 6 8 2 -> 22         2 4 6 8 2         2 4 6 8 2
 4 6 8 2 4 6 -> 30       4 6 8 2 4 6       4 6 8 2 4 6
8 2 4 6 8 2 4 -> 34     8 2 4 6 8 2 4     8 2 4 6 8 2 4
 6 8 2 4 6 8 -> 34       6 8 2 4 6 8       6 8 2 4 6 8
  2 4 6 8 2 -> 22         2 4 6 8 2         2 4 6 8 2
   4 6 8 2 -> 20           4 6 8 2           4 6 8 2

The maximum beam value in our example is 34.

Test...

from itertools import cycle
def max_hexagon_beam(n: int, seq: tuple):
    q = cycle(seq)
    sx, sy, sz = [0] * (2 * n - 1), [0] * (2 * n - 1), [0] * (2 * n - 1)
    for z in range(-(n - 1), n):
        xp = -(n-1) if z >= 0 else -(n - 1) - z
        xk = n-1 if z <= 0 else n - 1 - z
        for x in range(xp, xk + 1):
            y = -(z + x)
            v = next(q)
            sx[x + n - 1] += v
            sy[y + n - 1] += v
            sz[z + n - 1] += v
    return max(sz + sy + sx)


Solve in Python:
In this kata, your task is to identify the pattern underlying a sequence of numbers. For example, if the sequence is [1, 2, 3, 4, 5], then the pattern is [1], since each number in the sequence is equal to the number preceding it, plus 1. See the test cases for more examples.

A few more rules :

pattern may contain negative numbers.
sequence will always be made of a whole number of repetitions of the pattern.
Your answer must correspond to the shortest form of the pattern, e.g. if the pattern is [1], then [1, 1, 1, 1] will not be considered a correct answer.

def find_pattern(sequence):
    pattern = [a-b for a, b in zip(sequence[1:], sequence)]

    for size in range(1, len(pattern)+1):
        if len(pattern) // size * pattern[:size] == pattern:
            return pattern[:size]


Solve in Python:
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)

Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
 Step 1: remove all spaces in the string (but remember their positions)
 Step 2: shift the order of characters in the new string to the right by n characters
 Step 3: put the spaces back in their original positions
 Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n

Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example

```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True

'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'

Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'

Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'

Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni...

def rotate(n, s):
    i = -n % len(s) if len(s) > 0 else 1
    return s[i:] + s[:i]

def cipher(n, s):
    sp = [i for i, c in enumerate(s) if c == " "] + [len(s)]
    s = s.split(' ')
    if n < 0:
        s = [rotate(n, w) for w in s]
    s = rotate(n, ''.join(s))
    s = [s[i+1-x:j-x] for x, (i, j) in enumerate(zip([-1] + sp, sp))]
    if n > 0:
        s = [rotate(n, w) for w in s]
    return ' '.join(s)

def encode(n, strng):
    s = strng
    for _ in range(n):
        s = cipher(n, s)
    return "{} {}".format(n, s)

def decode(strng):
    n, s = strng.split(" ", 1)
    n = int(n)
    for _ in range(n):
        s = cipher(-n, s)
    return s


Solve in Python:
In this kata, your task is to write a function `to_bytes(n)` (or `toBytes(n)` depending on language) that produces a list of bytes that represent a given non-negative integer `n`. Each byte in the list is represented by a string of `'0'` and `'1'` of length 8. The most significant byte is first in the list. The example test cases should provide you with all the details. You may assume that the argument `n` is valid.

def to_bytes(n):
    return [''.join(t) for t in zip(*[iter(format(n,'0{}b'.format((max(1,n.bit_length())+7)//8*8)))]*8)]


Solve in Python:
In this kata, your task is to write a function that returns the smallest and largest integers in an unsorted string. In this kata, a range is considered a finite sequence of consecutive integers.
Input
Your function will receive two arguments:

A string comprised of integers in an unknown range; think of this string as the result when a range of integers is shuffled around in random order then joined together into a string
An integer value representing the size of the range

Output
Your function should return the starting (minimum) and ending (maximum) numbers of the range in the form of an array/list comprised of two integers.

Test Example

```python
input_string = '1568141291110137'

mystery_range(input_string, 10) # [6, 15]

# The 10 numbers in this string are:
# 15 6 8 14 12 9 11 10 13 7
# Therefore the range of numbers is from 6 to 15
```

Technical Details

The maximum size of a range will be 100 integers
The starting number of a range will be: 0 < n < 100
Full Test Suite: 21 fixed tests, 100 random tests
Use Python 3+ for the Python translation
For JavaScript, require has been disabled and most built-in prototypes have been frozen (prototype methods can be added to Array and Function)
All test cases will be valid

If you enjoyed this kata, be sure to check out my other katas

def mystery_range(s,n):
    ss=sorted(s)
    for i in range(1,100):
        jj=sorted("".join(str(k) for k in range(i,i+n)))
        if jj==ss:
            if all(str(j) in s for j in range(i,i+n-1)):
                return [i,i+n-1]


Solve in Python:
In this problem the input will consist of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks ' (apostrophe), . (full stop), , (comma), ; (semicolon), :(colon) and white space characters (blank, newline).
Your task is print the words in the text in lexicographic order (that is, dictionary order). Each word should appear exactly once in your list. You can ignore the case (for instance, "The" and "the" are to be treated as the same word). There should be no uppercase letters in the output.
For example, consider the following candidate for the input text:
This is a sample piece of text to illustrate this
problem.

The corresponding output would read as:
a
illustrate
is
of
piece
problem
sample
text
this
to

-----Input format-----
- The first line of input contains a single integer $N$, indicating the number of lines in the input.
- This is followed by $N$ lines of input text.

-----Output format-----
- The first line of output contains a single integer $M$ indicating the number of distinct words in the given text.
- The next $M$ lines list out these words in lexicographic order.

-----Constraints-----
- $1 \leq N \leq 10000$
- There are at most 80 characters in each line.
- There are at the most 1000 distinct words in the given text.

-----Sample Input-----
2
This is a sample piece of text to illustrate this
problem.

-----Sample Output-----
10
a
illustrate
is
of
piece
problem
sample
text
this
to

lst=[]
ans=[]
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
t=int(input())
for i in range(t):
    str= input()
    s=str.lower()
    no_punct = ""
    for char in s:
       if char not in punctuations:
           no_punct = no_punct + char
    lst.extend(no_punct.split())

for i in lst:
    if i not in ans:
        ans.append(i)
ans.sort()
print(len(ans))
for j in ans:
    print(j)


Solve in Python:
In this problem the input will consist of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks ' (apostrophe), . (full stop), , (comma), ; (semicolon), :(colon) and white space characters (blank, newline). Your task is print the words in the text in reverse order without any punctuation marks.
For example consider the following candidate for the input text:
$ $
This is a sample piece of text to illustrate this
problem.  If you are smart you will solve this right.

$ $
The corresponding output would read as:
$ $
right this solve will you smart are you If problem
this illustrate to text of piece sample a is This

$ $
That is, the lines are printed in reverse order and in each line the words are printed in reverse order.

-----Input:-----
The first line of input contains a single integer $N$, indicating the number of lines in the input. This is followed by $N$ lines of input text.

-----Output:-----
$N$ lines of output text containing the input lines in reverse order and where each line contains the words in reverse order as illustrated above.

-----Constraints:-----
- $1 \leq N \leq 10000$.
- There are at most $80$ characters in each line

-----Sample input-----
2
This is a sample piece of text to illustrate this
problem.  If you are smart you will solve this right.

-----Sample output-----
right this solve will you smart are you If problem
this illustrate to text of piece sample a is This

n=int(input())
arr=[]
d=["'" , "." , "," , ";" , ":"]
for i in range(n) :
    temp=input().strip()
    for j in d :
        if j in temp :
            temp=temp.replace(j , '')
    temp=temp.split()
    temp.reverse()
    arr.append(temp)
for i in range (len(arr)-1 , -1 , -1) :
    print(" ".join(arr[i]))


Solve in Python:
In this problem we are concerned with words constructed using the lowercase letters of the English alphabet - that is, a,b,c,…,z. These words need not necessarily be meaningful: any sequence of letters forms a word. For example, abbca is a word.
We say that we can "hop" from the word $w_1$ to the word $w_2$ if they are "sufficiently close". We define $w_2$ to be sufficiently close to $w_1$ if one of the following holds:
- $w_2$ is obtained from $w_1$ by deleting one letter.
- $w_2$ is obtained from $w_1$ by replacing one of the letters in $w_1$ by some letter that appears to its right in $w_1$ and which is also to its right in alphabetical order.
For example, we can hop from abbca to abca by deleting the second (or third letter). We can hop from aabca to abbca by replacing the a in the second position by the letter b that appears to the right of the a in aabca and which is also to its right in alphabetical order. On the other hand we cannot hop from abbca to aabca since we would need to replace the b in the second position by a, but a is to the left of b in alphabetical order.
You will be given a collection of words $W$. Your task is to find the length of the longest sequence $w_1, w_2, \ldots $ of distinct words from $W$ such that we may hop from $w_1$ to $w_2$, $w_2$ to $w_3$ and so on. We call this the hopping number for this set.
For example, if
$W$ = {abacd, bcdada, dd, abcd,bcdd, adcd, addd, aa, ccd, add, ad}
then, the hopping number is 7 corresponding to the sequence
abacd, abcd, adcd, addd, add, ad, dd

-----Input Format:-----
- The first line of the input contains one integer $N$ indicating the number of words in the input.
- This is followed by $N$ lines of input, lines 2, 3,…, $N$+1, each containing one word over the letters {a,b,…, z}.

-----Output Format:-----
The output should be a single integer, indicating the hopping number of the given set of words.

-----Test Data:-----
- $N \leq 100$
- You may assume that each word has at most 10 letters.

-----Sample...

def codn1(s1,s2,p):
	c=0
	ind=0
	for i in range(len(s1)):
		if s1[i]!=s2[i]:
			c+=1
			ind=i
	if c>1 or ind==len(s1)-1:
		return 0
	if s1[ind]>s2[ind] and s1[ind] in s2[ind+1:]:
		p[0]=True
	if s1[ind]<s2[ind] and s2[ind] in s1[ind+1:]:
		p[1]=True
	return 1

def codn2(s1,s2):
	if len(s1)<len(s2):
		for i in range(len(s2)):
			if s2[:i]+s2[i+1:]==s1:
				return 1
	else:
		for i in range(len(s1)):
			if s1[:i]+s1[i+1:]==s2:
				return 2

def longest(k):
	if cost[k]>0:
		return cost[k]
	for i in list(d[k]):
			cost[k]=max(cost[k],longest(i)+1)
	return cost[k]

n=int(input())
l=[]
#parent=[0]*n
d={}
cost={}
for i in range(n):
	l.append(input())
	d[i]=[]
	cost[i]=0

for i in range(n):
	for j in range(n):
		if i!=j:
			p=[False,False]
			if len(l[i])==len(l[j]):
				if codn1(l[i],l[j],p):
					if p[0]==True:
						d[j].append(i)
					if p[1]==True:
						d[i].append(j)
			elif abs(len(l[i])-len(l[j]))==1:
				y=codn2(l[i],l[j])
				if y==1:
					d[j].append(i)
				if y==2:
					d[i].append(j)
ans=0
#print(d)

for i in range(n):
	ans=max(ans,longest(i))
print(ans+1)


Solve in Python:
In this problem you are given a sequence of $N$ positive integers $S[1],S[2],\dots,S[N]$. In addition you are given an integer $T$, and your aim  is to find the number of quadruples $(i,j,k,l)$, such that $1 \le i < j < k < l \le N$, and $S[i] + S[j] + S[k] + S[l] = T$.  That is, the number of ways of picking four numbers from the sequence summing up to $T$.

-----Constraints:-----
For all test cases,
- $1 \le N \le 5000$
- $1 \le T \le 10^6$
- $1 \le S[i] \le 10^9$, for all $i$.
Subtask $1:10\%$
It is guaranteed that $N \le 50$.
Subtask $2:50\%$
It is guaranteed that $N \le 300$.
Subtask $3:40\%$
No additional guarantees.

-----Input Format:-----
There is only one line of input with $N+2$ space separated integers. The first two integers are $N$ and $T$. The next $N$ integers are $S[1],S[2],\dots,S[N]$.

-----Output Format:-----
A single integer which is the number of valid quadruples.

-----Sample Input 1:-----
6 20 3 1 1 2 5 10

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

-----Explanation 1:-----
The quadruple $(1,4,5,6)$ is valid  because $S[1]+S[4]+S[5]+S[6]=3+2+5+10=20$. You can check that no other quadruple is valid and hence the answer is $1$.

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

-----Sample Output 2:-----
3

-----Explanation 2:-----
You can verify that the only quadruples that are valid are $(2,3,4,6),(1,3,4,5)$  and $(1,3,5,6)$. Thus, the answer is $3$.

-----Note:-----
As the answer might be large, please use 64 bit integers (long long int in
C/C++ and long in Java) instead of 32 bit int.

inp = list(map(int, input().split()))
N = inp[0]
T = inp[1]
array = inp[2:]
array.sort()

sums = [0 for i in range(T)]
total = 0
for i in range(N):
    for forward in range(i+1, N):
        sm = array[i] + array[forward]
        if sm < T:
            total += sums[T - sm]
    for backward in range(i):
        sm = array[i] + array[backward]
        if sm < T:
            sums[sm] += 1
print(total)


Solve in Python:
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $s$ starting from the $l$-th character and ending with the $r$-th character as $s[l \dots r]$. The characters of each string are numbered from $1$.

We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.

Binary string $a$ is considered reachable from binary string $b$ if there exists a sequence $s_1$, $s_2$, ..., $s_k$ such that $s_1 = a$, $s_k = b$, and for every $i \in [1, k - 1]$, $s_i$ can be transformed into $s_{i + 1}$ using exactly one operation. Note that $k$ can be equal to $1$, i. e., every string is reachable from itself.

You are given a string $t$ and $q$ queries to it. Each query consists of three integers $l_1$, $l_2$ and $len$. To answer each query, you have to determine whether $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$.

-----Input-----

The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of string $t$.

The second line contains one string $t$ ($|t| = n$). Each character of $t$ is either 0 or 1.

The third line contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries.

Then $q$ lines follow, each line represents a query. The $i$-th line contains three integers $l_1$, $l_2$ and $len$ ($1 \le l_1, l_2 \le |t|$, $1 \le len \le |t| - \max(l_1, l_2) + 1$) for the $i$-th query.

-----Output-----

For each query, print either YES if $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$, or NO otherwise. You may print each letter in any...

import sys
input = sys.stdin.readline

MOD = 987654103

n = int(input())
t = input()

place = []
f1 = []
e1 = []

s = []
curr = 0
count1 = 0
for i in range(n):
    c = t[i]
    if c == '0':
        if count1:
            e1.append(i - 1)
            if count1 & 1:
                s.append(1)
                curr += 1
                e1.append(-1)
                f1.append(-1)
            count1 = 0
        else:
            f1.append(-1)
            e1.append(-1)

        place.append(curr)
        curr += 1
        s.append(0)
    else:
        if count1 == 0:
            f1.append(i)
        count1 += 1
        place.append(curr)

if count1:
    if count1 & 1:
        s.append(1)
    else:
        s.append(0)
    curr += 1
    e1.append(n - 1)

    e1.append(-1)
    f1.append(-1)
place.append(curr)

pref = [0]
val = 0
for i in s:
    val *= 3
    val += i + 1
    val %= MOD
    pref.append(val)

q = int(input())
out = []
for _ in range(q):
    l1, l2, leng = list(map(int, input().split()))
    l1 -= 1
    l2 -= 1

    starts = (l1, l2)
    hashes = []
    for start in starts:
        end = start + leng - 1

        smap = place[start]
        emap = place[end]
        if t[end] == '1':
            emap -= 1
        if s[smap] == 1:
            smap += 1

        prep = False
        app = False

        if t[start] == '1':
            last = e1[place[start]]
            last = min(last, end)
            count = last - start + 1
            if count % 2:
                prep = True
        if t[end] == '1':
            first = f1[place[end]]
            first = max(first, start)
            count = end - first + 1
            if count % 2:
                app = True

        preHash = 0
        length = 0
        if smap <= emap:
            length = emap - smap + 1
            preHash = pref[emap + 1]
            preHash -= pref[smap] * pow(3, emap - smap + 1, MOD)
            preHash %= MOD

        if length == 0 and prep and app:
            app = False

        #print(preHash, prep, app,...


Solve in Python:
In this problem, you will be given a polynomial, you have to print what it becomes after differentiation.

Following are the rules for differentiation:
- For a polynomial f(x), its differentiation is defined as f'(x).
- If a is a constant, then differentiation of af(x) is af'(x).
- If f(x) = h(x) + g(x) , then f'(x) = h'(x) + g'(x)
- If f(x) = x n, then f'(x) = nxn-1. This is true for all  n ≠ 0 .
- If f(x) = c, where c is a constant, f'(x) = 0.

If you are still uncomfortable with differentiation, please read the following:
-  Link to Wikihow page
- Link to Wikipedia entry.

-----Input-----

First line contains T, the number of test cases to follow.

Each test case contains the follows, the first line contains N, the number of non zero terms in the polynomial. Then N lines follow, each line contains a pair of integer which denotes a term in the polynomial, where the first element denotes the coefficient (a) and the second denotes the exponent (p) of the term.

-----Output-----
Print the polynomial after differentiation in the desired format as described below.
-  If the coefficient of a term in the output polynomial is 3, and the corresponding exponent is 2, print it as 3x^2
- Print " + " (with single space on both side) between each output term.
-  Print the terms in decreasing value of exponent.
-  For the constant term (if any), you have to just print the coefficient. You should not print x^0.

-----Constraints-----
- 1 ≤ T ≤ 10
-   Subtask 1 (20 points)

- 1 ≤ N ≤ 3
- 1 ≤ a ≤ 10
- 0 ≤ p ≤ 10
- Subtask 2 (80 points)

- 1 ≤ N ≤ 10000
- 1 ≤ a ≤ 100000000
- 0 ≤ p ≤ 100000000
-  No two inputs in a test case will have the same exponent.

-----Example-----
Input:
2
1
1 2
3
1 3
1 1
1 0

Output:
2x^1
3x^2 + 1

import sys

for __ in range(eval(input())) :
 n = eval(input())
 ans ,const = "" , False
 for i in range(n) :
  p , a = list(map(int,sys.stdin.readline().split()))
  coeff , power = 0 , 0
  if a > 0 :
   coeff = a*p
   power = a-1
   if power != 0 :
    if n == 1 :
     ans += str(coeff)+'x^'+str(power)
     const = True
    else :
     ans += str(coeff)+'x^'+str(power)+" + "
   else :
    ans += str(coeff)
    const = True
 print(0 if ans=="" else ans.strip() if const else ans[:len(ans)-3].strip())


Solve in Python:
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?

**Example:**
``` c
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` cfml
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` csharp
Kata.MakeNegative(1); // return -1
Kata.MakeNegative(-5); // return -5
Kata.MakeNegative(0); // return 0
```
``` java
Kata.makeNegative(1); // return -1
Kata.makeNegative(-5); // return -5
Kata.makeNegative(0); // return 0
```
``` python
make_negative(1);  # return -1
make_negative(-5); # return -5
make_negative(0);  # return 0
```
``` javascript
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
makeNegative(0.12); // return -0.12
```
``` typescript
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` cpp
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` haskell
makeNegative    1 -- return -1
makeNegative (-5) -- return -5
makeNegative    0 -- return 0
makeNegative 0.12 -- return -0.12
```
``` ruby
makeNegative(1); # return -1
makeNegative(-5); # return -5
makeNegative(0); # return 0
```
``` coffeescript
makeNegative 1    # return -1
makeNegative -5   # return -5
makeNegative 0    # return 0
```
``` elixir
make_negative 1    # return -1
make_negative -5   # return -5
make_negative 0    # return 0
```
``` go
MakeNegative(1)    # return -1
MakeNegative(-5)   # return -5
MakeNegative(0)    # return 0
```
``` julia
Kata.makeNegative(1)  # return -1
Kata.makeNegative(-5) # return -5
Kata.makeNegative(0)  # return 0
```
``` kotlin
Kata().makeNegative(1)  // return -1
Kata().makeNegative(-5) // return -5
Kata().makeNegative(0)  // return 0
```
``` asm
make_negative(1);    // return -1
make_negative(-5);   // return -5
make_negative(0);    // return 0
```
``` groovy
Kata.makeNegative(1)    // return -1
Kata.makeNegative(-5)   // return...

make_negative = lambda a: -a if a > 0 else a


Solve in Python:
In this simple exercise, you will build a program that takes a value, `integer `, and returns a list of its multiples up to another value, `limit `. If `limit` is a multiple of ```integer```, it should be included as well. There will only ever be positive integers passed into the function, not consisting of 0. The limit will always be higher than the base.

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

If you can, try writing it in only one line of code.

def find_multiples(integer, limit):
    list = []
    i = 1
    while i <= (limit/integer):
        list.append(integer*i)
        i = i + 1
    return list


Solve in Python:
In this simple exercise, you will create a program that will take two lists of integers, ```a``` and ```b```. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids ```a``` and ```b```. You must find the difference of the cuboids' volumes regardless of which is bigger.

For example, if the parameters passed are ```([2, 2, 3], [5, 4, 1])```, the volume of ```a``` is 12 and the volume of ```b``` is 20. Therefore, the function should return ```8```.

Your function will be tested with pre-made examples as well as random ones.

**If you can, try writing it in one line of code.**

def find_difference(a, b):
    a_volume = a[0] * a[1] * a[2]
    b_volume = b[0] * b[1] * b[2]
    return abs(a_volume - b_volume)


Solve in Python:
In this task you have to code process planner.

You will be given initial thing, target thing and a set of processes to turn one thing into another (in the form of _[process\_name, start\_thing, end\_thing]_). You must return  names of shortest sequence of processes to turn initial thing into target thing, or empty sequence if it's impossible.

If start already equals end, return [], since no path is required.

Example:

```python
test_processes = [
        ['gather', 'field', 'wheat'],
        ['bake', 'flour', 'bread'],
        ['mill', 'wheat', 'flour']
];

processes('field', 'bread', test_processes) # should return ['gather', 'mill', 'bake']
processes('field', 'ferrari', test_processes) # should return []
processes('field', 'field', test_processes) # should return [], since no processes are needed
```

Good luck!

def processes(start, end, procs):
    def _p(start, end, procs, re_):
        for step in procs:
            res = re_[:]
            if step[1] == start:
                res.append(step[0])

                _p(step[2], end, [x for x in procs if x != step], res)

                if step[2] == end:
                    _p.gres.append(res);

    _p.gres = []
    _p(start, end, procs, [])
    return min(_p.gres, key=lambda x: len(x)) if _p.gres else []


Solve in Python:
In universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x and y is |x - y|.
Given the integer array position and the integer m. Return the required force.

Example 1:

Input: position = [1,2,3,4,7], m = 3
Output: 3
Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.

Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
Explanation: We can use baskets 1 and 1000000000.

Constraints:

n == position.length
2 <= n <= 10^5
1 <= position[i] <= 10^9
All integers in position are distinct.
2 <= m <= position.length

class Solution:
    def feasible(self, d, m):
        last_pos = self.position[0]
        i = 1
        num_placed = 1
        while num_placed < m and i < self.plen:
            if self.position[i] - last_pos >= d:
                last_pos = self.position[i]
                num_placed += 1
            i += 1
        return num_placed == m

    def maxDistance(self, position: List[int], m: int) -> int:
        self.position = position
        self.plen = len(self.position)
        self.position.sort()
        left = 1
        right = self.position[-1] - self.position[0] + 1
        while left + 1 < right:
            mid = (left + right) // 2
            if self.feasible(mid, m):
                left = mid
            else:
                right = mid
        return left


Solve in Python:
In your class, you have started lessons about "arithmetic progression". Because you are also a programmer, you have decided to write a function.

This function, arithmetic_sequence_sum(a, r, n), should return the sum of the first (n) elements of a sequence in which each element is the sum of the given integer (a), and a number of occurences of the given integer (r), based on the element's position within the sequence.

For example:

arithmetic_sequence_sum(2, 3, 5) should return 40:

```
1     2        3          4            5
a + (a+r) + (a+r+r) + (a+r+r+r) + (a+r+r+r+r)
2 + (2+3) + (2+3+3) + (2+3+3+3) + (2+3+3+3+3) = 40
```

def arithmetic_sequence_sum(a, r, n):
    return n * (a + a + ( n - 1) * r) / 2


Solve in Python:
In your class, you have started lessons about [arithmetic progression](https://en.wikipedia.org/wiki/Arithmetic_progression). Since you are also a programmer, you have decided to write a function that will return the first `n` elements of the sequence with the given common difference `d` and first element `a`. Note that the difference may be zero!

The result should be a string of numbers, separated by comma and space.

## Example

```python
# first element: 1, difference: 2, how many: 5
arithmetic_sequence_elements(1, 2, 5) == "1, 3, 5, 7, 9"
```

~~~if:fortran
*NOTE: In Fortran, your returned string is* **not** *permitted to contain redundant leading/trailing whitespace.*
~~~

def arithmetic_sequence_elements(a, r, n):
    return ', '.join(str(a + b * r) for b in range(n))


Solve in Python:
In your class, you have started lessons about geometric progression.
Since you are also a programmer, you have decided to write a function that will print first `n` elements of the sequence with the given constant `r` and first element `a`.

Result should be separated by comma and space.

### Example

```python
geometric_sequence_elements(2, 3, 5) == '2, 6, 18, 54, 162'
```

More info: https://en.wikipedia.org/wiki/Geometric_progression

def geometric_sequence_elements(a, r, n):
    return str([a*pow(r,i) for i in range(n)])[1:-1]


Solve in Python:
Increasing COVID cases have created panic amongst the people of Chefland, so the government is starting to push for production of a vaccine. It has to report to the media about the exact date when vaccines will be available.
There are two companies which are producing vaccines for COVID. Company A starts producing vaccines on day $D_1$ and it can produce $V_1$ vaccines per day. Company B starts producing vaccines on day $D_2$ and it can produce $V_2$ vaccines per day. Currently, we are on day $1$.
We need a total of $P$ vaccines. How many days are required to produce enough vaccines? Formally, find the smallest integer $d$ such that we have enough vaccines at the end of the day $d$.

-----Input-----
- The first and only line of the input contains five space-separated integers $D_1$, $V_1$, $D_2$, $V_2$ and $P$.

-----Output-----
Print a single line containing one integer ― the smallest required number of days.

-----Constraints-----
- $1 \le D_1, V_1, D_2, V_2 \le 100$
- $1 \le P \le 1,000$

-----Subtasks-----
Subtask #1 (30 points): $D_1 = D_2$
Subtask #2 (70 points): original constraints

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

-----Example Output 1-----
3

-----Explanation-----
Since $D_1 = D_2 = 1$, we can produce $V_1 + V_2 = 5$ vaccines per day. In $3$ days, we produce $15$ vaccines, which satisfies our requirement of $14$ vaccines.

-----Example Input 2-----
5 4 2 10 100

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

-----Explanation-----
There are $0$ vaccines produced on the first day, $10$ vaccines produced on each of days $2$, $3$ and $4$, and $14$ vaccines produced on the fifth and each subsequent day. In $9$ days, it makes a total of $0 + 10 \cdot 3 + 14 \cdot 5 = 100$ vaccines.

d1,v1,d2,v2,p=list(map(int,input().split()))
check=0
if d1==d2:
 check=1
 start=d1-1
 v0=(v1+v2)
 if p%v0==0:
  print((p//v0)+start)
 else:
  print((p//v0)+1+start)
elif d2<d1:
 con=d2
 pon=d1
 von=v2
else:
 con=d1
 pon=d2
 von=v1
if check!=1:
 starting_day=con-1
 second=pon-con
 third=(second*von)
 if third>p:
  if p%von==0:
   print((p//von)+starting_day)
  else:
   print((p//von)+1+starting_day)

 elif third==p:
  print(second+starting_day)
 else:
  v0=(v2+v1)
  if (p-third)%v0==0:
   print(((p-third)//v0)+second+starting_day)
  else:
   print(((p-third)//v0)+second+starting_day+1)


Solve in Python:
Indian National Olympiad in Informatics 2012
The Republic of Tutaria is celebrating its 37th year of independence. To mark the occasion, the nation is organising a contest where all its N citizens take part. The event has three tracks, a COBOL programming competition, pole vault, and a doughnut-eating competition. Each citizen takes part in these three tracks in the same order—a citizen starts with the programming competition, continues with the pole vault as soon as his or her COBOL masterpiece is ready, and then starts gorging on doughnuts as soon as the pole vault is done.
The Supreme Leader of Tutaria closely monitors all citizens and knows the exact amount of time each citizen will take in each of the three tracks. She wants to schedule the event so that it will finish as early as possible. However, the Republic of Tutaria has only one computer, and, as a result, only one person can participate in the COBOL programming event at a time. However, any number of people may simultaneously participate in the pole vault and doughnut-eating competitions.
The event works as follows. The Supreme Leader fixes the order in which contestants get access to the computer. At time 0, the first citizen in the list starts writing his or her COBOL program, while the remaining citizens wait for the computer to be free. As soon as the first citizen is done, he or she proceeds to the pole vault, and the second citizen gets the computer for the programming round. In general whenever the computer becomes free, the next citizen gets to use it. Whenever a citizen is done using the computer, he or she proceeds to the pole vault immediately, regardless of what the other citizens are doing. Similarly, whenever a citizen is done with the pole vault, he or she proceeds to the doughnut- eating track immediately, independently of the others. The event ends as soon as all the citizens have finished all the three tracks of the event.
For example, suppose N = 3, and the time they need for the three tracks are as follows:
Citizen...

# cook your dish here
while True:
    try:
        n=int(input())
        lis=[]
        for i in range(n):
            k=list(map(int,input().split()))
            k.append(k[1]+k[2])
            lis.append(k)

        #print(lis)
        p=sorted(lis,key=lambda x:x[3],reverse=True)
        #print(p)
        maxi=0
        s=0
        w=0
        for i in range(n):
            s+=p[i][0]
            w=s+p[i][1]+p[i][2]
            maxi=max(maxi,w)

        print(maxi)

    except:
        break


Solve in Python:
Indian National Olympiad in Informatics 2012
You are given a table with 2 rows and N columns. Each cell has an integer in it. The score of such a table is defined as follows: for each column, consider the sum of the two numbers in the column; the maximum of the N numbers so obtained is the score. For example, for the table
7162
1234

the score is max(7 + 1, 1 + 2, 6 + 3, 2 + 4) = 9.

The first row of the table is fixed, and given as input. N possible ways to fill the second row are considered:
1,2,...,N
2,3,...,N,1
3,4,...,N,1,2
···
N, 1, ... , ,N − 1

For instance, for the example above, we would consider each of the following as possibilities for the second row.
1234
2341
3412
4123

Your task is to find the score for each of the above choices of the second row. In the example above, you would evaluate the following four tables,
7162 7162 7162 7162
1234 2341 3412 4123

and compute scores 9, 10, 10 and 11, respectively.

-----Input format -----
The first line of the input has a single integer, N. The second line of the input has N integers, representing the first row, from left to right.

-----Output format -----
The output should consist of a single line with N integers. For 1 ² k ² N, the kth number in the output should be the score when the second row of the table is taken to be k,k+1,...,N,1,...,k−1.

-----Test Data -----
The testdata is grouped into two subtasks with the following constraints on the inputs.
• Subtask 1 [30 points] : 1 ≤ N ≤ 3000.
• Subtask 2 [70 points] : 1 ≤ N ≤ 200000.
In both the subtasks, all the integers in the first row of the table are between 1 and 100000, inclusive.

-----Example -----
Here is the sample input and output corresponding to the example above.

-----Sample input -----
4
7 1 6 2

-----Sample output-----
9 10 10 11

Note: Your program should not print anything other than what is specified in the output format. Please remove all diagnostic print statements before making your final submission. A program with extraneous output will be treated as incorrect!

# cook your dish here
try:
    n=int(input())

    list_n = list(range(1,n+1))
    list_n_flag=[]

    fix_arr = list(map(int,input().split()))

    k=1
    res_list=[]
    fin_list=[]
    list_n_flag = list_n[k:] + list_n[:k]
    res_list = [list_n[i] + fix_arr[i] for i in range(len(fix_arr))]
    maxx = max(res_list)
    fin_list.append(maxx)
    while list_n!=list_n_flag:

        res_list = [list_n_flag[i] + fix_arr[i] for i in range(len(fix_arr))]
        maxx = max(res_list)
        fin_list.append(maxx)
        list_n_flag = list_n_flag[k:] + list_n_flag[:k]

    print(*fin_list,sep=" ")
except:
    pass


Solve in Python:
Indian National Olympiad in Informatics 2013
Calvin wakes up early one morning and finds that all his friends in the hostel are asleep. To amuse himself, he decides to play the following game : he draws a sequence of N squares on the ground, numbered 1 to N, and writes an integer in each square. He starts at square k (1 ≤ k ≤ N). The game consists of one forward phase followed by one backward phase.
- In the forward phase, Calvin makes zero or more moves of the following type : if his current position is p, he can jump to p+1 or p+2 as long as he stays within the N squares.
- In the backward phase, Calvin makes zero or more moves of the following type : if his current position is p, he can jump to p−1 or p−2 as long as he stays within the N squares.
He plays such that he finally ends up at square 1, and then he stops. He starts with a score of 0, and each time he jumps from square i to square j, he adds the integer written in square j to his score. Find the maximum score Calvin can obtain by playing this game. Recall that Calvin must start at square k and end at square 1. The integer on the square where he starts is not included in his score.
For example, suppose N = 5 and the numbers in squares are 5, 3, −2, 1, 1. If k = 2, Calvin starts on the second square. He can make a forward move to square 4, another to square 5, a backward move to square 4, another to square 2, and another to square 1. His total score is 1+1+1+3+5 = 11. You can check that this is the maximum score possible.

-----Input format-----
• Line 1 : Two space-separated integers, N and k, with 1 ≤ k ≤ N.
• Line 2 : A space-separated sequence of N integers, the numbers in squares 1, 2 . . . , N .

-----Output format-----
A single line with a single integer, the maximum score Calvin can obtain by playing the game.

-----Test Data-----
The testdata is grouped into two subtasks with the following constraints on the inputs.
• Subtask 1 [30 points] : 1 ≤ N ≤ 3000.
• Subtask 2 [70 points] : 1 ≤ N ≤ 106.
In all subtasks, the number in each square is...

try:
    n, k=list(map(int, input().split()))
    arr=list(map(int, input().split()))
    forward = [0]*(n+1)
    backward= [0]*(n+1)
    backward[0]=arr[0]
    backward[1]=arr[0]+arr[1]

    for i in range(k, n):
     forward[i]=arr[i] +max(forward[i-1],forward[i-2])

    for i in range(2, n):
     backward[i]=arr[i]+max(backward[i-1],backward[i-2])

    ans=-float("inf")

    for i in range(k-1, n):
     ans=max(ans, forward[i]+backward[i]-arr[i])

    print(ans)
except Exception:
    pass


Solve in Python:
Indian National Olympiad in Informatics 2013
N people live in Sequence Land. Instead of a name, each person is identified by a sequence of integers, called his or her id. Each id is a sequence with no duplicate elements. Two people are said to be each other’s relatives if their ids have at least K elements in common. The extended family of a resident of Sequence Land includes herself or himself, all relatives, relatives of relatives, relatives of relatives of relatives, and so on without any limit.
Given the ids of all residents of Sequence Land, including its President, and the number K, find the number of people in the extended family of the President of Sequence Land.
For example, suppose N = 4 and K = 2. Suppose the President has id (4, 6, 7, 8) and the other three residents have ids (8, 3, 0, 4), (0, 10), and (1, 2, 3, 0, 5, 8). Here, the President is directly related to (8, 3, 0, 4), who in turn is directly related to (1, 2, 3, 0, 5, 8). Thus, the President’s extended family consists of everyone other than (0, 10) and so has size 3.

-----Input format-----
• Line 1: Two space-separated integers, N followed by K.
• Lines 2 to N + 1: Each line describes an id of one of the residents of Sequence Land, beginning with the President on line 2. Each line consists of an integer p, followed by p distinct integers, the id.

-----Output format-----
The output consists of a single integer, the number of people in the extended family of the President.

-----Test Data-----
The testdata is grouped into two subtasks. In both subtasks, 1 ≤ N ≤ 300 and 1 ≤ K ≤ 300. Each number in each id is between 0 and 109 inclusive.
• Subtask 1 [30 points]: The number of elements in each id is between 1 and 10 inclusive.
• Subtask 2 [70 points]: The number of elements in each id is between 1 and 300 inclusive.

-----Example-----
Here is the sample input and output corresponding to the example above.

-----Sample input -----
4 2
4 4 6 7 8
4 8 3 0 4
2 0 10
6 1 2 3 0 5 8

-----Sample output-----
3

Note: Your program should not print...

def dfs(graph,i):
    visited[i]=True
    for j in graph[i]:
        if not visited[j]:
            dfs(graph,j)

N, K = map(int, input().split())
arr = []
for i in range(N):
    arr.append(list(map(int, input().split())))
nodes = [[] for _ in range(N)]
for i in range(N-1):
    for j in range(i+1,N):
        count = len(set(arr[i]).intersection(set(arr[j])))
        if count>= K:
            nodes[i].append(j)
            nodes[j].append(i)
visited = [False]*N
dfs(nodes, 0)
print(visited.count(True))


Solve in Python:
Indian National Olympiad in Informatics 2014
Due to resurfacing work, all north-south traffic on the highway is being diverted through the town of Siruseri. Siruseri is a modern, planned town and the section of roads used for the diversion forms a rectangular grid where all cars enter at the top-left intersection (north- west) and leave at the bottom-right intersection (south-east). All roads within the grid are one-way, allowing traffic to move north to south (up-down) and west to east (left-right) only.
The town authorities are concerned about highway drivers overspeeding through the town. To slow them down, they have made a rule that no car may travel more than d consecutive road segments in the same direction without turning. (Closed-circuit TV cameras have been installed to enforce this rule.)
Of course, there is also repair work going on within the town, so some intersections are blocked and cars cannot pass through these.
You are given the layout of the rectangular grid of roads within Siruseri and the constraint on how many consecutive road segments you may travel in the same direction. Your task is to compute the total number of paths from the entry (top-left) to the exit (bottom-right).
For instance, suppose there are 3 rows and 4 columns of intersec- tions, numbered from (1,1) at the top-left to (3,4) at the bottom-right, as shown on the right. Intersection (2,1) in the second row, first column is blocked, and no car may travel more than 2 consecutive road seg- ments in the same direction.

Here, (1,1) → (1,2) → (2,2) → (3,2) → (3,3) → (3,4) is a valid path from (1,1) to (3,4), but (1,1) → (1,2) → (1,3) → (1,4) → (2,4) → (3,4) is not, because this involves 3 consecutive road segments from left to right. The path (1, 1) → (2, 1) → (2, 2) → (2, 3) → (3, 3) → (3, 4) is ruled out because it goes through a blocked intersection. In this example, you can check that the total number of valid paths is 5.

-----Input format-----
• Line 1: Three space-separated integers, R, C and d, where R is the number of...

MOD = 20011

n, m, d = map(int, input().split())
gr = [list(map(int, input().split())) for _ in range(n)]

dp = [[0] * m for _ in range(n)]

for i in range(min(n, d+1)):
    if gr[i][0] == 0:
        break

    dp[i][0] = 1

for i in range(min(m, d+1)):
    if gr[0][i] == 0:
        break

    dp[0][i] = 1

for i in range(1, n):
    for j in range(1, m):
        if gr[i][j] == 0:
            dp[i][j] = 0
            continue

        dp[i][j] = dp[i-1][j] + dp[i][j-1]

        if i - d - 1 > 0:
            for r in range(i-d, i):
                if not gr[r][j]:
                    break
            else:
                dp[i][j] -= dp[i - d - 1][j]

        if j - d - 1 > 0:
            for r in range(j-d, j):
                if not gr[i][r]:
                    break
            else:
                dp[i][j] -= dp[i][j - d - 1]

        dp[i][j] = max(dp[i][j], 0) % MOD

print(dp[n-1][m-1])


Solve in Python:
Indian National Olympiad in Informatics 2015
A string is any nonempty sequence of 0s and 1s. Examples of strings are 00, 101, 111000, 1, 0, 01. The length of a string is the number of symbols in it. For example, the length of 111000 is 6. If u and v are strings, then uv is the string obtained by concatenating u and v. For example if u = 110 and v = 0010 then uv = 1100010.
A string w is periodic if there exists a string v such that w = vn = vv · · · v (n times), for some n ≥ 2. Note that in this case the length of v is strictly less than that of w. For example, 110110 is periodic, because it is vv for v = 110.
Given a positive integer N , find the number of strings of length N which are not periodic. Report the answer modulo M . The non-periodic strings of length 2 are 10 and 01. The non- periodic strings of length 3 are 001, 010, 011, 100, 101, and 110.

-----Input format-----
A single line, with two space-separated integers, N and M .

-----Output format-----
A single integer, the number of non-periodic strings of length N , modulo M .

-----Test Data-----
In all subtasks, 2 ≤ M ≤ 108. The testdata is grouped into 4 subtasks.
Subtask 1 (10 marks) 1 ≤ N ≤ 4000. N is the product of two distinct prime numbers.
Subtask 2 (20 marks) 1 ≤ N ≤ 4000. N is a power of a prime number.
Subtask 3 (35 marks) 1 ≤ N ≤ 4000.
Subtask 4 (35 marks) 1 ≤ N ≤ 150000.

-----Example-----
Here is the sample input and output corresponding to the example above:

-----Sample input-----
3 176

-----Sample output-----
6

Note: Your program should not print anything other than what is specified in the output format. Please remove all diagnostic print statements before making your final submission. A program with extraneous output will be treated as incorrect!

from math import sqrt

def per(n):
    if n in diz:
        return diz[n]
    else:
        counter=pow(2,n,m)
        for i in range(1,int(sqrt(n))+1):
            if n%i==0:
                counter-=per(i)
                if i!=1 and i!=(n//i):
                    counter-=per(n//i)
                counter%=m
        return counter

n, m = map(int, input().split())
diz={1:2}
print(per(n))
counter=pow(2,n,m)


Solve in Python:
Indian National Olympiad in Informatics 2015
In this problem you are given two lists of N integers, a1, a2, ..., aN and b1, b2, ... bN. For any pair (i, j) with i, j ϵ {1, 2, ..., N} we define the segment from i to j, written as [i, j], to be i, i + 1, ..., j if i ≤ j and i, i + 1, ..., N, 1, 2, ...,j if i > j. Thus if N = 5 then the [2, 4] = {2, 3, 4} and [4, 2] = {4, 5, 1, 2}.
With each segment [i, j] we associate a special sum SSum[i, j] as follows:
- SSum[i, i] = ai.
- If i ≠ j then,

The positions i and j contribute ai and aj, respectively, to the sum while every other position k in [i, j] contributes bk.
Suppose N = 5 and that the two given sequences are as follows:
i
1
2
3
4
5
ai
2
3
2
3
1
bi
3
4
4
6
3

Then, SSum[1, 1] = 2, SSum[2, 4] = 3 + 4 + 3 = 10 and SSum[4, 2] = 3 + 3 + 3 + 3 = 12. Your aim is to compute the maximum value of SSum[i, j] over all segments [i, j]. In this example you can verify that this value is 18 (SSum[2, 1] = 18).

-----Input format-----
- The first line contains a single positive integer N.
- This is followed by a line containing N integers giving the values of the ais and this is followed by a line containing N integers giving the values of the bis.

-----Output format-----
A single integer in a single line giving the maximum possible special segment sum.
Note: The final value may not fit in a 32 bit integer. Use variables of an appropriate type to store and manipulate this value (long long in C/C++, long in Java).

-----Test Data-----
You may assume that -109 ≤ ai, bi ≤ 109.
Subtask 1 (10 Marks) 1 ≤ N ≤ 3000.
Subtask 2 (20 Marks) 1 ≤ N ≤ 106 and ai = bi for all 1 ≤ i ≤ N.
Subtask 3 (30 Marks) 3 ≤ N ≤106. Further a1 = b1 = aN = bN = -109 and for each
1 < k < N we have -999 ≤ ak, bk ≤ 999.
Subtask 4 (40 Marks) 1 ≤ N ≤ 106.

-----Example-----
Here is the sample input and output corresponding to the example above:

-----Sample input-----
5
2 3 2 3 1
3 4 4 6 3

-----Sample output-----
18

Note: Your program should not print anything other than what is specified in the output...

from itertools import accumulate
n=int(input())
a=tuple(map(int,input().split()))
b=tuple(accumulate(map(int,input().split())))
ssum=0
for i in range(0,n):
    for j in range(i,n):
        if i==j:
            flag=a[i]
        else:
            if i==0:
                flag=a[i]+a[j]+max(b[j-1]-b[i],b[n-1]-b[j])
            else:
                flag=a[i]+a[j]+max(b[j-1]-b[i],b[n-1]-b[j]+b[i-1])
        ssum=max(ssum,flag)
print(ssum)


Solve in Python:
Indian National Olympiad in Informatics 2016
	Boing Inc, has N employees, numbered 1 ... N. Every employee other than Mr. Hojo (the head of the company) has a manager (P[i] denotes the manager of employee i). Thus an employee may manage any number of other employees but he reports only to one manager, so that the organization forms a tree with Mr. Hojo at the root. We say that employee B is a subordinate of employee A if B appears in the subtree rooted at A.

	Mr. Hojo, has hired Nikhil to analyze data about the employees to suggest how to identify faults in Boing Inc. Nikhil, who is just a clueless consultant, has decided to examine wealth disparity in the company. He has with him the net wealth of every employee (denoted A[i] for employee i). Note that this can be negative if the employee is in debt. He has already decided that he will present evidence that wealth falls rapidly as one goes down the organizational tree. He plans to identify a pair of employees i and j, j a subordinate of i, such A[i] - A[j] is maximum. Your task is to help him do this.

	Suppose, Boing Inc has 4 employees and the parent (P[i]) and wealth information (A[i]) for each employee are as follows:

i		1	2	3	4
A[i]		5	10	6	12
P[i]		2	-1	4	2

P[2] = -1 indicates that employee 2 has no manager, so employee 2 is Mr. Hojo.

In this case, the possible choices to consider are (2,1) with a difference in wealth of 5, (2,3) with 4, (2,4) with -2 and (4,3) with 6. So the answer is 6.

-----Input format-----
	There will be one line which contains (2*N + 1) space-separate integers. The first integer is N, giving the number of employees in the company. The next N integers A[1], .., A[N] give the wealth of the N employees. The last N integers are P[1], P[2], .., P[N], where P[i] identifies the manager of employee i. If Mr. Hojo is employee i then, P[i] = -1, indicating that he has no manager.

-----Output format-----
	One integer, which is the needed answer.

-----Test data-----
-108 ≤ A[i] ≤ 108, for all i.
Subtask 1 (30 Marks) 1 ≤ N ≤...

# cook your dish here
from collections import defaultdict
from operator import itemgetter
from collections import deque

def visit(v):
    height[v][1]=0
    i=0
    coda=deque()
    coda.append(v)
    while len(coda)>0:
        num=len(coda)
        i+=1
        for _ in range(num):
            u=coda.popleft()
            for son in sons[u]:
                height[son][1]=i
                coda.append(son)
    return

inp=list(map(int, input().split()))
n=inp[0]
wealth=inp[1:n+1]
father=[i-1 if i>0 else i for i in inp[n+1:]]
sons=defaultdict(lambda:[])
for i in range(n):
    if father[i]!=-1:
        sons[father[i]].append(i)
    else:
        boss=i

height=[[i,0] for i in range(n)]
visit(boss)

height.sort(key=itemgetter(1), reverse=True)
minimi=[0]*n
diff=[0]*n

for el in height:
    v=el[0]
    if len(sons[v])==0:
        minimi[v]=wealth[v]
        diff[v]=-float('Inf')
    else:
        minimo=min([minimi[u] for u in sons[v]])
        minimi[v]=min(minimo, wealth[v])
        diff[v]=max(max([diff[u] for u in sons[v]]), wealth[v]-minimo)

print(diff[boss])


Solve in Python:
Indian National Olympiad in Informatics 2016
	There are k types of brackets each with its own opening bracket and closing bracket. We assume that the first pair is denoted by the numbers 1 and k+1, the second by 2 and k+2 and so on. Thus the opening brackets are denoted by 1,2,.., k, and the corresponding closing brackets are denoted by k+1,k+2,..., 2*k respectively.

	Some sequences with elements from 1,2, ... 2*k form well-bracketed sequences while others don't. A sequence is well-bracketed, if we can match or pair up opening brackets and closing brackets of the same type in such a way that the following holds:

	 1) every bracket is paired up

	 2) in each matched pair, the opening bracket occurs before the closing bracket

	 3) for a matched pair, any other matched pair lies either completely between them or outside them.

	For the examples discussed below, let us assume that k = 2. The sequence 1,1,3 is not well-bracketed as one of the two 1's cannot be paired. The sequence 3,1,3,1 is not well-bracketed as there is no way to match the second 1 to a closing bracket occurring after it. The sequence 1,2,3,4 is not well-bracketed as the matched pair 2,4 is neither completely between the matched pair 1,3 nor completely outside it. That is, the matched pairs cannot overlap. The sequence 1,2,4,3,1,3 is well-bracketed. We match the first 1 with the first 3, the 2 with the 4 and the second 1 with the second 3, satisfying all the 3 conditions. If you rewrite these sequences using [,{,],} instead of 1,2,3,4 respectively, this will be quite clear.

	In this problem you are given a sequence of brackets, of length N: B[1], .., B[N], where each B[i] is one of the brackets. You are also given an array of Values: V[1],.., V[N].

	Among all the subsequences in the Values array, such that the corresponding bracket subsequence in the B Array is a well-bracketed sequence, you need to find the maximum sum. Suppose N = 6, k = 3 and the values of V and B are as follows:

i	1	2	3	4	5	6
V[i]	4	5	-2	1	1	6
B[i]	1	3	4	2	5	6

	Then,...

a,b,*c=list(map(int,input().strip().split()))
d=[]
e=[]
for i in range(a):
    e.append(c[i])
    d.append(c[i+a])
DP1=[[-1 for i in range(a)] for j in range(a)]
def DP(l,r):
    nonlocal d,e,b,DP1
    if l>=r:
        return 0
    elif DP1[l][r]!=-1:
        return DP1[l][r]
    else:
        DP1[l][r]=max(DP1[l][r],DP(l+1,r))
        DP1[l][r]=max(DP1[l][r],DP(l,r-1))
        if d[l]+b==d[r]:
            DP1[l][r]=max(DP1[l][r],e[l]+e[r]+DP(l+1,r-1))
        for i in range(l,r):
            if d[l]+b==d[i] or d[i]+b==d[r]:
                DP1[l][r]=max(DP1[l][r],DP(l,i)+DP(i+1,r))
    return DP1[l][r]
print(DP(0,a-1))


Solve in Python:
Indraneel has to sort the books in his library. His library has one long shelf. His books are numbered $1$ through $N$ and he wants to rearrange the books so that they appear in the sequence $1,2, ..., N$.
He intends to do this by a sequence of moves. In each move he can pick up any book from the shelf and insert it at a different place in the shelf. Suppose Indraneel has $5$ books and they are initially arranged in the order
21453214532 \quad 1 \quad 4 \quad 5 \quad 3
Indraneel will rearrange this in ascending order by first moving book $1$ to the beginning of the shelf to get
12453124531 \quad 2 \quad 4 \quad 5 \quad 3
Then, moving book $3$ to position $3$, he gets
12345123451 \quad 2 \quad 3 \quad 4 \quad 5
Your task is to write a program to help Indraneel determine the minimum number of moves that are necessary to sort his book shelf.

-----Input:-----
The first line of the input will contain a single integer $N$ indicating the number of books in Indraneel's library. This is followed by a line containing a permutation of $1, 2, ..., N$ indicating the intial state of Indraneel's book-shelf.

-----Output:-----
A single integer indicating the minimum number of moves necessary to sort Indraneel's book-shelf.

-----Constraints:-----
- $1 \leq N \leq 200000$.
- You may also assume that in $50 \%$ of the inputs, $1 \leq N \leq 5000$.

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

-----Sample Output-----
2

n=int(input())
arr=[int(x) for x in input().split()]
l=[1]*n
if n==0 or n==1:
    print('0')
for i in range(0,len(arr)):
    for j in range(i):
        if arr[i]>=arr[j] and l[i]<l[j]+1:
            l[i]=l[j]+1

print(n-max(l))


Solve in Python:
Indraneel's student has given him data from two sets of experiments that the student has performed. Indraneel wants to establish a correlation between the two sets of data. Each data set is a sequence of $N$ numbers. The two data sets do not match number for number, but Indraneel believes that this is because data has been shifted due to inexact tuning of the equipment.
For example, consider the following two sequences:
$ $
3  8   4  23  9  11  28
2  3  22  26  8  16  12

$ $
Indraneel observes that if we consider the subsequences $3,4,23,9$ and $2,3,22,8$ and examine their successive differences we get $1,19,-14$. He considers these two subsequences to be "identical". He would like to find the longest such pair of subsequences so that the successive differences are identical. Your task is to help him do this.

-----Input:-----
The first line of the input will contain a single integer $N$ indicating the number of data points in each of Indraneel's student's data sets. This is followed by two lines, each containing $N$ integers.

-----Output:-----
The output consists of three lines. The first line of output contains a single integer indicating the length of the longest pair of subsequences (one from each sequence) that has identical successive differences. This is followed by two lines each containing the corresponding subsequences. If there is more than one answer, it suffices to print one.

-----Constraints:-----
- $1 \leq N \leq 150$.
- $0 \leq$ Each data point $\leq 1000$

-----Sample Input-----
7
3 8 4 23 9 11 28
2 3 22 26 8 16 12

-----Sample Output-----
4
3 4 23 9
2 3 22 8

# cook your dish here
ans = []
mxlen = 0

def lcs(a,b,d,mxlen):
    L = [0]*(n+1)
    for i in range(n+1):
        L[i] = [0]*(n+1)
    #print("#",L,a,b)
    for i in range(1,n+1):
        for j in range(1,n+1):
            if a[i-1] == b[j-1]:
                L[i][j] = L[i-1][j-1] + 1
            else:
                L[i][j] = max(L[i-1][j],L[i][j-1])
    #print(L)
    if L[n][n] > mxlen:
        mxlen = L[n][n]
        i,j = n,n
        t = []
        while i>0 and j>0:
            if a[i-1] == b[j-1]:
                t.insert(0,a[i-1])
                i -= 1
                j -= 1
            elif L[i-1][j] > L[i][j-1]:
                i -= 1
            else:
                j -= 1
        #print(t)
        ans.append({d:t})

try:
    n = int(input())
    a = [int(w) for w in input().split()]
    b = [int(w) for w in input().split()]
    minb = min(b)
    b = [(i-minb-1) for i in b]
    for i in range(-1000,1001):
        bb = b.copy()
        bb = [(j+i) for j in bb]
        lcs(a,bb,i,mxlen)
    ans = sorted(ans, key=lambda i: len(list(i.values())[0]),reverse = True)
    t = ans[0]
    d = list(t.keys())[0]
    t = t[d]
    print(len(t))
    print(*t)
    t = [(i-d+minb+1) for i in t]
    print(*t)
except:
    pass


Solve in Python:
Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:

Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
Paste: You can paste the characters which are copied last time.

Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.

Example 1:

Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.

Note:

The n will be in the range [1, 1000].

class Solution:
     def minSteps(self, n):
         """
         :type n: int
         :rtype: int
         """
         f=2
         s=0
         while f*f<=n:
             while n%f==0:
                 s+=f
                 n=int(n/f)
             f+=1
         if n>1:
             s+=n
         return int(s)


Solve in Python:
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.

The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.

Example 1:

Input: "UD"
Output: true

Example 2:

Input: "LL"
Output: false

class Solution:
     def judgeCircle(self, moves):
         """
         :type moves: str
         :rtype: bool
         """
         if not moves:
             return True
         if len(moves) % 2 == 1:
             return False

         up, left = 0, 0
         for move in moves:
             if move == 'U':
                 up += 1
             if move == 'D':
                 up -= 1
             if move == 'L':
                 left += 1
             if move == 'R':
                 left -= 1
         return up == 0 and left == 0