Solve in Python:
Your task in this Kata is to emulate text justification in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width.

Here are the rules:

  * Use spaces to fill in the gaps between words.
  * Each line should contain as many words as possible.
  * Use '\n' to separate lines.
  * Gap between words can't differ by more than one space.
  * Lines should end with a word not a space.
  * '\n' is not included in the length of a line.
  * Large gaps go first, then smaller ones ('Lorem--ipsum--dolor--sit-amet,' (2, 2, 2, 1 spaces)).
  * Last line should not be justified, use only one space between words.
  * Last line should not contain '\n'
  * Strings with one word do not need gaps ('somelongword\n').

Example with width=30:

```
Lorem  ipsum  dolor  sit amet,
consectetur  adipiscing  elit.
Vestibulum    sagittis   dolor
mauris,  at  elementum  ligula
tempor  eget.  In quis rhoncus
nunc,  at  aliquet orci. Fusce
at   dolor   sit   amet  felis
suscipit   tristique.   Nam  a
imperdiet   tellus.  Nulla  eu
vestibulum    urna.    Vivamus
tincidunt  suscipit  enim, nec
ultrices   nisi  volutpat  ac.
Maecenas   sit   amet  lacinia
arcu,  non dictum justo. Donec
sed  quam  vel  risus faucibus
euismod.  Suspendisse  rhoncus
rhoncus  felis  at  fermentum.
Donec lorem magna, ultricies a
nunc    sit    amet,   blandit
fringilla  nunc. In vestibulum
velit    ac    felis   rhoncus
pellentesque. Mauris at tellus
enim.  Aliquam eleifend tempus
dapibus. Pellentesque commodo,
nisi    sit   amet   hendrerit
fringilla,   ante  odio  porta
lacus,   ut   elementum  justo
nulla et dolor.
```

Also you can always take a look at how justification works in your text editor or directly in HTML (css: text-align: justify).

Have fun :)

from textwrap import wrap
def justify(text, width):
    lines = wrap(text, width)

    def justify_line(line):
        spaces = line.count(' ')

        if not spaces:
            return line

        n, r = divmod(width - sum(map(len, line)), spaces)
        print(sum(map(len,line)))
        subs = ' ' * (n + 1)
        return line.replace(' ', subs).replace(subs, subs + ' ', r)

    return '\n'.join([*map(justify_line, lines[:-1]), lines[-1]])


Solve in Python:
Your task in this Kata is to emulate text justify right in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width.

Here are the rules:

- Use spaces to fill in the gaps on the left side of the words.
- Each line should contain as many words as possible.
- Use '\n' to separate lines.
- Gap between words can't differ by more than one space.
- Lines should end with a word not a space.
- '\n' is not included in the length of a line.
- Last line should not contain '\n'

Example with width=30:

```
        Bacon ipsum dolor amet
excepteur ut kevin burgdoggen,
   shankle cupim dolor officia
       ground round id ullamco
   deserunt nisi. Commodo tail
    qui salami, brisket boudin
tri-tip. Labore flank laboris,
  cow enim proident aliqua sed
      hamburger consequat. Sed
     consequat ut non bresaola
   capicola shoulder excepteur
 veniam, bacon kevin. Pastrami
   shank laborum est excepteur
 non eiusmod bresaola flank in
nostrud. Corned beef ex pig do
   kevin filet mignon in irure
 deserunt ipsum qui duis short
        loin. Beef ribs dolore
  meatball officia rump fugiat
  in enim corned beef non est.
```

If you enjoyed this one and want more of a challenge try https://www.codewars.com/kata/text-align-justify/python

If you like bacon ipsum https://baconipsum.com

import textwrap

def align_right(text, width):
    wrapper = textwrap.TextWrapper(width=width, break_on_hyphens=True)
    return '\n'.join(line.rjust(width) for line in wrapper.wrap(text))


Solve in Python:
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635.

*Note: only positive integers will be tested.*

import re

def sum_of_integers_in_string(s):
    return sum(int(x) for x in re.findall(r"(\d+)", s))


Solve in Python:
Your task in this kata is to implement the function `create_number_class` which will take a string parameter `alphabet` and return a class representing a number composed of this alphabet.

The class number will implement the four classical arithmetic operations (`+`, `-`, `*`, `//`), a method to convert itself to string, and a `convert_to` method which will take another class number as parameter and will return the value of the actual class number converted to the equivalent value with tha alphabet of the parameter class (return a new instance of this one).

Example:

```python
BinClass = create_number_class('01')
HexClass = create_number_class('0123456789ABCDEF')

x = BinClass('1010')
y = BinClass('10')

print(x+y)                   => '1100'
isinstance(x+y, BinClass)    => True
print(x.convert_to(HexClass) => 'A'
```

___Notes:___

* Only positives integers will be used (either as parameters or results of calculations).
* You'll never encounter invalid calculations (divisions by zero or things like that).
* Alphabets will contain at least 2 characters.

def create_number_class(alphabet):
    jinwei = len(alphabet)
    def str2dec(string : str) -> int:
        dec, base = 0, 1
        for dig in reversed(string):
            dec += base * alphabet.index(dig)
            base *= jinwei
        return dec
    def dec2str(dec : int) -> str:
        string = ''
        while 1:
            string += alphabet[dec % jinwei]
            dec = dec // jinwei
            if 0 is dec: return string[::-1]
    class number:
        def __init__(self, str_or_dec):
            if isinstance(str_or_dec, str):
                self.str = str_or_dec
                self.dec = str2dec(self.str)
            else:
                self.dec = str_or_dec
                self.str = dec2str(self.dec)
        def convert_to(self, _class):
            return _class(self.dec)
        def __str__(self):
            return self.str
        def __add__(self, x):
            return number(self.dec + x.dec)
        def __sub__(self, x):
            return number(self.dec - x.dec)
        def __mul__(self, x):
            return number(self.dec * x.dec)
        def __floordiv__(self, x):
            return number(self.dec // x.dec)
    return number


Solve in Python:
Your task is simply to count the total number of lowercase letters in a string.

## Examples

def lowercase_count(strng):
    letters = str(strng)
    lowercase = 0
    for i in letters:
        if i.islower():
            lowercase += 1

    return lowercase


Solve in Python:
Your task is the exact same as for the easy version. But this time, the marmots subtract the village's population P from their random number before responding to Heidi's request.

Also, there are now villages with as few as a single inhabitant, meaning that $1 \leq P \leq 1000$.

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

-----Input-----

Same as for the easy and medium versions. But remember that now 1 ≤ P ≤ 1000 and that the marmots may provide positive as well as negative integers.

-----Output-----

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

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

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

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

    print("{}".format("uniform" if max(V) < 1.9*(S**0.5) else "poisson"))


Solve in Python:
Your task is to Combine two Strings. But consider the rule...

By the way you don't have to check errors or incorrect input values, everything is ok without bad tricks, only two input strings and as result one output string;-)...

And here's the rule:
Input Strings `a` and `b`: For every character in string `a` swap the casing of every occurrence of the same character in string `b`. Then do the same casing swap with the inputs reversed. Return a single string consisting of the changed version of `a` followed by the changed version of `b`. A char of `a` is in `b` regardless if it's in upper or lower case - see the testcases too.
I think that's all;-)...

Some easy examples:

````
Input: "abc" and "cde"      => Output: "abCCde"
Input: "ab" and "aba"       => Output: "aBABA"
Input: "abab" and "bababa"  => Output: "ABABbababa"
````

Once again for the last example - description from `KenKamau`, see discourse;-):

a) swap the case of characters in string `b` for every occurrence of that character in string `a`
char `'a'` occurs twice in string `a`, so we swap all `'a'` in string `b` twice. This means we start with `"bababa"` then `"bAbAbA"` => `"bababa"`
char `'b'` occurs twice in string `a` and so string `b` moves as follows: start with `"bababa"` then `"BaBaBa"` => `"bababa"`

b) then, swap the case of characters in string `a` for every occurrence in string `b`
char `'a'` occurs `3` times in string `b`. So string `a` swaps cases as follows: start with `"abab"` then => `"AbAb"` => `"abab"` => `"AbAb"`
char `'b'` occurs `3` times in string `b`. So string `a` swaps as follow: start with `"AbAb"` then => `"ABAB"` => `"AbAb"` => `"ABAB"`.

c) merge new strings `a` and `b`
return `"ABABbababa"`

There are some static tests at the beginning and many random tests if you submit your solution.

Hope you have fun:-)!

from collections import Counter

def work_on_strings(a, b):
    sa, sb = ("".join(x + x.upper() for x, y in Counter(s.lower()).items() if y % 2) for s in (a, b))
    return a.translate(str.maketrans(sb, sb.swapcase())) + b.translate(str.maketrans(sa, sa.swapcase()))


Solve in Python:
Your task is to ___Reverse and Combine Words___. It's not too difficult, but there are some things you have to consider...

### So what to do?

Input: String containing different "words" separated by spaces

```
1. More than one word? Reverse each word and combine first with second, third with fourth and so on...
   (odd number of words => last one stays alone, but has to be reversed too)
2. Start it again until there's only one word without spaces
3. Return your result...
```

### Some easy examples:
```
Input:  "abc def"
Output: "cbafed"

Input:  "abc def ghi 123"
Output: "defabc123ghi"

Input:  "abc def gh34 434ff 55_eri 123 343"
Output: "43hgff434cbafed343ire_55321"
```

I think it's clear?! First there are some static tests, later on random tests too...

### Hope you have fun! :-)

def reverse_and_combine_text(text):
    t = text.split()
    while len(t) > 1:
        t = [f'{a[::-1]}{b[::-1]}' for a, b in zip(*[iter([*t, ''])] * 2)]
    return t[0]


Solve in Python:
Your task is to ___find the next higher number (int) with same '1'- Bits___.

I.e. as much `1` bits as before and output next higher than input. Input is always an int in between 1 and 1<<30 (inclusive). No bad cases or special tricks...

### Some easy examples:

```
Input: 129  => Output: 130 (10000001 => 10000010)
Input: 127 => Output: 191 (01111111 => 10111111)
Input: 1 => Output: 2 (01 => 10)
Input: 323423 => Output: 323439 (1001110111101011111 => 1001110111101101111)
```

First some static tests, later on many random tests too;-)!

### Hope you have fun! :-)

def next_higher(value):
    value2=value+1
    while (bin(value)).count("1")!=(bin(value2)).count("1"):
        value2+=1
    return value2


Solve in Python:
Your task is to build a model^(1) which can predict y-coordinate.
You can pass tests if predicted y-coordinates are inside error margin.

You will receive train set which should be used to build a model.
After you build a model tests will call function ```predict``` and pass x to it.

Error is going to be calculated with RMSE.

Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy

