Solve in Python:
Write
```python
function repeating_fractions(numerator, denominator)
```
that given two numbers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part has repeated digits, replace those digits with a single digit in parentheses.

For example:
```python
repeating_fractions(1,1) === '1'
repeating_fractions(1,3) === '0.(3)'
repeating_fractions(2,888) === '0.(0)(2)5(2)5(2)5(2)5(2)5(2)'
```

def repeating_fractions(n,d):
    a=str(n/d).split('.')
    pos,out, m=0,'',False
    while pos<len(a[1])-1:
        if a[1][pos]==a[1][pos+1]:
            m=True
        else:
            out+=m*'('+a[1][pos]+m*')'
            m=False
        pos+=1
    out+=m*'('+a[1][-1]+m*')'
    return a[0]+'.'+out


Solve in Python:
Write
```python
remove(text, what)
```
that takes in a string ```str```(```text``` in Python) and an object/hash/dict/Dictionary ```what``` and returns a string with the chars removed in ```what```.
For example:
```python
remove('this is a string',{'t':1, 'i':2}) == 'hs s a string'
# remove from 'this is a string' the first 1 't' and the first 2 i's.
remove('hello world',{'x':5, 'i':2}) == 'hello world'
# there are no x's or i's, so nothing gets removed
remove('apples and bananas',{'a':50, 'n':1}) == 'pples d bnns'
# we don't have 50 a's, so just remove it till we hit end of string.
```

def remove(text, what):
    for char, count in list(what.items()):
        text = "".join(text.split(char, count))
    return text


Solve in Python:
Write
```python
smaller(arr)
```
that given an array ```arr```, you have to return the amount of numbers that are smaller than ```arr[i]``` to the right.

For example:
```python
smaller([5, 4, 3, 2, 1]) == [4, 3, 2, 1, 0]
smaller([1, 2, 0]) == [1, 1, 0]
```
``` haskell
smaller [5,4,3,2,1]  `shouldBe` [4,3,2,1,0]
smaller [1,2,3]      `shouldBe` [0,0,0]
smaller [1, 2, 0]    `shouldBe` [1, 1, 0]
```
If you've completed this one and you feel like testing your performance tuning of this same kata, head over to the much tougher version How many are smaller than me II?

def smaller(nums):
    i = 0; res = []
    while i < len(nums):
        j = i + 1; nb = 0
        while j < len(nums):
            if nums[i] > nums[j]:
                nb += 1
            j += 1
        res.append(nb)
        i += 1
    return res


Solve in Python:
Write
```python
word_pattern(pattern, string)
```
that given a ```pattern``` and a string ```str```, find if ```str``` follows the same sequence as ```pattern```.

For example:
```python
word_pattern('abab', 'truck car truck car') == True
word_pattern('aaaa', 'dog dog dog dog') == True
word_pattern('abab', 'apple banana banana apple') == False
word_pattern('aaaa', 'cat cat dog cat') == False
```

def word_pattern(pattern, string):
    words = string.split(" ")
    return len(pattern) == len(words) and len(set(zip(pattern, words))) == len(set(pattern)) == len(set(words))


Solve in Python:
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order.

Example Input:
`['b', 'ba', 'ab', 'bb', 'c']`

Expected Output:
`['ab', 'b', 'ba', 'bb', 'c']`

* The argument for your function will be a generator that will return a new word for each call of next()
* Your function will return its own generator of the same words, except your generator will return the words in lexographic order
* All words in the list are unique
* All words will be comprised of lower case letters only (a-z)
* All words will be between 1 and 8 characters long
* There will be hundreds of thousands of words to sort
* You may not use Python's sorted built-in function
* You may not use Python's list.sort method
* An empty list of words should result in an empty list.
* `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it

from heapq import heapify, heappop

def sort(words):
    words = list(words)
    heapify(words)
    while words:
        yield heappop(words)


Solve in Python:
Write a class Random that does the following:

1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```

2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```

3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```

Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!

import hashlib

class Random():
    HASH_MAX = (1 << 32 * 4) - 1

    def __init__(self, seed):
        self.seed = seed
    def random(self):
        x = int(hashlib.md5(str(self.seed).encode()).hexdigest(), 16)
        self.seed += 1
        return x / self.HASH_MAX
    def randint(self, start, end):
        return start + int(self.random() * (end+1-start))


Solve in Python:
Write a class StockSpanner which collects daily price quotes for some stock, and returns the span of that stock's price for the current day.
The span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backwards) for which the price of the stock was less than or equal to today's price.
For example, if the price of a stock over the next 7 days were [100, 80, 60, 70, 60, 75, 85], then the stock spans would be [1, 1, 1, 2, 1, 4, 6].