Explanation
[1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.

class Datamining:

    def __init__(self, train_set):
        total = len(train_set)
        x = []
        for i in train_set:
            x.append(i[0])
        y = []
        for i in train_set:
            y.append(i[1])
        xmean = sum(x)/total
        ymean = sum(y)/total
        a = 0
        b = 0
        for i in range(total):
            a += (x[i]-xmean) * (y[i] - ymean)
            b+= (x[i]-xmean)**2
        self.z = a/b
        self.y = ymean - (self.z*xmean)

    def predict(self, x):
        return x*self.z + self.y
        pass


Solve in Python:
Your task is to build a model^(1) which can predict y-coordinate.
You can pass tests if predicted y-coordinates are inside error margin.

You will receive train set which should be used to build a model.
After you build a model tests will call function ```predict``` and pass x to it.

Error is going to be calculated with RMSE.

Side note: Points in test cases are from different polynomials (up to 5th degree).

Easier version: Data mining #1

Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy

Explanation
[1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.

class Datamining:

    def __init__(self, train_set):
        self.X = [s[0] for s in train_set[:6]]
        self.Y = [s[1] for s in train_set[:6]]

    def predict(self, x):
        y = 0
        for j in range(len(self.X)):
            Lj, xj = 1, self.X[j]
            for k in range(len(self.X)):
                xk = self.X[k]
                if xk != xj:
                    Lj *= (x-xk)/(xj-xk)
            y += Lj * self.Y[j]

        return y


Solve in Python:
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.

Example1:

a = 2
b = [3]

Result: 8

Example2:

a = 2
b = [1,0]

Result: 1024

Credits:Special thanks to @Stomach_ache for adding this problem and creating all test cases.

class Solution:
     def superPow(self, a, b):
         """
         :type a: int
         :type b: List[int]
         :rtype: int
         """
         temp1 = a
         temp = 1
         for i in range(len(b)-1,-1,-1):
             if i<len(b)-1:
                 temp1 = pow(temp1,10) % 1337
             temp2 = pow(temp1,b[i]) % 1337
             temp = temp * temp2 % 1337
         return temp


Solve in Python:
Your task is to calculate logical value of boolean array. Test arrays are one-dimensional and their size is in the range 1-50.

Links referring to logical operations: [AND](https://en.wikipedia.org/wiki/Logical_conjunction), [OR](https://en.wikipedia.org/wiki/Logical_disjunction) and [XOR](https://en.wikipedia.org/wiki/Exclusive_or).

You should begin at the first value, and repeatedly apply the logical operation across the remaining elements in the array sequentially.

First Example:

Input: true, true, false, operator: AND

Steps: true AND true -> true, true AND false -> false

Output: false

Second Example:

Input: true, true, false, operator: OR

Steps: true OR true -> true, true OR false -> true

Output: true

Third Example:

Input: true, true, false, operator: XOR

Steps: true XOR true -> false, false XOR false -> false

Output: false
___

Input:

boolean array, string with operator' s name: 'AND', 'OR', 'XOR'.

Output:

calculated boolean

from functools import reduce

def logical_calc(array, op):
    if op == "AND": return reduce(lambda a,b: a and b, array)
    if op == "OR": return reduce(lambda a,b: a or b, array)
    return reduce(lambda a,b: a ^ b, array)


Solve in Python:
Your task is to construct a building which will be a pile of n cubes.
The cube at the bottom will have a volume of n^3, the cube above
will have  volume of (n-1)^3 and so on until the top which will have a volume of 1^3.

You are given the total volume m of the building.
Being given m can you find the number n of cubes you will have to build?

The parameter of the function findNb `(find_nb, find-nb, findNb)` will be an integer m
and you have to return the integer n such as
n^3 + (n-1)^3 + ... + 1^3 = m
if such a n exists or -1 if there is no such n.

## Examples:
```
findNb(1071225) --> 45
findNb(91716553919377) --> -1
```

from decimal import *

def find_nb(m):
    getcontext().prec = 24
    squareRootM = Decimal(m).sqrt()
    squareRootDelta = Decimal(1+8*squareRootM).sqrt()
    num = (squareRootDelta-1)/2
    return num if num % 1 == 0 else -1


Solve in Python:
Your task is to convert a given number into a string with commas added for easier readability.  The number should be rounded to 3 decimal places and the commas should be added at intervals of three digits before the decimal point. There does not need to be a comma at the end of the number.

You will receive both positive and negative numbers.

## Examples

```python
commas(1) == "1"
commas(1000) == "1,000"
commas(100.2346) == "100.235"
commas(1000000000.23) == "1,000,000,000.23"
commas(-1) == "-1"
commas(-1000000.123) == "-1,000,000.123"
```

def commas(num):
    return str('{:,.3f}'.format(num)).rstrip('0').rstrip('.')


Solve in Python:
Your task is to create a function called ```sum_arrays()``` in Python or ```addArrays``` in Javascript, which takes two arrays consisting of integers, and returns the sum of those two arrays.

The twist is that (for example) ```[3,2,9]``` does not equal ``` 3 + 2 + 9```, it would equal ```'3' + '2' + '9'``` converted to an integer for this kata, meaning it would equal ```329```. The output should be an array of the the sum  in a similar fashion to the input (for example, if the sum is ```341```, you would return ```[3,4,1]```). Examples are given below of what two arrays should return.
```python
[3,2,9],[1,2] --> [3,4,1]
[4,7,3],[1,2,3] --> [5,9,6]
[1],[5,7,6] --> [5,7,7]
```
If both arrays are empty, return an empty array.

In some cases, there will be an array containing a negative number as the first index in the array. In this case treat the whole number as a negative number. See below:
```python
[3,2,6,6],[-7,2,2,8] --> [-3,9,6,2] # 3266 + (-7228) = -3962
```

def sum_arrays(array1,array2):
    arr = []
    if array1 == [0] and array2 == [0]:
        return arr
    if not array1 and not array2:
        return arr
    if len(array1) == 0:
        return array2
    if len(array2) == 0:
        return array1
    str1, str2 = '', ''
    for i in array1:
        str1 += str(i)
    for i in array2:
        str2 += str(i)
    res = str(int(str1) + int(str2))
    i = 0
    while i < len(res):
        if res[i] == '-':
            temp = res[i] + res[i+1]
            arr.append(int(temp))
            i += 2
        else:
            arr.append(int(res[i]))
            i += 1
    return arr


Solve in Python:
Your task is to create a function that does four basic mathematical operations.

The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.

### Examples

```python
basic_op('+', 4, 7)         # Output: 11
basic_op('-', 15, 18)       # Output: -3
basic_op('*', 5, 5)         # Output: 25
basic_op('/', 49, 7)        # Output: 7
```

def basic_op(operator, value1, value2):
    operation = str(value1) + str(operator) + str(value2)
    return eval(operation)


Solve in Python:
Your task is to create a new implementation of `modpow` so that it computes `(x^y)%n` for large `y`. The problem with the current implementation is that the output of `Math.pow` is so large on our inputs that it won't fit in a 64-bit float.

You're also going to need to be efficient, because we'll be testing some pretty big numbers.

def power_mod(x, y, n):
    x = x%n
    b = bin(y)[2:]
    l = len(b)
    res = [0]*l
    for i in range(l):
        res[-i-1] = x
        x *= x
        x = x%n
    prod = 1
    for i in range(l):
        if b[-i-1] == '1':
            prod *= res[-i-1]
            prod = prod%n
    return prod


Solve in Python:
Your task is to create function```isDivideBy``` (or ```is_divide_by```) to check if an integer number is divisible by each out of two arguments.

A few cases:

```

(-12, 2, -6)  ->  true
(-12, 2, -5)  ->  false

(45, 1, 6)    ->  false
(45, 5, 15)   ->  true

(4, 1, 4)     ->  true
(15, -5, 3)   ->  true

```

def is_divide_by(number: int, a: int, b: int) -> bool:
    """
    check is number is divisble by both a and b
    """
    return True if number % a is 0 and number % b is 0 else False


Solve in Python:
Your task is to define a function that understands basic mathematical expressions and solves them.
For example:

```python
calculate("1 + 1")        # => 2
calculate("18 + 4*6")     # => 42
calculate("245 - 826")    # => -581
calculate("09 + 000482")  # => 491
calculate("8 / 4 + 6")    # => 8
calculate("5 + 1 / 5")    # => 5.2
calculate("1+2+3")        # => 6
calculate("9 /3 + 12/ 6") # => 5
```
Notes:

- Input string will contain numbers (may be integers and floats) and arithmetic operations.
- Input string may contain spaces, and all space characters should be ignored.
- Operations that will be used: addition (+), subtraction (-), multiplication (*), and division (/)
- Operations must be done in the order of operations: First multiplication and division, then addition and subtraction.
- In this kata, input expression will not have negative numbers. (ex: "-4 + 5")
- If output is an integer, return as integer. Else return as float.
- If input string is empty, contains letters, has a wrong syntax, contains division by zero or is not a string, return False.

import re
def calculate(input):
    try:
        return eval(re.sub(r'(\d+)', lambda m: str(int(m.group(1))), input))
    except:
        return False


Solve in Python:
Your task is to determine how many files of the copy queue you will be able to save into your Hard Disk Drive. The files must be saved in the order they appear in the queue.

### Input:

* Array of file sizes `(0 <= s <= 100)`
* Capacity of the HD `(0 <= c <= 500)`

### Output:

* Number of files that can be fully saved in the HD.

### Examples:

```
save([4,4,4,3,3], 12) -> 3
# 4+4+4 <= 12, but 4+4+4+3 > 12
```

```
save([4,4,4,3,3], 11) -> 2
# 4+4 <= 11, but 4+4+4 > 11
```

Do not expect any negative or invalid inputs.

from bisect import bisect
from itertools import accumulate

def save(sizes, hd):
    return bisect(list(accumulate(sizes)), hd)


Solve in Python:
Your task is to determine the top 3 place finishes in a pole vault competition involving several different competitors. This is isn't always so simple, and it is often a source of confusion for people who don't know the actual rules.

Here's what you need to know:

As input, you will receive an array of objects. Each object contains the respective competitor's name (as a string) and his/her results at the various bar heights (as an array of strings):

[{name: "Sergey", results: ["", "O", "XO", "O", "XXO", "XXX", "", ""]}{name: "Jan", results: ["", "", "", "O", "O", "XO", "XXO", "XXX"]}{name: "Bruce", results: ["", "XO", "XXO", "XXX", "", "", "", ""]}{name: "HerrWert", results: ["XXX", "", "", "", "", "", "", ""]}]

In the array of strings described above, each string represents the vaulter's performance at a given height. The possible values are based on commonly used written notations on a pole vault scoresheet:
An empty string indicates that the vaulter did not jump at this height for a variety of possible reasons ("passed" at this height, was temporarily called away to a different track and field event, was already eliminated from competition, or withdrew due to injury, for example).An upper-case X in the string represents an unsuccessful attempt at the height. (As you may know, the vaulter is eliminated from the competition after three consecutive failed attempts.)An upper-case O represents a successful attempt. If present at all, this will be the final character in the string, because it indicates that the vaulter has now successfully completed this height and is ready to move on.

All vaulters will have a result string (though possibly empty) for every height involved in the competition, making it possible to match up the results of different vaulters with less confusion.

Obviously, your first task is to determine who cleared the greatest height successfully. In other words, who has a "O" mark at a higher array element than any other competitor? You might want to work through the arrays from right to...

def score_pole_vault(vaulter_list):
    i = j = 0
    retDict = {}
    vaulter = {}
    updatedVaulterList = []

    for vaulter_dict in vaulter_list:
        vaulter = {'name': vaulter_dict['name'], 'results': vaulter_dict['results']}
        highestVaulterJump = 0
        totalUnsuccessfulAttempts = 0
        unsuccessfulAttemptsAtHighestJump = 0
        j = 0
        for resultsList in vaulter_list[i]['results']:
            j -= 1
            if 'O' in resultsList:
                highestVaulterJump = j
                unsuccessfulAttemptsAtHighestJump = resultsList.count('X')
            totalUnsuccessfulAttempts += resultsList.count('X')
        vaulter['highestSuccessfulJump'] = highestVaulterJump
        vaulter['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump'] = unsuccessfulAttemptsAtHighestJump
        vaulter['numOfTotalUnsuccessfulAttempts'] = totalUnsuccessfulAttempts
        updatedVaulterList.append(dict(vaulter))
        i += 1

    updatedVaulterList = sorted(updatedVaulterList, key = lambda i: (i['highestSuccessfulJump'], i['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump'], i['numOfTotalUnsuccessfulAttempts'], i['name']))
    jumpOff = 0
    positionsAssigned = 0
    for i in range(len(updatedVaulterList)):
        if i == 0:
            retDict['1st'] = updatedVaulterList[i]['name']
            positionsAssigned += 1
        if i > 0:
            if updatedVaulterList[i]['highestSuccessfulJump'] == updatedVaulterList[0]['highestSuccessfulJump']:
                if updatedVaulterList[i]['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump'] == updatedVaulterList[0]['numOfUnsuccessfulAttemptsAtHighestSuccessfulJump']:
                    if updatedVaulterList[i]['numOfTotalUnsuccessfulAttempts'] == updatedVaulterList[0]['numOfTotalUnsuccessfulAttempts']:
                        retDict['1st'] = retDict['1st'] + ", " + updatedVaulterList[i]['name']
                        jumpOff = 1
                        positionsAssigned += 1
    if jumpOff:
        retDict['1st'] =...


Solve in Python:
Your task is to find all the elements of an array that are non consecutive.

A number is non consecutive if it is not exactly one larger than the previous element in the array. The first element gets a pass and is never considered non consecutive.

~~~if:javascript,haskell,swift
Create a function named `allNonConsecutive`
~~~
~~~if:python,rust
Create a function name `all_non_consecutive`
~~~

E.g., if we have an array `[1,2,3,4,6,7,8,15,16]` then `6` and `15` are non-consecutive.

~~~if:javascript,python
You should return the results as an array of objects with two values `i: ` and `n: `.
~~~
~~~if:haskell,swift,rust
You should return the results as an array of tuples with two values: the index of the non-consecutive number and the non-consecutive number.
~~~

E.g., for the above array the result should be:
```python
[
  {'i': 4, 'n': 6},
  {'i': 7, 'n': 15}
]
```

If the whole array is consecutive or has one element then return an empty array.

The array elements will all be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive and/or negetive and the gap could be larger than one.

If you like this kata, maybe try this one next: https://www.codewars.com/kata/represent-array-of-numbers-as-ranges

def all_non_consecutive(arr):
    return [{'i': i + 1, 'n': n} for i, n in enumerate(arr[1:]) if arr[i + 1] - arr[i] != 1]


Solve in Python:
Your task is to find the first element of an array that is not consecutive.

By not consecutive we mean not exactly 1 larger than the previous element of the array.

E.g. If we have an array `[1,2,3,4,6,7,8]` then `1` then `2` then `3` then `4` are all consecutive but `6` is not, so that's the first non-consecutive number.

```if:c
If a non consecutive number is found then return `true` and set the passed in pointer to the number found.

If the whole array is consecutive then return `false`.
```
```if-not:c
If the whole array is consecutive then return `null`^(2).
```
The array will always have at least `2` elements^(1) and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too!

If you like this Kata, maybe try this one next: https://www.codewars.com/kata/represent-array-of-numbers-as-ranges

```if:c
^(1) Can you write a solution that will return `false` for both `[]` and `[ x ]` (an empty array and one with a single number) though? (This is an empty array and one with a single number and is not tested for, but you can write your own example test. )
```
```if-not:c
^(1) Can you write a solution that will return `null`^(2) for both `[]` and `[ x ]` though?  (This is an empty array and one with a single number and is not tested for, but you can write your own example test. )

^(2)
Swift, Ruby and Crystal: `nil`
Haskell: `Nothing`
Python, Rust: `None`
Julia: `nothing`
Nim: `none(int)` (See [options](https://nim-lang.org/docs/options.html))
```

def first_non_consecutive(arr):
    init = arr[0]
    for i in arr:
        if init != i:
            return i
        else:
            init += 1
    return None


Solve in Python:
Your task is to find the number couple with the greatest difference from a given array of number-couples.

All number couples will be given as strings and all numbers in them will be positive integers.

For instance: ['56-23','1-100']; in this case, you should identify '1-100' as the number couple with the greatest difference and return it.

In case there are more than one option, for instance ['1-3','5-7','2-3'], you should identify whichever is first, so in this case '1-3'.

If there is no difference, like so ['11-11', '344-344'], return false.

def difference(x):
    a, b = map(int, x.split('-'))
    return abs(a-b)

def diff(arr):
    if not arr:
        return False
    x = max(arr, key=difference)
    if difference(x) == 0:
        return False
    return x


Solve in Python:
Your task is to form an integer array nums from an initial array of zeros arr that is the same size as nums.
Return the minimum number of function calls to make nums from arr.
The answer is guaranteed to fit in a 32-bit signed integer.

Example 1:
Input: nums = [1,5]
Output: 5
Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).
Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).
Increment by 1 (both elements)  [0, 4] -> [1, 4] -> [1, 5] (2 operations).
Total of operations: 1 + 2 + 2 = 5.

Example 2:
Input: nums = [2,2]
Output: 3
Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).
Double all the elements: [1, 1] -> [2, 2] (1 operation).
Total of operations: 2 + 1 = 3.