Example 1:
Input: ["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]]
Output: [null,1,1,1,2,1,4,6]
Explanation:
First, S = StockSpanner() is initialized.  Then:
S.next(100) is called and returns 1,
S.next(80) is called and returns 1,
S.next(60) is called and returns 1,
S.next(70) is called and returns 2,
S.next(60) is called and returns 1,
S.next(75) is called and returns 4,
S.next(85) is called and returns 6.

Note that (for example) S.next(75) returned 4, because the last 4 prices
(including today's price of 75) were less than or equal to today's price.

Note:

Calls to StockSpanner.next(int price) will have 1 <= price <= 10^5.
There will be at most 10000 calls to StockSpanner.next per test case.
There will be at most 150000 calls to StockSpanner.next across all test cases.
The total time limit for this problem has been reduced by 75% for C++, and 50% for all other languages.

class StockSpanner:

    def __init__(self):
        self.s = list()

    def next(self, price: int) -> int:
        weight = 1
        stack = self.s
        while(stack and stack[-1][0] <= price):
            weight += stack[-1][-1]
            stack.pop()
        stack.append((price, weight))
        return weight

# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)


Solve in Python:
Write a class called User that is used to calculate the amount that a user will progress through a ranking system similar to the one Codewars uses.

##### Business Rules:

* A user starts at rank -8 and can progress all the way to 8.
* There is no 0 (zero) rank. The next rank after -1 is 1.
* Users will complete activities. These activities also have ranks.
* Each time the user completes a ranked activity the users rank progress is updated based off of the activity's rank
* The progress earned from the completed activity is relative to what the user's current rank is compared to the rank of the activity
* A user's rank progress starts off at zero, each time the progress reaches 100 the user's rank is upgraded to the next level
* Any remaining progress earned while in the previous rank will be applied towards the next rank's progress (we don't throw any progress away). The exception is if there is no other rank left to progress towards (Once you reach rank 8 there is no more progression).
* A user cannot progress beyond rank 8.
* The only acceptable range of rank values is -8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8. Any other value should raise an error.

The progress is scored like so:

* Completing an activity that is ranked the same as that of the user's will be worth 3 points
* Completing an activity that is ranked one ranking lower than the user's will be worth 1 point
* Any activities completed that are ranking 2 levels or more lower than the user's ranking will be ignored
* Completing an activity ranked higher than the current user's rank will accelerate the rank progression. The greater the difference between rankings the more the progression will be increased. The formula is `10 * d * d` where `d` equals the difference in ranking between the activity and the user.

##### Logic Examples:
* If a user ranked -8 completes an activity ranked -7 they will receive 10 progress
* If a user ranked -8 completes an activity ranked -6 they will receive 40 progress
* If a user ranked -8 completes an activity...

class User():
    '''Creates a User class for a codewars style website'''

    def __init__(self):
        self.ranks = [-8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8]    #15
        self.progress = 0
        self.level = 0
        self.rank = self.ranks[self.level]

    def inc_progress(self, rank):

        if rank not in self.ranks:
            raise Exception('Invalid rank')

        activityrank = self.ranks.index(rank)
        rank = self.level
        difference = activityrank - rank

        if self.level < 15:

            if difference > 0:
                points = 10 * difference * difference
                self.progress += points

            elif difference == 0: self.progress += 3

            elif difference == -1: self.progress += 1

            if self.progress == 100:
                self.level += 1
                self.rank = self.ranks[self.level]
                self.progress = 0

            while self.progress >= 100:
                self.level += 1
                leftover = self.progress - 100
                self.rank = self.ranks[self.level]

                if self.level < 15:
                    self.progress = leftover

                elif self.level >= 15:
                    self.progress = 0


Solve in Python:
Write a code that receives an array of numbers or strings, goes one by one through it while taking one value out, leaving one value in, taking, leaving, and back again to the beginning until all values are out.
It's like a circle of people who decide that every second person will leave it, until the last person is there. So if the last element of the array is taken, the first element that's still there, will stay.
The code returns a new re-arranged array with the taken values by their order. The first value of the initial array is always taken.

Examples:

def yes_no(a):
    if len(a)<=1: return a
    a.append(a.pop(1))
    return [a.pop(0)] + yes_no(a)


Solve in Python:
Write a comparator for a list of phonetic words for the letters of the [greek alphabet](https://en.wikipedia.org/wiki/Greek_alphabet).

A comparator is:
> *a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument*

*(source: https://docs.python.org/2/library/functions.html#sorted)*

The greek alphabet is preloded for you as `greek_alphabet`:

```python
greek_alphabet = (
    'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
    'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu',
    'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',
    'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')
```

## Examples

```python
greek_comparator('alpha', 'beta')   <  0
greek_comparator('psi', 'psi')      == 0
greek_comparator('upsilon', 'rho')  >  0
```

def greek_comparator(lhs, rhs):
    if lhs == rhs:
        return 0
    a = [greek_alphabet.index(x) for x in [lhs, rhs]]
    if a[0] > a[1]:
        return 1
    else:
        return -1


Solve in Python:
Write a function
```python
alternate_sort(l)
```
that combines the elements of an array by sorting the elements ascending by their **absolute value** and outputs negative and non-negative integers alternatingly (starting with the negative value, if any).

E.g.
```python
alternate_sort([5, -42, 2, -3, -4, 8, -9,]) == [-3, 2, -4, 5, -9, 8, -42]
alternate_sort([5, -42, 2, -3, -4, 8, 9]) == [-3, 2, -4, 5, -42, 8, 9]
alternate_sort([5, 2, -3, -4, 8, -9]) == [-3, 2, -4, 5, -9, 8]
alternate_sort([5, 2, 9, 3, 8, 4]) == [2, 3, 4, 5, 8, 9]
```

def alternate_sort(l):
    xs = sorted(l)
    pos, neg, result = [], [], []
    for x in xs:
        [pos, neg][x < 0].append(x)
    while pos and neg:
        result.extend([neg.pop(), pos.pop(0)])
    return result + neg[::-1] + pos


Solve in Python:
Write a function

```python
vowel_2_index```

that takes in a string and replaces all the vowels [a,e,i,o,u] with their respective positions within that string.
E.g:

```python
vowel_2_index('this is my string') == 'th3s 6s my str15ng'
vowel_2_index('Codewars is the best site in the world') == 'C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld'
vowel_2_index('') == ''
```
 Your function should be case insensitive to the vowels.

VOWELS = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'}

def vowel_2_index(string):
    return ''.join(str(i) if a in VOWELS else a
                   for i, a in enumerate(string, start=1))


Solve in Python:
Write a function

`titleToNumber(title) or title_to_number(title) or titleToNb title ...`

(depending on the language)

that given a column title as it appears in an Excel sheet, returns its corresponding column number. All column titles will be uppercase.

Examples:
```
titleTonumber('A') === 1
titleTonumber('Z') === 26
titleTonumber('AA') === 27
```

title_to_number = lambda a: 0 if a == '' else 1 + ord(a[-1]) - ord('A') + 26 * title_to_number(a[:-1])


Solve in Python:
Write a function
```javascript
tripledouble(num1,num2)
```
```python
triple_double(num1, num2)
```
which takes numbers `num1` and `num2` and returns `1` if there is a straight triple of a number at any place in `num1` and also a straight double of the **same** number in `num2`.

If this isn't the case, return `0`

## Examples

```python
triple_double(451999277, 41177722899) == 1
# num1 has straight triple 999s and num2 has straight double 99s

triple_double(1222345, 12345) == 0
# num1 has straight triple 2s but num2 has only a single 2

triple_double(12345, 12345) == 0

triple_double(666789, 12345667) == 1
```

def triple_double(num1, num2):
    DECIMAL_BASE = 10
    tripples = []
    previous, previous_previous = None, None

    while num1:
        (num1, rem) = divmod(num1, DECIMAL_BASE)
        if rem == previous and previous == previous_previous:
            tripples.append(rem)
        previous_previous = previous
        previous = rem

    while num2:
        (num2, rem) = divmod(num2, DECIMAL_BASE)
        if rem == previous and rem in tripples:
            return 1
        previous = rem
    return 0


Solve in Python:
Write a function ```convert_temp(temp, from_scale, to_scale)``` converting temperature from one scale to another.
Return converted temp value.

Round converted temp value to an integer(!).

Reading: http://en.wikipedia.org/wiki/Conversion_of_units_of_temperature

```
possible scale inputs:
    "C"  for Celsius
    "F"  for Fahrenheit
    "K"  for Kelvin
    "R"  for Rankine
    "De" for Delisle
    "N"  for Newton
    "Re" for Réaumur
    "Ro" for Rømer
```

```temp``` is a number, ```from_scale``` and ```to_scale``` are strings.

```python
convert_temp(   100, "C",  "F") # => 212
convert_temp(    40, "Re", "C") # => 50
convert_temp(    60, "De", "F") # => 140
convert_temp(373.15, "K",  "N") # => 33
convert_temp(   666, "K",  "K") # => 666
```


Solve in Python:
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another.

Example:

```python
unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar']
```

Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.

def unpack(li,s=None):
    if s is None : s = []
    for i in li:
        if type(i) in [list, tuple, set] : unpack(i,s)
        elif type(i) == dict : unpack(sum([[k, l] for k, l in i.items()], []),s)
        else : s.append(i)
    return s


x = lambda n: [[int(i == j or i == n - j - 1) for i in range(n)] for j in range(n)]


Solve in Python:
Write a function `consonantCount`, `consonant_count` or `ConsonantCount` that takes a string of English-language text and returns the number of consonants in the string.

Consonants are all letters used to write English excluding the vowels `a, e, i, o, u`.

def consonant_count(s):
    return sum(x.lower() in 'bcdfghjklmnpqrstvwxyz' for x in s)


Solve in Python:
Write a function `count_vowels` to count the number of vowels in a given string.

### Notes:

- Return `nil` or `None` for non-string inputs.
- Return `0` if the parameter is omitted.

### Examples:

```python
count_vowels("abcdefg") => 2
count_vowels("aAbcdeEfg") => 4

count_vowels(12) => None
```

def count_vowels(s = ''):
    if not isinstance(s, str):
        return None
    return sum(c in "aeiouAEIOU" for c in s)


Solve in Python:
Write a function `generatePairs` that accepts an integer argument `n` and generates an array containing the pairs of integers `[a, b]` that satisfy the following conditions:
```
0 <= a <= b <= n
```

The pairs should be sorted by increasing values of `a` then increasing values of `b`.

For example, `generatePairs(2)` should return
```
[ [0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2] ]
```

def generate_pairs(n):
    return [[i, x] for i in range(n+1) for x in range(n+1) if x >= i]


Solve in Python:
Write a function `getDrinkByProfession`/`get_drink_by_profession()` that receives as input parameter a string, and produces outputs according to the following table:

Input
Output

"Jabroni"
"Patron Tequila"

"School Counselor"
"Anything with Alcohol"

 "Programmer"
 "Hipster Craft Beer"

 "Bike Gang Member"
"Moonshine"

 "Politician"
"Your tax dollars"

 "Rapper"
"Cristal"

 *anything else*
"Beer"

Note: *anything else* is the default case: if the input to the function is not any of the values in the table, then the return value should be "Beer."

Make sure you cover the cases where certain words do not show up with correct capitalization. For example, getDrinkByProfession("pOLitiCIaN") should still return "Your tax dollars".

def get_drink_by_profession(param):
    if param.lower() in ["jabroni"]:
        return "Patron Tequila";
    elif param.lower() in ["school counselor"]:
        return "Anything with Alcohol";
    elif param.lower() in ["programmer"]:
        return "Hipster Craft Beer";
    elif param.lower() in ["bike gang member"]:
        return "Moonshine";
    elif param.lower() in ["rapper"]:
        return "Cristal";
    elif param.lower() in ["politician"]:
        return "Your tax dollars";
    else:
        return "Beer";


Solve in Python:
Write a function `insertDash(num)`/`InsertDash(int num)` that will insert dashes ('-') between each two odd numbers in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number.

Note that the number will always be non-negative (>= 0).

def insert_dash(num):
    num = str(num)
    ans = ""
    for i in range(len(num) - 1):
        ans += num[i]
        if int(num[i]) % 2 == 1 and int(num[i + 1]) % 2 == 1:
            ans += '-'
    ans += num[-1]
    return ans


Solve in Python:
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure)

(the dedicated builtin(s) functionalities are deactivated)

def reverse(lst):
    empty_list = list()
    for i in lst:
        empty_list = [i] + empty_list
    return empty_list


Solve in Python:
Write a function `sumTimesTables` which sums the result of the sums of the elements specified in `tables` multiplied by all the numbers in between `min` and `max` including themselves.

For example, for `sumTimesTables([2,5],1,3)` the result should be the same as
```
2*1 + 2*2 + 2*3 +
5*1 + 5*2 + 5*3
```
i.e. the table of two from 1 to 3 plus the table of five from 1 to 3

All the numbers are integers but you must take in account:

* `tables` could be empty.
* `min` could be negative.
* `max` could be really big.

def sum_times_tables(table, a, b):
    return sum(x * y for x in table for y in range(a, b + 1))


Solve in Python:
Write a function `take_umbrella()` that takes two arguments: a string representing the current weather and a float representing the chance of rain today.

Your function should return `True` or `False` based on the following criteria.

* You should take an umbrella if it's currently raining or if it's cloudy and the chance of rain is over `0.20`.
* You shouldn't take an umbrella if it's sunny unless it's more likely to rain than not.

The options for the current weather are `sunny`, `cloudy`, and `rainy`.

For example, `take_umbrella('sunny', 0.40)` should return `False`.

As an additional challenge, consider solving this kata using only logical operaters and not using any `if` statements.

def take_umbrella(weather, rain_chance):
        return((weather == "rainy")
        or ((rain_chance > 0.2) and (weather == "cloudy"))
        or ((rain_chance > 0.5) and (weather == "sunny")))


Solve in Python:
Write a function called "filterEvenLengthWords".

Given an array of strings, "filterEvenLengthWords" returns an array containing only the elements of the given array whose length is an even number.

var output = filterEvenLengthWords(['word', 'words', 'word', 'words']);

console.log(output); // --> ['word', 'word']

def filter_even_length_words(words):
    arr = []
    for el in words:
        if len(el) % 2 == 0:
            arr.append(el)
    return arr


Solve in Python:
Write a function called `LCS` that accepts two sequences and returns the longest subsequence common to the passed in sequences.

### Subsequence
A subsequence is different from a substring. The terms of a subsequence need not be consecutive terms of the original sequence.

### Example subsequence
Subsequences of `"abc"` = `"a"`, `"b"`, `"c"`, `"ab"`, `"ac"`, `"bc"` and `"abc"`.

### LCS examples
```python
lcs( "abcdef" , "abc" ) => returns "abc"
lcs( "abcdef" , "acf" ) => returns "acf"
lcs( "132535365" , "123456789" ) => returns "12356"
```

### Notes
* Both arguments will be strings
* Return value must be a string
* Return an empty string if there exists no common subsequence
* Both arguments will have one or more characters (in JavaScript)
* All tests will only have a single longest common subsequence. Don't worry about cases such as `LCS( "1234", "3412" )`, which would have two possible longest common subsequences: `"12"` and `"34"`.

Note that the Haskell variant will use randomized testing, but any longest common subsequence will be valid.

Note that the OCaml variant is using generic lists instead of strings, and will also have randomized tests (any longest common subsequence will be valid).

### Tips

Wikipedia has an explanation of the two properties that can be used to solve the problem:

- [First property](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#First_property)
- [Second property](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Second_property)

def lcs(x, y):
    if not x or not y: return ""
    if x[0] == y[0]: return x[0] + lcs(x[1:], y[1:])

    return max(lcs(x[1:], y), lcs(x, y[1:]), key=len)


Solve in Python:
Write a function called `sumIntervals`/`sum_intervals()` that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once.

### Intervals

Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: `[1, 5]` is an interval from 1 to 5. The length of this interval is 4.

### Overlapping Intervals

List containing overlapping intervals:

```
[
   [1,4],
   [7, 10],
   [3, 5]
]
```

The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4.

### Examples:

```C#
// empty intervals
Intervals.SumIntervals(new (int, int)[]{ });  // => 0
Intervals.SumIntervals(new (int, int)[]{ (2, 2), (5, 5)});  // => 0

// disjoined intervals
Intervals.SumIntervals(new (int, int)[]{
  (1, 2), (3, 5)
});  // => (2-1) + (5-3) = 3

// overlapping intervals
Intervals.SumIntervals(new (int, int)[]{
  (1, 4), (3, 6), (2, 8)
});  // (1,8) => 7
```

def sum_of_intervals(intervals):
    result = set()
    for start, end in intervals:
        result |= set(range(start, end))
    return len(result)


Solve in Python:
Write a function called calculate that takes 3 values. The first and third values are numbers. The second value is a character. If the character is "+" , "-", "*", or "/", the function will return the result of the corresponding mathematical function on the two numbers. If the string is not one of the specified characters, the function should return null (throw an `ArgumentException` in C#).

Keep in mind, you cannot divide by zero. If an attempt to divide by zero is made, return null (throw an `ArgumentException` in C#)/(None in Python).

def calculate(num1, operation, num2):
    ops = {"+": (lambda x, y: x + y), "-": (lambda x, y: x - y), "*": (lambda x, y: x * y), "/": (lambda x, y: x / y)}
    try: return ops[operation](num1, num2)
    except: return None


Solve in Python:
Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return `true` if the string is valid, and `false` if it's invalid.

## Examples

```
"()"              =>  true
")(()))"          =>  false
"("               =>  false
"(())((()())())"  =>  true
```

## Constraints

`0 <= input.length <= 100`

~~~if-not:javascript,go
Along with opening (`(`) and closing (`)`) parenthesis, input may contain any valid ASCII characters.  Furthermore, the input string may be empty and/or not contain any parentheses at all.  Do **not** treat other forms of brackets as parentheses (e.g. `[]`, `{}`, `<>`).
~~~

def valid_parentheses(string):
    count = 0
    for i in string:
        if i == "(":
            count += 1
        elif i == ")":
            count -= 1
        if count < 0:
            return False
    return count == 0


Solve in Python:
Write a function generator that will generate the first `n` primes grouped in tuples of size `m`. If there are not enough primes for the last tuple it will have the remaining values as `None`.

## Examples

```python
For n = 11 and m = 2:
(2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, None)

For n = 11 and m = 3:
(2, 3, 5), (7, 11, 13), (17, 19, 23), (29, 31, None)

For n = 11 and m = 5:
(2, 3, 5, 7, 11), (13, 17, 19, 23, 29), (31, None, None, None, None)]

For n = 3 and m = 1:
(2,), (3,), (5,)
```

Note: large numbers of `n` will be tested, up to 50000

from itertools import zip_longest
import math

def get_primes(how_many, group_size=2):
    if how_many>0:
        pr = primes(how_many)
        yield from [ tuple(e) for e in zip_longest(*[iter(pr)]*group_size ) ]

def is_prime(n):
    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))

def primes(n):
    i, pr = 3, [2]
    while n>1:
        if is_prime(i):
            n -= 1
            pr.append(i)
        i += 2
    return pr


Solve in Python:
Write a function getMean that takes as parameters an array (arr) and 2 integers (x and y). The function should return the mean between the mean of the the first x elements of the array and the mean of the last y elements of the array.

The mean should be computed if both x and y have values higher than 1 but less or equal to the array's length. Otherwise the function should return -1.

getMean([1,3,2,4], 2, 3) should return 2.5 because: the mean of the the first 2 elements of the array is (1+3)/2=2 and the mean of the last 3 elements of the array is (4+2+3)/3=3 so the mean of those 2 means is (2+3)/2=2.5.

getMean([1,3,2,4], 1, 2) should return -1 because x is not higher than 1.

getMean([1,3,2,4], 2, 8) should return -1 because 8 is higher than the array's length.

from statistics import mean

def get_mean(arr, x, y):
    if all(1 < i < len(arr) + 1 for i in (x, y)):
        return mean((mean(arr[:x]), mean(arr[-y:])))
    return -1


Solve in Python:
Write a function getNumberOfSquares that will return how many integer (starting from 1, 2...) numbers raised to power of 2 and then summed up are less than some number given as a parameter.

E.g 1: For n = 6 result should be 2 because 1^2 + 2^2 = 1 + 4 = 5 and 5 < 6
E.g 2: For n = 15 result should be 3 because 1^2 + 2^2 + 3^2 = 1 + 4 + 9 = 14 and 14 < 15

def get_number_of_squares(n):
    sm = 0
    i = 0
    while n > sm:
        i += 1
        sm += i ** 2
    return i - 1


Solve in Python:
Write a function groupIn10s which takes any number of arguments, and groups them into sets of 10s and sorts each group in ascending order.

The return value should be an array of arrays, so that numbers between 0-9 inclusive are in position 0 and numbers 10-19 are in position 1, etc.

Here's an example of the required output:

```python
grouped = group_in_10s(8, 12, 38, 3, 17, 19, 25, 35, 50)

grouped[0]     # [3, 8]
grouped[1]     # [12, 17, 19]
grouped[2]     # [25]
grouped[3]     # [35, 38]
grouped[4]     # None
grouped[5]     # [50]
```
``` haskell
groupIn10s [8, 12, 3, 17, 19, 24, 35, 50] `shouldBe`  [[3,8],[12,17,19],[24],[35],[],[50]]
```

from collections import defaultdict

def group_in_10s(*args):
    d = defaultdict(list)
    for x in args:
        d[x // 10].append(x)
    return [sorted(d[k]) if k in d else None for k in range(0, max(d) + 1)] if d else []


Solve in Python:
Write a function name `nextPerfectSquare` that returns the first perfect square that is greater than its integer argument. A `perfect square` is a integer that is equal to some integer squared. For example 16 is a perfect square because `16=4*4`.
```
example

n   next perfect sqare

6    9
36   49
0    1
-5   0
```
```if-not:csharp
caution! the largest number tested is closer to `Number.MAX_SAFE_INTEGER`
```
```if:csharp
Caution! The largest number test is close to `Int64.MaxValue`
```

from math import floor
def next_perfect_square(n):
    return (floor(n**(1/2)) + 1) ** 2 if n > 0 else 0 if n != 0 else 1


Solve in Python:
Write a function named `first_non_repeating_letter` that takes a string input, and returns the first character that is not repeated anywhere in the string.

For example, if given the input `'stress'`, the function should return `'t'`, since the letter *t* only occurs once in the string, and occurs first in the string.

As an added challenge, upper- and lowercase letters are considered the **same character**, but the function should return the correct case for the initial letter.  For example, the input `'sTreSS'` should return `'T'`.

If a string contains *all repeating characters*, it should return an empty string (`""`) or `None` -- see sample tests.

def first_non_repeating_letter(string):

    s = string.lower()

    for i in string:
        if s.count(i.lower()) == 1:
            return i
    return ''


Solve in Python:
Write a function named `repeater()` that takes two arguments (a string and a number), and returns a new string where the input string is repeated that many times.

## Example:

should return

def repeater(string, n):
    return string * n # The string is multiplied n and is then returned


Solve in Python:
Write a function named setAlarm which receives two parameters. The first parameter, employed, is true whenever you are employed and the second parameter, vacation is true whenever you are on vacation.
The function should return true if you are employed and not on vacation (because these are the circumstances under which you need to set an alarm). It should return false otherwise. Examples:

```if-not:julia,racket
setAlarm(true, true) -> false
setAlarm(false, true) -> false
setAlarm(false, false) -> false
setAlarm(true, false) -> true
```

def set_alarm(employed, vacation):
    # Your code here
    if employed == True and vacation == True:
        return False
    elif employed == True and vacation == False:
        return True
    elif employed == False and vacation == True:
        return False
    elif employed == False and vacation == True:
        return False
    elif employed == False and vacation == False:
        return False


Solve in Python:
Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits.  For example:

```python
  sum_digits(10)  # Returns 1
  sum_digits(99)  # Returns 18
  sum_digits(-32) # Returns 5
```

Let's assume that all numbers in the input will be integer values.

def sum_digits(number):
    sum = 0
    number = abs(number)
    number = str(number)
    for i in number:
        print(i)
        sum += int(i)
    return sum


Solve in Python:
Write a function taking in a string like `WOW this is REALLY          amazing` and returning `Wow this is really amazing`. String should be capitalized and properly spaced. Using `re` and `string` is not allowed.

Examples:

```python
filter_words('HELLO CAN YOU HEAR ME') #=> Hello can you hear me
filter_words('now THIS is REALLY interesting') #=> Now this is really interesting
filter_words('THAT was EXTRAORDINARY!') #=> That was extraordinary!
```

def filter_words(st):
    return " ".join(st.split()).capitalize()


Solve in Python:
Write a function that accepts a square matrix (`N x N` 2D array) and returns the determinant of the matrix.

How to take the determinant of a matrix -- it is simplest to start with the smallest cases:

A 1x1 matrix `|a|` has determinant `a`.

A 2x2 matrix `[ [a, b], [c, d] ]` or
```
|a  b|
|c  d|
```
has determinant: `a*d - b*c`.

The determinant of an `n x n` sized matrix is calculated by reducing the problem to the calculation of the determinants of `n` matrices of`n-1 x n-1` size.

For the 3x3 case, `[ [a, b, c], [d, e, f], [g, h, i] ]` or
```
|a b c|
|d e f|
|g h i|
```
the determinant is: `a * det(a_minor) - b * det(b_minor) + c * det(c_minor)` where `det(a_minor)` refers to taking the determinant of the 2x2 matrix created by crossing out the row and column in which the element a occurs:
```
|- - -|
|- e f|
|- h i|
```
Note the alternation of signs.

The determinant of larger matrices are calculated analogously, e.g. if M is a 4x4 matrix with first row `[a, b, c, d]`, then:

`det(M) = a * det(a_minor) - b * det(b_minor) + c * det(c_minor) - d * det(d_minor)`

def determinant(m):
    if len(m) == 1 : return m[0][0]
    if len(m) == 2 : return (m[0][0]*m[1][1]) - (m[0][1]*m[1][0])
    li = [[m[j][:i] + m[j][i+1:] for j in range(1,len(m))] for i in range(len(m))]
    return sum(-m[0][i]*(determinant(j)) if i&1 else m[0][i]*(determinant(j)) for i,j in enumerate(li))


Solve in Python:
Write a function that accepts a string, and returns true if it is in the form of a phone number. Assume that any integer from 0-9 in any of the spots will produce a valid phone number.

Only worry about the following format:
(123) 456-7890   (don't forget the space after the close parentheses)
Examples:

```
validPhoneNumber("(123) 456-7890")  =>  returns true
validPhoneNumber("(1111)555 2345")  => returns false
validPhoneNumber("(098) 123 4567")  => returns false
```

def validPhoneNumber(phoneNumber):
    number = ''
    template = '(xxx) xxx-xxxx'
    for l in phoneNumber:
        if l.isdigit():
            number += 'x'
        else:
            number += l

    return number == template


Solve in Python:
Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.

Example:

```python
create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
```
```f#
createPhoneNumber [1; 2; 3; 4; 5; 6; 7; 8; 9; 0] // => returns "(123) 456-7890"
```

The returned format must be correct in order to complete this challenge.
Don't forget the space after the closing parentheses!

def create_phone_number(n):
    n = "".join([str(x) for x in n] )
    return("(" + str(n[0:3]) + ")" + " " + str(n[3:6]) + "-" + str(n[6:]))


Solve in Python:
Write a function that accepts two arguments: an array/list of integers and another integer (`n`).

Determine the number of times where two integers in the array have a difference of `n`.

For example:
```
[1, 1, 5, 6, 9, 16, 27], n=4  -->  3  # (1,5), (1,5), (5,9)
[1, 1, 3, 3], n=2             -->  4  # (1,3), (1,3), (1,3), (1,3)
```

int_diff = lambda arr, n: len([abs(x[0]-x[1]) for x in __import__('itertools').combinations(arr, 2) if abs(x[0]-x[1]) == n])


Solve in Python:
Write a function that accepts two parameters (a and b) and says whether a is smaller than, bigger than, or equal to b.

Here is an example code:
var noIfsNoButs = function (a,b) {
  if(a > b) return a + " is greater than " + b
  else if(a < b) return a + " is smaller than " + b
  else if(a == b) return a + " is equal to " + b
}

There's only one problem...

You can't use if statements, and you can't use shorthands like (a < b)?true:false;

in fact the word "if" and the character "?" are not allowed in the code.

Inputs are guarenteed to be numbers

You are always welcome to check out some of my other katas:

Very Easy (Kyu 8)
Add Numbers
Easy (Kyu 7-6)
Convert Color image to greyscale
Array Transformations
Basic Compression
Find Primes in Range
No Ifs No Buts
Medium (Kyu 5-4)
Identify Frames In An Image
Photoshop Like - Magic Wand
Scientific Notation
Vending Machine - FSA
Find Matching Parenthesis
Hard (Kyu 3-2)
Ascii Art Generator

def no_ifs_no_buts(a, b):
    compare =   {
        -1: " is smaller than ",
        0 : " is equal to ",
        1 : " is greater than "
    }
    return str(a) + compare[(a > b) - (a < b)] + str(b)


Solve in Python:
Write a function that accepts two parameters, i) a string (containing a list of words) and ii) an integer (n).  The function should alphabetize the list based on the nth letter of each word.

The letters should be compared case-insensitive. If both letters are the same, order them normally (lexicographically), again, case-insensitive.

example:
```javascript
function sortIt('bid, zag', 2) //=> 'zag, bid'
```
```ruby
function sortIt('bid, zag', 2) //=> 'zag, bid'
```
```python
function sortIt('bid, zag', 2) #=> 'zag, bid'
```

The length of all words provided in the list will be >= n.  The format will be "x, x, x". In Haskell you'll get a list of `String`s instead.

def sort_it(words, i):
    return ", ".join(sorted(words.split(", "), key=lambda w: w[i-1]))


Solve in Python:
Write a function that accepts two square (`NxN`) matrices (two dimensional arrays), and returns the product of the two. Only square matrices will be given.

How to multiply two square matrices:

We are given two matrices, A and B, of size 2x2 (note: tests are not limited to 2x2). Matrix C, the solution, will be equal to the product of A and B. To fill in cell `[0][0]` of matrix C, you need to compute: `A[0][0] * B[0][0] + A[0][1] * B[1][0]`.

More general: To fill in cell `[n][m]` of matrix C, you need to first multiply the elements in the nth row of matrix A by the elements in the mth column of matrix B, then take the sum of all those products. This will give you the value for cell `[m][n]` in matrix C.

## Example
```
  A         B          C
|1 2|  x  |3 2|  =  | 5 4|
|3 2|     |1 1|     |11 8|
```

Detailed calculation:
```
C[0][0] = A[0][0] * B[0][0] + A[0][1] * B[1][0] = 1*3 + 2*1 =  5
C[0][1] = A[0][0] * B[0][1] + A[0][1] * B[1][1] = 1*2 + 2*1 =  4
C[1][0] = A[1][0] * B[0][0] + A[1][1] * B[1][0] = 3*3 + 2*1 = 11
C[1][1] = A[1][0] * B[0][1] + A[1][1] * B[1][1] = 3*2 + 2*1 =  8
```
Link to Wikipedia explaining matrix multiplication (look at the square matrix example):
http://en.wikipedia.org/wiki/Matrix_multiplication

A more visual explanation of matrix multiplication: http://matrixmultiplication.xyz

~~~if:c
**Note:** In **C**, the dimensions of both square matrices `n` will be passed into your function.  However, since the dimensions of your returned "matrix" is expected to be the same as that of the inputs, you will not need to keep track of the dimensions of your matrix in another variable.
~~~

import numpy as np
def matrix_mult(a, b):
  return np.dot(a,b).tolist()


Solve in Python:
Write a function that accepts two square matrices (`N x N` two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size `N x N` (square), containing only integers.

How to sum two matrices:

Take each cell `[n][m]` from the first matrix, and add it with the same `[n][m]` cell from the second matrix. This will be cell `[n][m]` of the solution matrix.

Visualization:
```
|1 2 3|     |2 2 1|     |1+2 2+2 3+1|     |3 4 4|
|3 2 1|  +  |3 2 3|  =  |3+3 2+2 1+3|  =  |6 4 4|
|1 1 1|     |1 1 3|     |1+1 1+1 1+3|     |2 2 4|
```

## Example

def matrix_addition(a, b):
    return [ [a[row][col] + b[row][col] for col in range(len(a[0]))]
                for row in range(len(a)) ]


Solve in Python:
Write a function that calculates the *least common multiple* of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return `1`.

~~~if:objc
NOTE: The first (and only named) argument of the function `n` specifies the number of arguments in the variable-argument list. Do **not** take `n` into account when computing the LCM of the numbers.
~~~

from math import gcd
from functools import reduce
def lcm(*args):
    return reduce(lambda x,y : abs(x*y)//gcd(x,y), args) if args else 1


Solve in Python:
Write a function that calculates the original product price, without VAT.

## Example
If a product price is `200.00` and VAT is `15%`, then the final product price (with VAT) is: `200.00 + 15% = 230.00`

Thus, if your function receives `230.00` as input, it should return `200.00`

**Notes:**

* VAT is *always* `15%` for the purposes of this Kata.
* Round the result to 2 decimal places.
* If `null` value given then return `-1`

def excluding_vat_price(price):
    return round(price/(1+0.15),2) if price else -1


Solve in Python:
Write a function that checks if all the letters in the second string are present in the first one at least once, regardless of how many times they appear:

```
["ab", "aaa"]    =>  true
["trances", "nectar"]    =>  true
["compadres", "DRAPES"]  =>  true
["parses", "parsecs"]    =>  false
```

Function should not be case sensitive, as indicated in example #2. Note: both strings are presented as a **single argument** in the form of an array.

def letter_check(arr):
    a, b = [set(i.lower()) for i in arr]
    return not b - a


Solve in Python:
Write a function that checks the braces status in a string, and return `True` if all braces are properly closed, or `False` otherwise. Available types of brackets: `()`, `[]`, `{}`.

**Please note, you need to write this function without using regex!**

## Examples
```python
'([[some](){text}here]...)'  =>  True
'{([])}'                     =>  True
'()[]{}()'                   =>  True
'(...[]...{(..())}[abc]())'  =>  True
'1239(df){'                  =>  False
'[()])'                      =>  False
')12[x]34('                  =>  False
```
Don't forget to rate this kata! Thanks :)

def braces_status(s):
    matching = {"}":"{","]":"[",")":"("}
    stack = []
    for c in s:
        if c in "[({":
            stack.append(c)
        elif c in matching and (not stack or stack.pop() != matching[c]):
            return False
    return not stack


Solve in Python:
Write a function that counts how many different ways you can make change for an amount of money, given an array of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2:
```
1+1+1+1, 1+1+2, 2+2.
```
The order of coins does not matter:
```
1+1+2 == 2+1+1
```
Also, assume that you have an infinite amount of coins.

Your function should take an amount to change and an array of unique denominations for the coins:

```python
  count_change(4, [1,2]) # => 3
  count_change(10, [5,2,3]) # => 4
  count_change(11, [5,7]) # => 0
```

def count_change(money, coins):
    if money<0:
        return 0
    if money == 0:
        return 1
    if money>0 and not coins:
        return 0
    return count_change(money-coins[-1],coins) + count_change(money,coins[:-1])


Solve in Python:
Write a function that determines whether a string is a valid guess in a Boggle board, as per the rules of Boggle. A Boggle board is a 2D array of individual characters, e.g.:
```python
[ ["I","L","A","W"],
  ["B","N","G","E"],
  ["I","U","A","O"],
  ["A","S","R","L"] ]
```
Valid guesses are strings which can be formed by connecting adjacent cells (horizontally, vertically, or diagonally) without re-using any previously used cells.

For example, in the above board "BINGO", "LINGO", and "ILNBIA" would all be valid guesses, while "BUNGIE", "BINS", and "SINUS" would not.

Your function should take two arguments (a 2D array and a string) and return true or false depending on whether the string is found in the array as per Boggle rules.

Test cases will provide various array and string sizes (squared arrays up to 150x150 and strings up to 150 uppercase letters). You do not have to check whether the string is a real word or not, only if it's a valid guess.

import numpy as np

def find_word(board, word, seen=[]):
    board = np.array(board)
    inds = np.argwhere(board == word[0])
    if seen:
        inds = inds[[list(ind) not in seen for ind in inds]]
        last = seen[-1]
        inds = inds[[max(row) == 1 for row in abs(inds - last)]]

    if len(word) == 1:
        return len(inds) > 0
    return any(find_word(board, word[1:], seen=seen + [list(ind)]) for ind in inds)


Solve in Python:
Write a function that flattens an `Array` of `Array` objects into a flat `Array`.  Your function must only do one level of flattening.

```python
flatten [1,2,3] # => [1,2,3]
flatten [[1,2,3],["a","b","c"],[1,2,3]]  # => [1,2,3,"a","b","c",1,2,3]
flatten [[[1,2,3]]] # => [[1,2,3]]
```

def flatten(lst):
    return sum((([x], x)[isinstance(x, list)] for x in lst), [])


Solve in Python:
Write a function that gets a sequence and value and returns `true/false` depending on whether the variable exists in a multidimentional sequence.

Example:
```
locate(['a','b',['c','d',['e']]],'e'); // should return true
locate(['a','b',['c','d',['e']]],'a'); // should return true
locate(['a','b',['c','d',['e']]],'f'); // should return false
```

def locate(seq, value):
    f = 0
    for e in seq:
        if type(e) == list and not f:
            f = locate(e, value)
        elif e == value:
            f = 1
    return f


Solve in Python:
Write a function that merges two sorted arrays into a single one. The arrays only contain integers. Also, the final outcome must be sorted and not have any duplicate.

def merge_arrays(first, second):
    res = []
    [res.append(x) for x in first+second if x not in res]
    return sorted(res)


Solve in Python:
Write a function that outputs the transpose of a matrix - a new matrix
where the columns and rows of the original are swapped.

For example, the transpose of:

    | 1 2 3 |
    | 4 5 6 |

is

    | 1 4 |
    | 2 5 |
    | 3 6 |

The input to your function will be an array of matrix rows. You can
assume that each row has the same length, and that the height and
width of the matrix are both positive.

import numpy as np
def transpose(matrix):
    return np.transpose(matrix).tolist()


Solve in Python:
Write a function that rearranges an integer into its largest possible value.

```python
super_size(123456) # 654321
super_size(105)    # 510
super_size(12)     # 21
```
``` haskell
superSize 123456 `shouldBe` 654321
superSize    105 `shouldBe`    510
superSize     12 `shouldBe`     21
```

If the argument passed through is single digit or is already the maximum possible integer, your function should simply return it.

def super_size(n):
    uporz = list(str(n))
    uporz.sort(reverse=True)
    return int(''.join(uporz))


Solve in Python:
Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second.

For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned.
If the second string isn't a valid rotation of the first string, the method returns -1.

Examples:
```
"coffee", "eecoff" => 2
"eecoff", "coffee" => 4
"moose", "Moose" => -1
"isn't", "'tisn" => 2
"Esham", "Esham" => 0
"dog", "god" => -1
```

For Swift, your function should return an Int?. So rather than returning -1 when the second string isn't a valid rotation of the first, return nil.

def shifted_diff(first, second):
    return -1 if len(first) != len(second) else f"{second}{second}".find(first)


Solve in Python:
Write a function that receives two strings as parameter. This strings are in the following format of date: `YYYY/MM/DD`.
Your job is: Take the `years` and calculate the difference between them.

Examples:
```
'1997/10/10' and '2015/10/10' -> 2015 - 1997 = returns 18
'2015/10/10' and '1997/10/10' -> 2015 - 1997 = returns 18
```
At this level, you don't need validate months and days to calculate the difference.

def how_many_years (date1, date2):
    get_year = lambda date: int(date.split('/')[0])
    return abs(get_year(date1) - get_year(date2))


Solve in Python:
Write a function that removes every lone 9 that is inbetween 7s.

```python
seven_ate9('79712312') => '7712312'
seven_ate9('79797') => '777'
```

Input: String
Output: String

from re import compile

r = compile(r"79(?=7)")

def seven_ate9(s: str) -> str:
    return r.sub("7", s)


Solve in Python:
Write a function that replaces 'two', 'too' and 'to' with the number '2'. Even if the sound is found mid word (like in octopus) or not in lowercase grandma still thinks that should be replaced with a 2. Bless her.

```text
'I love to text' becomes 'I love 2 text'
'see you tomorrow' becomes 'see you 2morrow'
'look at that octopus' becomes 'look at that oc2pus'
```

Note that 'too' should become '2', not '2o'

import re
def textin(st):
    return re.sub(r'(TOO)|(TWO)|(TO)', '2', st, flags=re.IGNORECASE)


Solve in Python:
Write a function that returns a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than two characters or longer than 100 characters, the function should return "invalid string".

For example:
`````
"abcdefghijklm" --> ["b", "d", "f", "h", "j", "l"]
"a"             --> "invalid string"
`````

def even_chars(s):
    return list(s[1::2]) if 2 <= len(s) <= 100 else 'invalid string'


Solve in Python:
Write a function that returns the count of characters that have to be removed in order to get a string with no consecutive repeats.

*Note:* This includes any characters

##  Examples

```python
'abbbbc'  => 'abc'    #  answer: 3
'abbcca'  => 'abca'   #  answer: 2
'ab cca'  => 'ab ca'  #  answer: 1
```

count_repeats = lambda s: sum(sum(1 for _ in n) - 1 for _, n in __import__("itertools").groupby(s))


Solve in Python:
Write a function that returns the index of the first occurence of the word "Wally".  "Wally" must not be part of another word, but it can be directly followed by a punctuation mark.  If no such "Wally" exists, return -1.

Examples:

"Wally" => 0

"Where's Wally" => 8

"Where's Waldo" => -1

"DWally Wallyd .Wally" => -1

"Hi Wally." => 3

"It's Wally's." => 5

"Wally Wally" => 0

"'Wally Wally" => 7

import re

def wheres_wally(string):
    match = re.search(r"(?<!\S)\bWally\b", string)
    return match.start() if match else -1


Solve in Python:
Write a function that returns the number of '2's in the factorization of a number.
For example,
```python
two_count(24)
```
should return 3, since the factorization of 24 is 2^3 x 3
```python
two_count(17280)
```
should return 7, since the factorization of 17280 is 2^7 x 5 x 3^3
The number passed to two_count (twoCount)  will always be a positive integer greater than or equal to 1.

def two_count(n):
  i = 0
  while True:
      n, r = divmod(n, 2)
      if r:
          break
      i += 1
  return i


Solve in Python:
Write a function that reverses the bits in an integer.

For example, the number `417` is `110100001` in binary. Reversing the binary is `100001011` which is `267`.

You can assume that the number is not negative.

def reverse_bits(n):
    return int(format(n, "b")[::-1], 2)


Solve in Python:
Write a function that solves an algebraic expression given as a string.

* The expression can include only sums and products.

* The numbers in the expression are in standard notation (NOT scientific).

* In contrast, the function should return a string with the calculated value given in scientific notation with 5 decimal digits.

# Example:
```python
strexpression = "5 * 4 + 6"
sum_prod(strexpression) = "2.60000e+01"
```


Solve in Python:
Write a function that takes a list comprised of other lists of integers and returns the sum of all numbers that appear in two or more lists in the input list.  Now that might have sounded confusing, it isn't:
```python
repeat_sum([[1, 2, 3],[2, 8, 9],[7, 123, 8]])
>>> sum of [2, 8]
return 10

repeat_sum([[1], [2], [3, 4, 4, 4], [123456789]])
>>> sum of []
return 0

repeat_sum([[1, 8, 8], [8, 8, 8], [8, 8, 8, 1]])
sum of [1,8]
return 9
```

repeat_sum=lambda x:sum(list(set([j for i in x for j in i if sum(1for q in x if j in q)>1])))


Solve in Python:
Write a function that takes a list of at least four elements as an argument and returns a list of the middle two or three elements in reverse order.

reverse_middle = lambda a: a[len(a)+1>>1:(len(a)>>1)-2:-1]


Solve in Python:
Write a function that takes a number or a string and gives back the number of **permutations without repetitions** that can generated using all of its element.; more on permutations [here](https://en.wikipedia.org/wiki/Permutation).

For example, starting with:
```
1
45
115
"abc"
```

You could respectively generate:
```
1
45,54
115,151,511
"abc","acb","bac","bca","cab","cba"
```

So you should have, in turn:
```python
perms(1)==1
perms(45)==2
perms(115)==3
perms("abc")==6
```

from collections import Counter
from math import factorial as fact
from functools import reduce
from operator import mul

def perms(element):
    s = str(element)
    c = Counter(s)
    return fact(len(s)) / reduce(mul, [fact(n) for n in c.values()], 1)


Solve in Python:
Write a function that takes a piece of text in the form of a string and returns the letter frequency count for the text. This count excludes numbers, spaces and all punctuation marks. Upper and lower case versions of a character are equivalent and the result should all be in lowercase.

The function should return a list of tuples (in Python and Haskell) or arrays (in other languages) sorted by the most frequent letters first. The Rust implementation should return an ordered BTreeMap.
Letters with the same frequency are ordered alphabetically.
For example:

```python
  letter_frequency('aaAabb dddDD hhcc')
```
```C++
  letter_frequency("aaAabb dddDD hhcc")
```

will return

```python
  [('d',5), ('a',4), ('b',2), ('c',2), ('h',2)]
```
```C++
  std::vector>{{'d',5}, {'a',4}, {'b',2}, {'c',2}, {'h',2}}
```

Letter frequency analysis is often used to analyse simple substitution cipher texts like those created by the Caesar cipher.

import re
from collections import Counter
def letter_frequency(text):
  letters = re.findall('[a-z]', text.lower())
  freqs   = Counter(letters).most_common()
  return sorted(freqs, lambda a, b: cmp(b[1], a[1]) or cmp(a[0], b[0]))


Solve in Python:
Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits.

For example:

```python
next_smaller(21) == 12
next_smaller(531) == 513
next_smaller(2071) == 2017
```

Return -1 (for `Haskell`: return `Nothing`, for `Rust`: return `None`), when there is no smaller number that contains the same digits. Also return -1 when the next smaller number with the same digits would require the leading digit to be zero.

```python
next_smaller(9) == -1
next_smaller(135) == -1
next_smaller(1027) == -1  # 0721 is out since we don't write numbers with leading zeros
```
```ruby
next_smaller(9) == -1
next_smaller(135) == -1
next_smaller(1027) == -1  # 0721 is out since we don't write numbers with leading zeros
```

 * some tests will include very large numbers.
 * test data only employs positive integers.

*The function you write for this challenge is the inverse of this kata: "[Next bigger number with the same digits](http://www.codewars.com/kata/next-bigger-number-with-the-same-digits)."*

def swap(s, a, b):
    s = list(s)
    s[a], s[b] = s[b], s[a]
    return ''.join(s)

def maximized_range(s, left): # Maximize value in range [left, end]
    return s[:left] + ''.join(sorted(s[left:], reverse=True))

def next_smaller(n):
    s = str(n)
    k = len(s)
    for i in range(k-1, -1, -1):
        for j in range(k-1, i, -1):
            if s[j] < s[i]:
                t = swap(s, i, j)
                if t[0] != '0':
                    return int(maximized_range(t, i+1))
    return -1


Solve in Python:
Write a function that takes a positive integer n, sums all the cubed values from 1 to n, and returns that sum.

Assume that the input n will always be a positive integer.

Examples:

```python
sum_cubes(2)
> 9
# sum of the cubes of 1 and 2 is 1 + 8
```

def sum_cubes(n):
    return sum((i+1)**3 for i in range(n)) # ahuel, da


Solve in Python:
Write a function that takes a single array as an argument (containing multiple strings and/or positive numbers and/or arrays), and returns one of four possible string values, depending on the ordering of the lengths of the elements in the input array:

Your function should return...

- “Increasing” - if the lengths of the elements increase from left to right (although it is possible that some neighbouring elements may also be equal in length)
- “Decreasing” - if the lengths of the elements decrease from left to right (although it is possible that some neighbouring elements may also be equal in length)
- “Unsorted” - if the lengths of the elements fluctuate from left to right
- “Constant” - if all element's lengths are the same.

Numbers and Strings should be evaluated based on the number of characters or digits used to write them.

Arrays should be evaluated based on the number of elements counted directly in the parent array (but not the number of elements contained in any sub-arrays).

Happy coding! :)

from operator import le, ge

size = lambda x: len(str(x)) if type(x) == int else len(x)

def order_type(arr):
    L = list(map(size, arr))
    if len(set(L)) <= 1: return "Constant"
    if all(map(le, L, L[1:])): return "Increasing"
    if all(map(ge, L, L[1:])): return "Decreasing"
    return "Unsorted"


Solve in Python:
Write a function that takes a string and returns an array containing binary numbers equivalent to the ASCII codes of the characters of the string. The binary strings should be eight digits long.

Example: `'man'` should return `[ '01101101', '01100001', '01101110' ]`

def word_to_bin(s):
    return list(map(lambda x: format(ord(x),'08b'),s))


Solve in Python:
Write a function that takes a string and returns an array of the repeated characters (letters, numbers, whitespace) in the string.

If a charater is repeated more than once, only show it once in the result array.

Characters should be shown **by the order of their first repetition**. Note that this may be different from the order of first appearance of the character.

Characters are case sensitive.

For F# return a "char list"

## Examples:

```python
remember("apple") => returns ["p"]
remember("apPle") => returns []          # no repeats, "p" != "P"
remember("pippi") => returns ["p","i"]   # show "p" only once
remember('Pippi') => returns ["p","i"]   # "p" is repeated first
```

def remember(str):
    lst = []
    for i, j in enumerate(str):
        if j in str[:i] and j not in lst:
            lst.append(j)
    return lst


Solve in Python:
Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

Note:
The vowels does not include the letter "y".

class Solution:
     def reverseVowels(self, s):
         """
         :type s: str
         :rtype: str
         """
         if not s:
             return s
         vowels=['a','e','i','o','u','A','E','I','O','U']
         left=0
         right=len(s)-1
         res=[s[0]]*len(s)
         while left<right:
             if s[left] in vowels and s[right] in vowels:
                 res[left],res[right]=s[right],s[left]
                 left+=1
                 right-=1
             else:
                 if s[left] not in vowels:
                     res[left]=s[left]
                     left+=1
                 if s[right] not in vowels:
                     res[right]=s[right]
                     right-=1
         if left==right:
             res[left]=s[left]
         return ''.join(res)


Solve in Python:
Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return `true` if the string is valid, and `false` if it's invalid.

This Kata is similar to the [Valid Parentheses](https://www.codewars.com/kata/valid-parentheses) Kata, but introduces new characters: brackets `[]`, and curly braces `{}`. Thanks to `@arnedag` for the idea!

All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: `()[]{}`.

### What is considered Valid?

A string of braces is considered valid if all braces are matched with the correct brace.

## Examples

```
"(){}[]"   =>  True
"([{}])"   =>  True
"(}"       =>  False
"[(])"     =>  False
"[({})](]" =>  False
```

def validBraces(s):
    pairs = ['{}', '()', '[]']
    while any(pair in s for pair in pairs):
        for pair in pairs:
            s = s.replace(pair, "")
    return s == ""


Solve in Python:
Write a function that takes a string which has integers inside it separated by spaces, and your task is to convert each integer in the string into an integer and return their sum.

### Example
```python
summy("1 2 3")  ==> 6
```

Good luck!

import re

def summy(s):
    return sum(map(int, re.split(r'[^\d]+', s)))


Solve in Python:
Write a function that takes an arbitrary number of strings and interlaces them (combines them by alternating characters from each string).

For example `combineStrings('abc', '123')` should return `'a1b2c3'`.

If the strings are different lengths the function should interlace them until each string runs out, continuing to add characters from the remaining strings.

For example `combineStrings('abcd', '123')` should return `'a1b2c3d'`.

The function should take any number of arguments and combine them.

For example `combineStrings('abc', '123', '£$%')` should return `'a1£b2$c3%'`.

**Note: if only one argument is passed return only that string. If no arguments are passed return an empty string.**

from itertools import zip_longest, chain
def combine_strings(*args):
    return ''.join(chain(*zip_longest(*args, fillvalue = '')))


Solve in Python:
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: `(index1, index2)`.

For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.

The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).

Based on: http://oj.leetcode.com/problems/two-sum/

def two_sum(numbers, target):
    numbers.sort()

    i = 0
    j = len(numbers) - 1

    sum_ = numbers[i] + numbers[j]
    while sum_ != target:
        if sum_ < target:
            i += 1
        elif sum_ > target:
            j -= 1
        sum_ = numbers[i] + numbers[j]
    return [i, j]


Solve in Python:
Write a function that takes an array/list of numbers and returns a number such that

Explanation
total([1,2,3,4,5]) => 48

1+2=3--\ 3+5 =>     8 \
2+3=5--/ \            ==  8+12=>20\
          ==>5+7=> 12 / \           20+28 => 48
3+4=7--\ /            == 12+16=>28/
4+5=9--/ 7+9 =>     16  /

if total([1,2,3]) => 8 then

first+second => 3 \
                   then 3+5 => 8
second+third => 5 /

### Examples
```python
total([-1,-1,-1]) => -4
total([1,2,3,4])  => 20
```

**Note:** each array/list will have at least an element and all elements will be valid numbers.

def total(arr):
    while len(arr) > 1:
        arr = [x+y for x,y in zip(arr,arr[1:])]
    return arr[0]


Solve in Python:
Write a function that takes an integer and returns an array `[A, B, C]`, where `A` is the number of multiples of 3 (but not 5) below the given integer, `B` is the number of multiples of 5 (but not 3) below the given integer and `C` is the number of multiples of 3 and 5 below the given integer.

For example, `solution(20)` should return `[5, 2, 1]`

~~~if:r
```r
# in R, returns a numeric vector
solution(20)
[1] 5 2 1

class(solution(20))
[1] "numeric"
```
~~~

def solution(number):
    returnArray = [0, 0, 0]
    for i in range(1, number):
        if i % 15 == 0:
            returnArray[2] += 1
        elif i % 5 == 0 and (not (i % 3 == 0)):
            returnArray[1] += 1
        elif i % 3 == 0:
            returnArray[0] += 1
    return returnArray


Solve in Python:
Write a function that takes an integer in input and outputs a string with currency format.

Integer in currency format is expressed by a string of number where every three characters are separated by comma.

For example:

```
123456 --> "123,456"
```

Input will always be an positive integer, so don't worry about type checking or negative/float values.

def to_currency(price):
    price = str(price)[::-1]
    x = [price[i:i+3] for i in range(0, len(price), 3)]
    return ",".join(x)[::-1]


Solve in Python:
Write a function that takes as its parameters *one or more numbers which are the diameters of circles.*

The function should return the *total area of all the circles*, rounded to the nearest integer in a string that says "We have this much circle: xyz".

You don't know how many circles you will be given, but you can assume it will be at least one.

So:
```python
sum_circles(2) == "We have this much circle: 3"
sum_circles(2, 3, 4) == "We have this much circle: 23"
```

Translations and comments (and upvotes!) welcome!

from math import pi

OUTPUT = 'We have this much circle: {:.0f}'.format

def sum_circles(*args):
    return OUTPUT(sum(pi * (diameter / 2.0) ** 2 for diameter in args))


Solve in Python:
Write a function that takes in a binary string and returns the equivalent decoded text (the text is ASCII encoded).

Each 8 bits on the binary string represent 1 character on the ASCII table.

The input string will always be a valid binary string.

Characters can be in the range from "00000000" to "11111111" (inclusive)

Note: In the case of an empty binary string your function should return an empty string.

import re

def binary_to_string(bits):
    return ''.join(chr(int(byte, 2)) for byte in re.findall(r'\d{8}', bits))


Solve in Python:
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.

Examples:
spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw"
spinWords( "This is a test") => returns "This is a test"
spinWords( "This is another test" )=> returns "This is rehtona test"

def spin_words(sentence):
    return ' '.join([i if len(i) < 5 else i[::-1] for i in sentence.split()])


Solve in Python:
Write a function that takes one or more arrays and returns a new array of unique values in the order of the original provided arrays.

In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.

The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.

Check the assertion tests for examples.

*Courtesy of [FreeCodeCamp](https://www.freecodecamp.com/challenges/sorted-union), a great place to learn web-dev; plus, its founder Quincy Larson is pretty cool and amicable. I made the original one slightly more tricky ;)*

from itertools import chain

def unite_unique(*args):
    return list(dict.fromkeys(chain.from_iterable(args)))


Solve in Python:
Write a function that takes two arguments, and returns a new array populated with the elements **that only appear once, in either one array or the other, taken only once**; display order should follow what appears in arr1 first, then arr2:

```python
hot_singles([1, 2, 3, 3], [3, 2, 1, 4, 5]) # [4, 5]
hot_singles(["tartar", "blanket", "cinnamon"], ["cinnamon", "blanket", "domino"]) # ["tartar", "domino"]
hot_singles([77, "ciao"], [78, 42, "ciao"]) # [77, 78, 42]
hot_singles([1, 2, 3, 3], [3, 2, 1, 4, 5, 4]) # [4,5]
```

SPECIAL THANKS: @JulianKolbe !

def hot_singles(arr1, arr2):
    vals = arr1 + arr2
    return sorted(set(arr1).symmetric_difference(arr2), key=vals.index)


Solve in Python:
Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:
```python
domain_name("http://github.com/carbonfive/raygun") == "github"
domain_name("http://www.zombie-bites.com") == "zombie-bites"
domain_name("https://www.cnet.com") == "cnet"
```

import re

def domain_name(url):
    pattern = r'^(https?://(www.)?|(www.))?([^.]+)\..*$'
    return re.sub(pattern, r'\4', url)


Solve in Python:
Write a function that when given a number >= 0, returns an Array of ascending length subarrays.

```
pyramid(0) => [ ]
pyramid(1) => [ [1] ]
pyramid(2) => [ [1], [1, 1] ]
pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]
```

**Note:** the subarrays should be filled with `1`s

def pyramid(n):
    return [[1]*x for x in range(1, n+1)]


Solve in Python:
Write a function that will check whether the permutation of an input string is a palindrome. Bonus points for a solution that is efficient and/or that uses _only_ built-in language functions. Deem yourself **brilliant** if you can come up with a version that does not use _any_ function whatsoever.

# Example

  `madam` -> True
  `adamm` -> True
  `junk`  -> False

## Hint
The brute force approach would be to generate _all_ the permutations of the string and check each one of them whether it is a palindrome. However, an optimized approach will not require this at all.

def permute_a_palindrome(stg):
    return sum(stg.count(c) % 2 for c in set(stg)) == len(stg) % 2


Solve in Python:
Write a function that will encrypt a given sentence into International Morse Code, both the input and out puts will be strings.

Characters should be separated by a single space.
Words should be separated by a triple space.

For example, "HELLO WORLD" should return -> ".... . .-.. .-.. ---   .-- --- .-. .-.. -.."

To find out more about Morse Code follow this link: https://en.wikipedia.org/wiki/Morse_code

A preloaded object/dictionary/hash called CHAR_TO_MORSE will be provided to help convert characters to Morse Code.


Solve in Python:
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python).

A few examples:

```
randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt"

randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs"
```

Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.

from random import choice

def random_case(x):
    cases = (str.lower, str.upper)
    return ''.join(choice(cases)(char) for char in x)


Solve in Python:
Write a function that, given a string of text (possibly with punctuation and line-breaks),
returns an array of the top-3 most occurring words, in descending order of the number of occurrences.

Assumptions:
------------

- A word is a string of letters (A to Z) optionally containing one or more apostrophes (') in ASCII. (No need to handle fancy punctuation.)
- Matches should be case-insensitive, and the words in the result should be lowercased.
- Ties may be broken arbitrarily.
- If a text contains fewer than three unique words, then either the top-2 or top-1 words should be returned, or an empty array if a text contains no words.

Examples:
------------

```
top_3_words("In a village of La Mancha, the name of which I have no desire to call to
mind, there lived not long since one of those gentlemen that keep a lance
in the lance-rack, an old buckler, a lean hack, and a greyhound for
coursing. An olla of rather more beef than mutton, a salad on most
nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra
on Sundays, made away with three-quarters of his income.")
# => ["a", "of", "on"]

top_3_words("e e e e DDD ddd DdD: ddd ddd aa aA Aa, bb cc cC e e e")
# => ["e", "ddd", "aa"]

top_3_words("  //wont won't won't")
# => ["won't", "wont"]
```

```if:java
For java users, the calls will actually be in the form: `TopWords.top3(String s)`, expecting you to return a `List`.
```

Bonus points (not really, but just for fun):
------------

1. Avoid creating an array whose memory footprint is roughly as big as the input text.
2. Avoid sorting the entire array of unique words.

import re
from collections import Counter

def top_3_words(text):
    words = re.findall(r"[a-z']*[a-z]+[a-z']*", text.lower())
    top_3 = Counter(words).most_common(3)
    return [tup[0] for tup in top_3]


Solve in Python:
Write a function to calculate compound tax using the following table:

For $10 and under, the tax rate should be 10%.
For $20 and under, the tax rate on the first $10 is %10, and the tax on the rest is 7%.
For $30 and under, the tax rate on the first $10 is still %10, the rate for the next $10 is still 7%, and everything else is 5%.
Tack on an additional 3% for the portion of the total above $30.
Return 0 for invalid input(anything that's not a positive real number).

Examples:

An input of 10, should return 1 (1 is 10% of 10)
An input of 21, should return 1.75 (10% of 10 + 7% of 10 + 5% of 1)

* Note that the returned value should be rounded to the nearest penny.

def tax_calculator(total):

    if type(total) not in [int, float] or total < 0:
        return 0

    if total <= 10:
        tax = 0.1 * total
    elif total <= 20:
        tax = 1 + 0.07 * (total - 10)
    else:
        tax = 1.7 + 0.05 * min(total - 20, 10)
        if total > 30:
            tax += 0.03 * (total - 30)

    return round(tax, 2)


Solve in Python:
Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.

IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1;

Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid.

IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases).

However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address.

Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid.

Note:
You may assume there is no extra space or special characters in the input string.

Example 1:

Input: "172.16.254.1"

Output: "IPv4"

Explanation: This is a valid IPv4 address, return "IPv4".

Example 2:

Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"

Output: "IPv6"

Explanation: This is a valid IPv6 address, return "IPv6".

Example 3:

Input: "256.256.256.256"

Output: "Neither"

Explanation: This is neither a IPv4 address nor a IPv6 address.

class Solution:
     def validIPAddress(self, IP):

         def isIPv4(s):
             try: return str(int(s)) == s and 0 <= int(s) <= 255
             except: return False

         def isIPv6(s):
             if len(s) > 4: return False
             try: return int(s, 16) >= 0 and s[0] != '-'
             except: return False

         if IP.count(".") == 3 and all(isIPv4(i) for i in IP.split(".")):
             return "IPv4"
         if IP.count(":") == 7 and all(isIPv6(i) for i in IP.split(":")):
             return "IPv6"
         return "Neither"


Solve in Python:
Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

class Solution:
     def _longestCommonPrefix(self, left, right):
         prefix = ''
         i = j = 0
         while(i < len(left) and j < len(right)):
             if left[i] == right[j]:
                 prefix += left[i]
             else:
                 break
             i += 1
             j += 1
         return prefix

     def longestCommonPrefix(self, strs):
         """
         :type strs: List[str]
         :rtype: str
         """
         if not strs:
           return ''
         elif len(strs) == 1:
           return strs[0]
         mid = len(strs)//2
         left, right = self.longestCommonPrefix(strs[mid:]), self.longestCommonPrefix(strs[:mid])
         return self._longestCommonPrefix(left, right)


Solve in Python:
Write a function to split a string and convert it into an array of words. For example:

```python
"Robin Singh" ==> ["Robin", "Singh"]

"I love arrays they are my favorite" ==> ["I", "love", "arrays", "they", "are", "my", "favorite"]
```

#input - string
#output - list/array of words
#edge cases - no input given, integer or other data type given
#assumptions - I need to take a string and return a list of the words in the string.

#sample data - ("Robin Singh"), ["Robin", "Singh"]
#do I need to create a separate array? no
#I can just use string split function

#function string_to_array(string)
def string_to_array(s):
    return s.split(' ')


Solve in Python:
Write a function which converts the input string to uppercase.

~~~if:bf
For BF all inputs end with \0, all inputs are lowercases and there is no space between.
~~~

def make_upper_case(s):
    is_upper = s.upper()
    return is_upper


Solve in Python:
Write a function which makes a list of strings representing all of the ways you can balance `n` pairs of parentheses

### Examples

```python
balanced_parens(0) => [""]
balanced_parens(1) => ["()"]
balanced_parens(2) => ["()()","(())"]
balanced_parens(3) => ["()()()","(())()","()(())","(()())","((()))"]
```

from functools import lru_cache

@lru_cache()
def balanced_binaries(n):
    return {0} if not n else \
        set.union(*({2 | x << 2, 1 << 2*n-1 | x << 1, 2 << 2*(n-1) | x} for x in balanced_binaries(n-1))) | \
        {a<<2*i | b for i in range(2, n-1) for b in balanced_binaries(i) for a in balanced_binaries(n-i)}

def balanced_parens(n, table=str.maketrans('10', '()')):
    return [bin(x).lstrip('0b').translate(table) for x in balanced_binaries(n)]


Solve in Python:
Write a function which outputs the positions of matching bracket pairs. The output should be a dictionary with keys the positions of the open brackets '(' and values the corresponding positions of the closing brackets ')'.

For example: input = "(first)and(second)" should return {0:6, 10:17}

If brackets cannot be paired or if the order is invalid (e.g. ')(') return False. In this kata we care only about the positions of round brackets '()', other types of brackets should be ignored.

def bracket_pairs(string):
    result = {}
    stack = []
    for i, c in enumerate(string):
        if c == ')':
            if not stack:
                return False
            result[stack.pop()] = i
        elif c == '(':
            stack.append(i)
    if stack:
        return False
    return result


Solve in Python:
Write a function which reduces fractions to their simplest form! Fractions will be presented as an array/tuple (depending on the language), and the reduced fraction must be returned as an array/tuple:

```
input:   [numerator, denominator]
output:  [newNumerator, newDenominator]
example: [45, 120] --> [3, 8]
```

All numerators and denominators will be positive integers.

Note: This is an introductory Kata for a series... coming soon!

def mcd(fraccion):
    if fraccion[0]%fraccion[1]==0:
        return fraccion[1]
    else:
        return mcd((fraccion[1], fraccion[0]%fraccion[1]))

def reduce_fraction(fraccion):
    return (fraccion[0]//mcd(fraccion), fraccion[1]//mcd(fraccion))


Solve in Python:
Write a function which takes a number and returns the corresponding ASCII char for that value.

Example:

~~~if-not:java,racket
```
get_char(65) # => 'A'
```
~~~
~~~if:java
~~~
~~~if:racket
~~~

For ASCII table, you can refer to http://www.asciitable.com/

def get_char(ascii):
    return chr(ascii)


Solve in Python:
Write a function which takes one parameter representing the dimensions of a checkered board. The board will always be square, so 5 means you will need a 5x5 board.

The dark squares will be represented by a unicode white square, while the light squares will be represented by a unicode black square (the opposite colours ensure the board doesn't look reversed on code wars' dark background). It should return a string of the board with a space in between each square and taking into account new lines.

An even number should return a board that begins with a dark square. An odd number should return a board that begins with a light square.

The input is expected to be a whole number that's at least two, and returns false otherwise (Nothing in Haskell).

Examples:

```python
checkered_board(5)
```

returns the string
```
■ □ ■ □ ■
□ ■ □ ■ □
■ □ ■ □ ■
□ ■ □ ■ □
■ □ ■ □ ■
```

**There should be no trailing white space at the end of each line, or new line characters at the end of the string.**

**Note**
Do not use HTML entities for the squares (e.g. `□` for white square) as the code doesn't consider it a valid square. A good way to check is if your solution prints a correct checker board on your local terminal.

**Ruby note:**
CodeWars has encoding issues with rendered unicode in Ruby.
You'll need to use unicode source code (e.g. "\u25A0") instead of rendered unicode (e.g "■").

def checkered_board(n):
    if isinstance(n, int) and n > 1:
        return '\n'.join((' '.join(('□' if ((i % 2 == j % 2) ^ n) % 2 else '■' for j in range(n))) for i in range(n)))
    else:
        return False


Solve in Python:
Write a function with the signature shown below:
```python
def is_int_array(arr):
    return True
```
* returns `true  / True`  if every element in an array is an integer or a float with no decimals.
* returns `true  / True`  if array is empty.
* returns `false / False` for every other input.

def is_int_array(arr):
    return isinstance(arr, list) and all(isinstance(x, int) or isinstance(x, float) and x.is_integer() for x in arr)


Solve in Python:
Write a function, `gooseFilter` / `goose-filter` / `goose_filter` /` GooseFilter`, that takes an array of strings as an argument and returns a filtered array containing the same elements but with the 'geese' removed.

The geese are any strings in the following array, which is pre-populated in your solution:

```python
geese = ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"]
```

For example, if this array were passed as an argument:

```python
["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"]
```

Your function would return the following array:

```python
["Mallard", "Hook Bill", "Crested", "Blue Swedish"]
```

The elements in the returned array should be in the same order as in the initial array passed to your function, albeit with the 'geese' removed. Note that all of the strings will be in the same case as those provided, and some elements may be repeated.

geese = ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"]

def goose_filter(birds):
    return [el for i, el in enumerate(birds) if el not in geese]


Solve in Python:
Write a function, `persistence`, that takes in a positive parameter `num` and returns its multiplicative persistence, which is the number of times you must multiply the digits in `num` until you reach a single digit.

For example:

```python
 persistence(39) => 3  # Because 3*9 = 27, 2*7 = 14, 1*4=4
                       # and 4 has only one digit.

 persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,
                       # 1*2*6 = 12, and finally 1*2 = 2.

 persistence(4) => 0   # Because 4 is already a one-digit number.
```
```python
 persistence(39) # returns 3, because 3*9=27, 2*7=14, 1*4=4
                 # and 4 has only one digit

 persistence(999) # returns 4, because 9*9*9=729, 7*2*9=126,
                  # 1*2*6=12, and finally 1*2=2

 persistence(4) # returns 0, because 4 is already a one-digit number
```

def persistence(n):
    n = str(n)
    count = 0
    while len(n) > 1:
        p = 1
        for i in n:
            p *= int(i)
        n = str(p)
        count += 1
    return count
    # your code


Solve in Python:
Write a function, that doubles every second integer in a list starting from the left.

def double_every_other(lst):
    for ind, item in enumerate(lst):
        if ind % 2 != 0:
            lst[ind] = item*2
    return lst


Solve in Python:
Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (`HH:MM:SS`)

* `HH` = hours, padded to 2 digits, range: 00 - 99
* `MM` = minutes, padded to 2 digits, range: 00 - 59
* `SS` = seconds, padded to 2 digits, range: 00 - 59

The maximum time never exceeds 359999 (`99:59:59`)

You can find some examples in the test fixtures.

def make_readable(seconds):
    h= seconds/60**2
    m= (seconds%60**2)/60
    s= (seconds%60**2%60)
    return "%02d:%02d:%02d" % (h, m, s)
    # Do something


Solve in Python:
Write a method `alternate_sq_sum()` (JS: `alternateSqSum` ) that takes an array of integers as input and finds the sum of squares of the elements at even positions (*i.e.,* 2nd, 4th, *etc.*) plus the sum of the rest of the elements at odd position.

NOTE:
The values at even *position* need to be squared. For a language with zero-based indices, this will occur at oddly-indexed locations. For instance, in Python, the values at indices 1, 3, 5, *etc.* should be squared because these are the second, fourth, and sixth positions in the list.
For Example:

```python
alternate_sq_sum([11, 12, 13, 14, 15]) #should return 379
```

Explanation:

Elements at indices 0, 2, 4 are 11, 13, 15 and they are at odd positions as 11 is at position #1, 13 is at position #3 and 15 at #5.

Elements at indices 1, 3 are 12 and 14 and they are at even position.
So we need to add 11, 13, 15 as they are and square of 12 and 14

--> 11 + 13 + 15 + 12^2 + 14^2
  = 11 + 13 + 15 + 144 + 196
  = 379

For empty arrays, result should be 0 (zero) (except for Haskell).

def alternate_sq_sum(arr):
    return sum([x ** 2 if pos % 2 != 0 else x for pos, x in enumerate(arr)])


Solve in Python:
Write a method named `getExponent(n,p)` that returns the largest integer exponent `x` such that p^(x) evenly divides `n`. if `p<=1` the method should return `null`/`None` (throw an `ArgumentOutOfRange` exception in C#).

def get_exponent(n, p):
    if p <= 1:
        return None
    x, e = 0, 1
    while n % e == 0:
        x += 1
        e *= p
    return x - 1


Solve in Python:
Write a method that returns true if a given parameter is a power of 4, and false if it's not. If parameter is not an Integer (eg String, Array) method should return false as well.

(In C# Integer means all integer Types like Int16,Int32,.....)

### Examples

```python
isPowerOf4 1024 #should return True
isPowerOf4  102 #should return False
isPowerOf4   64 #should return True
```

def powerof4(n):
    if type(n)!=type(1):
        return False
    while n%4==0:
        n=n/4
    return n==1


Solve in Python:
Write a method that takes a string as an argument and groups the number of time each character appears in the string as a hash sorted by the highest number of occurrences.

The characters should be sorted alphabetically e.g:

```python
get_char_count("cba") == {1: ["a", "b", "c"]}
```

You should ignore spaces, special characters and count uppercase letters as lowercase ones.

For example:
```python
get_char_count("Mississippi")           ==  {4: ["i", "s"], 2: ["p"], 1: ["m"]}
get_char_count("Hello. Hello? HELLO!")  ==  {6: ["l"], 3: ["e", "h", "o"]}
get_char_count("aaa...bb...c!")         ==  {3: ["a"], 2: ["b"], 1: ["c"]}
get_char_count("abc123")                ==  {1: ["1", "2", "3", "a", "b", "c"]}
get_char_count("aaabbbccc")             ==  {3: ["a", "b", "c"]}
```

from collections import Counter, defaultdict
def get_char_count(s):
    d = defaultdict(list)
    c = Counter(sorted(s.lower()))
    for i,j in c.items():
        if i.isalnum() : d[j].append(i)
    return dict(sorted(d.items())[::-1])


Solve in Python:
Write a method that takes one argument as name and then greets that name, capitalized and ends with an exclamation point.

Example:

```
"riley" --> "Hello Riley!"
"JACK"  --> "Hello Jack!"
```

def greet(name):
    # your code here
    y = (name.lower()).capitalize()
    return "Hello " + y + "!"


Solve in Python:
Write a method that will search an array of strings for all strings that contain another string, ignoring capitalization. Then return an array of the found strings.

The method takes two parameters, the query string and the array of strings to search, and returns an array.

If the string isn't contained in any of the strings in the array, the method returns an array containing a single string: "Empty" (or `Nothing` in Haskell, or "None" in Python and C)

### Examples
If the string to search for is "me", and the array to search is ["home", "milk", "Mercury", "fish"], the method should return ["home", "Mercury"].

def word_search(q, l):
    return [w for w in l if q.lower() in w.lower()]or['None']


Solve in Python:
Write a program that outputs the `n` largest elements from a list.

Example:
```python
largest(2, [7,6,5,4,3,2,1])
# => [6,7]
```

import heapq

def largest(n,xs):
  """Find the n highest elements in a list"""
  return sorted(heapq.nlargest(n, xs))


Solve in Python:
Write a program that prints a chessboard with N rows and M columns with the following rules:
The top left cell must be an asterisk (*)
Any cell touching (left, right, up or down) a cell with an asterisk must be a dot (.)
Any cell touching (left, right, up or down) a cell with a dot must be an asterisk.

A chessboard of 8 rows and 8 columns printed using these rules would be:
```
*.*.*.*.
.*.*.*.*
*.*.*.*.
.*.*.*.*
*.*.*.*.
.*.*.*.*
*.*.*.*.
.*.*.*.*
```
Input

A single line with two integers N and M separated by space. The number N will represent the number of rows and M the number of columns.

Output

Return N lines each containing M characters with the chessboard pattern.
Empty string if N, M or both are 0.

From: 2016 AIPO National Finals
http://aipo.computing.dcu.ie/2016-aipo-national-finals-problems

def chessboard(s):m,n=map(int,s.split());return'\n'.join(('*.'*n)[i%2:n+i%2]for i in range(m))


Solve in Python:
Write a program that reads numbers until -1 is not given.
The program finds how many of the given numbers are more than 30, $N$.
It also finds the average weighted sum of even numbers, $A$.
The weight of the $i$th number is defined as the position of the number (1 based indexing) times the number. To find the average weighted sum, you need to add all these weights for the even numbers, then divide the sum by the sum of the positions of the numbers.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains some numbers, terminated by -1

-----Output:-----
For each testcase, output in a single line the count of numbers that are greater than 30, $N$, and the average weighted sum of the even numbers, $A$, separated by a space. Make sure to set the precision of the average weighted sum to 2 places after the decimal point.

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N \leq 1000$

-----Sample Input:-----
1
33 100 77 42 12 -1

-----Sample Output:-----
4 38.91

-----EXPLANATION:-----
In the series of numbers 33 100 77 42 12 -1, the count of numbers greater than 30 is 4
The average weighted sum of the even numbers is given by:
((2 * 100) + (4 * 42) + (5 * 12)) / (2 + 4 + 5)

for i in range(int(input())):
    c = 0
    arr = list(map(int,input().split()))
    for k in arr:
        if k==-1:
            break
            arr.append(a)
        if k >30:
            c=c+1
    num = 0
    den = 0
    for i in range(0,len(arr)):
        if arr[i]%2==0:
            num = num + arr[i]*(i+1)
            den = den + i + 1
    print(c, "{:.2f}".format(num/den))


Solve in Python:
Write a program that reads two numbers $X$ and $K$. The program first finds the factors of $X$ and then gives the sum of $K$th power of every factor. The program also finds the factor of $k$ and outputs the sum of $X$ times of every factor.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, two integers $X, R$.

-----Output:-----
For each testcase, output in a single line the factors of $X$ and the $K$th power of every factor, seperated by a space.

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq X, K \leq 10^9$

-----Sample Input:-----
1
8 6

-----Sample Output:-----
266304 88

-----EXPLANATION:-----
Factors of x = 8 are 2, 4, and 8. Also, factors of k = 6 are 2, 3, and 6.
2^6 + 4^6 + 8^6 = 266304 and 2 × 8 + 3 × 8 + 6 × 8 = 88.
(Where a ^b denotes a raised to the power of b).

for _ in range(int(input())):
    x,k=map(int,input().split(" "))
    s=0
    for i in range(2,x+1):
        if x%i==0:
            s+=(i**k)
    s1=0
    for i in range(2,k+1):
        if k%i==0:
            s1+=(i*x)
    print(s,s1)


Solve in Python:
Write a program that takes in a letterclass ID of a ship and display the equivalent string class description of the given ID. Use the table below.

Class ID Ship ClassB or bBattleShipC or cCruiserD or dDestroyerF or fFrigate

-----Input-----

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

-----Output-----
For each test case, display the Ship Class depending on ID, in a new line.

-----Constraints-----
- 1 ≤ T ≤ 1000

-----Example-----
Input

3
B
c
D

Output
BattleShip
Cruiser
Destroyer

t = int(input())

for i in range(t):
    num = (input())
    if (num == "B" or num == "b"):
        print("BattleShip")
    elif (num == "C" or num == "c"):
        print("Cruiser")
    elif (num == "D" or num == "d"):
        print("Destroyer")
    elif (num == "F" or num == "f" ):
        print("Frigate")


Solve in Python:
Write a program that will calculate the number of trailing zeros in a factorial of a given number.

`N! = 1 * 2 * 3 *  ... * N`

Be careful `1000!` has 2568 digits...

For more info, see: http://mathworld.wolfram.com/Factorial.html

## Examples

```python
zeros(6) = 1
# 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero

zeros(12) = 2
# 12! = 479001600 --> 2 trailing zeros
```

*Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.*

def zeros(n):
    # find the exponent of a prime factor p in the prime factorization of n!
    def find_exponent(n,p):
        factor = 0
        p_helper = p
        while n>p_helper:
            factor += int(n/p_helper)
            p_helper *= p
        return factor

    five_exponent = find_exponent(n,5)

    return five_exponent


Solve in Python:
Write a program that will take a string of digits and give you all the possible consecutive slices of length `n` in that string.

Raise an error if `n` is larger than the length of the string.

## Examples

For example, the string `"01234"` has the following 2-digit slices:
```
[0, 1], [1, 2], [2, 3], [3, 4]
```

The same string has the following 4-digit slices:
```
[0, 1, 2, 3], [1, 2, 3, 4]
```

def series_slices(digits, n):
    if n > len(digits):
        raise ValueError
    else:
        return [[int(digit) for digit in digits[i:i+n]] for i in range(0, len(digits)-n+1)]