Example 3:
Input: nums = [4,2,5]
Output: 6
Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).

Example 4:
Input: nums = [3,2,2,4]
Output: 7

Example 5:
Input: nums = [2,4,8,16]
Output: 8

Constraints:

1 <= nums.length <= 10^5
0 <= nums[i] <= 10^9

def get_num_ops(num):
     assert num >= 0
     d_ops, s_ops = 0, 0
     while num != 0:
         if num%2 == 1:
             num = num - 1
             s_ops += 1
         else:
             num = num//2
             d_ops += 1
     return d_ops, s_ops

class Solution:
    def minOperations(self, nums: List[int]) -> int:
        num_ops = 0
        doubling_ops = []
        for num in nums:
            d, s = get_num_ops(num)
            doubling_ops.append(d)
            num_ops += d + s
            print(num_ops)

        doubling_ops = sorted(doubling_ops)
        change = [doubling_ops[0]]
        for i in range(1, len(doubling_ops)):
            change.append(doubling_ops[i] - doubling_ops[i-1])

        for i, c in enumerate(change):
            num_ops = num_ops - c * (len(change) -i - 1)

        return num_ops


Solve in Python:
Your task is to generate the Fibonacci sequence to `n` places, with each alternating value as `"skip"`. For example:

`"1 skip 2 skip 5 skip 13 skip 34"`

Return the result as a string

You can presume that `n` is always a positive integer between (and including) 1 and 64.

fib, result = [1, 1], ["1", "skip"]
for i in range(100):
    fib.append(fib[-1] + fib[-2])
    result.append("skip" if i&1 else str(fib[-1]))

def skiponacci(n):
    return ' '.join(result[:n])


Solve in Python:
Your task is to get Zodiac Sign using input ```day``` and ```month```.

For exapmle:

```python
get_zodiac_sign(1,5) => 'Taurus'
get_zodiac_sign(10,10) => 'Libra'
```

Correct answers are (preloaded):
```python
SIGNS = ['Capricorn', 'Aquarius', 'Pisces', 'Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius']
```

P.S. Each argument is correct integer number.

WESTERN ASTROLOGY STAR SIGN DATES

* Aries (March 21-April 19)
* Taurus (April 20-May 20)
* Gemini (May 21-June 20)
* Cancer (June 21-July 22)
* Leo (July 23-August 22)
* Virgo (August 23-September 22)
* Libra (September 23-October 22)
* Scorpio (October 23-November 21)
* Sagittarius (November 22-December 21)
* Capricorn (December 22-January 19)
* Aquarius (January 20 to February 18)
* Pisces (February 19 to March 20)

from datetime import datetime

data = """
Aries March 21 April 19
Taurus April 20 May 20
Gemini May 21 June 20
Cancer June 21 July 22
Leo July 23 August 22
Virgo August 23 September 22
Libra September 23 October 22
Scorpio October 23 November 21
Sagittarius November 22 December 21
Capricorn December 22 January 19
Aquarius January 20 February 18
Pisces February 19 March 20
"""
data = [line.split() for line in data.split('\n') if line.strip()]
month = lambda s: datetime.strptime(s, '%B').month
data = [(z, month(m1), int(d1), month(m2), int(d2)) for z, m1, d1, m2, d2 in data]

def get_zodiac_sign(day, month):
    for z, m1, d1, m2, d2 in data:
        if (m1 == month and d1 <= day) or (m2 == month and day <= d2):
            return z


Solve in Python:
Your task is to implement a function that calculates an election winner from a list of voter selections using an [Instant Runoff Voting](http://en.wikipedia.org/wiki/Instant-runoff_voting) algorithm. If you haven't heard of IRV, here's a basic overview (slightly altered for this kata):

- Each voter selects several candidates in order of preference.
- The votes are tallied from the each voter's first choice.
- If the first-place candidate has more than half the total votes, they win.
- Otherwise, find the candidate who got the least votes and remove them from each person's voting list.
- In case of a tie for least, remove all of the tying candidates.
- In case of a complete tie between every candidate, return nil(Ruby)/None(Python)/undefined(JS).
- Start over.
- Continue until somebody has more than half the votes; they are the winner.

Your function will be given a list of voter ballots; each ballot will be a list of candidates (symbols) in descending order of preference. You should return the symbol corresponding to the winning candidate. See the default test for an example!

def runoff(voters):
    if voters == []:
        return None
    elif len(voters[0]) == 1:
        return voters[0][0]
    voters_dict = {elem: [x[0] for x in voters].count(elem) for elem in voters[0]}
    expelled = sorted([voters_dict.get(x) for x in voters_dict])[0]
    return runoff([i for i in [[x for x in choices if
                                voters_dict.get(x) != expelled] for choices in voters] if i != []])


Solve in Python:
Your task is to implement a function that takes one or more dictionaries and combines them in one result dictionary.

The keys in the given dictionaries can overlap. In that case you should combine all source values in an array. Duplicate values should be preserved.

Here is an example:
```cs
var source1 = new Dictionary{{"A", 1}, {"B", 2}};
var source2 = new Dictionary{{"A", 3}};

Dictionary result = DictionaryMerger.Merge(source1, source2);
// result should have this content: {{"A", [1, 3]}, {"B", [2]}}

```
```python
source1 = {"A": 1, "B": 2}
source2 = {"A": 3}

result = merge(source1, source2);
// result should have this content: {"A": [1, 3]}, "B": [2]}

```

You can assume that only valid dictionaries are passed to your function.
The number of given dictionaries might be large. So take care about performance.

from collections import defaultdict

def merge(*dicts):
    d = defaultdict(list)
    [d[key].append(value) for dictionary in dicts for key, value in list(dictionary.items()) ]
    return d


Solve in Python:
Your task is to make a program takes in a sentence (without puncuation), adds all words to a list and returns the sentence as a string which is the positions of the word in the list. Casing should not matter too.

Example
-----

`"Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country"`

becomes

`"01234567802856734"`

Another example
-----

`"the one bumble bee one bumble the bee"`

becomes

`"01231203"`

def compress(sentence):
    words = sentence.lower().split()
    uniq = sorted(set(words), key=words.index)
    return "".join(str(uniq.index(word)) for word in words)


Solve in Python:
Your task is to make function, which returns the sum of a sequence of integers.

The sequence is defined by 3 non-negative values: **begin**, **end**, **step**.

If **begin** value is greater than the **end**, function should returns **0**

*Examples*

~~~if-not:nasm

~~~

This is the first kata in the series:

1) Sum of a sequence (this kata)
2) [Sum of a Sequence [Hard-Core Version]](https://www.codewars.com/kata/sum-of-a-sequence-hard-core-version/javascript)

def sequence_sum(begin_number, end_number, step):
    x = list(range(begin_number, end_number+1))
    return sum(x[::step])


Solve in Python:
Your task is to make two functions, ```max``` and ```min``` (`maximum` and `minimum` in PHP and Python) that take a(n) array/vector of integers ```list``` as input and outputs, respectively, the largest and lowest number in that array/vector.

#Examples
```python
maximun([4,6,2,1,9,63,-134,566]) returns 566
minimun([-52, 56, 30, 29, -54, 0, -110]) returns -110
maximun([5]) returns 5
minimun([42, 54, 65, 87, 0]) returns 0
```

#Notes
- You may consider that there will not be any empty arrays/vectors.

def minimum(arr):
    min = 1000000000
    for i in arr:
        if i < min:
            min = i
    return min

def maximum(arr):
    max = -1000000000
    for i in arr:
        if i > max:
            max = i
    return max


Solve in Python:
Your task is to remove all duplicate words from a string, leaving only single (first) words entries.

Example:

Input:

'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'

Output:

'alpha beta gamma delta'

def remove_duplicate_words(s):
    no_dup = []
    no_dup1 = []
    for c in s.split(' '):
        if c not in no_dup:
            no_dup.append(c)
        else:
            no_dup1.append(c)
    return ' '.join(no_dup)


Solve in Python:
Your task is to return how many times a string contains a given character.

The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count.

For example, if you get an input string "Hello world" and the character to find is "o", return 2.

def string_counter(string, char):
    return string.count(char)


Solve in Python:
Your task is to return the number of visible dots on a die after it has been rolled(that means the total count of dots that would not be touching the table when rolled)

6, 8, 10, 12, 20 sided dice are the possible inputs for "numOfSides"

topNum is equal to the number that is on top, or the number that was rolled.

for this exercise, all opposite faces add up to be 1 more than the total amount of sides
  Example: 6 sided die would have 6 opposite 1, 4 opposite 3, and so on.
for this exercise, the 10 sided die starts at 1 and ends on 10.

Note: topNum will never be greater than numOfSides

def totalAmountVisible(top, sides):
    return sides * (sides + 1 ) / 2 + top - sides - 1


Solve in Python:
Your task is to return the sum of Triangular Numbers up-to-and-including the `nth` Triangular Number.

Triangular Number: "any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc."

```
[01]
02 [03]
04 05 [06]
07 08 09 [10]
11 12 13 14 [15]
16 17 18 19 20 [21]
```

e.g. If `4` is given: `1 + 3 + 6 + 10 = 20`.

Triangular Numbers cannot be negative so return 0 if a negative number is given.

from itertools import accumulate
sum_triangular_numbers = lambda _:sum(accumulate(range(0,_+1)))


Solve in Python:
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.

Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

If the input string is empty, return an empty string.
The words in the input String will only contain valid consecutive numbers.

## Examples

```
"is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2"  -->  "Fo1r the2 g3ood 4of th5e pe6ople"
""  -->  ""
```

def order(sentence):
    if not sentence:
        return ""
    result = []    #the list that will eventually become our setence

    split_up = sentence.split() #the original sentence turned into a list

    for i in range(1,10):
        for item in split_up:
            if str(i) in item:
                 result.append(item)    #adds them in numerical order since it cycles through i first

    return " ".join(result)


Solve in Python:
Your task is to validate rhythm with a meter.

_________________________________________________
Rules:

1. Rhythmic division requires that in one whole note (1) there are two half notes (2) or four quarter notes (4) or eight eighth notes (8).
Examples: 1 = 2 + 2, 1 = 4 + 4 + 4 + 4 ...
Note that: 2 = 4 + 4, 4 = 8 + 8, 2 = 8 + 8 + 4 ...

2. Meter gives an information how many rhythmic types of notes should be in one bar. Bar is the the primary section of a musical score.
Examples:
          4/4 -> 4 quarter notes in a bar
          5/2 -> 5 half notes in a bar
          3/8 -> 3 eighth notes in a bar
Note that:
for 4/4 valid bars are: '4444', '88888888', '2488' ...
for 5/2 valid bars are: '22222', '2244244', '8888244888844' ...
for 3/8 valid bars are: '888', '48' ...

3. Anacrusis occurs when all bars but the first and last are valid, and the notes in the first and last bars when combined would also make a valid bar.

Examples:
for 4/4 valid anacrusis is -> 44|...|44 or 88|...|888888 or 2|...|488
for 5/2 valid anacrusis is -> 22|...|222 or 222|...|22 or  2244|...|244
for 3/8 valid anacrusis is -> 8|...|88 or 4|...|8 or 8|...|4
Note:
When anacrusis is valid but other bars in score are not -> return 'Invalid rhythm'
________________________________________________

Input:
meter - array: eg. [4, 4],
score - string, bars separated with '|': eg. '4444|8484842|888'

Output:
string message: 'Valid rhythm', 'Valid rhythm with anacrusis' or 'Invalid rhythm'

def validate_rhythm(m, score):
    t = m[0]/m[1]
    if t == 1 and m[0] not in [1,2,4,8]: return 'Invalid rhythm'
    a = score.split('|')

    for c in score:
        if c not in '|1248': return 'Invalid rhythm'

    for s in a[1:-1]:
        if sum([1/int(c) for c in s]) != t:
            return 'Invalid rhythm'

    bool = True
    for s in [a[0],a[-1]]:
        if sum([1/int(c) for c in s]) != t:
            bool = False
    if bool: return 'Valid rhythm'

    if sum([1/int(c) for c in a[0]+a[-1]]) == t:
        return 'Valid rhythm with anacrusis'

    return 'Invalid rhythm'


Solve in Python:
Your task is to write a function named `do_math` that receives a single argument.
This argument is a string that contains multiple whitespace delimited numbers. Each number has a single alphabet letter somewhere within it.
```
Example : "24z6 1x23 y369 89a 900b"
```
As shown above, this alphabet letter can appear anywhere within the number. You have to extract the letters and sort the numbers according to their corresponding letters.
```
Example : "24z6 1x23 y369 89a 900b" will become 89 900 123 369 246 (ordered according to the alphabet letter)
```
Here comes the difficult part, now you have to do a series of computations on the numbers you have extracted.

* The sequence of computations are `+ - * /`. Basic math rules do **NOT** apply, you have to do each computation in exactly this order.
* This has to work for any size of numbers sent in (after division, go back to addition, etc).
* In the case of duplicate alphabet letters, you have to arrange them according to the number that appeared first in the input string.
* Remember to also round the final answer to the nearest integer.

```
Examples :
"24z6 1x23 y369 89a 900b" = 89 + 900 - 123 * 369 / 246 = 1299
"24z6 1z23 y369 89z 900b" = 900 + 369 - 246 * 123 / 89 = 1414
"10a 90x 14b 78u 45a 7b 34y" = 10 + 45 - 14 * 7 / 78 + 90 - 34 = 60
```
Good luck and may the CODE be with you!

from re import findall
from itertools import cycle

def do_math(s) :
    numbers = [''.join(findall(r'\d+', num)) for num in sorted(s.split(), key = lambda x: max(x))]
    res = numbers[0]
    for i, operation in zip(numbers[1:], cycle('+-*/')):
        res = eval(f'{res} {operation} {i}')
    return round(float(res))


Solve in Python:
Your task is to write a function that does just what the title suggests (so, fair warning, be aware that you are not getting out of it just throwing a lame bas sorting method there) with an array/list/vector of integers and the expected number `n` of smallest elements to return.

Also:

* the number of elements to be returned cannot be higher than the array/list/vector length;
* elements can be duplicated;
* in case of duplicates, just return them according to the original order (see third example for more clarity).

Same examples and more in the test cases:

```python
first_n_smallest([1,2,3,4,5],3) == [1,2,3]
first_n_smallest([5,4,3,2,1],3) == [3,2,1]
first_n_smallest([1,2,3,4,1],3) == [1,2,1]
first_n_smallest([1,2,3,-4,0],3) == [1,-4,0]
first_n_smallest([1,2,3,4,5],0) == []
```

[Performance version by FArekkusu](https://www.codewars.com/kata/5aeed69804a92621a7000077) also available.

def first_n_smallest(arr, n):
    lst = sorted(enumerate(arr), key=lambda it: it[1])[:n]
    lst.sort(key=lambda it:it[0])
    return [v for _,v in lst]


Solve in Python:
Your task is to write a function that takes two or more objects and returns a new object which combines all the input objects.

All input object properties will have only numeric values. Objects are combined together so that the values of matching keys are added together.

An example:

```python
objA = { 'a': 10, 'b': 20, 'c': 30 }
objB = { 'a': 3, 'c': 6, 'd': 3 }
combine(objA, objB) # Returns { a: 13, b: 20, c: 36, d: 3 }
```

The combine function should be a good citizen, so should not mutate the input objects.

def combine(*dictionaries):
    result = {}
    for dict in dictionaries:
        for key, value in list(dict.items()):
            result[key] = value + result.get(key, 0)
    return result


Solve in Python:
Your task is to write a function which counts the number of squares contained in an ASCII art picture.

The input pictures contain rectangles---some of them squares---drawn with the characters `-`, `|`, and `+`, where `-` and `|` are used to represent horizontal and vertical sides, and `+` is used to represent corners and intersections. Each picture may contain multiple, possibly overlapping, rectangles.

A simple example input looks like this:

    +--+  +----+
    |  |  |    |    +-+
    |  |  +----+    | |
    +--+            +-+

There are two squares and one rectangle in this picture, so your function should return 2 for this input.

The following picture does not contain any squares, so the answer for this one is 0:

    +------+
    |      |
    +------+

Here is another, more complex input:

    +---+
    |   |
    | +-+-+
    | | | |
    +-+-+ |
      |   |
      +---+

The answer for this one is 3: two big squares, and a smaller square formed by the intersection of the two bigger ones. Similarly, the answer for the following picture is 5:

    +-+-+
    | | |
    +-+-+
    | | |
    +-+-+

You are going to implement a function `count_squares()` which takes an ASCII art picture as input and returns the number of squares the picture shows. The input to that function is an array of strings, where each string corresponds to a line of the ASCII art picture. Each string is guaranteed to contain only the characters `-`, `|`, `+`, and `` `` (space).

The smallest valid square has a side length of 2 and is represented by four `+` characters arranged in a square; a single `+` character is not considered a square.

Have fun!

def isInvalid(lines, y, x, chars):
    if y >= len(lines) or x >= len(lines[y]):
        return True
    return lines[y][x] not in chars

def isSquare(lines, x, y, size):
    if isInvalid(lines, y, x, '+') or \
       isInvalid(lines, y+size, x, '+') or \
       isInvalid(lines, y, x+size, '+') or \
       isInvalid(lines, y+size, x+size, '+'):
      return False
    for s in range(size + 1):
        if isInvalid(lines, y, x+s, '+-') or \
           isInvalid(lines, y+s, x, '+|') or \
           isInvalid(lines, y+size, x+s, '+-') or \
           isInvalid(lines, y+s, x+size, '+|'):
            return False
    return True

def count_squares(lines):
    count = 0
    for y in range(len(lines)):
        for x in range(len(lines[y])):
            for s in range(1, min(len(lines)-y, len(lines[y])-x)):
                if isSquare(lines, x, y, s):
                    count += 1
    return count


Solve in Python:
Your task is to write an update for a lottery machine. Its current version produces a sequence of random letters and integers (passed as a string to the function). Your code must filter out all letters and return **unique** integers as a string, in their order of first appearance. If there are no integers in the string return `"One more run!"`

## Examples

```
"hPrBKWDH8yc6Lt5NQZWQ"  -->  "865"
"ynMAisVpHEqpqHBqTrwH"  -->  "One more run!"
"555"                   -->  "5"
```

def lottery(s):
    seen = set(); seen_add = seen.add; seq = [i for i in s if i in '0123456789']
    return ''.join(x for x in seq if not (x in seen or seen_add(x))) or "One more run!"


Solve in Python:
Your task is to write function ```findSum```.

Upto and including ```n```, this function will return the sum of all multiples of 3 and 5.

For example:

```findSum(5)``` should return 8 (3 + 5)

```findSum(10)``` should return 33 (3 + 5 + 6 + 9 + 10)

def find(n):
    result = 0
    while n > 0:
        if n == 0:
            break
        elif n%3 == 0 or n%5 == 0:
            result += n
        n-=1
    return result


Solve in Python:
Your task is to write function which takes string and list of delimiters as an input and returns list of strings/characters after splitting given string.

Example:
```python
multiple_split('Hi, how are you?', [' ']) => ['Hi,', 'how', 'are', 'you?']
multiple_split('1+2-3', ['+', '-']) => ['1', '2', '3']
```

List of delimiters is optional and can be empty, so take that into account.

Important note: Result cannot contain empty string.

def multiple_split(s, delimiters=[]):
    if s == "": return []
    elif delimiters == []:  return [s]

    return [ w for w in s.translate("".maketrans("".join(delimiters), delimiters[0]*len(delimiters)) ).split(delimiters[0]) if w != ""]


Solve in Python:
Your task is very simple. Given an input string s, case\_sensitive(s), check whether all letters are lowercase or not. Return True/False and a list of all the entries that are not lowercase in order of their appearance in s.

For example, case\_sensitive('codewars') returns [True, []], but case\_sensitive('codeWaRs') returns [False, ['W', 'R']].

Goodluck :)

Have a look at my other katas!

Alphabetically ordered
Find Nearest square number
Not prime numbers

def case_sensitive(s):
    lst = [x for x in s if x.isupper()]
    return [len(lst) == 0, lst]


Solve in Python:
Your task is very simple. Just write a function `isAlphabetic(s)`, which takes an input string `s` in lowercase and returns `true`/`false` depending on whether the string is in alphabetical order or not.

For example, `isAlphabetic('kata')` is False as 'a' comes after 'k', but `isAlphabetic('ant')` is True.

Good luck :)

alphabetic = lambda str: sorted(str) == list(str)


Solve in Python:
Your task it to return ```true``` if the fractional part (rounded to 1 digit) of the result (```a``` / ```b```) exists, more than ```0``` and is multiple of ```n```.
Otherwise return ```false```. (For Python return True or False)

All arguments are positive digital numbers.

Rounding works like toFixed() method. (if more than...5 rounds up)

Find exapmles below:

```

isMultiple(5, 2, 3) -> false // 2.5 -> 5 is not multiple of 3
isMultiple(5, 3, 4) -> false // 1.7 -> 7 is not multiple of 4
isMultiple(5, 4, 3) -> true // 1.3 -> 3 is multiple of 3
isMultiple(666, 665, 2) -> false // 1.0 -> return false

```

def isMultiple(a, b, n):
    x=int((a/b-a//b)*10+0.5)
    return 0<x<10 and x%n==0


Solve in Python:
Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering.

Write a function which takes a list of strings and returns each line prepended by the correct number.

The numbering starts at 1. The format is `n: string`. Notice the colon and space in between.

**Examples:**

```python
number([]) # => []
number(["a", "b", "c"]) # => ["1: a", "2: b", "3: c"]
```

def number(lines):

    out = []
    for i in range(len(lines)):
        out.append('{}: {}'.format(i+1,lines[i]))

    return out


Solve in Python:
Your users passwords were all stole in the Yahoo! hack, and it turns out they have been lax in creating secure passwords.  Create a function that checks their new password (passed as a string) to make sure it meets the following requirements:

Between 8 - 20 characters

Contains only the following characters: (and at least one character from each category): uppercase letters, lowercase letters, digits, and the special characters !@#$%^&*?

Return "valid" if passed or else "not valid"


Solve in Python:
Your website is divided vertically in sections, and each can be of different size (height).
You need to establish the section index (starting at `0`) you are at, given the `scrollY` and `sizes` of all sections.
Sections start with `0`, so if first section is `200` high, it takes `0-199` "pixels" and second starts at `200`.

### Example:

`getSectionIdFromScroll( 300, [300,200,400,600,100] )`

will output number `1` as it's the second section.

`getSectionIdFromScroll( 1600, [300,200,400,600,100] )`

will output number `-1` as it's past last section.

Given the `scrollY` integer (always non-negative) and an array of non-negative integers (with at least one element), calculate the index (starting at `0`) or `-1` if `scrollY` falls beyond last section (indication of an error).

from bisect import bisect
from itertools import accumulate

def get_section_id(scroll, sizes):
    return bisect(list(accumulate(sizes)), scroll) if scroll < sum(sizes) else -1


Solve in Python:
Your wizard cousin works at a Quidditch stadium and wants you to write a function that calculates the points for the Quidditch scoreboard!

# Story

Quidditch is a sport with two teams. The teams score goals by throwing the Quaffle through a hoop, each goal is worth **10 points**.

The referee also deducts 30 points (**- 30 points**) from the team who are guilty of carrying out any of these fouls: Blatching, Blurting, Bumphing, Haverstacking, Quaffle-pocking, Stooging

The match is concluded when the Snitch is caught, and catching the Snitch is worth **150 points**. Let's say a Quaffle goes through the hoop just seconds after the Snitch is caught, in that case the points of that goal should not end up on the scoreboard seeing as the match is already concluded.

You don't need any prior knowledge of how Quidditch works in order to complete this kata, but if you want to read up on what it is, here's a link: https://en.wikipedia.org/wiki/Quidditch

# Task

You will be given a string with two arguments, the first argument will tell you which teams are playing and the second argument tells you what's happened in the match. Calculate the points and return a string containing the teams final scores, with the team names sorted in the same order as in the first argument.

# Examples:

# Given an input of:

# The expected output would be:

Separate the team names from their respective points with a colon and separate the two teams with a comma.

Good luck!

def quidditch_scoreboard(t,s,x=0,y=0):
    a,b=t.split(' vs ')
    for X in s.split(','):
        k,v =X.strip().split(':')
        if k==a:x+=10if' Quaffle goal'==v else 150if' Caught Snitch'==v else -30
        if k==b:y+=10if' Quaffle goal'==v else 150if' Caught Snitch'==v else -30
        if ' Caught Snitch'==v:break
    return '%s: %d, %s: %d'%(a,x,b,y)


Solve in Python:
Your work is to write a method that takes a value and an index, and returns the value with the bit at given index flipped.

The bits are numbered from the least significant bit (index 1).

Example:
```python
flip_bit(15, 4) == 7 # 15 in binary is 1111, after flipping 4th bit, it becomes 0111, i.e. 7
flip_bit(15, 5) == 31 # 15 in binary is 1111, 5th bit is 0, after flipping, it becomes 11111, i.e., 31
```
Note : index number can be out of number's range : e.g number is 3 (it has 2 bits) and index number is 8(for C# this number is up to 31) -> result will be 131

See more examples in test classes

Good luck!


Solve in Python:
Yup!! The problem name reflects your task; just add a set of numbers. But you may feel yourselves condescended, to write a C/C++ program just to add a set of numbers. Such a problem will simply question your erudition. So, lets add some flavor of ingenuity to it. Addition operation requires cost now, and the cost is the summation of those two to be added. So,to add 1 and 10, you need a cost of 11. If you want to add 1, 2 and 3. There are several ways

```c++
1 + 2 = 3, cost = 3,
3 + 3 = 6, cost = 6,
Total = 9.
```
```c++
1 + 3 = 4, cost = 4,
2 + 4 = 6, cost = 6,
Total = 10.
```
```c++
2 + 3 = 5, cost = 5,
1 + 5 = 6, cost = 6,
Total = 11.
```
I hope you have understood already your mission, to add a set of integers so that the cost is minimal

# Your Task
Given a vector of integers, return the minimum total cost of addition.

import heapq

def add_all(xs):
    heapq.heapify(xs)
    cost = 0
    while len(xs) > 1:
        c = heapq.heappop(xs) + xs[0]
        cost += c
        heapq.heapreplace(xs, c)
    return cost


Solve in Python:
ZCO is approaching, and you want to be well prepared!
There are $N$ topics to cover and the $i^{th}$ topic takes $H_i$ hours to prepare (where $1 \le i \le N$). You have only $M$ days left to prepare, and you want to utilise this time wisely. You know that you can't spend more than $S$ hours in a day preparing, as you get tired after that. You don't want to study more than one topic in a day, and also, don't want to spend more than two days on any topic, as you feel that this is inefficient.
Given these constraints, can you find the maximum number of topics you can prepare, if you choose the topics wisely?

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line of each test case contains three space-separated integers: $N$, $M$ and $S$, denoting the number of topics, the number of days remaining and the number of hours you can study in a day.
- The second line of each test case contains $N$ space-separated integers $H_i$, denoting the number of hours needed to prepare for the $i^{th}$ topic.

-----Output:-----
For each testcase, output in a single line: the maximum number of topics you can prepare.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $1 \leq M \leq 10^5$
- $1 \leq S \leq 16$
- $1 \leq H_i \leq 50$

-----Subtasks-----
- 30 points : Every topic takes the same number of hours to prepare (i.e. all $H_i$ are equal).
- 70 points : Original constraints.

-----Sample Input:-----
2
5 4 10
10 24 30 19 40
5 4 16
7 16 35 10 15

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

-----Explanation:-----
Testcase 1:

You can choose topics $1$ and $4$. Topic $1$ will consume a single day , while topic $4$ will consume two days.  Thus, you'll be able to prepare these two topics within the 4 remaining days. But you can check that you cannot do any better.
Testcase 2:

You can choose topics $1$, $2$, $4$, and $5$. Each of them will consume one day each. Thus you'll be able to cover $4$ topics.

# cook your dish here
for _ in range(int(input())):
 n,m,s=list(map(int,input().split()))
 arr=list(map(int,input().split()))
 arr.sort()
 count=0
 for a in arr:
  if a<=s and m>=1:
   count+=1
   m-=1
  elif a<=2*s and m>=2:
   count+=1
   m-=2
 print(count)


Solve in Python:
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '$\sqrt{}$' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1.

When ZS the Coder is at level k, he can :  Press the ' + ' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes x + k. Press the '$\sqrt{}$' button. Let the number on the screen be x. After pressing this button, the number becomes $\sqrt{x}$. After that, ZS the Coder levels up, so his current level becomes k + 1. This button can only be pressed when x is a perfect square, i.e. x = m^2 for some positive integer m.

Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '$\sqrt{}$' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5.

ZS the Coder needs your help in beating the game — he wants to reach level n + 1. In other words, he needs to press the '$\sqrt{}$' button n times. Help him determine the number of times he should press the ' + ' button before pressing the '$\sqrt{}$' button at each level.

Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level n + 1, but not necessarily a sequence minimizing the number of presses.

-----Input-----

The first and only line of the input contains a single integer n (1 ≤ n ≤ 100 000), denoting that ZS the Coder wants to reach level n + 1.

-----Output-----

Print n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the ' + ' button before pressing the '$\sqrt{}$'...

n = int(input())
print(2)
for i in range(2, n+1):
    print(i*(i+1)*(i+1) - i+1)


Solve in Python:
ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of n × m rooms, and the rooms are arranged in n rows (numbered from the top to the bottom starting from 1) and m columns (numbered from the left to the right starting from 1). The room in the i-th row and j-th column is denoted by (i, j). A player starts in the room (1, 1) and wants to reach the room (n, m).

Each room has four doors (except for ones at the maze border), one on each of its walls, and two adjacent by the wall rooms shares the same door. Some of the doors are locked, which means it is impossible to pass through the door. For example, if the door connecting (i, j) and (i, j + 1) is locked, then we can't go from (i, j) to (i, j + 1). Also, one can only travel between the rooms downwards (from the room (i, j) to the room (i + 1, j)) or rightwards (from the room (i, j) to the room (i, j + 1)) provided the corresponding door is not locked. [Image] This image represents a maze with some doors locked. The colored arrows denotes all the possible paths while a red cross denotes a locked door.

ZS the Coder considers a maze to have difficulty x if there is exactly x ways of travelling from the room (1, 1) to the room (n, m). Two ways are considered different if they differ by the sequence of rooms visited while travelling.

Your task is to create a maze such that its difficulty is exactly equal to T. In addition, ZS the Coder doesn't like large mazes, so the size of the maze and the number of locked doors are limited. Sounds simple enough, right?

-----Input-----

The first and only line of the input contains a single integer T (1 ≤ T ≤ 10^18), the difficulty of the required maze.

-----Output-----

The first line should contain two integers n and m (1 ≤ n, m ≤ 50) — the number of rows and columns of the maze respectively.

The next line should contain a single integer k (0 ≤ k ≤ 300) — the number of locked doors in the maze.

Then, k lines describing locked doors should follow. Each of them should contain...


Solve in Python:
Zaikia has $N$ sticks of distinct positive lengths $A_1,A_2,\dots,A_N$. For no good reason at all, he wants to know if there is a triplet of sticks which when connected end-to-end will form a non-trivial triangle. Here non-trivial refers to a triangle with positive area.
Help Zaikia know if such a triplet exists or not. If such a triplet exists, help him find the lexicographically largest applicable triplet.Input
- The first line contains an integer $N$.
- The second line contains $N$ space-seperated integers $A_1,A_2,\dots,A_N$. Output
- In the first line print YES if a triplet exists or NO if it doesn't.
- If such a triplet exists, then in the second line print the lexicographically largest applicable triplet.Constraints
- $3 \leq N \leq {2}\times{10}^{5}$
- $1 \leq A_i \leq {10}^{9}$ for each valid $i$Sample Input 1
5
4 2 10 3 5
Sample Output 1
YES
5 4 3
Explanation 1
There are three unordered triplets of sticks which can be used to create a triangle:
- $4,2,3$
- $4,2,5$
- $4,3,5$
Arranging them in lexicographically largest fashion
- $4,3,2$
- $5,4,2$
- $5,4,3$
Here $5,4,3$ is the lexicographically largest so it is the triplet which dristiron wantsSample Input 2
5
1 2 4 8 16
Sample Output 2
NO
Explanation 2
There are no triplets of sticks here that can be used to create a triangle.

#from itertools import combinations as c
n=int(input());l=list(map(int,input().split()))
l1=[]
if(n<3):
    print("NO")
else:
    l.sort()
    for i in range(n-2):
        if(l[i]+l[i+1]>l[i+2]):
            l1.append([l[i+2],l[i+1],l[i]])
if(len(l1)!=0):
    print("YES")
    print(*max(l1))
else:
    print("NO")


Solve in Python:
Ziota found a video game called "Monster Invaders".

Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns.

For the sake of simplicity, we only consider two different types of monsters and three different types of guns.

Namely, the two types of monsters are:   a normal monster with $1$ hp.  a boss with $2$ hp.

And the three types of guns are:   Pistol, deals $1$ hp in damage to one monster, $r_1$ reloading time  Laser gun, deals $1$ hp in damage to all the monsters in the current level (including the boss), $r_2$ reloading time  AWP, instantly kills any monster, $r_3$ reloading time

The guns are initially not loaded, and the Ziota can only reload 1 gun at a time.

The levels of the game can be considered as an array $a_1, a_2, \ldots, a_n$, in which the $i$-th stage has $a_i$ normal monsters and 1 boss. Due to the nature of the game, Ziota cannot use the Pistol (the first type of gun) or AWP (the third type of gun) to shoot the boss before killing all of the $a_i$ normal monsters.

If Ziota damages the boss but does not kill it immediately, he is forced to move out of the current level to an arbitrary adjacent level (adjacent levels of level $i$ $(1 < i < n)$ are levels $i - 1$ and $i + 1$, the only adjacent level of level $1$ is level $2$, the only adjacent level of level $n$ is level $n - 1$). Ziota can also choose to move to an adjacent level at any time. Each move between adjacent levels are managed by portals with $d$ teleportation time.

In order not to disrupt the space-time continuum within the game, it is strictly forbidden to reload or shoot monsters during teleportation.

Ziota starts the game at level 1. The objective of the game is rather simple, to kill all the bosses in all the levels. He is curious about the minimum time to finish the game (assuming it takes no time to shoot the monsters with a loaded gun and Ziota has infinite ammo on all the three guns). Please help him find this value.

-----Input-----

The first line of the...

import sys
readline = sys.stdin.readline

INF = 10**18
N, r1, r2, r3, d = map(int, readline().split())
A = list(map(int, readline().split()))

dp1 = [INF]*(N+1)
dp2 = [INF]*(N+1)
dp1[0] = -d
dp2 = -d

mj = INF
rr = r1+r2

C = [0]*(N+1)
for i in range(N):
    a = A[i]
    C[i+1] = min(rr, (a+2)*r1)
CC = C[:]
for i in range(1, N+1):
    CC[i] += CC[i-1]
for i in range(1, N+1):
    a = A[i-1]
    dp1[i] = dp2 + d + C[i]
    dp2 = min(dp2+d+r1*a+r3, CC[i] + 3*d*i + mj)
    mj = min(mj, dp1[i]-3*i*d-CC[i])

ans = min(dp2, 2*d + dp1[-1])
ans = min(ans, dp1[N-1] + 3*d + C[N])
zz = min(r1*A[-1]+r3, 2*d+min(rr, (A[-1]+2)*r1))

for i in range(1, N):
    ans = min(ans, dp1[i] + 2*(N-i)*d + zz + CC[N-1] - CC[i])

print(ans)


Solve in Python:
Zombies zombies everywhere!!
In a parallel world of zombies, there are N zombies. There are infinite number of unused cars, each of same model only differentiated by the their colors. The cars are of K colors.

A zombie parent can give birth to any number of zombie-children (possibly zero), i.e. each zombie will have its parent except the head zombie which was born in the winters by combination of ice and fire.

Now, zombies are having great difficulties to commute to their offices without cars, so they decided to use the cars available. Every zombie will need only one car. Head zombie called a meeting regarding this, in which he will allow each zombie to select a car for him.

Out of all the cars, the head zombie chose one of cars for him. Now, he called his children to choose the cars for them. After that they called their children and so on till each of the zombie had a car. Head zombie knew that it won't be a good idea to allow children to have cars of same color as that of parent, as they might mistakenly use that. So, he enforced this rule during the selection of cars.

Professor James Moriarty is a criminal mastermind and has trapped Watson again in the zombie world. Sherlock somehow manages to go there and met the head zombie. Head zombie told Sherlock that they will let Watson free if and only if Sherlock manages to tell him the maximum number of ways in which the cars can be selected by N Zombies among all possible hierarchies. A hierarchy represents parent-child relationships among the N zombies. Since the answer may be large, output the answer modulo 109 + 7. Sherlock can not compute big numbers, so he confides you to solve this for him.

-----Input-----
The first line consists of a single integer T, the number of test-cases.

Each test case consists of two space-separated integers N and K, denoting number of zombies and the possible number of colors of the cars respectively.

-----Output-----
For each test-case, output a single line denoting the answer of the problem.

-----Constraints-----
- 1...

# your code goes here
t = eval(input())
for i in range(0,t):
 a,b=list(map(int,input().split()))
 if(b==1):
  print(0)
 else:
  ans=b*((b-1)**(a-1))
  ans=ans%1000000007
  print(ans)


Solve in Python:
Zonal Computing Olympiad 2012, 26 Nov 2011

A sequence of opening and closing brackets is well-bracketed if we can pair up each opening bracket with a matching closing bracket in the usual sense.  For instance, the sequences (), (()) and ()(()) are well-bracketed, while (, ()), (()(), and )(  are not well-bracketed.

The nesting depth of a well-bracketed sequence tells us the maximum number of levels of inner matched brackets enclosed within outer matched brackets.  For instance, the nesting depth of () and ()()() is 1, the nesting depth of (()) and ()(()) is 2, the nesting depth of ((())) is 3, and so on.

Given a well-bracketed sequence, we are interested in computing the following:
-  The nesting depth, and the first position where it occurs–this will be the position of the first opening bracket at this nesting depth, where the positions are numbered starting with 1.
-  The maximum number of symbols between any pair of matched  brackets, including both the outer brackets, and the first position where this occurs–that is, the position of the first opening bracket of this segment

For instance, the nesting depth of ()(())()(()())(()()) is 2 and the first position where this occurs is 4.  The opening bracket at position 10 is also at nesting depth 2 but we have to report the first position where this occurs, which is 4.

In this sequence, the maximum number of symbols between a pair of matched bracket is 6, starting at position 9. There is another such sequence of length 6 starting at position 15, but this is not the first such position.

-----Input format-----
The input consists of two lines. The first line is a single integer N, the length of the bracket sequence. Positions in the sequence are numbered 1,2,…,N. The second line is a sequence of N space-separated integers that encode the bracket expression as follows: 1 denotes an opening bracket ( and 2 denotes a closing bracket ).  Nothing other than 1 or 2 appears in the second line of input and the corresponding expression is guaranteed to be...

n=int(input())
a=list(map(int,input("").strip().split()))[:n]
s=list()
li=list()
k=0;
pos=0;
sik=list()
for l in range(len(a)):
    if a[l]==1:
        li.append('(')
        s.append('(')
    elif a[l]==2:
        s.append(')')
        if len(li)!=0:
            if k<len(li):
                pos=l;
                k=len(li)
            del li[len(li)-1]
        if len(li)==0:
            sik.append(s);
            s=list()
le=0;
for i in sik:
    if le<len(i):
        le=len(i);
se=0;
for i in sik:
    if le==len(i):
        break;
    se+=len(i);
print(k,pos,le,se+1)


Solve in Python:
Zonal Computing Olympiad 2012, 26 Nov 2011

It's dinner time in Castle Camelot, and the fearsome Knights of the Round Table are clamouring for dessert. You, the chef, are in a soup.  There are N knights, including King Arthur, each with a different preference for dessert, but you cannot afford to make desserts for all of them.

You are given the cost of manufacturing each Knight's preferred dessert–since it is a round table, the list starts with the cost of King Arthur's dessert, and goes counter-clockwise.

You decide to pick the cheapest desserts to make, such that for every pair of adjacent Knights, at least one gets his dessert. This will ensure that the Knights do not protest.
A strange feature of the Knights is that they will not complain about not getting dessert unless they get support from both their neighbours.  So, you decide to pick the cheapest desserts to make, such that for every pair of adjacent Knights, at least one gets his dessert.

What is the minimum cost of tonight's dinner, given this condition?

For instance, suppose there are 5 Knights and their desserts cost 1, 2, 1, 2 and 2.  In this case, the minimum cost is 4, which you can achieve by feeding the first, third and fourth (or fifth) Knights.

-----Input format-----
There are 2 lines of input.  The first line contains a single integer N, the number of seats at the table. The next line contains N space separated integers, each being the cost of the dessert of a Knight, listed in counterclockwise order around the table, starting with King Arthur.

-----Output format-----
The output should be a single line containing a single integer, the minimum possible cost for you, the chef.

-----Testdata-----
Each Knight's dessert costs strictly more than 0 and strictly less than 1000.  You may assume that 1 ≤ N ≤ 106.  In 30% of the test cases, 1 ≤ N ≤ 103.

- Subtask 1 (30 marks)
- Subtask 2 (70 marks)

-----Sample Input-----
5
1 2 1 2 2

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

# cook your dish here
def fun(arr,n):
    cost = [0]*n
    cost[n-1] = arr[n-1]
    if(n>=2):
        cost[n-2] = arr[n-2]
        for i in range(n-3,-1,-1):
            cost[i] = min(cost[i+1],cost[i+2]) + arr[i]
    return cost[0]

n = int(input())
a = list(map(int,input().split()))
b = list(reversed(a))

print(min(fun(a,n),fun(b,n)))


Solve in Python:
Zonal Computing Olympiad 2012, 26 Nov 2011

The year is 2102 and today is the day of ZCO. This year there are N contests and the starting and ending times of each contest is known to you. You have to participate in exactly one of these contests. Different contests may overlap. The duration of different contests might be different.

There is only one examination centre. There is a wormhole V that transports you from your house to the examination centre and another wormhole W that transports you from the examination centre back to your house. Obviously, transportation through a wormhole does not take any time; it is instantaneous. But the wormholes can be used at only certain fixed times, and these are known to you.

So, you use a V wormhole to reach the exam centre, possibly wait for some time before the next contest begins, take part in the contest, possibly wait for some more time and then use a W wormhole to return back home. If you leave through a V wormhole at time t1 and come back through a W wormhole at time t2, then the total time you have spent is (t2 - t1 + 1). Your aim is to spend as little time as possible overall while ensuring
that you take part in one of the contests.

You can reach the centre exactly at the starting time of the contest, if possible. And you can leave the examination centre the very second the contest ends, if possible. You can assume that you will always be able to attend at least one contest–that is, there will always be a contest such that there is a V wormhole before it and a W wormhole after it.

For instance, suppose there are 3 contests with (start,end) times (15,21), (5,10), and (7,25), respectively.  Suppose the V wormhole is available at times 4, 14, 25, 2 and the W wormhole is available at times 13 and 21.  In this case, you can leave by the V wormhole at time 14, take part in the contest from time 15 to 21, and then use the W wormhole at time 21 to get back home.  Therefore the time you have spent is (21 - 14 + 1) = 8. You can check that you cannot do better than...

import bisect
def wormholes(tlist,vlist,wlist):
 sumlist=[]
 for i in range(len(tlist)):
  if tlist[i][0] not in vlist:
   x=bisect.bisect_left(vlist,tlist[i][0])
   x=x-1
   if x<0:
    continue
  else:
   x=vlist.index(tlist[i][0])
  if tlist[i][1] not in wlist:
   y=bisect.bisect_right(wlist,tlist[i][1])
   if y>=len(wlist):
    continue
  else:
   y=wlist.index(tlist[i][1])
  sumlist.append(wlist[y]-vlist[x]+1)
 return min(sumlist)
n,x,y=input().split()
n,x,y=int(n),int(x),int(y)
timelist=[]
for i in range(n):
 s,e=input().split()
 s,e=int(s),int(e)
 timelist.append([s,e])
v=list(map(int,input().strip().split()))
w=list(map(int,input().strip().split()))
v.sort()
w.sort()
print(wormholes(timelist,v,w))


Solve in Python:
Zonal Computing Olympiad 2012, 26 Nov 2011

We consider sequences of opening and closing brackets with two types of brackets, () and [].  A bracket sequence is well-bracketed if we can pair up each opening bracket with a matching closing bracket in the usual sense.  For instance, the sequences (), [] ([]) and []([]) are well-bracketed, while (, ()], (], )( and [(]) are not well-bracketed.  In the last case, each opening bracket has a matching closing bracket and vice versa, but the intervals spanned by the different types of brackets intersect each other instead of being contained one within the other.

The alternating depth of a well-bracketed sequence tells us the maximum number of times we switch between the two types of brackets when we have inner matched brackets enclosed within outer matched brackets.  For instance, the alternating depth of (), [[[]]] and ()[][] is 1, the alternating depth of [()] and ()([]) is 2, the alternating depth of ([()]) and [()][(([]))] is 3, and so on.

Given a well-bracketed sequence, we are interested in computing three quantities.
- The alternating depth of the sequence.
- The maximum number of symbols between any pair of matched brackets of the type ( and ), including both the outer brackets.
- The maximum number of symbols between any pair of matched brackets of the type [ and ], including both the outer brackets.

For instance, the alternating depth of (([]))[[[()]]] is 2, the maximum number of symbols between a matched pair () is 6 and the maximum number of symbols between a matched pair [] is 8.

-----Input format-----
The input consists of two lines.  The first line is a single integer N, the length of the bracket sequence. Positions in the sequence are numbered 1,2,…,N. The second line is a sequence of N space-separated integers that encode the bracket expression as follows: 1 denotes an opening bracket (, 2 denotes a closing bracket ), 3 denotes an opening bracket [ and 4 denotes a closing bracket ].  Nothing other than 1, 2, 3 or 4 appears in the second line of...

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

n = inp()
x = ip()
brac,ind = [],[]
dt = {2:0,4:0}
for i in range(n):
    if x[i] in [1,3]:
        brac.append(x[i])
        ind.append(i)
        continue
    dt[x[i]] = max(dt[x[i]],i-ind[-1]+1)
    ind.pop()
    brac.pop()
alt = 0
brac,depth = [],[]
for i in range(n):
    if (x[i] == 1 or x[i] == 3) and brac == []:
        brac.append(x[i])
        depth.append(1)
        alt = max(alt,depth[-1])
    elif x[i]*brac[-1] == 3:
        brac.append(x[i])
        depth.append(depth[-1]+1)
        alt = max(alt,depth[-1])
    elif x[i]==1 or x[i]==3:
        brac.append(x[i])
        depth.append(depth[-1])
        alt = max(alt,depth[-1])
    elif x[i]==2 or x[i]==4:
        brac.pop()
        depth.pop()

print(alt,dt[2],dt[4])


Solve in Python:
Zonal Computing Olympiad 2013, 10 Nov 2012

Little Red Riding Hood is carrying a basket with berries through the forest to her grandmother's house.  The forest is arranged in the form of a square N × N grid of cells.  The top left corner cell, where Little Red Riding Hood starts her journey, is numbered (1,1) and the bottom right corner cell, where her grandmother lives, is numbered (N,N).  In each step, she can move either one position right or one position down.

The forest is full of dangerous wolves and she is looking for a safe path to reach her destination.  Little Red Riding Hood's fairy godmother has placed some special anti-wolf magical charms in some of the cells in the grid.  Each charm has a strength.  If the charm in cell (i,j) has strength k then its zone of influence is all the cells within k steps of (i,j); that is, all cells (i',j') such that |i - i'| + |j - j'| ≤ k.  A cell within the zone of influence of a charm is safe from wolves.  A safe path from (1,1) to (N,N) is one in which every cell along the path is safe.

Little Red Riding Hood is carrying a basket with berries. In each cell, she drops some berries while pushing her way through the thick forest.  However, sometimes she is also able to pick up fresh berries.  Each cell is labelled with an integer that indicates the net change in the number of berries in her basket on passing through the cell; that is, the number of berries she picks up in that cell minus the number of berries she drops.  You can assume that there are enough berries in her basket to start with so that the basket never becomes empty.

Little Red Riding Hood knows the positions and strengths of all the magic charms and is looking for a safe path along which the number of berries she has in the basket when she reaches her grandmother's house is maximized.

As an example consider the following grid:

3  3  2  4  3
2  1 -1 -2  2
-1  2  4  3 -3
-2  2  3  2  1
3 -1  2 -1  2

Suppose there are 3 magic charms, at position (1,2) with strength 2, at position (4,5)...

n , m = map(int, input().split())
grid = []
grid_charm = []
cost = []
for i in range(n):
	hehe = [0 for i in range(n)]
	maggi = [0 for i in range(n)]
	row = list(map(int , input().split()))
	grid.append(row)
	grid_charm.append(hehe)
	cost.append(maggi)

for i in range(m):
	x , y , k = map(int, input().split())
	x , y = x-1 , y-1
	for j in range(k+1):
		for z in range(k +1):
			if not j + z  <= k:
				break
			alpha , beta , gamma, lol = x-j , y-z , x + j , y + z
			if alpha >=0:
				if beta >=0:
					grid_charm[alpha][beta] = 1
				if lol < n:
					grid_charm[alpha][lol] = 1
			if beta >= 0:
				if gamma < n:
					grid_charm[gamma][beta] = 1
			if gamma < n:
				if lol < n:
					grid_charm[gamma][lol] = 1

# for i in grid_charm:
# 	print(*i)
cost[0][0] = grid[0][0]
for i in range(n):
	for j in range(n):
		lol = -999999999999
		if i > 0:
			if grid_charm[i-1][j] == 1:
				lol = grid[i][j] + cost[i-1][j]

		if j > 0:
			if grid_charm[i][j-1] == 1:
				lol = max(lol , grid[i][j] + cost[i][j-1])

		if grid_charm[i][j] == 0:
			cost[i][j] = -999999999999
		else:
			if not(i == 0 and j ==0):
				cost[i][j] = lol

# for i in cost:
# 	print(*i)
if cost[n-1][n-1] == -999999999999:
	print('NO')
else:
	print('YES')
	print(cost[n-1][n-1])


Solve in Python:
Zonal Computing Olympiad 2013, 10 Nov 2012
N teams participate in a league cricket tournament on Mars, where each pair of distinct teams plays each other exactly once. Thus, there are a total of (N × (N-1))/2 matches. An expert has assigned a strength to each team, a positive integer. Strangely, the Martian crowds love one-sided matches and the advertising revenue earned from a match is the absolute value of the difference between the strengths of the two matches. Given the strengths of the N teams, find the total advertising revenue earned from all the matches.

For example, suppose N is 4 and the team strengths for teams 1, 2, 3, and 4 are 3, 10, 3, and 5 respectively. Then the advertising revenues from the 6 matches are as follows:

Match Team A Team B Ad revenue 1 1 2 7  2 1 3 0  3 1 4 2  4 2 3 7  5 2 4 5  6 3 4 2

Thus the total advertising revenue is 23.

-----Input format-----
Line 1 : A single integer, N.
Line 2 : N space-separated integers, the strengths of the N teams.

-----Output format-----
A single integer, the total advertising revenue from the tournament.

-----Sample input-----
4
3 10 3 5

-----Sample output-----
23

-----Test data-----
In all subtasks, the strength of each team is an integer between 1 and 1,000 inclusive.
- Subtask 1 (30 marks) : 2 ≤ N ≤ 1,000.
- Subtask 2 (70 marks) : 2 ≤ N ≤ 200,000.

-----Live evaluation data-----
- Subtask 1: Testcases 0,1,2.
- Subtask 2: Testcases 3,4,5.

-----Note-----
The answer might not fit in a variable of type int. We recommend that type long long be used for computing all advertising revenues. If you use printf and scanf, you can use %lld for long long.

n = int(input())
l = list(map(int,input().split()))
l.sort()
c,sum = 0,0
for i in l:
    if c < len(l):
        c+=1
        for x in l[c:]:
            sum = sum + abs(i-x)

print(sum)


Solve in Python:
Zonal Computing Olympiad 2014, 30 Nov 2013

In ICO School, all students have to participate regularly in SUPW.  There is a different SUPW activity each day, and each activity has its own duration.  The SUPW schedule for the next term has been announced, including information about the number of minutes taken by each activity.

Nikhil has been designated SUPW coordinator.  His task is to assign SUPW duties to students, including himself.  The school's rules say that no student can go three days in a row without any SUPW duty.

Nikhil wants to find an assignment of SUPW duty for himself that minimizes the number of minutes he spends overall on SUPW.

-----Input format-----
Line 1: A single integer N, the number of days in the future for which SUPW data is available.
Line 2: N non-negative integers, where the integer in position i represents the number of minutes required for SUPW work on day i.

-----Output format-----
The output consists of a single non-negative integer, the minimum number of minutes that Nikhil needs to spend on SUPW duties this term

-----Sample Input 1-----
10
3 2 1 1 2 3 1 3 2 1

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

(Explanation: 1+1+1+1)

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

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

(Explanation: 2+2+1)

-----Test data-----
There is only one subtask worth 100 marks.  In all inputs:

• 1 ≤ N ≤ 2×105
• The number of minutes of SUPW each day is between 0 and
104, inclusive.

-----Live evaluation data-----
There are 12 test inputs on the server during the exam.

# cook your dish here
n=int(input())
arr=[int(x) for x in input().split()]
if n<3:
    ans=min(arr)
    print(ans)
else:
    dp=[None for x in range(n)]
    dp[0]=arr[0];dp[1]=arr[1];dp[2]=arr[2]
    for i in range(3,n):
        dp[i]=min(dp[i-1],dp[i-2],dp[i-3])+arr[i]
    print(min(dp[-1],dp[-2],dp[-3]))


Solve in Python:
Zonal Computing Olympiad 2014, 30 Nov 2013

In IPL 2025, the amount that each player is paid varies from match to match.  The match fee depends on the quality of opposition, the venue etc.

The match fees for each match in the new season have been announced in advance.  Each team has to enforce a mandatory rotation policy so that no player ever plays three matches in a row during the season.

Nikhil is the captain and chooses the team for each match. He wants to allocate a playing schedule for himself to maximize his earnings through match fees during the season.

-----Input format-----
Line 1: A single integer N, the number of games in the IPL season.
Line 2: N non-negative integers, where the integer in
position i represents the fee for match i.

-----Output format-----
The output consists of a single non-negative integer, the
maximum amount of money that Nikhil can earn during this IPL
season.

-----Sample Input 1-----
5
10 3 5 7 3

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

(Explanation: 10+3+7+3)

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

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

(Explanation: 3+3+3+5+3)

-----Test data-----
There is only one subtask worth 100 marks.  In all inputs:

• 1 ≤ N ≤ 2×105
• The fee for each match is between 0 and 104, inclusive.

-----Live evaluation data-----
There are 12 test inputs on the server during the exam.

# cook your dish here
N = int(input())
matches = list(map(int,input().split()))
games = matches[:3]
for i in range(3,N):
    games.append(min(games[i-1],games[i-2],games[i-3]) + matches[i])
print(sum(matches) - min(games[-1],games[-2],games[-3]))


Solve in Python:
Zonal Computing Olympiad 2015, 29 Nov 2014

We say that two integers x and y have a variation of at least K, if |x − y| ≥ K (the absolute value of their difference is at least K). Given a sequence of N integers a1,a2,...,aN and K, the total variation count is the number of pairs of elements in the sequence with variation at least K, i.e. it is the size of the set of pairs

{(i,j)|1≤i<j≤N and|ai−aj|≥K}

For example if K = 1 and the sequence is 3,2,4 the answer is 3. If K = 1 and the sequence is 3, 1, 3 then the answer is 2.

Your task is to write a program that takes a sequence and the value K as input and computes the total variation count.

-----Input format-----
The first line contains two positive integers N and K, separated by a space.

This is followed by a line containing N integers separated by space giving the values
of the sequence.

-----Output format-----
A single integer in a single line giving the total variation count.

-----Test data-----
You may assume that all integers in the input are in the range 0 to 10^8 inclusive.

Subtask 1 (40 marks) : 1 ≤ N ≤ 4000, 1 ≤ K ≤ 10^8
Subtask 2 (60 marks) : 1 ≤ N ≤ 65000, 1 ≤ K ≤ 10^8

-----Sample Input-----
3 1
3 1 3

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

import sys
n,k=list(map(int,input().strip().split()))
a=list(map(int,sys.stdin.readline().strip().split()))
s=0
for i in range(len(a)):
    for j in range(i+1,len(a)):
        if abs(a[i]-a[j])>=k:
            s+=1

print(s)


Solve in Python:
Zonk is addictive dice game. In each round player rolls 6 dice. Then (s)he composes combinations from them. Each combination gives certain points.

Then player can take one or more dice combinations to his hand and re-roll remaining dice or save his score. Dice in player's hand won't be taken into account in subsequent rolls.

If no combinations can be composed - situation is called "zonk". Player thrown zonk loses all points in this round and next player moves. So it's player decision when to reroll and when to stop and save his score.

Your task is simple - just evaluate current roll and return maximum number of points can be scored from it. If no combinations can be made - function must return string ``"Zonk"`` (without quotes).

There are different variations of Zonk. In this kata, we will use most common table of combinations:

CombinationExample rollPoints
Straight (1,2,3,4,5 and 6)6 3 1 2 5 41000 points
Three pairs of any dice2 2 4 4 1 1750 points
Three of 11 4 1 11000 points
Three of 22 3 4 2 2200 points
Three of 33 4 3 6 3 2300 points
Three of 44 4 4400 points
Three of 52 5 5 5 4500 points
Three of 66 6 2 6600 points
Four of a kind1 1 1 1 4 62 × Three-of-a-kind score (in example, 2000 pts)
Five of a kind5 5 5 4 5 53 × Three-of-a-kind score (in example, 1500 pts)
Six of a kind4 4 4 4 4 44 × Three-of-a-kind score (in example, 1600 pts)
Every 14 3 1 2 2100 points
Every 55 2 650 points

Each die cannot be used in multiple combinations the same time, so three pairs of 2, 3 and 5 will worth you only ``750`` points (for three pairs), not 850 (for three pairs and two fives). But you can select multiple combinations, ``2 2 2 1 6`` will worth you ``300`` points (200 for three-of-kind '2' plus 100 for single '1' die)

Examples:
```python
  get_score([1,2,3]) # returns 100 = points from one 1
  get_score([3,4,1,1,5]) # returns 250 = points from two 1 and one 5
  get_score([2,3,2,3,3,2]) # returns 500 = three of 2 + three of 3
  get_score([1,1,1,1,1,5]) # returns 3050 = five 1 + one 5
  get_score([2,3,4,3,6,6])...

def get_score(dice):
    freq = {e:dice.count(e) for e in set(dice)}
    score = 0

    if all(e in freq for e in range(1,7)):
        return 1000

    if len(freq) is 3 and all(e is 2 for e in freq.values()):
        return 750

    for d in range(1, 7):
        if d in freq and freq[d] is 6:
            return d * 4000 if d is 1 else d * 400
        elif d in freq and freq[d] is 5:
            score += d * 3000 if d is 1 else d * 300
            del freq[d]
        elif d in freq and freq[d] is 4:
            score += d * 2000 if d is 1 else d * 200
            del freq[d]
        elif d in freq and freq[d] is 3:
            score += d * 1000 if d is 1 else d * 100
            del freq[d]

    score += freq[1] * 100 if 1 in freq else 0
    score += freq[5] * 50  if 5 in freq else 0

    return "Zonk" if score is 0 else score


Solve in Python:
Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string $s_1s_2\ldots s_n$ of length $n$. $1$ represents an apple and $0$ represents an orange.

Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguous sequence of apples. Let $f(l,r)$ be the longest contiguous sequence of apples in the substring $s_{l}s_{l+1}\ldots s_{r}$.

Help Zookeeper find $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$, or the sum of $f$ across all substrings.

-----Input-----

The first line contains a single integer $n$ $(1 \leq n \leq 5 \cdot 10^5)$.

 The next line contains a binary string $s$ of length $n$ $(s_i \in \{0,1\})$

-----Output-----

Print a single integer: $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$.

-----Examples-----
Input
4
0110

Output
12

Input
7
1101001

Output
30

Input
12
011100011100

Output
156

-----Note-----

In the first test, there are ten substrings. The list of them (we let $[l,r]$ be the substring $s_l s_{l+1} \ldots s_r$):  $[1,1]$: 0  $[1,2]$: 01  $[1,3]$: 011  $[1,4]$: 0110  $[2,2]$: 1  $[2,3]$: 11  $[2,4]$: 110  $[3,3]$: 1  $[3,4]$: 10  $[4,4]$: 0

The lengths of the longest contiguous sequence of ones in each of these ten substrings are $0,1,2,2,1,2,2,1,1,0$ respectively. Hence, the answer is $0+1+2+2+1+2+2+1+1+0 = 12$.

n = int(input())
a = list(map(int, input()))

acc = 0
back = 0
top = 0
cur = 0
s = []

for i,x in enumerate(a):
	if x == 0:
		cur = 0
	else:
		if cur > 0:
			s.pop()
		cur += 1
		if cur >= top:
			top = cur
			back = (cur + 1) * (cur) // 2 + (i - cur + 1) * cur
			s = [(cur, i)]
		else:
			back += i - (s[-1][1] - cur + 1)
			if cur >= s[-1][0]:
				s.pop()
			s += [(cur, i)]
	acc += back
	#print(i,x,acc, back, top, cur)
	#print(s)

print(acc)