description
stringlengths 38
154k
| category
stringclasses 5
values | solutions
stringlengths 13
289k
| name
stringlengths 3
179
| id
stringlengths 24
24
| tags
listlengths 0
13
| url
stringlengths 54
54
| rank_name
stringclasses 8
values |
|---|---|---|---|---|---|---|---|
## Task
You are watching a volleyball tournament, but you missed the beginning of the very first game of your favorite team. Now you're curious about how the coach arranged the players on the field at the start of the game.
The team you favor plays in the following formation:
```
0 3 0
4 0 2
0 6 0
5 0 1
```
where positive numbers represent positions occupied by players. After the team gains the serve, its members rotate one position in a clockwise direction, so the player in position 2 moves to position 1, the player in position 3 moves to position 2, and so on, with the player in position 1 moving to position 6.
Here's how the players change their positions:

Given the current `formation` of the team and the number of times `k` it gained the serve, find the `initial position` of each player in it.
## Example
For
```
formation = [["empty", "Player5", "empty"],
["Player4", "empty", "Player2"],
["empty", "Player3", "empty"],
["Player6", "empty", "Player1"]]
and k = 2
```
the output should be
```
[
["empty", "Player1", "empty"],
["Player2", "empty", "Player3"],
["empty", "Player4", "empty"],
["Player5", "empty", "Player6"]
]
```
For
```
formation = [["empty", "Alice", "empty"],
["Bob", "empty", "Charlie"],
["empty", "Dave", "empty"],
["Eve", "empty", "Frank"]]
and k = 6
```
the output should be
```
[
["empty", "Alice", "empty"],
["Bob", "empty", "Charlie"],
["empty", "Dave", "empty"],
["Eve", "empty", "Frank"]
]
```
## Input
- 2D string array `formation`
A `4 × 3` array of strings representing names of the players in the positions corresponding to those in the schema above.
It is guaranteed that for each empty position the corresponding element of formation is "empty".
It is also guaranteed that there is no player called "empty" in the team.
- Integer `k`
The number of times the team gained the serve.
Constraints: `0 ≤ k ≤ 1000000000.`
## Output
- 2D string array
Team arrangement at the start of the game.
|
games
|
from collections import deque
POS = [(3, 2), (1, 2), (0, 1), (1, 0), (3, 0), (2, 1)]
def volleyball_positions(formation, k):
players = deque([formation[x][y] for x, y in POS])
players . rotate(k % 6)
baseForm = [l[:] for l in formation]
for i, (x, y) in enumerate(POS):
baseForm[x][y] = players[i]
return baseForm
|
Simple Fun #58: Volleyball Positions
|
5889f08eb71a7dcee600006c
|
[
"Puzzles"
] |
https://www.codewars.com/kata/5889f08eb71a7dcee600006c
|
6 kyu
|
# Task
Define crossover operation over two equal-length strings A and B as follows:
the result of that operation is a string of the same length as the input strings result[i] is chosen at random between A[i] and B[i].
Given array of strings `arr` and a string result, find for how many pairs of strings from `arr` the result of the crossover operation over them may be equal to result.
Note that (A, B) and (B, A) are the same pair. Also note that the pair cannot include the same element of the array twice (however, if there are two equal elements in the array, they can form a pair).
# Example
For `arr = ["abc", "aaa", "aba", "bab"]` and `result = "bbb"`, the output should be `2`.
```
"abc" and "bab" can crossover to "bbb"
"aba" and "bab" can crossover to "bbb"
```
# Input/Output
- `[input]` string array `arr`
A non-empty array of equal-length strings.
Constraints: `2 ≤ arr.length ≤ 10, 1 ≤ arr[i].length ≤ 10.`
- `[input]` string `result`
A string of the same length as each of the arr elements.
Constraints: `result.length = arr[i].length.`
- `[output]` an integer
|
games
|
from itertools import combinations
def strings_crossover(arr, result):
return sum(1 for s1, s2 in combinations(arr, 2) if all(r in (x, y) for x, y, r in zip(s1, s2, result)))
|
Simple Fun #54: Strings Crossover
|
5889902f53ad4a227100003f
|
[
"Puzzles"
] |
https://www.codewars.com/kata/5889902f53ad4a227100003f
|
6 kyu
|
Each exclamation mark's weight is 2; each question mark's weight is 3. Putting two strings `left` and `right` on the balance - are they balanced?
If the left side is more heavy, return `"Left"`; if the right side is more heavy, return `"Right"`; if they are balanced, return `"Balance"`.
## Examples
```python
"!!", "??" --> "Right"
"!??", "?!!" --> "Left"
"!?!!", "?!?" --> "Left"
"!!???!????", "??!!?!!!!!!!" --> "Balance"
```
```haskell
-- For Haskell use the Comparison type defined in Preloaded code
-- data Comparison = Left | Right | Balance deriving (Show, Eq, Enum, Bounded)
balance :: String -> String -> Comparison
balance "!!" "??" == Right
balance "!??" "?!!" == Left
balance "!?!!" "?!?" == Left
balance "!!???!????" "??!!?!!!!!!!" == Balance
```
|
reference
|
def balance(left, right):
left_count = left . count("!") * 2 + left . count("?") * 3
right_count = right . count("!") * 2 + right . count("?") * 3
if (left_count > right_count):
return "Left"
elif (right_count > left_count):
return "Right"
else:
return "Balance"
|
Exclamation marks series #17: Put the exclamation marks and question marks on the balance - are they balanced?
|
57fb44a12b53146fe1000136
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/57fb44a12b53146fe1000136
|
6 kyu
|
# Task
`EvilCode` is a game similar to `Codewars`. You have to solve programming tasks as quickly as possible. However, unlike `Codewars`, `EvilCode` awards you with a medal, depending on the time you took to solve the task.
To get a medal, your time must be (strictly) inferior to the time corresponding to the medal. You can be awarded `"Gold", "Silver" or "Bronze"` medal, or `"None"` medal at all. Only one medal (the best achieved) is awarded.
You are given the time achieved for the task and the time corresponding to each medal. Your task is to return the awarded medal.
Each time is given in the format `HH:MM:SS`.
# Input/Output
`[input]` string `userTime`
The time the user achieved.
`[input]` string `gold`
The time corresponding to the gold medal.
`[input]` string `silver`
The time corresponding to the silver medal.
`[input]` string `bronze`
The time corresponding to the bronze medal.
It is guaranteed that `gold < silver < bronze`.
`[output]` a string
The medal awarded, one of for options: `"Gold", "Silver", "Bronze" or "None"`.
# Example
For
```
userTime = "00:30:00", gold = "00:15:00",
silver = "00:45:00" and bronze = "01:15:00"```
the output should be `"Silver"`
For
```
userTime = "01:15:00", gold = "00:15:00",
silver = "00:45:00" and bronze = "01:15:00"```
the output should be `"None"`
# For Haskell version
```
In Haskell, the result is a Maybe, returning Just String indicating
the medal if they won or Nothing if they don't.
```
|
games
|
def evil_code_medal(user_time, gold, silver, bronze):
for medal, time in [["Gold", gold], ["Silver", silver], ["Bronze", bronze]]:
if user_time < time:
return medal
return "None"
|
Simple Fun #270: Evil Code Medal
|
5915686ed2563aa6650000ab
|
[
"Puzzles"
] |
https://www.codewars.com/kata/5915686ed2563aa6650000ab
|
7 kyu
|
# Description:
Remove the minimum number of exclamation marks from the start/end of each word in the sentence to make their amount equal on both sides.
### Notes:
* Words are separated with spaces
* Each word will include at least 1 letter
* There will be no exclamation marks in the middle of a word
___
## Examples
```
remove("Hi!") === "Hi"
remove("!Hi! Hi!") === "!Hi! Hi"
remove("!!Hi! !Hi!!") === "!Hi! !Hi!"
remove("!!!!Hi!! !!!!Hi !Hi!!!") === "!!Hi!! Hi !Hi!"
```
|
reference
|
def remove(s): return ' ' . join(
r for r, _ in __import__('re'). findall(r'((!*)\w+\2)', s))
|
Exclamation marks series #10: Remove some exclamation marks to keep the same number of exclamation marks at the beginning and end of each word
|
57fb04649610ce369a0006b8
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/57fb04649610ce369a0006b8
|
6 kyu
|
# Task
You are given `N` ropes, where the length of each rope is a positive integer. At each step, you have to reduce all the ropes by the length of the smallest rope.
The step will be repeated until no ropes are left. Given the length of N ropes, print the number of ropes that are left before each step.
# Example
For `a = [3, 3, 2, 9, 7]`, the result should be `[5, 4, 2, 1]`
```
You have 5 ropes:
3 3 2 9 7 ( 5 left)
step 1: 1 1 0 7 5 ( 4 left)
step 2: 0 0 0 6 4 ( 2 left)
step 3: 0 0 0 0 2 ( 1 left)
step 4: 0 0 0 0 0
Hence the result is [5, 4, 2, 1]
```
# Input/Output
- `[input]` integer array `a`
length of each rope.
`3 <= a.length <= 2000`
`1 <= a[i] <= 100`
- `[output]` an integer array
number of ropes before each step.
|
algorithms
|
def cut_the_ropes(a):
if not a:
return []
m = min(a)
return [len(a)] + cut_the_ropes([x - m for x in a if x > m])
|
Simple Fun #160: Cut The Ropes
|
58ad388555bf4c80e800001e
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58ad388555bf4c80e800001e
|
6 kyu
|
Mr. Odd is my friend. Some of his common dialogues are: _"Am I looking odd?", "It’s looking very odd",_ etc. Actually, "odd" is his favorite word. This Valentine's Day he went to meet his girlfriend, but he forgot to take a gift. So he told her that he did an _odd_ thing. His girlfriend became angry and gave him a puzzle. She gave him a string (`str`) that contains only lowercase letters and told him:
> _Take 3 indexes `i, j, k` such that `i < j < k` and `str[i] = "o", str[j] = "d", str[k] = "d"` and **cut them from the string** to make a new string `"odd"`. How many such new strings can you make?_
Mr. Odd wants to impress his girlfriend, so he wants to make the maximum number of `"odd"` strings. As he is lazy, he asks you to help him and find the possible maximum.
## Examples
For `"oudddbo"` the result should be 1:
* cut one `"odd"`: `"[o]u[d][d]dbo" --> "_u__dbo"`
* no more `"odd"` in string
For `"ooudddbd"` the result should be 2:
* 1: `"[o]ou[d][d]dbd" --> "_ou__dbd"`
* 2: `"_[o]u__[d]b[d]" --> "__u___b_"`
* no more `"odd"` in string
## Input/Output
- `[input]` string `str`: a non-empty string that contains only lowercase letters, `0 < str.length <= 10 000`
- `[output]` an integer: the maximum number of `"odd"` that can be cut
|
games
|
import re
pattern = re . compile('o(.*?)d(.*?)d')
def odd(s):
n = 0
while pattern . search(s):
n += 1
s = pattern . sub(r'\1\2', s, count=1)
return n
|
Simple Fun #121: Mr. Odd
|
589d74722cae97a7260000d9
|
[
"Puzzles"
] |
https://www.codewars.com/kata/589d74722cae97a7260000d9
|
6 kyu
|
### Longest Palindrome
Find the length of the longest substring in the given string `s` that is the same in reverse.
As an example, if the input was “I like racecars that go fast”, the substring (`racecar`) length would be `7`.
If the length of the input string is `0`, the return value must be `0`.
### Example:
```
"a" -> 1
"aab" -> 2
"abcde" -> 1
"zzbaabcd" -> 4
"" -> 0
```
|
reference
|
def longest_palindrome(s):
"""Manacher algorithm - Complexity O(n)"""
# Transform S into T.
# For example, S = "abba", T = "^#a#b#b#a#$".
# ^ and $ signs are sentinels appended to each end to avoid bounds checking
T = '#' . join('^{}$' . format(s))
n = len(T)
P = [0] * n
C = R = 0
for i in range(1, n - 1):
P[i] = (R > i) and min(R - i, P[2 * C - i]) # equals to i' = C - (i-C)
# Attempt to expand palindrome centered at i
while T[i + 1 + P[i]] == T[i - 1 - P[i]]:
P[i] += 1
# If palindrome centered at i expand past R,
# adjust center based on expanded palindrome.
if i + P[i] > R:
C, R = i, i + P[i]
# Find the maximum element in P.
maxLen, centerIndex = max((n, i) for i, n in enumerate(P))
return maxLen
|
longest_palindrome
|
54bb6f887e5a80180900046b
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/54bb6f887e5a80180900046b
|
6 kyu
|
# Task
The sequence of `Chando` is an infinite sequence of all Chando's numbers in ascending order.
A number is called `Chando's` if it is an integer that can be represented as a sum of different positive integer powers of 5.
The first Chando's numbers is 5 (5^1). And the following n<sup>th</sup> Chando's numbers are:
```
25 (5^2)
30 (5^1 + 5^2)
125 (5^3)
130 (5^1 + 5^3)
150 (5^2 + 5^3)
...
...
```
Your task is to find the Chando's n<sup>th</sup> number for a given `n`.
# Input/Output
- `[input]` integer `n`
`1 <= n <= 7000`
- `[output]` an integer
n<sup>th</sup> Chando's number
|
algorithms
|
def nth_chandos_number(n):
return int((bin(n) + "0")[2:], 5)
|
Simple Fun #146: Chandos Number
|
58aa8368ae929ea2e00000d9
|
[
"Algorithms",
"Number Theory"
] |
https://www.codewars.com/kata/58aa8368ae929ea2e00000d9
|
6 kyu
|
Removed due to copyright infringement.
<!---
# Task
Given the positions of a white `bishop` and a black `pawn` on the standard chess board, determine whether the bishop can capture the pawn in one move.
The `bishop` has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move:

# Example
For `bishop = "a1" and pawn = "c3"`, the output should be `true`.

For `bishop = "h1" and pawn = "h3"`, the output should be `false`.

# Input/Output
- `[input]` string `bishop`
Coordinates of the white bishop in the chess notation.
- `[input]` string `pawn`
Coordinates of the black pawn in the same notation.
- `[output]` a boolean value
`true` if the bishop can capture the pawn, `false` otherwise.
--->
|
games
|
def bishop_and_pawn(bishop, pawn):
return abs(ord(bishop[0]) - ord(pawn[0])) == abs(int(bishop[1]) - int(pawn[1]))
|
Chess Fun #2: Bishop And Pawn
|
589425c2561a35dd1a0000a2
|
[
"Puzzles",
"Games"
] |
https://www.codewars.com/kata/589425c2561a35dd1a0000a2
|
6 kyu
|
Removed due to copyright infringement.
<!---
# Task
In the Land Of Chess, bishops don't really like each other. In fact, when two bishops happen to stand on the same diagonal, they immediately rush towards the opposite ends of that same diagonal.
Given the initial positions (in chess notation) of two bishops, `bishop1` and `bishop2`, calculate their future positions. Keep in mind that bishops won't move unless they see each other along the same diagonal.
# Example
For `bishop1 = "d7" and bishop2 = "f5"`, the output should be `["c8", "h3"]`.

For `bishop1 = "d8" and bishop2 = "b5"`, the output should be `["b5", "d8"]`.
The bishops don't belong to the same diagonal, so they don't move.

# Input/Output
- `[input]` string `bishop1`
Coordinates of the first bishop in chess notation.
- `[input]` string `bishop2`
Coordinates of the second bishop in the same notation.
- `[output]` a string array
Coordinates of the bishops in lexicographical order after they check the diagonals they stand on.
--->
|
games
|
def bishop_diagonal(a, b):
a, b = sorted([['abcdefgh' . index(f), '12345678' . index(r)]
for f, r in [a, b]])
m = int((b[1] - a[1]) / (b[0] - a[0])) if abs(a[1] - b[1]
) == abs(a[0] - b[0]) and abs(a[1] - b[1]) else 0
if m:
while all(0 < e < 7 for e in a):
a = [a[0] - 1, a[1] - m]
while all(0 < e < 7 for e in b):
b = [b[0] + 1, b[1] + m]
return ['abcdefgh' [c] + '12345678' [r] for c, r in [a, b]]
|
Chess Fun #4: Bishop Diagonal
|
5897e394fcc4b9c310000051
|
[
"Puzzles",
"Games"
] |
https://www.codewars.com/kata/5897e394fcc4b9c310000051
|
5 kyu
|
Among the ruins of an ancient city a group of archaeologists found a mysterious function with lots of HOLES in it called ```getNum(n)``` (or `get_num(n)` in ruby, python, or r). They tried to call it with some arguments. And finally they got this journal:
```javascript
getNum(300) #-> returns 2
getNum(90783) #-> returns 4
getNum(123321) #-> returns 0
getNum(89282350306) #-> returns 8
getNum(3479283469) #-> returns 5
```
```haskell
getNum 300 `shouldBe` 2
getNum 90783 `shouldBe` 4
getNum 123321 `shouldBe` 0
getNum 89282350306 `shouldBe` 8
getNum 3479283469 `shouldBe` 5
```
```r
get_num(300)
[1] 2
get_num(90783)
[1] 4
get_num(123321)
[1] 0
get_num(89282350306)
[1] 8
get_num(3479283469)
[1] 5
```
The archaeologists were totally stuck with this challenge. They were all in desperation but then.... came YOU the SUPER-AWESOME programmer. Will you be able to understand the mystery of this function and rewrite it?
|
games
|
def get_num(n):
return sum({'0': 1, '6': 1, '9': 1, '8': 2}. get(d, 0) for d in str(n))
|
Mysterious function
|
55217af7ecb43366f8000f76
|
[
"Puzzles"
] |
https://www.codewars.com/kata/55217af7ecb43366f8000f76
|
6 kyu
|
# Task
You are given a square that has a height of `n`.
Each `1 × 1` square has two diagonals as shown below:

Count the number of triangles formed by the squares sides and diagonals.
# Input/Output
`[input]` integer `n`
`1 ≤ n ≤ 100`
`[output]` an integer
The number of triangles.
# Example
For `n = 1`, the output shoule be `8`.
There are `4` small triangles (one at each side of the square) and `4` large ones, each consists of two small triangles. `4 + 4 = 8`
|
games
|
def count_triangles(n):
return [8, 44, 124, 268, 492, 816, 1256, 1832, 2560, 3460, 4548, 5844, 7364, 9128, 11152, 13456, 16056, 18972, 22220, 25820, 29788, 34144, 38904, 44088, 49712, 55796, 62356, 69412, 76980, 85080, 93728, 102944, 112744, 123148, 134172, 145836, 158156, 171152, 184840, 199240, 214368, 230244, 246884, 264308, 282532, 301576, 321456, 342192, 363800, 386300, 409708, 434044, 459324, 485568, 512792, 541016, 570256, 600532, 631860, 664260, 697748, 732344, 768064, 804928, 842952, 882156, 922556, 964172, 1007020, 1051120, 1096488, 1143144, 1191104, 1240388, 1291012, 1342996, 1396356, 1451112, 1507280, 1564880, 1623928, 1684444, 1746444, 1809948, 1874972, 1941536, 2009656, 2079352, 2150640, 2223540, 2298068, 2374244, 2452084, 2531608, 2612832, 2695776, 2780456, 2866892, 2955100, 3045100, 3136908][n-1]
|
Simple Fun #267: Count Triangles
|
5913ffb2cb1475215c000039
|
[
"Puzzles"
] |
https://www.codewars.com/kata/5913ffb2cb1475215c000039
|
6 kyu
|
# Task
`Triangular numbers` are defined by the formula `n * (n + 1) / 2` with `n` starting from 1. They count the number of objects that can form an equilateral triangle as shown in the picture below:

So the sequence of triangular numbers begins as follows:
`1, 3, 6, 10, 15, 21, 28, ....`
It is proven that the sum of squares of any two consecutive triangular numbers is equal to another triangular number.
You're given a triangular number `n`. Return `true` if it can be represented as `a sum of squares of two consecutive triangular numbers`, or `false` otherwise.
# Input/Output
`[input]` integer `n`
A positive triangular number
`3 ≤ n ≤ 10^9`
`[output]` a boolean value
`true` if it is possible to represent n as the sum of squares of two consecutive triangular numbers, and `false` otherwise.
# Example
For `n = 6`, the output should be `false`.
No two squared consecutive triangular numbers add up to 6.
For `n = 45`, the output should be `true`.
`3 * 3 + 6 * 6 = 9 + 36 = 45`
|
games
|
from math import sqrt
def triangular_sum(n):
return sqrt(2 * (sqrt(8 * n + 1) - 1)) % 2 == 0
|
Simple Fun #268: Triangular Sum
|
591404294ef3051cbe000035
|
[
"Puzzles"
] |
https://www.codewars.com/kata/591404294ef3051cbe000035
|
6 kyu
|
# Task
For the given set `S` its powerset is the set of all possible subsets of `S`.
Given an array of integers nums, your task is to return the powerset of its elements.
Implement an algorithm that does it in a depth-first search fashion. That is, for every integer in the set, we can either choose to take or not take it. At first, we choose `NOT` to take it, then we choose to take it(see more details in exampele).
# Example
For `nums = [1, 2]`, the output should be `[[], [2], [1], [1, 2]].`
Here's how the answer is obtained:
```
don't take element 1
----don't take element 2
--------add []
----take element 2
--------add [2]
take element 1
----don't take element 2
--------add [1]
----take element 2
--------add [1, 2]
```
For `nums = [1, 2, 3]`, the output should be
`[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]`.
# Input/Output
`[input]` integer array `nums`
Array of positive integers, `1 ≤ nums.length ≤ 10`.
[output] 2D integer array
The powerset of nums.
|
algorithms
|
def powerset(nums):
if not nums:
return [[]]
l = powerset(nums[1:])
a = nums[0]
return l + [[a] + q for q in l]
|
Simple Fun #273: Powerset
|
59157809f05d9a8ad7000096
|
[
"Algorithms"
] |
https://www.codewars.com/kata/59157809f05d9a8ad7000096
|
5 kyu
|
### Task
Given a fair dice that you can throw an unlimited number of times and a number `n`, find the number of ways to throw the dice so that the sum of the dots on its upper surface equals `n`.
### Input/Output
`[input]` integer `n`
The sum of dots, `1 ≤ n ≤ 50`.
`[output]` an integer
The number of ways to throw the dice.
### Example
For `n = 2`, the output should be `2`.
There are two ways to throw the dice:
```
1, 1;
2.
```
For `n = 4`, the output should be `8`.
The ways to throw the dice are:
```
1, 1, 1, 1;
1, 1, 2;
1, 2, 1;
2, 1, 1;
2, 2;
1, 3;
3, 1;
4.
```
|
reference
|
from functools import cache
# Basically fibonacci with the previous 6
@ cache
def throwing_dice(n):
return n == 0 or sum(map(throwing_dice, range(max(0, n - 6), n)))
|
Simple Fun #272: Throwing Dice
|
591575f6d64db0431c000009
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/591575f6d64db0431c000009
|
5 kyu
|
No Story
No Description
Only by Thinking and Testing
Look at result of testcase, guess the code!
# #Series:<br>
<a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br>
<a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br>
<a href="http://www.codewars.com/kata/56d931ecc443d475d5000003">03:True or False</a><br>
<a href="http://www.codewars.com/kata/56d93f249c844788bc000002">04:Something capitalized</a><br>
<a href="http://www.codewars.com/kata/56d949281b5fdc7666000004">05:Uniq or not Uniq</a> <br>
<a href="http://www.codewars.com/kata/56d98b555492513acf00077d">06:Spatiotemporal index</a><br>
<a href="http://www.codewars.com/kata/56d9b46113f38864b8000c5a">07:Math of Primary School</a><br>
<a href="http://www.codewars.com/kata/56d9c274c550b4a5c2000d92">08:Math of Middle school</a><br>
<a href="http://www.codewars.com/kata/56d9cfd3f3928b4edd000021">09:From nothingness To nothingness</a><br>
<a href="http://www.codewars.com/kata/56dae2913cb6f5d428000f77">10:Not perfect? Throw away!</a> <br>
<a href="http://www.codewars.com/kata/56db19703cb6f5ec3e001393">11:Welcome to take the bus</a><br>
<a href="http://www.codewars.com/kata/56dc41173e5dd65179001167">12:A happy day will come</a><br>
<a href="http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356">13:Sum of 15(Hetu Luosliu)</a><br>
<a href="http://www.codewars.com/kata/56dd3dd94c9055a413000b22">14:Nebula or Vortex</a><br>
<a href="http://www.codewars.com/kata/56dd927e4c9055f8470013a5">15:Sport Star</a><br>
<a href="http://www.codewars.com/kata/56de38c1c54a9248dd0006e4">16:Falsetto Rap Concert</a><br>
<a href="http://www.codewars.com/kata/56de4d58301c1156170008ff">17:Wind whispers</a><br>
<a href="http://www.codewars.com/kata/56de82fb9905a1c3e6000b52">18:Mobile phone simulator</a><br>
<a href="http://www.codewars.com/kata/56dfce76b832927775000027">19:Join but not join</a><br>
<a href="http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7">20:I hate big and small</a><br>
<a href="http://www.codewars.com/kata/56e0e065ef93568edb000731">21:I want to become diabetic ;-)</a><br>
<a href="http://www.codewars.com/kata/56e0f1dc09eb083b07000028">22:How many blocks?</a><br>
<a href="http://www.codewars.com/kata/56e1161fef93568228000aad">23:Operator hidden in a string</a><br>
<a href="http://www.codewars.com/kata/56e127d4ef93568228000be2">24:Substring Magic</a><br>
<a href="http://www.codewars.com/kata/56eccc08b9d9274c300019b9">25:Report about something</a><br>
<a href="http://www.codewars.com/kata/56ee0448588cbb60740013b9">26:Retention and discard I</a><br>
<a href="http://www.codewars.com/kata/56eee006ff32e1b5b0000c32">27:Retention and discard II</a><br>
<a href="http://www.codewars.com/kata/56eff1e64794404a720002d2">28:How many "word"?</a><br>
<a href="http://www.codewars.com/kata/56f167455b913928a8000c49">29:Hail and Waterfall</a><br>
<a href="http://www.codewars.com/kata/56f214580cd8bc66a5001a0f">30:Love Forever</a><br>
<a href="http://www.codewars.com/kata/56f25b17e40b7014170002bd">31:Digital swimming pool</a><br>
<a href="http://www.codewars.com/kata/56f4202199b3861b880013e0">32:Archery contest</a><br>
<a href="http://www.codewars.com/kata/56f606236b88de2103000267">33:The repair of parchment</a><br>
<a href="http://www.codewars.com/kata/56f6b4369400f51c8e000d64">34:Who are you?</a><br>
<a href="http://www.codewars.com/kata/56f7eb14f749ba513b0009c3">35:Safe position</a><br>
<br>
# #Special recommendation
Another series, innovative and interesting, medium difficulty. People who like to challenge, can try these kata:
<a href="http://www.codewars.com/kata/56c85eebfd8fc02551000281">Play Tetris : Shape anastomosis</a><br>
<a href="http://www.codewars.com/kata/56cd5d09aa4ac772e3000323">Play FlappyBird : Advance Bravely</a><br>
|
games
|
time_units = {'ms': 1, 's': 1000, 'm': 60000, 'h': 3600000, 'd': 86400000}
dist_units = {'mm': 1, 'cm': 10, 'dm': 100, 'm': 1000, 'km': 1000000}
def testit(a):
if all(unit(x) in time_units for x in a):
return sorted(a, key=lambda x: val(x) * time_units[unit(x)])
if all(unit(x) in dist_units for x in a):
return sorted(a, key=lambda x: val(x) * dist_units[unit(x)])
def unit(x):
return '' . join(filter(str . isalpha, x))
def val(x):
return int('' . join(filter(str . isdigit, x)))
|
Thinking & Testing : Spatiotemporal index
|
56d98b555492513acf00077d
|
[
"Puzzles",
"Arrays"
] |
https://www.codewars.com/kata/56d98b555492513acf00077d
|
6 kyu
|
## Task
Complete function `splitOddAndEven`, accept a number `n`(n>0), return an array that contains the continuous parts of odd or even digits.
Please don't worry about digit `0`, it won't appear ;-)
## Examples
```javascript
splitOddAndEven(123) === [1,2,3]
splitOddAndEven(223) === [22,3]
splitOddAndEven(111) === [111]
splitOddAndEven(13579) === [13579]
splitOddAndEven(135246) === [135,246]
splitOddAndEven(123456) === [1,2,3,4,5,6]
```
|
games
|
from itertools import groupby
def split_odd_and_even(n):
return [int("" . join(g))
for i, g in groupby(str(n), key=lambda x: int(x) % 2)]
|
T.T.T.17: Split odd and even
|
57a2ab1abb994466910003af
|
[
"Puzzles",
"Games"
] |
https://www.codewars.com/kata/57a2ab1abb994466910003af
|
6 kyu
|
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
* 232
* 110011
* 54322345
Complete the function to test if the given number (`num`) **can be <u>rearranged</u>** to form a numerical palindrome or not. Return a boolean (`true` if it can be rearranged to a palindrome, and `false` if it cannot). Return `"Not valid"` if the input is not an integer or is less than 0.
For this kata, single digit numbers are **NOT** considered numerical palindromes.
## Examples
```
5 => false
2121 => true
1331 => true
3357665 => true
1294 => false
"109982" => "Not valid"
-42 => "Not valid"
```
~~~if:cobol
In COBOL, `num` will always be an integer. Assign `0` to result if `num` is negative or if its digits cannot be rearranged to a palindrome, otherwise `1`.
~~~
## Other Kata in this Series:
<a href="https://www.codewars.com/kata/58ba6fece3614ba7c200017f">Numerical Palindrome #1</a>
<br><a href="https://www.codewars.com/kata/numerical-palindrome-number-1-dot-5">Numerical Palindrome #1.5</a>
<br><a href="https://www.codewars.com/kata/58de819eb76cf778fe00005c">Numerical Palindrome #2</a>
<br><a href="https://www.codewars.com/kata/58df62fe95923f7a7f0000cc">Numerical Palindrome #3</a>
<br><a href="https://www.codewars.com/kata/58e2708f9bd67fee17000080">Numerical Palindrome #3.5</a>
<br><a href="https://www.codewars.com/kata/58df8b4d010a9456140000c7">Numerical Palindrome #4</a>
<br><b>Numerical Palindrome #5</b>
|
reference
|
def palindrome(num):
s = str(num)
if not isinstance(num, int) or num < 0:
return "Not valid"
return num > 9 and sum(s . count(x) % 2 for x in set(s)) < 2
|
Numerical Palindrome #5
|
58e26b5d92d04c7a4f00020a
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/58e26b5d92d04c7a4f00020a
|
6 kyu
|
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: `2332, 110011, 54322345`
For a given number ```num```, write a function which returns an array of all the numerical palindromes contained within each number. The array should be sorted in ascending order and any duplicates should be removed.
In this kata, <font color="red">single digit numbers</font> and <font color="red">numbers which start or end with zeros</font> (such as `010` and `00`) are **NOT** considered valid numerical palindromes.
If `num` contains no valid palindromes, return `"No palindromes found"`.
Otherwise, return `"Not valid"` if the input is not an integer or is less than `0`.
## Examples
```
palindrome(1221) => [22, 1221]
palindrome(34322122) => [22, 212, 343, 22122]
palindrome(1001331) => [33, 1001, 1331]
palindrome(1294) => "No palindromes found"
palindrome("1221") => "Not valid"
```
~~~if:cobol
In COBOL, `num` will always be an integer. Return a table of all numerical palindromes found (empty table if no palindrome was found or `num` is negative).
~~~
---
### Other Kata in this Series:
<a href="https://www.codewars.com/kata/58ba6fece3614ba7c200017f">Numerical Palindrome #1</a>
<br><a href="https://www.codewars.com/kata/numerical-palindrome-number-1-dot-5">Numerical Palindrome #1.5</a>
<br><a href="https://www.codewars.com/kata/58de819eb76cf778fe00005c">Numerical Palindrome #2</a>
<br><a href="https://www.codewars.com/kata/58df62fe95923f7a7f0000cc">Numerical Palindrome #3</a>
<br><b>Numerical Palindrome #3.5</b>
<br><a href="https://www.codewars.com/kata/58df8b4d010a9456140000c7">Numerical Palindrome #4</a>
<br><a href="https://www.codewars.com/kata/numerical-palindrome-number-5-1">Numerical Palindrome #5</a>
|
reference
|
def palindrome(num):
if not isinstance(num, int) or num < 0:
return "Not valid"
n = str(num)
l = len(n)
result = {int(n[i: j]) for i in range(l - 1) for j in range(i +
2, l + 1) if int(n[i]) and n[i: j] == n[i: j][:: - 1]}
return sorted(result) if result else "No palindromes found"
|
Numerical Palindrome #3.5
|
58e2708f9bd67fee17000080
|
[
"Arrays",
"Fundamentals"
] |
https://www.codewars.com/kata/58e2708f9bd67fee17000080
|
6 kyu
|
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
2332
<br>110011
<br>54322345
For a given number ```num```, write a function which returns the number of numerical palindromes within each number. For this kata, single digit numbers will <u>NOT</u> be considered numerical palindromes.
Return "Not valid" if the input is not an integer or is less than 0.
```
palindrome(5) => 0
palindrome(1221) => 2
palindrome(141221001) => 5
palindrome(1294) => 0
palindrome("1221") => "Not valid"
```
~~~if:haskell
In Haskell, return a Maybe Int with Nothing for negative numbers.
~~~
~~~if:cobol
In COBOL, the input will always be an integer. Just assign the number of numerical palindromes contained in `num` to `result` (0 if `num` is negative).
~~~
<h2><u>Other Kata in this Series:</u></h2>
<a href="https://www.codewars.com/kata/58ba6fece3614ba7c200017f">Numerical Palindrome #1</a>
<br><a href="https://www.codewars.com/kata/numerical-palindrome-number-1-dot-5">Numerical Palindrome #1.5</a>
<br><a href="https://www.codewars.com/kata/58de819eb76cf778fe00005c">Numerical Palindrome #2</a>
<br><b>Numerical Palindrome #3</b>
<br><a href="https://www.codewars.com/kata/58e2708f9bd67fee17000080">Numerical Palindrome #3.5</a>
<br><a href="https://www.codewars.com/kata/58df8b4d010a9456140000c7">Numerical Palindrome #4</a>
<br><a href="https://www.codewars.com/kata/58e26b5d92d04c7a4f00020a">Numerical Palindrome #5</a>
|
reference
|
def palindrome(num):
if not isinstance(num, int) or num < 0:
return 'Not valid'
s = str(num)
return sum(sum(s[i: i + n] == s[i: i + n][:: - 1] for i in range(len(s) - n + 1)) for n in range(2, len(s) + 1))
|
Numerical Palindrome #3
|
58df62fe95923f7a7f0000cc
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/58df62fe95923f7a7f0000cc
|
6 kyu
|
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
<p>2332
<br>110011
<br>54322345
For this kata, single digit numbers will <u>not</u> be considered numerical palindromes.
For a given number ```num```, write a function to test if the number <b>contains</b> a numerical palindrome or not and return a boolean (true if it does and false if does not). Return "Not valid" if the input is not an integer or is less than 0.
Note: Palindromes should be found <u>without</u> permutating ```num```.
```
palindrome(5) => false
palindrome(1221) => true
palindrome(141221001) => true
palindrome(1215) => true
palindrome(1294) => false
palindrome("109982") => "Not valid"
```
```haskell
In Haskell, this returns a Maybe Bool, with Nothing for an input less than zero.
```
~~~if:cobol
In COBOL, `num` will always be an integer. Return `1` if it contains a numerical palindrome, otherwise `0`.
~~~
<h2><u>Other Kata in this Series:</u></h2>
<a href="https://www.codewars.com/kata/58ba6fece3614ba7c200017f">Numerical Palindrome #1</a>
<br><a href="https://www.codewars.com/kata/numerical-palindrome-number-1-dot-5">Numerical Palindrome #1.5</a>
<br><b>Numerical Palindrome #2</b>
<br><a href="https://www.codewars.com/kata/58df62fe95923f7a7f0000cc">Numerical Palindrome #3</a>
<br><a href="https://www.codewars.com/kata/58e2708f9bd67fee17000080">Numerical Palindrome #3.5</a>
<br><a href="https://www.codewars.com/kata/58df8b4d010a9456140000c7">Numerical Palindrome #4</a>
<br><a href="https://www.codewars.com/kata/58e26b5d92d04c7a4f00020a">Numerical Palindrome #5</a>
|
reference
|
def palindrome(num):
if type(num) != int or num < 0:
return "Not valid"
s = str(num)
for i in range(len(s) - 2):
if s[i] == s[i + 1] or s[i] == s[i + 2]:
return True
return len(s) != 1 and s[- 1] == s[- 2]
|
Numerical Palindrome #2
|
58de819eb76cf778fe00005c
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/58de819eb76cf778fe00005c
|
6 kyu
|
When we have a 2x2 square matrix we may have up to 24 different ones changing the positions of the elements.
We show some of them
```
a b a b a c a c a d a d b a b a
c d d c d b b d b c c b c d d c
```
You may think to generate the remaining ones until completing the set of 24 matrices.
Given a certain matrix of numbers, that may be repeated or not, calculate the total number of possible matrices that may be generated, changing the position of the elements.
E.g:
Case one
```
A = [[1,2,3],
[3,4,5]] #a 2x3 rectangle matrix with number 3 twice
```
generates a set of ```360``` different matrices
Case two
```
A = [[1,1,1],
[2,2,3],
[3,3,3]]
```
generates a set of ```1260``` different matrices.
Case three
```
A = [[1,2,3],
[4,5,6],
[7,8,9]]
```
generates a set of ```362880``` different matrices
This kata is not meant to apply a brute force algorithm to try to count the total amount of marices.
Features of The Random Tests
```
number of tests = 100
2 ≤ m ≤ 9
2 ≤ n ≤ 9
```
Enjoy it!
Available only in Python 2, Javascript and Ruby by the moment.
|
reference
|
from collections import Counter
from functools import reduce
from math import factorial
from operator import mul
def count_perms(matrix):
return factorial(len(matrix) * len(matrix[0])) / / reduce(mul, map(factorial, Counter(sum(matrix, [])). values()))
|
#6 Matrices: How Many Matrices Do These Elements Produce?
|
59040fdae1bfd334ca00007a
|
[
"Permutations",
"Matrix",
"Data Structures",
"Fundamentals"
] |
https://www.codewars.com/kata/59040fdae1bfd334ca00007a
|
6 kyu
|
# Task
A ciphertext alphabet is obtained from the plaintext alphabet by means of rearranging some characters. For example "bacdef...xyz" will be a simple ciphertext alphabet where a and b are rearranged.
A substitution cipher is a method of encoding where each letter of the plaintext alphabet is replaced with the corresponding (i.e. having the same index) letter of some ciphertext alphabet.
Given two strings, check whether it is possible to obtain them from each other using some (possibly, different) substitution ciphers.
# Example
For `string1 = "aacb" and string2 = "aabc"`, the output should be `true`
Any ciphertext alphabet that starts with acb... would make this transformation possible.
For `string1 = "aa" and string2 = "bc"`, the output should be `false`
# Input/Output
- `[input]` string `string1`
A string consisting of lowercase characters.
Constraints: `1 ≤ string1.length ≤ 10`.
- `[input]` string `string2`
A string consisting of lowercase characters of the same length as string1.
Constraints: `string2.length = string1.length`.
- `[output]` a boolean value
|
games
|
def is_substitution_cipher(s1, s2):
return len(set(s1)) == len(set(s2)) == len(set(zip(s1, s2)))
|
Simple Fun #31: Is Substitution Cipher?
|
58870742c815166a960000af
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58870742c815166a960000af
|
6 kyu
|
# Story
Old MacDingle had a farm.
To be more precise, he had a free-range chicken farm.
But Old MacDingle also had a fox problem.
Foxes ```F``` eat chickens ```C```
At night the only guaranteed "safe" chickens are in their cages ```[]``` (unless a fox has got into the cage with them!)
# Kata Task
Given the initial configuration of foxes and chickens what will the farm look like the next morning after the hungry foxes have been feasting?
# Examples
<table>
<tr><td rowspan=2 valign=top>Ex1<td>Before<td>
<pre style='background:black'>
CCC[CCC]FCC[CCCCC]CFFFF[CCC]FFFF
</pre>
</tr>
<tr><td>After<td>
<pre style='background:black'>
...[CCC]F..[CCCCC].FFFF[CCC]FFFF
</pre>
</tr>
<tr><td rowspan=2 valign=top>Ex2<td>Before<td>
<pre style='background:black'>
...[CCC]...[CCCFC].....[CCC]....
</pre>
</tr>
<tr><td>After<td>
<pre style='background:black'>
...[CCC]...[...F.].....[CCC]....
</pre>
</tr>
<tr><td rowspan=2 valign=top>Ex3<td>Before<td>
<pre style='background:black'>
CCC[CCC]FCC[CCCFC]CFFFF[CCC]FFFF
</pre>
</tr>
<tr><td>After<td>
<pre style='background:black'>
...[CCC]F..[...F.].FFFF[CCC]FFFF
</pre>
</tr>
</table>
# Notes
* Anything not a fox, a chicken, or a cage is just dirt ``.``
* All cages are intact (not open-ended), and there are no cages inside other cages
|
reference
|
import re
CHICKEN, FOX, DIRT = 'CF.'
CAGE = '[{}]'
def hungry_foxes(farm):
parts = re . split(r'[[\]]', farm)
inside, outside = slice(1, None, 2), slice(None, None, 2)
fox_outside = any(FOX in part for part in parts[outside])
parts[outside] = [fox_outside and part . replace(
CHICKEN, DIRT) or part for part in parts[outside]]
parts[inside] = [CAGE . format(FOX in part and part . replace(
CHICKEN, DIRT) or part) for part in parts[inside]]
return '' . join(parts)
|
The Hunger Games - Foxes and Chickens
|
591144f42e6009675300001f
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/591144f42e6009675300001f
|
6 kyu
|
Given a rational number n
``` n >= 0, with denominator strictly positive```
- as a string (example: "2/3" in Ruby, Python, Clojure, JS, CS, Go)
- or as two strings (example: "2" "3" in Haskell, Java, CSharp, C++, Swift, Dart)
- or as a rational or decimal number (example: 3/4, 0.67 in R)
- or two integers (Fortran)
decompose this number as a sum of rationals with numerators equal to one and without repetitions
(2/3 = 1/2 + 1/6 is correct but not 2/3 = 1/3 + 1/3, 1/3 is repeated).
The algorithm must be "greedy", so at each stage the new rational obtained in the decomposition must have a denominator as small as possible.
In this manner the sum of a few fractions in the decomposition gives a rather good approximation of the rational to decompose.
2/3 = 1/3 + 1/3 doesn't fit because of the repetition but also because the first 1/3 has a denominator bigger than the one in 1/2
in the decomposition 2/3 = 1/2 + 1/6.
#### Example:
(You can see other examples in "Sample Tests:")
```
decompose("21/23") or "21" "23" or 21/23 should return
["1/2", "1/3", "1/13", "1/359", "1/644046"] in Ruby, Python, Clojure, JS, CS, Haskell, Go
"[1/2, 1/3, 1/13, 1/359, 1/644046]" in Java, CSharp, C++, Dart
"1/2,1/3,1/13,1/359,1/644046" in C, Swift, R
```
#### Notes
1) The decomposition of 21/23 as
```
21/23 = 1/2 + 1/3 + 1/13 + 1/598 + 1/897
```
is exact but don't fulfill our requirement because 598 is bigger than 359.
Same for
```
21/23 = 1/2 + 1/3 + 1/23 + 1/46 + 1/69 (23 is bigger than 13)
or
21/23 = 1/2 + 1/3 + 1/15 + 1/110 + 1/253 (15 is bigger than 13).
```
2) The rational given to decompose could be greater than one or equal to one, in which case the first "fraction" will be an integer (with an implicit denominator of 1).
3) If the numerator parses to zero the function "decompose" returns [] (or "",, or "[]").
4) The number could also be a decimal which can be expressed as a rational.
#### Example:
`0.6` in Ruby, Python, Clojure,JS, CS, Julia, Go
`"66" "100"` in Haskell, Java, CSharp, C++, C, Swift, Scala, Kotlin, Dart, ...
`0.67` in R.
**Ref:**
http://en.wikipedia.org/wiki/Egyptian_fraction
|
reference
|
from math import ceil
from fractions import Fraction as F
def decompose(n):
f = F(n)
ff = int(f)
result = [str(ff)] if ff else []
f -= ff
while f > 0:
x = F(1, int(ceil(f * * - 1)))
f -= x
result . append(str(x))
return result
|
Some Egyptian fractions
|
54f8693ea58bce689100065f
|
[
"Algorithms",
"Mathematics"
] |
https://www.codewars.com/kata/54f8693ea58bce689100065f
|
5 kyu
|
My name is State Trooper Mark (_"skidmark"_ ) McDingle.
My job is maintaining 117 miles of the Interstate, keeping it clean and clear of dead varmints.
It is a serious job and I take my job seriously.
I am the <span style='color:red;font-size:1.5em;'><b>Road-Kill Detective</b></span>

Every time I find some dead critter I scrape it up and record what type it was in my dead-critter notebook.
Mostly I just cruise up and down the interstate and only find a few racoons or the occasional squirrel...
But recently the road-kill has become much more exotic.
There must be some illegal private zoo back in the woods with a major security problem.
But that's none of my business... Anything beyond the fog-line is out of my jurisdiction.
# <span style='color:red'>Evidence</span>
Here are some photos of what I came across last week:
* There was a thing that looked like a `hyena`
==========h===yyyyyy===eeee=n==a========
* a long black and white smudge that probably once was a `penguin`
======pe====nnnnnn=======================n=n=ng====u==iiii=iii==nn========================n=
* and an unlucky `bear` that was hit going the other direction
=====r=rrr=rra=====eee======bb====b=======
# <span style='color:red'>Kata Task</span>
Even for a professional like me, the identification of flattened exotic animals is not always easy!
If it ever happens that I can't find all of the remains, or if there are gaps or other parts that I don't recognise, then I record it as `??` in my dead-critter notebook.
What I really need is a program that I can scan my photos into which can give back the correct answer straight away.
Something like this:
### Input
* `photo` (not null)
### Output
* the detected animal name, or `??` if unknown<span style='color:red'>^</span>
<hr>
<span style='color:red'>^</span> Note: An array/list of all "known" animals is preloaded in a variable called `ANIMALS` (refer to the initial solution)
|
algorithms
|
from re import match
def road_kill(photo):
remains = photo . replace('=', '')
for animal in ANIMALS:
parts = '^' + '+' . join(c for c in animal) + '+$'
if match(parts, remains) or match(parts, remains[:: - 1]):
return animal
return '??'
|
The Road-Kill Detective
|
58e18c5434a3022d270000f2
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58e18c5434a3022d270000f2
|
5 kyu
|
# Task
In one city it is allowed to write words on the buildings walls. The local janitor, however, doesn't approve of it at all. Every night he vandalizes the writings by erasing all occurrences of some letter. Since the janitor is quite lazy, he wants to do this with just one swipe of his mop.
Given a `word`, find the minimum width of the mop required to erase `each of the letters`.
# Input/Output
`[input]` string `word`
A word consisting of only lowercase English letters.
`5 ≤ word.length ≤ 50`
`[output]` an integer array
An array of length 26. The first element is the minimum width of the mop to erase letter `'a'`, the second - letter `'b'` etc.
# Example
For `word = "abacaba"`, the output should be:
`[7, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`
(26 elements altogether)
First element `7` means: from `first "a"` to `last "a"` need a width of 7.
First element `5` means: from `first "b"` to `last "b"` need a width of 5.
First element `1` means: from `first "c"` to `last "c"` need a width of 1.
|
games
|
from string import ascii_lowercase as alphabet
def the_janitor(word):
return [word . rindex(c) - word . index(c) + 1 if c in word else 0 for c in alphabet]
|
Simple Fun #265: The Janitor And His Mop
|
59128363e5bc24091a00006f
|
[
"Puzzles"
] |
https://www.codewars.com/kata/59128363e5bc24091a00006f
|
6 kyu
|
## Task
Let's call `product(x)` the product of x's digits. Given an array of integers a, calculate `product(x)` for each x in a, and return the number of distinct results you get.
## Example
For `a = [2, 8, 121, 42, 222, 23]`, the output should be `3`.
Here are the products of the array's elements:
```
2: product(2) = 2;
8: product(8) = 8;
121: product(121) = 1 * 2 * 1 = 2;
42: product(42) = 4 * 2 = 8;
222: product(222) = 2 * 2 * 2 = 8;
23: product(23) = 2 * 3 = 6.```
As you can see, there are only `3` different products: `2, 6 and 8.`
# Input/Output
- `[input]` integer array `a`
Constraints:
`1 ≤ a.length ≤ 10000,`
`1 ≤ a[i] ≤ 1000000000.`
- `[output]` an integer
The number of different digit products in `a`.
|
games
|
from functools import reduce
from operator import mul
def unique_digit_products(a):
return len({reduce(mul, map(int, str(x))) for x in a})
|
Simple Fun #91: Unique Digit Products
|
5897d94dd07028546c00009d
|
[
"Puzzles"
] |
https://www.codewars.com/kata/5897d94dd07028546c00009d
|
6 kyu
|
# Description:
Find the longest successive exclamation marks and question marks combination in the string. A successive exclamation marks and question marks combination must contains two part: a substring of "!" and a substring "?", they are adjacent.
If more than one result are found, return the one which at left side; If no such a combination found, return `""`.
# Examples
```
find("!!") === ""
find("!??") === "!??"
find("!?!!") === "?!!"
find("!!???!????") === "!!???"
find("!!???!?????") === "!?????"
find("!????!!!?") === "????!!!"
find("!?!!??!!!?") === "??!!!"
```
# Note
Please don't post issue about difficulty or duplicate. Because:
>[That's unfair on the kata creator. This is a valid kata and introduces new people to javascript some regex or loops, depending on how they tackle this problem. --matt c](https://www.codewars.com/kata/remove-exclamation-marks/discuss#57fabb625c9910c73000024e)
|
reference
|
import re
def find(s):
return max(re . findall(r'(?=(!+\?+|\?+!+))', s), key=len, default='')
|
Exclamation marks series #16: Find the longest successive exclamation marks and question marks combination in the string
|
57fb3c839610ce39f7000023
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/57fb3c839610ce39f7000023
|
6 kyu
|
### Task
Yesterday you found some shoes in your room. Each shoe is described by two values:
```
type indicates if it's a left or a right shoe;
size is the size of the shoe.
```
Your task is to check whether it is possible to pair the shoes you found in such a way that each pair consists of a right and a left shoe of an equal size.
### Example
For:
```
shoes = [[0, 21],
[1, 23],
[1, 21],
[0, 23]]
```
the output should be `true`;
For:
```
shoes = [[0, 21],
[1, 23],
[1, 21],
[1, 23]]
```
the output should be `false`.
### Input/Output
- `[input]` 2D integer array `shoes`
Array of shoes. Each shoe is given in the format [type, size], where type is either 0 or 1 for left and right respectively, and size is a positive integer.
Constraints: `2 ≤ shoes.length ≤ 50, 1 ≤ shoes[i][1] ≤ 100.`
- `[output]` a boolean value
`true` if it is possible to pair the shoes, `false` otherwise.
|
games
|
def pair_of_shoes(a):
return sorted(s for lr, s in a if lr == 1) == sorted(s for lr, s in a if lr == 0)
|
Simple Fun #52: Pair Of Shoes
|
58885a7bf06a3d466e0000e3
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58885a7bf06a3d466e0000e3
|
6 kyu
|
# Description:
Remove odd number continuous exclamation marks and question marks(from the left to the right), until no continuous exclamation marks and question marks exist. Please note: One exclamation mark or question mark is not a continuous exclamation marks or question marks. The string only contains `!` and `?`.
# Examples
```
remove("") === ""
remove("!") === "!"
remove("!!") === "!!"
remove("!!!") === ""
remove("!??") === "!??"
remove("!???") === "!"
remove("!!!??") === "??"
remove("!!!???") === ""
remove("!??") === "!??"
remove("!???!!") === ""
("!???!!" --> "!!!" --> "")
remove("!????!!!?") === "!"
("!????!!!?" --> "!?????" --> "!")
```
# Note
Please don't post issue about difficulty or duplicate.
|
reference
|
import re
def remove(inp):
while True:
next = re . sub(r'!{3,}|\?{3,}', lambda m: "" if len(
m . group(0)) % 2 == 1 else m . group(0), inp)
if next == inp:
break
inp = next
return next
|
Exclamation marks series #12: Remove odd number continuous exclamation marks and question marks
|
57fb0f3f9610ced69000023c
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/57fb0f3f9610ced69000023c
|
6 kyu
|
# Task
Given array of integers `sequence` and some integer `fixedElement`, output the number of `even` values in sequence before the first occurrence of `fixedElement` or `-1` if and only if `fixedElement` is not contained in sequence.
# Input/Output
`[input]` integer array `sequence`
A non-empty array of positive integers.
`4 ≤ sequence.length ≤ 100`
`1 ≤ sequence[i] ≤ 9`
`[input]` integer `fixedElement`
An positive integer
`1 ≤ fixedElement ≤ 9`
`[output]` an integer
# Example
For `sequence = [1, 4, 2, 6, 3, 1] and fixedElement = 6`, the output should be `2`.
There are `2` even numbers before `6`: `4 and 2`
For `sequence = [2, 2, 2, 1] and fixedElement = 3`, the output should be `-1`.
There is no `3` appears in `sequence`. So returns `-1`.
For `sequence = [1, 3, 4, 3] and fixedElement = 3`, the output should be `0`.
`3` appears in `sequence`, but there is no even number before `3`.
|
reference
|
def even_numbers_before_fixed(s, f):
return len([x for x in s[: s . index(f)] if x % 2 == 0]) if f in s else - 1
|
Simple Fun #263: Even Numbers Before Fixed
|
5912701a89fc3d0a6a000169
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5912701a89fc3d0a6a000169
|
7 kyu
|
# Task
Given an initial string `s`, switch case of the minimal possible number of letters to make the whole string written in the upper case or in the lower case.
# Input/Output
`[input]` string `s`
String of odd length consisting of English letters.
3 ≤ inputString.length ≤ 99.
`[output]` a string
The resulting string.
# Example
For `s = "Aba"`, the output should be `"aba"`
For `s = "ABa"`, the output should be `"ABA"`
|
reference
|
def case_unification(s):
return s . upper() if sum(c . islower() for c in s) < len(s) / 2 else s . lower()
|
Simple Fun #262: Case Unification
|
59126cd3379de6ca5f00019c
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59126cd3379de6ca5f00019c
|
7 kyu
|
Businesses use keypad letters in creative ways to spell out a phone number and make it more memorable.
Example:
http://en.wikipedia.org/wiki/File:Telephone-keypad2.svg
Create a mapping for your dialer as given in the above link.
Constraints:
1. letters are all uppercase
2. digits 0, 1 are mapped to 0, 1 respectively
Write a function that takes four digits of a phone number, and returns a list of all of the words that can be written with that number. (You should return all permutations, not only English words.)
|
algorithms
|
from itertools import product
mapping = {
'0': '0',
'1': '1',
'2': 'ABC',
'3': 'DEF',
'4': 'GHI',
'5': 'JKL',
'6': 'MNO',
'7': 'PQRS',
'8': 'TUV',
'9': 'WXYZ',
}
def telephoneWords(digits):
digits = map(lambda x: mapping[x], digits)
return map('' . join, product(* digits))
|
telephone words
|
5653d33e78e3d9dfe600004e
|
[
"Strings",
"Arrays",
"Algorithms"
] |
https://www.codewars.com/kata/5653d33e78e3d9dfe600004e
|
6 kyu
|
You are playing euchre and you want to know the new score after finishing a hand. There are two teams and each hand consists of 5 tricks. The team who wins the majority of the tricks will win points but the number of points varies. To determine the number of points, you must know which team called trump, how many tricks each team won, and if anyone went alone. Scoring is as follows:
For the team that called trump:
- if they win 2 or less tricks -> other team wins 2 points
- if they win 3 or 4 tricks -> 1 point
- if they don't go alone and win 5 tricks -> 2 points
- if they go alone and win 5 tricks -> 4 points
Only the team who called trump can go alone and you will notice that it only increases your points if you win all 5 tricks.
Your job is to create a method to calculate the new score. When reading the arguments, team 1 is represented by 1 and team 2 is represented by 2. All scores will be stored with this order: { team1, team2 }.
|
algorithms
|
def update_score(sc, trmp, alone, trks):
tot = trks . count(trmp)
if tot <= 2:
sc[trmp % 2] += 2
elif 3 <= tot <= 4:
sc[trmp - 1] += 1
elif tot >= 5 and not alone:
sc[trmp - 1] += 2
elif tot >= 5 and alone:
sc[trmp - 1] += 4
else:
print("what happened here ??")
return sc
|
Get Euchre Score
|
586eca3b35396db82e000481
|
[
"Games",
"Arrays",
"Algorithms"
] |
https://www.codewars.com/kata/586eca3b35396db82e000481
|
6 kyu
|
# Task
Two players - `"black"` and `"white"` are playing a game. The game consists of several rounds. If a player wins in a round, he is to move again during the next round. If a player loses a round, it's the other player who moves on the next round. Given whose turn it was on the previous round and whether he won, determine whose turn it is on the next round.
# Input/Output
`[input]` string `lastPlayer`/`$last_player`
`"black"` or `"white"` - whose move it was during the previous round.
`[input]` boolean `win`/`$win`
`true` if the player who made a move during the previous round won, `false` otherwise.
`[output]` a string
Return `"white"` if white is to move on the next round, and `"black"` otherwise.
# Example
For `lastPlayer = "black" and win = false`, the output should be `"white"`.
For `lastPlayer = "white" and win = true`, the output should be `"white"`.
|
games
|
def whoseMove(lastPlayer, win):
return lastPlayer if win else 'white' if lastPlayer == 'black' else 'black'
|
Simple Fun #261: Whose Move
|
59126992f9f87fd31600009b
|
[
"Puzzles"
] |
https://www.codewars.com/kata/59126992f9f87fd31600009b
|
8 kyu
|
## Story
Jumbo Juice makes a fresh juice out of fruits of your choice.Jumbo Juice charges $5 for regular fruits and $7 for special ones. Regular fruits are Banana, Orange, Apple, Lemon and Grapes. Special ones are Avocado, Strawberry and Mango. Others fruits that are not listed are also available upon request. Those extra special fruits cost $9 per each. There is no limit on how many fruits she/he picks.The price of a cup of juice is the mean of price of chosen fruits. In case of decimal number (ex. $5.99), output should be the nearest integer (use the standard rounding function of your language of choice).
## Input
The function will receive an array of strings, each with the name of a fruit. The recognition of names should be case insensitive. There is no case of an empty array input.
## Example
```
['Mango', 'Banana', 'Avocado'] //the price of this juice bottle is (7+5+7)/3 = $6($6.333333...)
```
|
reference
|
def mix_fruit(arr):
regular = ["banana", "orange", "apple", "lemon", "grapes"]
special = ["avocado", "strawberry", "mango"]
return round(sum(5 if fruit . lower() in regular else (7 if fruit . lower() in special else 9) for fruit in arr) / len(arr))
|
Mix Fruit Juice
|
5905871c00881d0e85000015
|
[
"Fundamentals",
"Arrays"
] |
https://www.codewars.com/kata/5905871c00881d0e85000015
|
6 kyu
|
> When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description
You are given a number sequence (an array) that contains some positive integer and zero.
```
[3,2,1,0,5,6,4,0,1,5,3,0,4,2,8,0]
```
It can be split to some zero-terminated sub sequence, such as `[3,2,1,0], [5,6,4,0] ..`
Your task is: First, sort each sub sequence according to the ascending order (don't sort the zero, it always at the end); Second, sort all sub sequence according to their sum value (ascending order too).
- Arguments:
- `sequence`: The number sequence.
- Results & Note:
- The result is the sorted number sequence.
- If some sub sequences have the same sum value, sort them according to their original order.
# Some Examples
```
sortSequence([3,2,1,0,5,6,4,0,1,5,3,0,4,2,8,0]) should return
[1,2,3,0,1,3,5,0,2,4,8,0,4,5,6,0]
sortSequence([3,2,1,0,5,6,4,0,1,5,3,0,2,2,2,0]) should return
[1,2,3,0,2,2,2,0,1,3,5,0,4,5,6,0]
sortSequence([2,2,2,0,5,6,4,0,1,5,3,0,3,2,1,0]) should return
[2,2,2,0,1,2,3,0,1,3,5,0,4,5,6,0]
```
~~~if:lambdacalc
# Encodings
purity: `LetRec`
numEncoding: `BinaryScott`
export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding
~~~
|
games
|
from itertools import groupby
def sort_sequence(sequence):
return sum(sorted([sorted(y) + [0] for x, y in groupby(sequence, lambda x: x == 0) if not x], key=sum), [])
|
Sort the number sequence
|
5816b76988ca9613cc00024f
|
[
"Puzzles",
"Sorting",
"Algorithms"
] |
https://www.codewars.com/kata/5816b76988ca9613cc00024f
|
6 kyu
|
# Description:
Give you a sentence `s`. It contains some words and separated by spaces. Another arguments is `n`, its a number(1,2 or 3). You should convert `s` to camelCase n.
There are three kinds of camelCase:
```
camelCase 1: The first letter of each word should be capitalized.
Except for the first word.
Example: "Hello world" --> "helloWorld"
camelCase 2: The last letter of each word should be capitalized.
Except for the last word.
Example: "Hello world" --> "hellOworld"
camelCase 3: The first and last letters of each word should be capitalized.
Except for the first and lasts letter of sentence.
Example: "Hello world" --> "hellOWorld"
```
You can assume that all of the input data is valid. That is: `s` always be a string; It contains at least two words; Each word contains only letters(a-zA-Z); Each word contains ar least three letters; `n` always be 1,2 or 3.
# Examples
```
toCamelCase("hello world",1) === "helloWorld"
toCamelCase("hello world",2) === "hellOworld"
toCamelCase("hello world",3) === "hellOWorld"
toCamelCase("Hello world",1) === "helloWorld"
toCamelCase("Each number plus one",1) === "eachNumberPlusOne"
toCamelCase("Each number plus one",2) === "eacHnumbeRpluSone"
toCamelCase("Each number plus one",3) === "eacHNumbeRPluSOne"
```
Random tests may contains bug(I'm not sure), please test and feedback, thanks ;-)
|
games
|
def toCamelCase(s, n):
if n == 1:
return s[0]. lower() + s . title(). replace(' ', '')[1:]
elif n == 2:
return '' . join(map(lambda x: x[: - 1]. lower() + x[- 1]. upper(), s . split()))[: - 1] + s[- 1]. lower()
else:
return '' . join(map(lambda x: x[: - 1] + x[- 1]. upper(), (s[0]. lower() + s . title()[1:]). split()))[: - 1] + s[- 1]. lower()
|
From..To..Series #7: from sentence to camelCase. Can you convert it?
|
58097ae96037b88f57000105
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58097ae96037b88f57000105
|
6 kyu
|
Our friendly friend Pete is really a nice person, but he tends to be rather... Inappropriate.
And possibly loud, if given enough ethanol and free rein, so we ask you to write a function that should take its not always "clean" speech and cover as much as possible of it, in order not to offend some more sensible spirits.
For example, given an input like
```
What the hell am I doing here? And where is my wallet? PETE SMASH!
```
You are expected to turn it into something like:
```
W**t t*e h**l am i d***g h**e? A*d w***e is my w****t? P**e s***h!
```
In case you didn't figure out the rules yet: any words longer than 2 characters need to have its "inside" (meaning every character which is not the first or the last) changed into `*`; as we do not want Pete to scream too much, every uppercase letter which is not at the beginning of the string or coming after a punctuation mark among [".","!","?"] needs to be put to lowercase; spaces and other punctuation marks can be ignored.
Conversely, you need to be sure that the start of each sentence has a capitalized word at the beginning. Sentences are divided by the aforementioned punctuation marks.
Finally, the function will take an additional parameter consisting of an array/list of allowed words (upper or lower case) which are not to be replaced (the match has to be case insensitive).
Extra cookies if you can do it all in some efficient way and/or using our dear regexes ;)
**Note:** Absolutely not related to [a certain codewarrior I know](http://www.codewars.com/users/petegarvin1) :p
|
algorithms
|
import re
PATTERN = re . compile(r'(?P<first>(?:(?<=[.!?] )|^)\w+)|(?P<other>\w+)')
def pete_talk(speech, ok=[]):
def watchYourMouth(m):
w = (m . group("first") or m . group("other")). lower()
if w not in ok and len(w) > 1:
w = w[0] + '*' * (len(w) - 2) + w[- 1]
if m . group("first"):
w = w . capitalize()
return w
ok = set(map(str . lower, ok))
return PATTERN . sub(watchYourMouth, speech)
|
Pete's inappropriate speech
|
571d0c80eed4a1c850000ef2
|
[
"Regular Expressions",
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/571d0c80eed4a1c850000ef2
|
6 kyu
|
You have an 8x8 grid with coordinates ranging from `1` to `8`. The origin `(1, 1)` is in the top left corner. The bottom right corner is `(8, 8)`.
You are given a string as an input which will contain the 2 coordinates in this format: `"(x1 y1)(x2 y2)"`, where `(x1 y1)` represents point `A` and `(x2 y2)` represents point `B`. In the inputs provided, point `A` will always be up and to the left of point `B`. In other words, `x1 < x2` and `y1 < y2` will be true for every input.
Your goal is to find out the number of different paths you can take to get from point `A` to point `B` by moving one cell at a time either down or right.
## Example
Given an input of `"(2 3)(3 5)"`, the number of possible paths to get from `A` to `B` is 3.
```
. . . . . . . .
. . . . . . . .
. A . . . . . .
. . . . . . . .
. . B . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
```
Possible paths, marked with `x`:
```
A . A . A x
x . x x . x
x B . B . B
```
|
algorithms
|
from math import comb
def travel_chessboard(s):
x1, y1, x2, y2 = (int(e)
for e in s . replace(')(', ' ')[1: - 1]. split(' '))
return comb(x2 - x1 + y2 - y1, x2 - x1)
|
Travelling on a Grid
|
5845b080a87f768aaa00027c
|
[
"Puzzles",
"Algorithms"
] |
https://www.codewars.com/kata/5845b080a87f768aaa00027c
|
6 kyu
|
All Unix user know the command line `history`. This one comes with a set of useful commands know as the `bang` command.
For more information about the history command line you can take a look at:
- The man page -> simply type `man history` in your terminal.
- The online man page [here](https://linux.die.net/man/3/history).
- And for more information about the `bang` command you can read [this article](http://jaysoo.ca/2009/09/16/unix-history-and-bang-commands/)
For this 5th kata we will explore the `!?string` command, according to the man page this one refer to the most recent command preceding the current postition in the history list containing string.
In this kata you should complete a function that take in an string that correspond to `s`, and an `history` with the following format:
```
1 cd /pub
2 more beer
3 lost
4 ls
5 touch me
6 chmod 000 me
7 more me
8 history
```
and that should return the most recent command line that contains executed command line `s`, for example with `s`="me" and the above history it should return `more me`. If user ask for a `s` without any know entry for example `n=you` here, the function should return `!you: event not found`.
**Note**: Lot of the command line comes form some geeky t-shirt and form this [excellent page](http://langevin.univ-tln.fr/cours/UPS/extra/unix-shell-jokes.txt).
|
algorithms
|
def bang_contain_string(stg, history):
for line in history . splitlines()[:: - 1]:
if stg in line:
return line . lstrip(" 0123456789")
return f"! { stg } : event not found"
|
Linux history and `!` command. Series#5 The `!?string` command
|
581b29b549b2c0daeb001454
|
[
"Strings",
"Parsing",
"Regular Expressions",
"Algorithms"
] |
https://www.codewars.com/kata/581b29b549b2c0daeb001454
|
6 kyu
|
All Unix user know the command line `history`. This one comes with a set of useful commands know as the `bang` command.
For more information about the history command line you can take a look at:
- The man page -> simply type `man history` in your terminal.
- The online man page [here](https://linux.die.net/man/3/history).
- And for more information about the `bang` command you can read [this article](http://jaysoo.ca/2009/09/16/unix-history-and-bang-commands/)
For this 4th kata we will explore the `!string` command, according to the man page this one refer to command the most recent command preceding the current position in the history list starting with string.
In this kata you should complete a function that take in an string that correspond to `s`, and an `history` with the following format:
```
1 cd /pub
2 more beer
3 lost
4 ls
5 touch me
6 chmod 000 me
7 more me
8 history
```
and that should return the most recent command line that start with `s`, for example with `s`="more" and the above history it should return `more me`. If user ask for a `s` without any know entry for example `n=mkdir` here, the function should return `!mkdir: event not found`.
**Note**: Lot of the command line comes form some geeky t-shirt and form this [excellent page](http://langevin.univ-tln.fr/cours/UPS/extra/unix-qshell-jokes.txt).
|
algorithms
|
import re
_PATTERN = re . compile(r'\A\s*(\d+)\s+(.*)\Z')
def bang_start_string(n, history):
cmds = (_PATTERN . match(line). group(2)
for line in history . splitlines()[:: - 1])
return next((cmd for cmd in cmds if cmd . startswith(n)), '!{}: event not found' . format(n))
|
Linux history and `!` command. Series#4 The `!string` command
|
5818236ae7f457017b00022b
|
[
"Strings",
"Parsing",
"Regular Expressions",
"Algorithms"
] |
https://www.codewars.com/kata/5818236ae7f457017b00022b
|
6 kyu
|
All Unix user know the command line `history`. This one comes with a set of useful commands know as the `bang` command.
For more information about the history command line you can take a look at:
- The man page -> simply type `man history` in your terminal.
- The online man page [here](https://linux.die.net/man/3/history).
- And for more information about the `bang` command you can read [this article](http://jaysoo.ca/2009/09/16/unix-history-and-bang-commands/)
For this third kata we will explore the `!-n` command, according to the man page this one refer to command line -n.
In this kata you should complete a function that take in an integer that correspond to `n`, and an `history` with the following format:
```
1 cd /pub
2 more beer
3 lost
4 ls
5 touch me
6 chmod 000 me
7 more me
8 history
```
and that should return the `n`th executed command line, for example with `n`=4 and the above history it should return `touch me`. If user ask for a `n` without any know entry for exampl `n=12` here, the function should return `!12: event not found`.
**Note**: Lot of the command line comes form some geeky t-shirt and form this [excellent page](http://langevin.univ-tln.fr/cours/UPS/extra/unix-qshell-jokes.txt).
|
algorithms
|
def bang_minus_n(n, history):
try:
return history . split('\n')[- n]. split(' ')[- 1]
except:
return "!-{}: event not found" . format(n)
|
Linux history and `!` command. Series#3 The `!-n` command
|
5815fd7441e062463d0000f8
|
[
"Strings",
"Parsing",
"Regular Expressions",
"Algorithms"
] |
https://www.codewars.com/kata/5815fd7441e062463d0000f8
|
6 kyu
|
All Unix user know the command line `history`. This one comes with a set of useful commands know as the `bang` command.
For more information about the history command line you can take a look at:
- The man page -> simply type `man history` in your terminal.
- The online man page [here](https://linux.die.net/man/3/history).
- And for more information about the `bang` command you can read [this article](http://jaysoo.ca/2009/09/16/unix-history-and-bang-commands/)
For this second kata we will explore the `!n` command, according to the man page this one refer to command line n.
In this kata you should complete a function that take in an integer that correspond to `n`, and an `history` with the following format:
```
1 cd /pub
2 more beer
3 lost
4 ls
5 touch me
6 chmod 000 me
7 more me
8 history
```
and that should return the `n`th executed command line, for example with `n`=4 and the above history it should return `ls`. If user ask for a `n` without any know entry for example `n=12` here, the function should return `!12: event not found`. **Note**: For this kata we will assume that `n >= 1`.
**Note**: Lot of the command line comes form some geeky t-shirt and form this [excellent page](http://langevin.univ-tln.fr/cours/UPS/extra/unix-shell-jokes.txt).
|
algorithms
|
def bang_n(n, history):
try:
return history . split('\n')[n - 1]. split(' ')[- 1]
except:
return "!{}: event not found" . format(n)
|
Linux history and `!` command. Series#2 The `!n` command
|
5814bf3f3db1ffc0180000d3
|
[
"Strings",
"Parsing",
"Regular Expressions",
"Algorithms"
] |
https://www.codewars.com/kata/5814bf3f3db1ffc0180000d3
|
6 kyu
|
Earlier this year I was in a <a href="https://www.hackerrank.com/contests/regular-expresso/challenges">contest on HackerRank</a> which included a <a href="https://en.wikipedia.org/wiki/Code_golf">code golf</a>-style <a href="https://www.hackerrank.com/contests/regular-expresso/challenges/winning-tic-tac-toe">challenge</a> to write a regular expression of 50 or fewer characters that could determine whether or not a <a href="https://en.wikipedia.org/wiki/Tic-tac-toe">tic tac toe</a> (also known as noughts and crosses or Xs and Os) board had a winner.
I'm not going to force you to keep your regex at or under 50 characters here, or even force you to use a regex if you really don't want to (though if you really don't want to write a regex, why don't you do one of the <a href="https://www.codewars.com/kata/search/?q=tic+tac+toe">other tic tac toe katas</a> here instead?), but why not challenge yourself, maybe learn something, and perhaps earn some Best Practices/Clever honor points for yourself as well?
Your function will receive a string of nine "X", "O", and/or "-" characters representing the state of a tic tac toe board, for example the string
```
"X-OXXXO-O"
```
would represent the board
```
X-O
XXX
O-O
```
where player X has won by getting three in a row horizontally on the middle row.
Your function needs to return True/true/TRUE (depending on the language you're using) if either the X or the O player has won the game by getting three in a row vertically, horizontally, or diagonally; or False/false/FALSE if there is no winner.
A few more examples:
`"---------"` - False - no one has even made a move yet!
`"XOOOXXXXO"` - False - no one got three in a row here.
`"OXO-XOX-O"` - True - player O won by getting three in a row vertically in the third column.
Note: Occasionally one of the random boards in the Test Suite will have two three-in-a-rows instead of one or none, and this still counts as a winning board. If the two three-in-a-rows belong to the same player, this just means that the second player played so badly that the first player's fifth and final move created two three-in-a-rows. If the two three-in-a-rows belong to different players, this just means that although one player won the game, afterward (as sometimes happens in real life) the other player made their mark in another square anyway, just because even though they already lost, they feel better doing that. :-)
Have fun!
|
reference
|
import re
def regex_tic_tac_toe_win_checker(board):
regex = r'(\w)(\1\1(...)*$|..\1..\1|.\1.\1..$|...\1...\1)'
return bool(re . search(regex, board))
|
Regex Tic Tac Toe Win Checker
|
582e0450fe38013dbc0002d3
|
[
"Games",
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/582e0450fe38013dbc0002d3
|
6 kyu
|
You are given string "elements" and an int "n".
Your task is to return a string that is a palindrom using elements from the string "elements" with the length "n".
The format of the palindromization:
- Your palindrome begins with the first element of "elements".
- After obtaining a pair, you insert the next element in "elements" to the palindrome.
- The next element will be paired inside the first pair.
- Repeat
- If you have reached the last element of "elements" then repeat the process from the start.
Error cases: <br>
If the string elements is empty or n is smaller than 2, return the string "Error!" <br>
Examples: <br>
<<<<<<< mine
```
For elements = "123"
n = 2 => result = "11"
n = 3 => result = "121"
n = 4 => result = "1221"
n = 5 => result = "12321"
n = 6 => result = "123321"
n = 7 => result = "1231321"
n = 8 => result = "12311321"
n = 9 => result = "123121321"
n = 10=> result = "1231221321"
```
=======
|
algorithms
|
def palindromization(elements, n):
if not elements or n < 2:
return "Error!"
left = ((n / / len(elements) + 1) * elements)[:(n + 1) / / 2]
return left + left[- 1 - n % 2:: - 1]
|
Palindromization
|
5840107b6fcbf56d2000010b
|
[
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/5840107b6fcbf56d2000010b
|
6 kyu
|
## Pair of gloves
Winter is coming, you must prepare your ski holidays. The objective of this kata is to determine the number of pair of gloves you can constitute from the gloves you have in your drawer.
Given an array describing the color of each glove, return the number of pairs you can constitute, assuming that only gloves of the same color can form pairs.
### Examples:
```
input = ["red", "green", "red", "blue", "blue"]
result = 2 (1 red pair + 1 blue pair)
input = ["red", "red", "red", "red", "red", "red"]
result = 3 (3 red pairs)
```
~~~if:lambdacalc
### Encodings
purity: `LetRec`
numEncoding: `Church`
export constructors `nil, cons` for your `List` encoding
### `Preloaded`
datatypes `Colour` and `Ordering` ( both in Scott encoding ) and
`compare : Colour -> Colour -> Ordering` are exported from `Preloaded`
`compare` is used as `compare colour1 colour2 (colour1<colour2) (colour1==colour2) (colour1>colour2)`
eg. `le` may be derived as `\ colour1 colour2 . compare colour1 colour2 True True False`
full disclosure: for technical reasons, combinators `T, Y` are also exported from `Preloaded`
~~~
|
games
|
def number_of_pairs(gloves):
return sum(gloves . count(color) / / 2 for color in set(gloves))
|
Pair of gloves
|
58235a167a8cb37e1a0000db
|
[
"Arrays",
"Puzzles"
] |
https://www.codewars.com/kata/58235a167a8cb37e1a0000db
|
6 kyu
|
All Unix user know the command line `history`. This one comes with a set of useful commands know as the `bang` command.
For more information about the history command line you can take a look at:
- The man page -> simply type `man history` in your terminal.
- The online man page [here](https://linux.die.net/man/3/history).
- And for more information about the `bang` command you can read [this article](http://jaysoo.ca/2009/09/16/unix-history-and-bang-commands/)
For this first kata we will explore the `!!` command, according to the man page this one refer to the previous command. This is a synonym for `!-1`.
In this kata you should complete a function that take in argument an `history` with the following format:
```
1 cd /pub
2 more beer
3 lost
4 ls
5 touch me
6 chmod 000 me
7 more me
8 history
```
and that should return the last executed command line, in this case it will be `history`.
**Note**: Lot of the command line comes form some geeky t-shirt and form this [excellent page](http://langevin.univ-tln.fr/cours/UPS/extra/unix-shell-jokes.txt).
|
algorithms
|
def bang_bang(history):
return history . split(' ')[- 1]
|
Linux history and `!` command. Series#1 The `!!` command
|
58143221f9588e340e00009f
|
[
"Strings",
"Parsing",
"Regular Expressions",
"Algorithms"
] |
https://www.codewars.com/kata/58143221f9588e340e00009f
|
6 kyu
|
In case you might be unlucky enough not to know the best dark fantasy franchise ever, Berserk tells the story of a man that, hating gratuitous violence, decided to become a mercenary (thus one who sells violence, no gratuity anymore!) and starts an epic struggle against apparently unsormountable odds, unsure if he really wants to pursue a path of vengeance or to try to focus on his remaining and new loved ones.
<div style="float:right;text-align:center;margin:5px"><img src="https://upload.wikimedia.org/wikipedia/en/thumb/4/45/Berserk_vol01.jpg/230px-Berserk_vol01.jpg"/><p>*The main character, Gatsu,<br>ready to start yet another Tuesday</p>*</div>
Ok, the first part was a joke, but you can read more about the tale of the main character, a "Byronic hero" for wikipedia, in other pages like [here](https://en.wikipedia.org/wiki/Berserk_(manga%29).
After an insanely long waiting, finally fans got the [follow up](https://en.wikipedia.org/wiki/Berserk_(2016_TV_series%29) of [the acclaimed 90s show](https://en.wikipedia.org/wiki/Berserk_(1997_TV_series%29).
Regrettably, while the first adaption was considerably shortened, the latter was quite butchered, missing entire parts, like the "lost children" arc, but that would have actual children butchered and thus you might get why it was decided to skip it. And fan could somehow cope with it, if it was not for the very meager use of CG (Computer Graphic).
Luckily, I am a simple man and every time Gatsu swings his humongous sword, that is enough to make me forget about everything else.
Your goal is to build a Berserk Rater function that takes an array/list of events of each episode (as strings) and calculate a rating based on that: you start with a score of 0 (hey, it's a work from Miura-sensei, I have great expectations to satisfy!) and you have to:
* subtract 2 each time "CG" is mentioned (case insensitive);
* add 5 every time "Clang" is mentioned (case insensitive);
* if a sentence has both "Clang" and "CG", "Clang" wins (add 5);
* remove 1 every time neither is mentioned (I get bored easily, you know, particularly if you remove important parts and keep side character whining for half an episode).
You should then return a string, structured like this:
* if the finale score is less than 0: "worstest episode ever";
* if the score is between 0 and 10: the score itself, as a string;
* if the finale score is more than 10: "bestest episode ever".
Examples:
```csharp
Kata.BerserkRater(["is this the CG from a P2 game?","Hell, no! Even the CG in the Dreamcast game was more fluid than this!","Well, at least Gatsu does his clang even against a mere rabbit", "Hey, Cosette was not in this part of the story!", "Ops, everybody dead again! Well, how boring..."])=="worstest episode ever"
Kata.BerserkRater(["missing the Count arc","lame CG","Gatsu doing its clang against a few henchmen", "even more lame CG"])=="0"
Kata.BerserkRater(["Farnese unable to shut the fuck up","awful CG dogs assaulting everybody", "Gatsu clanging the pig apostle!"])=="2"
Kata.BerserkRater(["spirits of the dead attacking Gatsu and getting clanged for good", "but the wheel spirits where really made with bad CG", "Isidoro trying to steal the dragon Slayer and getting a sort of clang on his face", "Gatsu vs. the possessed horse: clang!", "Farnese whining again...","a shame the episode ends with that scrappy CG"])=="10"
Kata.BerserkRater(["Holy chain knights being dicks", "Serpico almost getting clanged by Gatsu, but without losing his composure","lame CG","Luka getting kicked","Gatsu going clang against the angels", "Gatsu clanging vs Mozgus, big time!"])=="bestest episode ever"
```
```javascript
berserkRater(["is this the CG from a P2 game?","Hell, no! Even the CG in the Dreamcast game was more fluid than this!","Well, at least Gatsu does his clang even against a mere rabbit", "Hey, Cosette was not in this part of the story!", "Ops, everybody dead again! Well, how boring..."])=="worstest episode ever"
berserkRater(["missing the Count arc","lame CG","Gatsu doing its clang against a few henchmen", "even more lame CG"])=="0"
berserkRater(["Farnese unable to shut the fuck up","awful CG dogs assaulting everybody", "Gatsu clanging the pig apostle!"])=="2"
berserkRater(["spirits of the dead attacking Gatsu and getting clanged for good", "but the wheel spirits where really made with bad CG", "Isidoro trying to steal the dragon Slayer and getting a sort of clang on his face", "Gatsu vs. the possessed horse: clang!", "Farnese whining again...","a shame the episode ends with that scrappy CG"])=="10"
berserkRater(["Holy chain knights being dicks", "Serpico almost getting clanged by Gatsu, but without losing his composure","lame CG","Luka getting kicked","Gatsu going clang against the angels", "Gatsu clanging vs Mozgus, big time!"])=="bestest episode ever"
```
```python
berserk_rater(["is this the CG from a P2 game?","Hell, no! Even the CG in the Dreamcast game was more fluid than this!","Well, at least Gatsu does his clang even against a mere rabbit", "Hey, Cosette was not in this part of the story!", "Ops, everybody dead again! Well, how boring..."])=="worstest episode ever"
berserk_rater(["missing the Count arc","lame CG","Gatsu doing its clang against a few henchmen", "even more lame CG"])=="0"
berserk_rater(["Farnese unable to shut the fuck up","awful CG dogs assaulting everybody", "Gatsu clanging the pig apostle!"])=="2"
berserk_rater(["spirits of the dead attacking Gatsu and getting clanged for good", "but the wheel spirits where really made with bad CG", "Isidoro trying to steal the dragon Slayer and getting a sort of clang on his face", "Gatsu vs. the possessed horse: clang!", "Farnese whining again...","a shame the episode ends with that scrappy CG"])=="10"
berserk_rater(["Holy chain knights being dicks", "Serpico almost getting clanged by Gatsu, but without losing his composure","lame CG","Luka getting kicked","Gatsu going clang against the angels", "Gatsu clanging vs Mozgus, big time!"])=="bestest episode ever"
```
```crystal
berserk_rater(["is this the CG from a P2 game?","Hell, no! Even the CG in the Dreamcast game was more fluid than this!","Well, at least Gatsu does his clang even against a mere rabbit", "Hey, Cosette was not in this part of the story!", "Ops, everybody dead again! Well, how boring..."])=="worstest episode ever"
berserk_rater(["missing the Count arc","lame CG","Gatsu doing its clang against a few henchmen", "even more lame CG"])=="0"
berserk_rater(["Farnese unable to shut the fuck up","awful CG dogs assaulting everybody", "Gatsu clanging the pig apostle!"])=="2"
berserk_rater(["spirits of the dead attacking Gatsu and getting clanged for good", "but the wheel spirits where really made with bad CG", "Isidoro trying to steal the dragon Slayer and getting a sort of clang on his face", "Gatsu vs. the possessed horse: clang!", "Farnese whining again...","a shame the episode ends with that scrappy CG"])=="10"
berserk_rater(["Holy chain knights being dicks", "Serpico almost getting clanged by Gatsu, but without losing his composure","lame CG","Luka getting kicked","Gatsu going clang against the angels", "Gatsu clanging vs Mozgus, big time!"])=="bestest episode ever"
```
```ruby
berserk_rater(["is this the CG from a P2 game?","Hell, no! Even the CG in the Dreamcast game was more fluid than this!","Well, at least Gatsu does his clang even against a mere rabbit", "Hey, Cosette was not in this part of the story!", "Ops, everybody dead again! Well, how boring..."])=="worstest episode ever"
berserk_rater(["missing the Count arc","lame CG","Gatsu doing its clang against a few henchmen", "even more lame CG"])=="0"
berserk_rater(["Farnese unable to shut the fuck up","awful CG dogs assaulting everybody", "Gatsu clanging the pig apostle!"])=="2"
berserk_rater(["spirits of the dead attacking Gatsu and getting clanged for good", "but the wheel spirits where really made with bad CG", "Isidoro trying to steal the dragon Slayer and getting a sort of clang on his face", "Gatsu vs. the possessed horse: clang!", "Farnese whining again...","a shame the episode ends with that scrappy CG"])=="10"
berserk_rater(["Holy chain knights being dicks", "Serpico almost getting clanged by Gatsu, but without losing his composure","lame CG","Luka getting kicked","Gatsu going clang against the angels", "Gatsu clanging vs Mozgus, big time!"])=="bestest episode ever"
```
Extra cookies if you manage to solve it all using a `reduce/inject` approach.
Oh, and in case you might want a taste of clang to fully understand it, [click](https://www.youtube.com/watch?v=IZgxH8MJFno) (one of the least gory samples I managed to find).
|
algorithms
|
def berserk_rater(synopsis):
n = sum([score(s . upper()) for s in synopsis])
return 'worstest episode ever' if n < 0 else 'bestest episode ever' if n > 10 else str(n)
def score(s):
return 5 if 'CLANG' in s else - 2 if 'CG' in s else - 1
|
Berserk rater: CG Vs. Clang
|
57fa3a33e8c829780a0001d2
|
[
"Algorithms"
] |
https://www.codewars.com/kata/57fa3a33e8c829780a0001d2
|
6 kyu
|
The [Padovan sequence](https://en.wikipedia.org/wiki/Padovan_sequence) is the sequence of integers defined by the initial values
```
P(0) = P(1) = P(2) = 1
```
and the recurrence relation
```
P(n) = P(n-2) + P(n-3)
```
The first few values of `P(n)` are:
```
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, ...
```
## Task
Your task is to write a method that returns `n`th Padovan number
|
algorithms
|
def padovan(n):
p0 = p1 = p2 = 1
for i in range(n):
p0, p1, p2 = p1, p2, p0 + p1
return p0
|
Padovan numbers
|
5803ee0ed5438edcc9000087
|
[
"Algorithms"
] |
https://www.codewars.com/kata/5803ee0ed5438edcc9000087
|
6 kyu
|
## Task
Given a positive integer as input, return the output as a string in the following format:
Each element, corresponding to a digit of the number, multiplied by a power of 10 in such a way that with the sum of these elements you can obtain the original number.
## Examples
Input | Output
--- | ---
0 | ""
56 | "5\*10+6"
60 | "6\*10"
999 | "9\*100+9\*10+9"
10004 | "1\*10000+4"
Note: `input >= 0`
|
reference
|
def simplify(n):
output = []
exp = 0
while n:
n, r = divmod(n, 10)
if r:
output . append(f" { r } * { 10 * * exp } " if exp else f" { r } ")
exp += 1
return "+" . join(output[:: - 1])
|
Simplify the number!
|
5800b6568f7ddad2c10000ae
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5800b6568f7ddad2c10000ae
|
6 kyu
|
You are given a string of words (x), for each word within the string you need to turn the word 'inside out'. By this I mean the internal letters will move out, and the external letters move toward the centre.
If the word is even length, all letters will move. If the length is odd, you are expected to leave the 'middle' letter of the word where it is.
An example should clarify:
'taxi' would become 'atix'
'taxis' would become 'atxsi'
|
reference
|
import re
def inside_out(s):
return re . sub(r'\S+', lambda m: inside_out_word(m . group()), s)
def inside_out_word(s):
i, j = len(s) / / 2, (len(s) + 1) / / 2
return s[: i][:: - 1] + s[i: j] + s[j:][:: - 1]
|
Inside Out Strings
|
57ebdf1c2d45a0ecd7002cd5
|
[
"Fundamentals",
"Strings",
"Arrays"
] |
https://www.codewars.com/kata/57ebdf1c2d45a0ecd7002cd5
|
6 kyu
|
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:
```javascript
perms(1)==1
perms(45)==2
perms(115)==3
perms("abc")==6
```
```ruby
perms(1)==1
perms(45)==2
perms(115)==3
perms("abc")==6
```
```python
perms(1)==1
perms(45)==2
perms(115)==3
perms("abc")==6
```
|
algorithms
|
from operator import mul
from math import factorial
from functools import reduce
from collections import Counter
def perms(inp):
return factorial(len(str(inp))) / / reduce(mul, map(factorial, Counter(str(inp)). values()), 1)
|
Number of permutations without repetitions
|
571bff6082661c8a11000823
|
[
"Permutations",
"Combinatorics",
"Algorithms"
] |
https://www.codewars.com/kata/571bff6082661c8a11000823
|
6 kyu
|
[Vowel harmony](https://en.wikipedia.org/wiki/Vowel_harmony) is a phenomenon in some languages. It means that "A vowel or vowels in a word are changed to sound the same (thus "in harmony.")" ([wikipedia](https://en.wikipedia.org/wiki/Vowel_harmony#Hungarian)). This kata is based on [vowel harmony in Hungarian](https://en.wikipedia.org/wiki/Vowel_harmony#Hungarian).
### Task:
Your goal is to create a function `instrumental()` which returns the valid form of a valid Hungarian word `w` in [instrumental case](http://www.hungarianreference.com/Nouns/val-vel-instrumental.aspx) i. e. append the correct suffix `-vel` or `-val` to the word `w` based on vowel harmony rules.
### Vowel Harmony Rules (simplified)
__Front vowels:__ `e, é, i, í, ö, ő, ü, ű`
__Back vowels:__ `a, á, o, ó, u, ú`
__Vowel pairs (short -> long)__: `a -> á`, `e -> é`, `i -> í`, `o -> ó`, `u -> ú`, `ö -> ő`, `ü -> ű`
__Digraphs:__ `sz`, `zs`, `cs`
#### Word ends with a vowel
1. Change the ending vowel from short to long form.
2. Append the suffix:
1. `vel` if the ending vowel is a _front vowel_
2. `val` if the ending vowel is a _back vowel_
#### Word ends with a consonant
##### Step one
1. Default case: Double the ending consonant and continue with step two.
2. Special case: If the word ends with a digraph then double the first letter (e. g. `sz` -> `ssz`)
##### Step two
Append the suffix:
1. `el` if the last vowel is a `front vowel`
2. `al` if the last vowel is a `back vowel`
### Examples:
```python
instrumental("fa") == "fával"
instrumental("teve") == "tevével"
instrumental("betű") == "betűvel"
instrumental("ablak") == "ablakkal"
instrumental("szék") == "székkel"
instrumental("otthon") == "otthonnal"
instrumental("kar") == "karral"
instrumental("rács") == "ráccsal"
instrumental("kosz") == "kosszal"
```
```php
instrumental("fa"); // "fával"
instrumental("teve"); // "tevével"
instrumental("betű"); // "betűvel"
instrumental("ablak"); // "ablakkal"
instrumental("szék"); // "székkel"
instrumental("otthon"); // "otthonnal"
instrumental("kar"); // "karral"
instrumental("rács"); // "ráccsal"
instrumental("kosz"); // "kosszal"
```
```groovy
Kata.instrumental("fa"); // "fával"
Kata.instrumental("teve"); // "tevével"
Kata.instrumental("betű"); // "betűvel"
Kata.instrumental("ablak"); // "ablakkal"
Kata.instrumental("szék"); // "székkel"
Kata.instrumental("otthon"); // "otthonnal"
Kata.instrumental("kar"); // "karral"
Kata.instrumental("rács"); // "ráccsal"
Kata.instrumental("kosz"); // "kosszal"
```
```typescript
instrumental("fa") === "fával"
instrumental("teve") === "tevével"
instrumental("betű") === "betűvel"
instrumental("ablak") === "ablakkal"
instrumental("szék") === "székkel"
instrumental("otthon") === "otthonnal"
instrumental("kar") === "karral"
instrumental("rács") === "ráccsal"
instrumental("kosz") === "kosszal"
```
```javascript
instrumental("fa") === "fával"
instrumental("teve") === "tevével"
instrumental("betű") === "betűvel"
instrumental("ablak") === "ablakkal"
instrumental("szék") === "székkel"
instrumental("otthon") === "otthonnal"
instrumental("kar") === "karral"
instrumental("rács") === "ráccsal"
instrumental("kosz") === "kosszal"
```
### Preconditions:
1. All strings are unicode strings.
2. The tests don't contain:
1. exceptional cases like `kávé -> kávéval`
2. words ending with doubled consonants (e. g. `tett`)
3. words ending with `y`
4. words ending with `u`, `i`
|
reference
|
mod = {"e": u"é", "i": u"í", u"ö": u"ő",
u"ü": u"ű", "a": u"á", "o": u"ó", "u": u"ú"}
def instrumental(word):
# find the last vowel
for c in word[:: - 1]:
if c in u"aáoóuú":
suf = "val"
break
elif c in u"eéiíöőüű":
suf = "vel"
break
# word ends with a vowel
if c == word[- 1]:
return word[: - 1] + mod . get(c, word[- 1]) + suf
# word ends with a consonant
if word[- 2:] in ("sz", "zs", "cs"):
word = word[: - 1] + word[- 2:]
else:
word += word[- 1]
return word + suf[1:]
|
Hungarian Vowel Harmony (harder)
|
57fe5b7108d102fede00137a
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/57fe5b7108d102fede00137a
|
6 kyu
|
# Task
There are `n` houses in a village on a circular road numbered `from 1 to n` starting from some house in clockwise order. It takes one minute to get from one house to any of two adjacent houses and there are no other roads in this village besides the circular one. Find the minimal time required to make all visits in the desired order starting from house 1.
# Input/Output
`[input]` integer `n`
The number of houses, positive integer.
`2 ≤ n ≤ 20.`
`[input]` integer array `visitsOrder`
An array of integers (each from 1 to n, inclusive) representing the order in which you have to visit the houses.
`1 ≤ visitsOrder.length ≤ 20,`
`1 ≤ visitsOrder[i] ≤ n.`
`[output]` an integer
The minimal time required to make all visits in the desired order starting from house 1.
# Example
For `n = 4 and visitsOrder = [1, 3, 2, 3, 1]`,
the output should be `6`.
Check out the image below for better understanding:

|
algorithms
|
def visits_on_circular_road(n, order):
return sum(min((d := abs(b - a)), n - d) for a, b in zip([1, * order], order))
|
Simple Fun #255: Visits On Circular Road
|
591074c7ea12ad515500007e
|
[
"Algorithms"
] |
https://www.codewars.com/kata/591074c7ea12ad515500007e
|
6 kyu
|
# Task
A masked number is a string that consists of digits and one asterisk (`*`) that should be replaced by exactly one digit. Given a masked number `s`, find all the possible options to replace the asterisk with a digit to produce an integer divisible by 6.
# Input/Output
`[input]` string `s`
A masked number.
`1 ≤ inputString.length ≤ 10000.`
`[output]` a string array
Sorted array of strings representing all non-negative integers that correspond to the given mask and are divisible by 6.
# Example
For `s = "1*0"`, the output should be `["120", "150", "180"].`
For `s = "*1"`, the output should be `[].`
For `s = "1234567890123456789012345678*0"`,
the output should be
```
[
"123456789012345678901234567800",
"123456789012345678901234567830",
"123456789012345678901234567860",
"123456789012345678901234567890"]```
As you can see, the masked number may be very large ;-)
|
games
|
import sys
sys . set_int_max_str_digits(0)
def is_divisible_by_6(s: str) - > list[str]:
res = []
for i in range(10):
num = int(s . replace("*", str(i)))
if num % 6 == 0:
res . append(str(num))
return res
|
Simple Fun #258: Is Divisible By 6
|
5911385598dcd432ae000004
|
[
"Puzzles"
] |
https://www.codewars.com/kata/5911385598dcd432ae000004
|
6 kyu
|
## Description
Give you a 2D array(n * n, n is an odd number more than 1), rotate it, remove elements, return the last surviving number.
```
arr=[
[3,5,8,4,2],
[1,9,2,3,8],
[4,6,7,2,2],
[7,5,5,5,5],
[6,5,3,8,1]
]
```
Rotate it in a counter clockwise direction:
```
2,8,2,5,1
4,3,2,5,8
8,2,7,5,3
5,9,6,5,5
3,1,4,7,6
```
Remove 1 maximum value and 1 minimum value of each row(remember, only remove 1 maximum value and 1 minimum value, not all of same, remove from left side)
```
2,2,5
4,3,5
7,5,3
6,5,5
3,4,6
```
Rotate again:
```
5,5,3,5,6
2,3,5,5,4
2,4,7,6,3
```
Remove again:
```
5,5,5
3,5,4
4,6,3
```
Rotate again:
```
5,4,3
5,5,6
5,3,4
```
Remove again:
```
4
5
4
```
Rotate again:
```
4,5,4
```
Remove again:
```
4
```
Return the last surviving number `4`
## Task
Complete function `rotateAndRemove` that accepts 1 argument `arr`. Returns the result in accordance with the rules above.
|
games
|
def rotate_and_remove(arr):
while len(arr) > 1:
arr = [popMinMax([* r]) for r in zip(* arr)][:: - 1]
return arr[0][0]
def popMinMax(r):
for f in min, max:
r . remove(f(r))
return r
|
myjinxin katas #001 : Rotate, Remove, Return
|
57dab71714e53f4bc9000310
|
[
"Puzzles",
"Algorithms",
"Arrays"
] |
https://www.codewars.com/kata/57dab71714e53f4bc9000310
|
5 kyu
|
Create a function hollow_triangle(height) that returns a hollow triangle of the correct height. The height is passed through to the function and the function should return a list containing each line of the hollow triangle.
```
hollow_triangle(6) should return : ['_____#_____', '____#_#____', '___#___#___', '__#_____#__', '_#_______#_', '###########']
hollow_triangle(9) should return : ['________#________', '_______#_#_______', '______#___#______', '_____#_____#_____', '____#_______#____', '___#_________#___', '__#___________#__', '_#_____________#_', '#################']
```
The final idea is for the hollow triangle is to look like this if you decide to print each element of the list:
```
hollow_triangle(6) will result in:
_____#_____ 1
____#_#____ 2
___#___#___ 3
__#_____#__ 4
_#_______#_ 5
########### 6 ---- Final Height
hollow_triangle(9) will result in:
________#________ 1
_______#_#_______ 2
______#___#______ 3
_____#_____#_____ 4
____#_______#____ 5
___#_________#___ 6
__#___________#__ 7
_#_____________#_ 8
################# 9 ---- Final Height
```
Pad spaces with underscores i.e _ so each line is the same length.Goodluck and have fun coding !
|
reference
|
def hollow_triangle(n):
return [(f'# { "_" * ( 2 * i - 1 )} #' if i else '#'). center(2 * n - 1, '_') for i in range(n - 1)] + ['#' * (2 * n - 1)]
|
Hollow Triangle
|
57819b700a8eb2d6b00002ab
|
[
"ASCII Art",
"Fundamentals"
] |
https://www.codewars.com/kata/57819b700a8eb2d6b00002ab
|
6 kyu
|
Given an array (ints) of n integers, find three integers in arr such that the sum is closest to a given number (num), target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
Example:
```ruby
closest_sum([-1, 2, 1, -4], 1) # 2 (-1 + 2 + 1 = 2)
```
Note: your solution should not modify the input array.
|
reference
|
from itertools import combinations
def closest_sum(ints, num):
return sum(min(combinations(ints, 3), key=lambda a: abs(num - sum(a))))
|
Closest Sum
|
577e694af5db624cf30002d0
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/577e694af5db624cf30002d0
|
6 kyu
|
If n is the numerator and d the denominator of a fraction, that fraction is defined a (reduced) proper fraction if and only if GCD(n,d)==1.
For example `5/16` is a proper fraction, while `6/16` is not, as both 6 and 16 are divisible by 2, thus the fraction can be reduced to `3/8`.
Now, if you consider a given number d, how many proper fractions can be built using d as a denominator?
For example, let's assume that d is 15: you can build a total of 8 different proper fractions between 0 and 1 with it: 1/15, 2/15, 4/15, 7/15, 8/15, 11/15, 13/15 and 14/15.
You are to build a function that computes how many proper fractions you can build with a given denominator:
```python
proper_fractions(1)==0
proper_fractions(2)==1
proper_fractions(5)==4
proper_fractions(15)==8
proper_fractions(25)==20
```
```ruby
proper_fractions(1)==0
proper_fractions(2)==1
proper_fractions(5)==4
proper_fractions(15)==8
proper_fractions(25)==20
```
```javascript
properFractions(1)==0
properFractions(2)==1
properFractions(5)==4
properFractions(15)==8
properFractions(25)==20
```
```racket
(proper-fractions 1) ; 0
(proper-fractions 2) ; 1
(proper-fractions 5) ; 4
(proper-fractions 15) ; 8
(proper-fractions 25) ; 20
```
Be ready to handle big numbers.
Edit: to be extra precise, the term should be "reduced" fractions, thanks to [girianshiido](http://www.codewars.com/users/girianshiido) for pointing this out and sorry for the use of an improper word :)
|
algorithms
|
def proper_fractions(n):
phi = n > 1 and n
for p in range(2, int(n * * .5) + 1):
if not n % p:
phi -= phi / / p
while not n % p:
n / /= p
if n > 1:
phi -= phi / / n
return phi
|
Number of Proper Fractions with Denominator d
|
55b7bb74a0256d4467000070
|
[
"Fundamentals",
"Mathematics"
] |
https://www.codewars.com/kata/55b7bb74a0256d4467000070
|
4 kyu
|
Removed due to copyright infringement.
<!---
# Task
In ChessLand there is a small but proud chess bishop with a recurring dream.
In the dream the bishop finds itself on an `n × m` chessboard with mirrors along each edge, and it is not a bishop but a ray of light. This ray of light moves only along diagonals (the bishop can't imagine any other types of moves even in its dreams), it never stops, and once it reaches an edge or a corner of the chessboard it reflects from it and moves on.
Given the initial position and the direction of the ray, find its position after `k` steps where a step means either moving from one cell to the neighboring one or reflecting from a corner of the board.
# Example
For `boardSize = [3, 7], initPosition = [1, 2], initDirection = [-1, 1] and k = 13,` the output should be `[0, 1]`.
Here is the bishop's path:
```
[1, 2] -> [0, 3] -(reflection from the top edge)
-> [0, 4] -> [1, 5] -> [2, 6] -(reflection from the bottom right corner)
-> [2, 6] ->[1, 5] -> [0, 4] -(reflection from the top edge)
-> [0, 3] ->[1, 2] -> [2, 1] -(reflection from the bottom edge)
-> [2, 0] -(reflection from the left edge)
-> [1, 0] -> [0, 1]```

# Input/Output
- `[input]` integer array `boardSize`
An array of two integers, the number of `rows` and `columns`, respectively. Rows are numbered by integers from `0 to boardSize[0] - 1`, columns are numbered by integers from `0 to boardSize[1] - 1` (both inclusive).
Constraints: `1 ≤ boardSize[i] ≤ 20.`
- `[input]` integer array `initPosition`
An array of two integers, indices of the `row` and the `column` where the bishop initially stands, respectively.
Constraints: `0 ≤ initPosition[i] < boardSize[i]`.
- `[input]` integer array `initDirection`
An array of two integers representing the initial direction of the bishop.
If it stands in `(a, b)`, the next cell he'll move to is `(a + initDirection[0], b + initDirection[1])` or whichever it'll reflect to in case it runs into a mirror immediately.
Constraints: `initDirection[i] ∈ {-1, 1}`.
- `[input]` integer `k`
Constraints: `1 ≤ k ≤ 1000000000`.
- `[output]` an integer array
The position of the bishop after `k` steps.
--->
|
games
|
def chess_bishop_dream(b, p, d, k):
yq, yr = divmod(p[0] + k * d[0], 2 * b[0])
xq, xr = divmod(p[1] + k * d[1], 2 * b[1])
return [min(yr, 2 * b[0] - yr - 1), min(xr, 2 * b[1] - xr - 1)]
|
Chess Fun #6: Chess Bishop Dream
|
5897ea323387497f460001a0
|
[
"Puzzles",
"Games"
] |
https://www.codewars.com/kata/5897ea323387497f460001a0
|
5 kyu
|
An array of size N x M represents pixels of an image.
Each cell of this array contains an array of size 3 with the pixel's color information: `[R,G,B]`
Convert the color image, into an *average* greyscale image.
The `[R,G,B]` array contains integers between 0 and 255 for each color.
To transform a color pixel into a greyscale pixel, average the values of that pixel:
```
p = [R,G,B] => [(R+G+B)/3, (R+G+B)/3, (R+G+B)/3]
```
**Note:** the values for the pixel must be integers, therefore you should round floats to the nearest integer.
## Example
Here's an example of a 2x2 image:
```javascript
[
[ [123, 231, 12], [56, 43, 124] ],
[ [78, 152, 76], [64, 132, 200] ]
]
```
Here's the expected image after transformation:
```javascript
[
[ [122, 122, 122], [74, 74, 74] ],
[ [102, 102, 102], [132, 132, 132] ]
]
```
<center>
You are always welcome to check out some of my other katas:
<b>Very Easy (Kyu 8)</b>
<a href="https://www.codewars.com/kata/5926d7494b2b1843780001e6">Add Numbers</a>
<b>Easy (Kyu 7-6)</b>
<a href="https://www.codewars.com/kata/590ee3c979ae8923bf00095b">Convert Color image to greyscale</a><br>
<a href="https://www.codewars.com/kata/591190fb6a57682bed00014d">Array Transformations</a><br>
<a href="https://www.codewars.com/kata/5914e068f05d9a011e000054">Basic Compression</a><br>
<a href="https://www.codewars.com/kata/5927db23fb1f934238000015">Find Primes in Range</a><br>
<a href="https://www.codewars.com/kata/592915cc1fad49252f000006">No Ifs No Buts</a>
<b>Medium (Kyu 5-4)</b>
<a href="https://www.codewars.com/kata/5910b92d2bcb5d98f8000001">Identify Frames In An Image</a><br>
<a href="https://www.codewars.com/kata/5912950fe5bc241f9b0000af">Photoshop Like - Magic Wand</a><br>
<a href="https://www.codewars.com/kata/59255740ca72049e760000cd">Scientific Notation</a><br>
<a href="https://www.codewars.com/kata/59267e389b424dcd3f0000c9">Vending Machine - FSA</a><br>
<a href="https://www.codewars.com/kata/59293c2cfafd38975600002d">Find Matching Parenthesis</a>
<b>Hard (Kyu 3-2)</b>
<a href="https://www.codewars.com/kata/59276216356e51478900005b">Ascii Art Generator</a>
|
algorithms
|
from statistics import mean
def grey(rgb):
return [int(round(mean(rgb)))] * 3
def color_2_grey(colors):
return [[grey(pixel) for pixel in row] for row in colors]
|
Convert Color image to greyscale
|
590ee3c979ae8923bf00095b
|
[
"Image Processing",
"Algorithms"
] |
https://www.codewars.com/kata/590ee3c979ae8923bf00095b
|
7 kyu
|
This is the rightful continuation to this easier Kata [**here**](https://www.codewars.com/kata/5853213063adbd1b9b0000be) and some rules are the same with few substantial alterations.
This time we have to deal with a situation like Super Street Fighter 2 Selection Screen:

As you may see, we now have 16 characters on 3 rows. You might think: let's make an array of 3 arrays! But that's not enough.
## Empty space
The first character of the first row (Ryu) is not aligned with the first of the second row (Balrog) but with the second (Ken) and the same goes with the other side; therefore we need to introduce something new, like an offset: the **Empty Space**.
The empty space, represented as empty string `""`, will allow us to keep the grid aligned and rectangular, with spaces that won't be selectable.
In this case we need 2 empty spaces (3 rows x 6 columns = 18 slots, 18 slots - 16 characters = 2 empty spaces). Like this:
```
| | Ryu | E.Honda | Blanka | Guile | |
| Balrog | Ken | Chun Li | Zangief | Dhalsim | Sagat |
| Vega | T.Hawk | Fei Long | Deejay | Cammy | M.Bison |
```
The moves of the selection cursor are the same as before: rotate horizontally but stop vertically.
When you find empty spaces (1 or more) you need to skip them if you approach them horizontally and get to the next selectable slot with the next fighter on the left or right; and if you approach them vertically you need to just stop and stay where you are.
Example: if you are on Ryu and move left, you must get to Guile; if you are on Balrog and move up, you must stay on Balrog.
Notice: I might put empty spaces *right in the middle* and the rectangular grids can be any size, not only 3x6, deal with this too.
## What's new
So, let's resume what are the **new issues** in this harder version of the Kata:
- The initial position might be any non-empty slot in the grid (given as input).
- The characters grid (also given as input) might have any rectangular layout, not only 3 rows.
- The grid might contain empty spaces, both on the borders or right in the middle.
## Input
~~~if-not:rust
- Fighters grid;
- Initial position;
- List of moves.
The third input parameter is still the list of moves (all valid ones: left, right, up or down).
~~~
~~~if:rust
- Fighters grid
- Initial position as `Position`
- List of moves as `Direction`
The `preloaded` module contains the following code:
```rust
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Direction {
Up,
Down,
Left,
Right,
}
#[derive(Debug, Copy, Clone)]
pub struct Position {
pub x: usize,
pub y: usize,
}
impl Position {
pub fn new(x: usize, y: usize) -> Self {
Self { x, y }
}
}
```
~~~
## Output
The output is the same as before: the list of characters that have been hovered by the selection cursor after each move, successful or not.
Hopefully test cases will complete my explanation.
|
reference
|
MOVES = {"up": (- 1, 0), "down": (1, 0), "right": (0, 1), "left": (0, - 1)}
def super_street_fighter_selection(fighters, initial_position, moves):
y, x = initial_position
hovered_fighters = []
for move in moves:
dy, dx = MOVES[move]
y += dy
if not 0 <= y < len(fighters) or not fighters[y][x]:
y -= dy
x = (x + dx) % len(fighters[y])
while not fighters[y][x]:
x = (x + dx) % len(fighters[y])
hovered_fighters . append(fighters[y][x])
return hovered_fighters
|
Street Fighter 2 - Character Selection - Part 2
|
58583922c1d5b415b00000ff
|
[
"Arrays",
"Lists",
"Fundamentals",
"Graph Theory"
] |
https://www.codewars.com/kata/58583922c1d5b415b00000ff
|
5 kyu
|
In this kata, you must write a function that expects a two-dimensional list `matrix` (minimum size: 2 x 2) as the only argument.
The return value will be a two-dimensional list (size: 2 x 2) showing only the corners after `n` clockwise rotations.
Examples of corner values, rotation and corners-only return value: `invalid as a kata test case, demonstration only!`
# corners = 1, 2, 3, 4
# non-corners = 0
[[1, 0, 2],
[0, 0, 0],
[4, 0, 3]]
# above 2D list after a single clockwise rotation
[[4, 0, 1],
[0, 0, 0],
[3, 0, 2]]
# return value of above 2D list showing only the corners
[[4, 1],
[3, 2]]
* The total number of clockwise rotations, `n`, is equal to the sum of all corner values multiplied by the sum of all non-corner values.
* Values in `matrix` are ASCII characters, booleans or integers. Use the integer values when determining the corner/non-corner sums.
* In the case of ASCII characters, use the corresponding ASCII value. `A == 65, Z == 90, etc`
* In the case of booleans, use the corresponding integer value. `True/true == 1, False/false == 0`
* `matrix` will always be a two-dimensional list (minimum size: 2 x 2)
* If the initial size of `matrix` is 2 x 2, no rotation is needed.
Examples:
```python
rotate_corners([[1, 2], [3, 4]]) == [[1, 2], [3, 4]]
rotate_corners([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[1, 3], [7, 9]]
rotate_corners([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'z']]) == [['g', 'a'], ['z', 'c']]
rotate_corners([['!', ':', 7, '^'], [997, 'T', '<', '+'], [47, 'v', 531, 'Q'], ['{', '[', ']', '}']]) == [['}', '{'], ['^', '!']]
rotate_corners([[True, 77, False], ['$', '^', 972]]) == [[False, 972], [True, '$']]
```
```javascript
rotateCorners([[1, 2], [3, 4]]) == [[1, 2], [3, 4]]
rotateCorners([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[1, 3], [7, 9]]
rotateCorners([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'z']]) == [['g', 'a'], ['z', 'c']]
rotateCorners([['!', ':', 7, '^'], [997, 'T', '<', '+'], [47, 'v', 531, 'Q'], ['{', '[', ']', '}']]) == [['}', '{'], ['^', '!']]
rotateCorners([[true, 77, false], ['$', '^', 972]]) == [[false, 972], [true, '$']]
```
```csharp
rotateCorners(new [] { new object[] { 1, 2 }, new object[] { 3, 4 } }) -> [[1, 2], [3, 4]]
rotateCorners(new [] { new object[] { 1, 2, 3 }, new object[] { 4, 5, 6 }, new object[] { 7, 8, 9 } }) -> [[1, 3], [7, 9]]
rotateCorners([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'z']]) == [['g', 'a'], ['z', 'c']]
rotateCorners(new [] { new object[] { '!', ':', 7, '^' }, new object[] { 997, 'T', '<', '+' }, new object[] { 47, 'v', 531, 'Q' }, new object[] { '{', '[', ']', '}'} }) -> [['}', '{'], ['^', '!']]
rotateCorners(new [] { new object[] { true, 77, false }, new object[] { '$', '^', 972 } }) -> [[false, 972], [true, '$']]
```
*This is my first authored kata. Any feedback/suggestions would be appreciated!*
|
reference
|
def rotate_corners(matrix):
def score(m): return sum(sum(ord(c) if isinstance(c, str) else int(c)
for c in r) for r in m)
corners = [[matrix[i][j] for j in (0, - 1)] for i in (0, - 1)]
n = (score(matrix) - score(corners)) * score(corners) % 4
for _ in range(n):
corners = list(map(list, zip(* corners[:: - 1])))
return corners
|
Rotate Corners
|
5717fbf85122b8f757001b3f
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5717fbf85122b8f757001b3f
|
6 kyu
|
Consider the sequence `a(1) = 7, a(n) = a(n-1) + gcd(n, a(n-1)) for n >= 2`:
`7, 8, 9, 10, 15, 18, 19, 20, 21, 22, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 69, 72, 73...`.
Let us take the differences between successive elements of the sequence and
get a second sequence `g: 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1...`.
For the sake of uniformity of the lengths of sequences **we add** a `1` at the head of g:
`g: 1, 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1...`
Removing the 1s gives a third sequence:
`p: 5, 3, 11, 3, 23, 3...`
where you can see prime numbers.
#### Task:
Write functions:
```
1: an(n) with parameter n: returns the first n terms of the series of a(n) (not tested)
2: gn(n) with parameter n: returns the first n terms of the series of g(n) (not tested)
3: countOnes(n) with parameter n: returns the number of 1 in the series gn(n)
(don't forget to add a `1` at the head) # (tested)
4: p(n) with parameter n: returns an array filled with the n first distinct primes in the same order they are found in the sequence gn (not tested)
5: maxPn(n) with parameter n: returns the biggest prime number of the above p(n) # (tested)
6: anOver(n) with parameter n: returns an array (n terms) of the a(i)/i for every i such g(i) != 1 (not tested but interesting result)
7: anOverAverage(n) with parameter n: returns as an *integer* the average of anOver(n) # (tested)
```
#### Note:
You can write directly functions `3:`, `5:` and `7:`. There is no need to write functions `1:`, `2:`, `4:` `6:` except out of pure curiosity.
|
reference
|
from fractions import gcd
def seq():
i, a, g = 1, 7, 1
while 1:
yield i, a, g
i += 1
g = gcd(i, a)
a += g
def count_ones(n):
return sum(g == 1 for _, (i, a, g) in zip(range(n), seq()))
def p(n):
seen = set()
for i, a, g in seq():
if not n:
break
if g > 1 and g not in seen:
n -= 1
seen . add(g)
yield g
def max_pn(n):
return max(p(n))
def an_over(n):
for i, a, g in seq():
if not n:
break
if g > 1:
n -= 1
yield a / i
def an_over_average(n):
return sum(an_over(n)) / n
|
Weird prime generator
|
562b384167350ac93b00010c
|
[
"Fundamentals",
"Mathematics"
] |
https://www.codewars.com/kata/562b384167350ac93b00010c
|
5 kyu
|
You will be given two inputs: a string of words and a letter. For each string, return the alphabetic character after every instance of letter(case insensitive).
If there is a number, punctuation or underscore following the letter, it should not be returned.
```
If letter = 'r':
comes_after("are you really learning Ruby?") # => "eenu"
comes_after("Katy Perry is on the radio!") # => "rya"
comes_after("Pirates say arrrrrrrrr.") # => "arrrrrrrr"
comes_after("r8 your friend") # => "i"
```
Return an empty string if there are no instances of `letter` in the given string.
Adapted from: [Ruby Kickstart](https://github.com/JoshCheek/ruby-kickstart/blob/master/session1/challenge/7_string.rb)
|
reference
|
def comes_after(st, letter):
letter = letter . lower()
return '' . join(b for a, b in zip(st . lower(), st[1:]) if a == letter and b . isalpha())
|
What comes after?
|
590f5b4a7bbb3e246000007d
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/590f5b4a7bbb3e246000007d
|
7 kyu
|
```
------------------------------------------------------------------
we are programmed just to do anything you want us to
w e a r e t h e r o b o t s
-----------------------------------------------------------[ d[(0)(0)]b]
```
Task.....
You will receieve an array of strings
such as
```
a = ["We're functioning automatik d[(0)(0)]b","And we are dancing mechanik d[(0)(0)]b"]
```
Count the robots represented by d[(0)(0)]b
Unless of course the factory replaced a part on the robot.....
```
d[(0)(0)]b could look a little different depending on the supplier maybe like this
d[(0)(0)]B or d[(0)(0}]B
```
It's pretty random actually but with a global supply chain it's hard to control which part you get. Most of the parts are made global except the ones made in the factory which do not change.
```
d[(0)(0)]B
In all robots the eyes do not change.
d[(0)(0)]B
...0..0...
^ ^
| |
The rest of the body can change at random.
legs any in => abcdefghijklmnopqrstuvwxyz
...0..0...
^ ^
| |
body any in => |};&#[]/><()*
...0..0...
^^ ^^ ^^
|| || ||
```
There may be cases where a part is totally missing and of course a robot cannot function at all without a part or where the factory put a valid part in the wrong place and it's again not a valid robot.
return an array of strings with a count of each of the following tasks.
Case insensitve count of robots in string with "automatik" or "mechanik". Strings do not contain both "automatik and "mechanik".
Return an array with the count like below
```
a[0] = automatik count
a[1] = mechanik count
["1 robots functioning automatik", "1 robots dancing mechanik"]
```
to pay tribute...respect :)
https://en.wikipedia.org/wiki/The_Robots
Songwriters: HUETTER, RALF / SCHNEIDER-ESLEBEN, FLORIAN / BARTOS, KARL
|
games
|
import re
LEGS = r'[a-z]'
BODY = r'[|};&#\[\]/><()*]'
def counRobots(strng, typeRobot):
return str(sum(len(re . findall(LEGS + BODY + "{2}0" + BODY + "{2}0" + BODY + "{2}" + LEGS, substr))
for substr in map(str . lower, strng)
if typeRobot in substr))
def count_robots(a):
return ["{} robots functioning automatik" . format(counRobots(a, "automatik")),
"{} robots dancing mechanik" . format(counRobots(a, "mechanik"))]
|
We are the Robots d[(0)(0)]b
|
587ae98e2ab0ef32ef00004c
|
[
"Algorithms",
"Data Structures",
"Regular Expressions",
"Puzzles",
"Strings"
] |
https://www.codewars.com/kata/587ae98e2ab0ef32ef00004c
|
6 kyu
|
In this Kata, you need to simulate an old mobile display, similar to this one:
```
***************************
* *
* *
* CodeWars *
* *
* *
* Menu Contacts *
***************************
```
**Input Parameters:**
- number of characters for width (`n`)
- height-to-width ratio in percentage (`p`)
Example:
if `n=30` and `p=40`, then display will be 30 characters large and its height will be 40% of n.
**Rules and Notes:**
- the border, as you can see, is filled with `*`;
- the rounding of divisions and float numbers is always by the integer (`1.2`, `1.5`, `1.9` they are always reduced to `1`), keep this in mind when you calculate proportions;
for Python: always multiply first, then divide.
- the menus `Menu` and `Contacts` are always in the second last line, at 1 character distance respectively from the left and from the right border;
- the `CodeWars` logo is always in the middle horizontally and in the `half-1` line vertically;
- the width `n` must be always at least 20 characters and the percentage `p` must be always at least 30%, take care of this (otherwise menus won't likely fit).
- random tests might get big and percentages might be higher than 100;
**OFF-TOPIC before Examples:**
A bit of advertisement for an old unnoticed Kata that I translated from Python to Javascript:
[Character Counter and Bars Graph](https://www.codewars.com/kata/character-counter-and-bars-graph)
**Examples:**
- mobileDisplay(30,40):
```
******************************
* *
* *
* *
* *
* CodeWars *
* *
* *
* *
* *
* Menu Contacts *
******************************
```
- mobileDisplay(25,50):
```
*************************
* *
* *
* *
* *
* CodeWars *
* *
* *
* *
* *
* Menu Contacts *
*************************
```
|
reference
|
def mobile_display(width, height_ratio):
width, height_ratio = max(width, 20), max(height_ratio, 30)
height = width * height_ratio / / 100
def center(string, width, filler, prefix, suffix):
width -= len(string) + len(prefix) + len(suffix)
left, right = width / / 2, (width + 1) / / 2
return prefix + left * filler + string + right * filler + suffix
title = [center('CodeWars', width, ' ', '*', '*')]
filler = [center('', width, ' ', '*', '*')]
header = [center('', width, '*', '', '')]
footer = [center('', width, ' ', '* Menu', 'Contacts *')] + header
return '\n' . join(center(title, height, filler, header, footer))
|
Old Mobile Display
|
584e8bba044a15d3ed00016c
|
[
"Strings",
"ASCII Art",
"Fundamentals"
] |
https://www.codewars.com/kata/584e8bba044a15d3ed00016c
|
6 kyu
|
Alan's child can be annoying at times.
When Alan comes home and tells his kid what he has accomplished today, his kid never believes him.
Be that kid.
Your function 'AlanAnnoyingKid' takes as input a sentence spoken by Alan (a string). The sentence contains the following structure:
"Today I " + [action_verb] + [object] + "."
(e.g.: "Today I played football.")
Your function will return Alan's kid response, which is another sentence with the following structure:
"I don't think you " + [action_performed_by_alan] + " today, I think you " + ["did" OR "didn't"] + [verb_of _action_in_present_tense] + [" it!" OR " at all!"]
(e.g.:"I don't think you played football today, I think you didn't play at all!")
Note the different structure depending on the presence of a negation in Alan's first sentence (e.g., whether Alan says "I dind't play football", or "I played football").
! Also note: Alan's kid is young and only uses simple, regular verbs that use a simple "ed" to make past tense.
There are random test cases.
Some more examples:
input = "Today I played football."
output = "I don't think you played football today, I think you didn't play at all!"
input = "Today I didn't attempt to hardcode this Kata."
output = "I don't think you didn't attempt to hardcode this Kata today, I think you did attempt it!"
input = "Today I didn't play football."
output = "I don't think you didn't play football today, I think you did play it!"
input = "Today I cleaned the kitchen."
output = "I don't think you cleaned the kitchen today, I think you didn't clean at all!"
|
reference
|
OUTPUT = "I don't think you {} today, I think you {} {} {}!" . format
def alan_annoying_kid(phrase):
words = phrase . split()
action = ' ' . join(words[2:]). rstrip('.')
if "didn't" in phrase:
return OUTPUT(action, 'did', words[3], 'it')
return OUTPUT(action, "didn't", words[2][: - 2], 'at all')
|
The Sceptical Kid Generator
|
570957fc20a35bd2df0004f9
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/570957fc20a35bd2df0004f9
|
6 kyu
|
A traveling salesman has to visit clients. He got each client's address e.g. `"432 Main Long Road St. Louisville OH 43071"` as a list.
The basic zipcode format usually consists of two capital letters followed by a white space and five digits.
The list of clients to visit was given as a string of all addresses, each separated from the others by a comma, e.g. :
`"123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432"`.
To ease his travel he wants to group the list by zipcode.
#### Task
The function `travel` will take two parameters `r` (addresses' list of all clients' as a string) and `zipcode` and returns a string in the following format:
`zipcode:street and town,street and town,.../house number,house number,...`
The street numbers must be in the same order as the streets where they belong.
If a given zipcode doesn't exist in the list of clients' addresses return `"zipcode:/"`
#### Examples
```
r = "123 Main Street St. Louisville OH 43071,432 Main Long Road St. Louisville OH 43071,786 High Street Pollocksville NY 56432"
travel(r, "OH 43071") --> "OH 43071:Main Street St. Louisville,Main Long Road St. Louisville/123,432"
travel(r, "NY 56432") --> "NY 56432:High Street Pollocksville/786"
travel(r, "NY 5643") --> "NY 5643:/"
```
#### Note for Elixir:
In Elixir the empty addresses' input is an empty *list*, not an empty string.
#### Note:
You can see a few addresses and zipcodes in the test cases.
|
reference
|
def travel(r, zipcode):
streets = []
nums = []
addresses = r . split(',')
for address in addresses:
if ' ' . join(address . split()[- 2:]) == zipcode:
streets . append(' ' . join(address . split()[1: - 2]))
nums += address . split()[: 1]
return '{}:{}/{}' . format(zipcode, ',' . join(streets), ',' . join(nums))
|
Salesman's Travel
|
56af1a20509ce5b9b000001e
|
[
"Fundamentals",
"Strings"
] |
https://www.codewars.com/kata/56af1a20509ce5b9b000001e
|
6 kyu
|
<h4>DevOps legacy roasting!</h4>
Save the business from technological purgatory.
Convert IT to DevOps, modernize application workloads, take it all to the Cloud…….
You will receive a string of workloads represented by words….some legacy and some modern mixed in with complaints from the business….your job is to burn the legacy in a disco inferno and count the value of each roasting and the number of complaints resolved.
Here is a list of all complaints which need to be resolved:
```
complaints (in this format, case-insensitive) -> "slow!", "expensive!", "manual!", "down!", "hostage!", "security!"
```
The value is based on real or perceived pain by the business and the expense of keeping it all running.
Pull the values from the list below...
```
1970s Disco Fever Architecture………
Sort of like a design from Saturday night Fever….
( . )
) ( )
. ' . ' . ' .
( , ) (. ) ( ', )
.' ) ( . ) , ( , ) ( .
). , ( . ( ) ( , ') .' ( , )
(_,) . ), ) _) _,') (, ) '. ) ,. (' )
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Burn Baby Burn in a Disco Inferno
Legacy is identified by the following keywords:
1000 points - COBOL of any kind whatsoever
keyword => "COBOL"
500 points - non-object oriented architecture
keyword => "nonobject"
500 points - monolithic architecture
keyword => "monolithic"
100 points - fax system dependencies
keyword => "fax"
100 points - modem dependencies
keyword => "modem"
50 points - thick client dependencies
keyword => "thickclient"
50 points - tape drive dependencies
keyword => "tape"
50 points - floppy drive dependencies
keyword => "floppy"
50 points - workloads with DevOps Anti-patterns
keyword => "oldschoolIT"
The count is based on case-insensitive words!
Return a string in the following format
->'Burn baby burn disco inferno 2400 points earned in this roasting and 2 complaints resolved!'
If there are no complaints and no legacy from above return
->'These guys are already DevOps and in the Cloud and the business is happy!'
```
If you have any doubt COBOL should be burned.. just look at
this quote from Dijkstra.
The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offense. Edsger Dijkstra
For more information on how to have a disco inferno
https://www.youtube.com/watch?v=A_sY2rjxq6M
Disclaimer - this should only be attempted by trained professionals and in accordance with local ordinances. EX: Disco may be outlawed in certain countries.
|
reference
|
import re
complaints = ["slow!", "expensive!", "manual!",
"down!", "hostage!", "security!"]
legacy = {
"cobol": 1000,
"nonobject": 500,
"monolithic": 500,
"fax": 100,
"modem": 100,
"thickclient": 50,
"tape": 50,
"floppy": 50,
"oldschoolit": 50
}
def roast_legacy(workloads):
complaining = sum(1 for _ in re . finditer(
'|' . join(complaints), workloads . lower()))
roasting = sum(legacy[m . group()] for m in re . finditer(
'|' . join(legacy), workloads . lower()))
if roasting or complaining:
return 'Burn baby burn disco inferno %d points earned in this roasting and %d complaints resolved!' % (roasting, complaining)
else:
return 'These guys are already DevOps and in the Cloud and the business is happy!'
|
DevOps legacy roasting -> disco inferno -> burn baby burn
|
58ade79f3c97367977000274
|
[
"Regular Expressions",
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/58ade79f3c97367977000274
|
6 kyu
|
In this Kata, we will calculate running pace. To do that, we have to know the distance and the time.
Create the following function:
```if:python
`running_pace(distance, time)`
```
```if:javascript, typescript
`runningPace(distance, time)`
```
Where:
`distance` - A float with the number of kilometres
`time` - A string containing the time it took to travel the distance. It will always be minutes:seconds. For example "25:00" means 25 minutes. You don't have to deal with hours.
The function should return the pace, for example "4:20" means it took 4 minutes and 20 seconds to travel one kilometre.
**Note**: The pace should always return only the number of minutes and seconds. You don't have to convert these into hours. Floor the number of seconds.
|
algorithms
|
def running_pace(distance, time):
m, s = map(int, time . split(':'))
second = m * 60 + s
pace = second / distance
return f' { int ( pace / / 60 )} : { int ( pace % 60 ):0 2 } '
|
What's your running pace?
|
578b8c0e84ac69a4d20004c8
|
[
"Mathematics",
"Strings",
"Algorithms",
"Date Time"
] |
https://www.codewars.com/kata/578b8c0e84ac69a4d20004c8
|
6 kyu
|
# Task
Let's call a string cool if it is formed only by Latin letters and no two lowercase and no two uppercase letters are in adjacent positions. Given a string, check if it is cool.
# Input/Output
`[input]` string `s`
A string that contains uppercase letters, lowercase letters numbers and spaces.
`1 ≤ s.length ≤ 20.`
`[output]` a boolean value
`true` if `s` is cool, `false` otherwise.
# Example
For `s = "aQwFdA"`, the output should be `true`
For `s = "aBC"`, the output should be `false`;
For `s = "AaA"`, the output should be `true`;
For `s = "q q"`, the output should be `false`.
|
reference
|
def cool_string(s):
return s . isalpha() and all(x . islower() != y . islower() for x, y in zip(s, s[1:]))
|
Simple Fun #253: Cool String
|
590fd3220f05b4f1ad00007c
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/590fd3220f05b4f1ad00007c
|
7 kyu
|
You will be given an array which lists the current inventory of stock in your store and another array which lists the new inventory being delivered to your store today.
Your task is to write a function that returns the updated list of your current inventory **in alphabetical order**.
## Example
```javascript
currentStock = [[25, 'HTC'], [1000, 'Nokia'], [50, 'Samsung'], [33, 'Sony'], [10, 'Apple']]
newStock = [[5, 'LG'], [10, 'Sony'], [4, 'Samsung'], [5, 'Apple']]
updateInventory(currentStock, newStock) ==>
[[15, 'Apple'], [25, 'HTC'], [5, 'LG'], [1000, 'Nokia'], [54, 'Samsung'], [43, 'Sony']]
```
```python
cur_stock = [(25, 'HTC'), (1000, 'Nokia'), (50, 'Samsung'), (33, 'Sony'), (10, 'Apple')]
new_stock = [(5, 'LG'), (10, 'Sony'), (4, 'Samsung'), (5, 'Apple')]
update_inventory(cur_stock, new_stock) ==>
[(15, 'Apple'), (25, 'HTC'), (5, 'LG'), (1000, 'Nokia'), (54, 'Samsung'), (43, 'Sony')]
```
```ruby
cur_stock = [[25, 'HTC'], [1000, 'Nokia'], [50, 'Samsung'], [33, 'Sony'], [10, 'Apple']]
new_stock = [[5, 'LG'], [10, 'Sony'], [4, 'Samsung'], [5, 'Apple']]
update_inventory(cur_stock, new_stock) ==>
[[15, 'Apple'], [25, 'HTC'], [5, 'LG'], [1000, 'Nokia'], [54, 'Samsung'], [43, 'Sony']]
```
___
*Kata inspired by the FreeCodeCamp's 'Inventory Update' algorithm.*
|
algorithms
|
from collections import defaultdict
def update_inventory(cur_stock, new_stock):
answer = defaultdict(int)
for stock, item in cur_stock + new_stock:
answer[item] += stock
return [(answer[item], item) for item in sorted(answer)]
|
Update inventory in your smartphone store
|
57a31ce7cf1fa5a1e1000227
|
[
"Algorithms",
"Data Structures",
"Arrays"
] |
https://www.codewars.com/kata/57a31ce7cf1fa5a1e1000227
|
6 kyu
|
We all love the future president (or Führer or duce or sōtō as he could find them more fitting) donald trump, but we might fear that some of his many fans like <a href="https://www.washingtonpost.com/politics/donald-trump-alter-ego-barron/2016/05/12/02ac99ec-16fe-11e6-aa55-670cabef46e0_story.html" target="_blank" title="donald trump is an egomaniac scammer">John Miller or John Barron</a> are not making him justice, sounding too much like their (and our as well, of course!) hero and thus risking to compromise him.
For this reason we need to create a function to detect the original and unique rhythm of our beloved leader, typically having a lot of extra vowels, all ready to fight the establishment.
The index is calculated based on how many vowels are repeated more than once in a row and dividing them by the total number of vowels a petty enemy of America would use.
For example:
```c
trump_detector("I will build a huge wall") == 0 // definitely not our trump: 0 on the trump score
trump_detector("HUUUUUGEEEE WAAAAAALL") == 4 // 4 extra "U", 3 extra "E" and 5 extra "A" on 3 different vowel groups: 12/3 make for a trumpy trumping score of 4: not bad at all!
trump_detector("listen migrants: IIII KIIIDD YOOOUUU NOOOOOOTTT") == 1.56 // 14 extra vowels on 9 base ones
```
```javascript
trumpDetector("I will build a huge wall")==0 #definitely not our trump: 0 on the trump score
trumpDetector("HUUUUUGEEEE WAAAAAALL")==4 #4 extra "U", 3 extra "E" and 5 extra "A" on 3 different vowel groups: 12/3 make for a trumpy trumping score of 4: not bad at all!
trumpDetector("listen migrants: IIII KIIIDD YOOOUUU NOOOOOOTTT")==1.56 //14 extra vowels on 9 base ones
```
```python
trump_detector("I will build a huge wall")==0 #definitely not our trump: 0 on the trump score
trump_detector("HUUUUUGEEEE WAAAAAALL")==4 #4 extra "U", 3 extra "E" and 5 extra "A" on 3 different vowel groups: 12/3 make for a trumpy trumping score of 4: not bad at all!
trump_detector("listen migrants: IIII KIIIDD YOOOUUU NOOOOOOTTT")==1.56 #14 extra vowels on 9 base ones
```
```ruby
trump_detector("I will build a huge wall")==0 #definitely not our trump: 0 on the trump score
trump_detector("HUUUUUGEEEE WAAAAAALL")==4 #4 extra "U", 3 extra "E" and 5 extra "A" on 3 different vowel groups: 12/3 make for a trumpy trumping score of 4: not bad at all!
trump_detector("listen migrants: IIII KIIIDD YOOOUUU NOOOOOOTTT")==1.56 #14 extra vowels on 9 base ones
```
**Notes:** vowels are only the ones in the patriotic group of "aeiou": "y" should go back to Greece if she thinks she can have the same rights of true American vowels; there is always going to be at least a vowel, as silence is the option of coward Kenyan/terrorist presidents and their friends.
Round each result by two decimal digits: there is no place for small fry in Trump's America.
*Special thanks for [Izabela](https://www.codewars.com/users/ijelonek) for support and proof-reading.*
|
algorithms
|
import re
def trump_detector(ts):
x = re . findall(r'([aeiou])(\1*)', ts, re . I)
y = [len(i[1]) for i in x]
return round(sum(y) / len(y), 2)
|
Trumpness detector
|
57829376a1b8d576640000d6
|
[
"Regular Expressions",
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/57829376a1b8d576640000d6
|
6 kyu
|
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! :)
|
reference
|
def order_type(arr):
if not arr:
return 'Constant'
arr = list(
map(len, [str(elt) if type(elt) == int else elt for elt in arr]))
cmp = sorted(arr)
if arr == [arr[0]] * len(arr):
s = 'Constant'
elif arr == cmp:
s = 'Increasing'
elif arr == cmp[:: - 1]:
s = 'Decreasing'
else:
s = 'Unsorted'
return s
|
Identify the array's ordering
|
57f669477c9a2b1b9700022d
|
[
"Arrays",
"Strings",
"Algorithms",
"Fundamentals"
] |
https://www.codewars.com/kata/57f669477c9a2b1b9700022d
|
6 kyu
|
You've just finished writing the last chapter for your novel when a virus suddenly infects your document. It has swapped the 'i's and 'e's in 'ei' words and capitalised random letters. Write a function which will:
a) remove the spelling errors in 'ei' words. (Example of 'ei' words: their, caffeine, deceive, weight)
b) only capitalise the first letter of each sentence. Make sure the rest of the sentence is in lower case.
Example:
He haD iEght ShOTs of CAffIEne. --> He had eight shots of caffeine.
|
reference
|
def proofread(s):
return '. ' . join(i . lower(). replace('ie', 'ei'). capitalize() for i in s . split('. '))
|
Proof Read
|
583710f6b468c07ba1000017
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/583710f6b468c07ba1000017
|
6 kyu
|
The principal of a school likes to put challenges to the students related with finding words of certain features.
One day she said: "Dear students, the challenge for today is to find a word that has only one vowel and seven consonants but cannot have the letters "y" and "m". I'll give a special award for the first student that finds it." One of the students used his dictionary and spent all the night without sleeping, trying in vain to find the word. The next day, the word had not been found yet.
This student observed that the principal has a pattern in the features for the wanted words:
- The word should have **n** vowels, may be repeated, for example: in "engineering", n = 5.
- The word should have **m** consonants, may be repeated also: in "engineering", m = 6.
- The word should not have some forbidden letters (in an array), forbid_letters
You will be provided with a list of words, WORD_LIST(python/crystal), wordList(javascript), wordList (haskell), $word_list(ruby), and you have to create the function, ```wanted_words()```, that receives the three arguments in the order given above, ```wanted_words(n, m, forbid_list)```and output an array with the word or an array, having the words in the order given in the pre-loaded list, in the case of two or more words were found.
Let's see some cases:
```haskell
wantedWords 1 7 ["m", "y"] == ["strength"]
wantedWords 3 7 ["m", "y"] == ["afterwards", "background", "photograph", "successful", "understand"]
```
```javascript
wantedWords(1, 7, ["m", "y"]) == ["strength"]
wantedWords(3, 7, ["m", "y"]) == ['afterwards', 'background', 'photograph', 'successful', 'understand']
```
```ruby
wanted_words(1, 7, ["m", "y"]) == ["strength"]
wanted_words(3, 7, ["m", "y"]) == ['afterwards', 'background', 'photograph', 'successful', 'understand']
```
```crystal
wanted_words(1, 7, ["m", "y"]) == ["strength"]
wanted_words(3, 7, ["m", "y"]) == ['afterwards', 'background', 'photograph', 'successful', 'understand']
```
```python
wanted_words(1, 7, ["m", "y"]) == ["strength"]
wanted_words(3, 7, ["m", "y"]) == ['afterwards', 'background', 'photograph', 'successful', 'understand']
```
For cases where no words are found the function will output an empty array.
```haskell
wantedWords 3 7 ["a", "s" , "m", "y"] == []
```
```javascript
wantedWords(3, 7, ["a", "s" , "m", "y"]) == []
```
```ruby
wanted_words(3, 7, ["a", "s" , "m", "y"]) == []
```
```crystal
wanted_words(3, 7, ["a", "s" , "m", "y"]) == []
```
```python
wanted_words(3, 7, ["a", "s" , "m", "y"]) == []
```
Help our student to win this and the next challenges of the school. He needs to sure about a suspect that he has. That many times there are no solutions for what the principal is asking for.
All words have its letters in lowercase format.
Enjoy it!
|
reference
|
def wanted_words(vowels, consonants, forbidden):
return [w for w in WORD_LIST
if len(w) == vowels + consonants
and sum(map(w . count, 'aeiou')) == vowels
and not any(c in w for c in forbidden)]
|
Word Challenges at School
|
580be55ca671827cfd000043
|
[
"Fundamentals",
"Logic",
"Strings",
"Data Structures",
"Algorithms"
] |
https://www.codewars.com/kata/580be55ca671827cfd000043
|
6 kyu
|
A bar of a certain metal of length ```l``` is subjected to the application of different perpendicular forces (that may have up or down direction). The bar has a foothold at its midpoint ``` S``` . Each point of application of the force is at a distance that has an integer value, respect to the point ``` S```.
<a href="http://imgur.com/KJkXsbl"><img src="http://i.imgur.com/KJkXsbl.png" title="source: imgur.com" /></a>
The array that represents the system drawn above is : ```[2, -3, 1, 2, 'S', 3, -4, 0, 2]```
We are interested in a code that may predict if the bar will rotate with clockwise or anti clockwise spin, or the bar will remain steady.
From Physics we will need the concept of Moment of a Force.
As all the forces are coplanar (the same plane) and the equation of ```the magnitude of the resultant Moment is```:
<a href="http://imgur.com/3fBS9nD"><img src="http://i.imgur.com/3fBS9nD.png?1" title="source: imgur.com" /></a>
Applying the equation to our situation, we will have:
```
M = 2*(-4) + (-3)*(-3) + 1*(-2) + 2*(-1) + 3*1 + (-4)*2 + 0*3 + 2*4 = -8 + 9 - 2 - 2 + 3 - 8 + 8 = 0
```
As the result of the total moment for all the applied forces is ```0```, the bar will not rotate.
Suposse that we change a bit the situation having a new force, of magnitud ```5``` that goes up, at the empty point, on the right of ```S```, at distance ```+3```.
Now the resultant Moment is ```(-5) * 3 = -15```, that means that ```the bar will rotate anti clockwise.```
The function: ```rot_pred()``` (```rotPred()``` in Javascript) will an array of odd amount of terms and a string 'S' in the middle.
```
python
rot_pred([2, -3, 1, 2, 'S', 3, -4, 0, 2]) == 'steady'
rot_pred([2, -3, 1, 2, 'S', 3, -4, -5, 2]) == 'anti clockwise' (
```
If the amount of elements on the right and on the left of ```S``` do not coincide the function will reject the entry.
```
rot_pred([2, -3, 1, 2 'S', 3, -4, -5]) == 'Not a Valid Entry'
```
Enjoy it!
|
reference
|
def rot_pred(arr):
pivot = len(arr) / / 2
if not len(arr) % 2 or arr[pivot] != 'S':
return 'Not a Valid Entry'
moment = sum(i * x for i, x in enumerate(arr, - pivot) if i)
return 'steady' if not moment else 'anti ' * (moment < 0) + 'clockwise'
|
Resultant Moment I
|
57a125e772292dadcb0005f5
|
[
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic"
] |
https://www.codewars.com/kata/57a125e772292dadcb0005f5
|
6 kyu
|
The aim of this Kata is to write a function which will reverse the case of all consecutive duplicate letters in a string. That is, any letters that occur one after the other and are identical.
If the duplicate letters are lowercase then they must be set to uppercase, and if they are uppercase then they need to be changed to lowercase.
**Examples:**
```javascript
reverseCase("puzzles") Expected Result: "puZZles"
reverseCase("massive") Expected Result: "maSSive"
reverseCase("LITTLE") Expected Result: "LIttLE"
reverseCase("shhh") Expected Result: "sHHH"
```
```python
reverse_case("puzzles") Expected Result: "puZZles"
reverse_case("massive") Expected Result: "maSSive"
reverse_case("LITTLE") Expected Result: "LIttLE"
reverse_case("shhh") Expected Result: "sHHH"
```
```ruby
reverse_case("puzzles") Expected Result: "puZZles"
reverse_case("massive") Expected Result: "maSSive"
reverse_case("LITTLE") Expected Result: "LIttLE"
reverse_case("shhh") Expected Result: "sHHH"
```
```crystal
reverse_case("puzzles") Expected Result: "puZZles"
reverse_case("massive") Expected Result: "maSSive"
reverse_case("LITTLE") Expected Result: "LIttLE"
reverse_case("shhh") Expected Result: "sHHH"
```
Arguments passed will include only alphabetical letters A–Z or a–z.
|
reference
|
import re
def reverse(s):
return re . sub(r'(.)\1+', lambda m: m . group(). swapcase(), s)
|
Case Reversal of Consecutive Duplicates
|
577c2d68311a24132a0002a5
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/577c2d68311a24132a0002a5
|
6 kyu
|
# Description:
Convert the continuous exclamation marks or question marks to a digit, Use all the digits to form a number. If this number is a prime number, return it. If not, divide this number by the smallest factor that it is greater than 1, until it becomes a prime number.
You can assume that all test results are greater than 1 and the length of a continuous substring(! or ?) is always less than 10.
# Examples
```
convert("!!") == 2
convert("!??") == 3
(12 --> 6 --> 3)
convert("!???") == 13
convert("!!!??") == 2
(32 --> 16 --> 8 --> 4 --> 2)
convert("!!!???") == 11
(33 --> 11)
convert("!???!!") == 11
(132 --> 66 --> 33 --> 11)
convert("!????!!!?") == 53
(1431 --> 477 --> 159 --> 53)
convert("!!!!!!!???????") == 11
(77 --> 11)
```
|
reference
|
from gmpy2 import is_prime, next_prime
from itertools import groupby
def convert(s):
x = int('' . join(str(sum(1 for _ in l)) for _, l in groupby(s)))
p = 2
while not is_prime(x):
while x > p and x % p == 0:
x / /= p
p = next_prime(p)
return x
|
Exclamation marks series #14: Convert the exclamation marks and question marks to a prime number
|
57fb1705f815ebd49e00024c
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/57fb1705f815ebd49e00024c
|
6 kyu
|
Time to win the lottery!
Given a lottery ticket (ticket), represented by an array of 2-value arrays, you must find out if you've won the jackpot.
Example ticket:
```javascript
[ [ 'ABC', 65 ], [ 'HGR', 74 ], [ 'BYHT', 74 ] ]
```
```cpp
{ { "ABC", 65 }, { "HGR", 74 }, { "BYHT", 74 } }
```
```c
{ { "ABC", 65 }, { "HGR", 74 }, { "BYHT", 74 } }
```
```julia
[ [ "ABC", 65 ], [ "HGR", 74 ], [ "BYHT", 74 ] ]
```
```rust
[ ( "ABC", 65 ), ( "HGR", 74 ), ( "BYHT", 74 ) ]
```
To do this, you must first count the 'mini-wins' on your ticket. Each subarray has both a string and a number within it. If the character code of any of the characters in the string matches the number, you get a mini win. Note you can only have one mini win per sub array.
Once you have counted all of your mini wins, compare that number to the other input provided (win). If your total is more than or equal to (win), return 'Winner!'. Else return 'Loser!'.
All inputs will be in the correct format. Strings on tickets are not always the same length.
|
reference
|
def bingo(ticket, win):
return 'Winner!' if sum(chr(n) in s for s, n in ticket) >= win else 'Loser!'
|
Lottery Ticket
|
57f625992f4d53c24200070e
|
[
"Fundamentals",
"Strings",
"Arrays"
] |
https://www.codewars.com/kata/57f625992f4d53c24200070e
|
6 kyu
|
Consider having a cow that gives a child every year from her fourth year of life on and all her subsequent children do the same.
After n years how many cows will you have?
| After n years | Cow count |
| - | - |
| 0 | 1 |
| 1 | 1 |
| 3 | 2 |
| 4 | 3 |
| 10 | 28 |
Return null if n is not an integer.
Note: Assume all the cows are alive after n years.
|
games
|
def count_cows(n):
if not isinstance(n, int):
return None
return 1 if n < 3 else count_cows(n - 1) + count_cows(n - 3)
|
How many cows do you have?
|
58311536e77f7d08de000085
|
[
"Mathematics",
"Puzzles"
] |
https://www.codewars.com/kata/58311536e77f7d08de000085
|
6 kyu
|
This Kata is like the game of <span style="font-weight:bold;color:red">Snakes & Ladders</span>
There is an array representing the squares on the game board.
The `starting` square is at array element 0. The `final` square is the last array element.
At each "turn" you move forward a number of places (according to the next dice throw).
The value at the square you end up on determines what happens next:
* ```0``` Stay where you are (until next turn)
* ```+n``` This is a "ladder". Go forward n places
* ```-n``` This is a "snake". Go back n places
Each snake or ladder will always end on a square with a 0, so you will only go up or down one at a time.
There are no ladders on the `starting` square, and there are no snakes on the `final` square.
# Rules
* You are given a number of dice throws. The game continues until either:
- You have no throws left, OR
- You end up exactly on the final square
* At each turn, make your move, then go up the "ladders" and down the "snakes" as appropriate.
* If the dice roll overshoots the final square then you cannot move. Roll the dice again.
# Task
Return the index of the array element that you ended up on at the end of the game.
# Example
Start
<pre>
Dice: [2, 1, 5, 1, 5, 4]
Board: [<span style="color:red">0</span>, 0, 3, 0, 0, 0, 0, -2, 0, 0, 0]
</pre>
<hr>
Roll a ```2```. Move forward 2 squares, then go up the ladder (+3)
<pre>
Dice: [<span style="color:yellow">2</span>, 1, 5, 1, 5, 4]
Board: [0, 0, <span style="color:red">3</span>, 0, 0, 0, 0, -2, 0, 0, 0]
Board: [0, 0, 3, 0, 0, <span style="color:red">0</span>, 0, -2, 0, 0, 0]
</pre>
<hr>
Roll a ```1```. Move forward 1 square
<pre>
Dice: [2, <span style="color:yellow">1</span>, 5, 1, 5, 4]
Board: [0, 0, 3, 0, 0, 0, <span style="color:red">0</span>, -2, 0, 0, 0]
</pre>
<hr>
Roll a ```5```. Can't move
<pre>
Dice: [2, 1, <span style="color:yellow">5</span>, 1, 5, 4]
Board: [0, 0, 3, 0, 0, 0, <span style="color:red">0</span>, -2, 0, 0, 0]
</pre>
<hr>
Roll a ```1```. Move forward 1 square, then go down the snake (-2)
<pre>
Dice: [2, 1, 5, <span style="color:yellow">1</span>, 5, 4]
Board: [0, 0, 3, 0, 0, 0, 0, <span style="color:red">-2</span>, 0, 0, 0]
Board: [0, 0, 3, 0, 0, <span style="color:red">0</span>, 0, -2, 0, 0, 0]
</pre>
<hr>
Roll a ```5```. Move forward 5 squares
<pre>
Dice: [2, 1, 5, 1, <span style="color:yellow">5</span>, 4]
Board: [0, 0, 3, 0, 0, 0, 0, -2, 0, 0, <span style="color:red">0</span>]
</pre>
<hr>
You are on the final square so the game ends. Return ```10```
:-)
|
reference
|
def snakes_and_ladders(board, dice):
pos = 0
for d in dice:
if pos + d < len(board):
pos += d + board[pos + d]
return pos
|
Snakes & Ladders
|
5821cd4770ca285b1f0001d5
|
[
"Arrays",
"Fundamentals"
] |
https://www.codewars.com/kata/5821cd4770ca285b1f0001d5
|
6 kyu
|
Laura really hates people using acronyms in her office and wants to force her colleagues to remove all acronyms before emailing her. She wants you to build a system that will edit out all known acronyms or else will notify the sender if unknown acronyms are present.
Any combination of <b>three or more letters in upper case</b> will be considered an acronym. Acronyms will not be combined with lowercase letters, such as in the case of 'KPIs'. They will be kept isolated as a word/words within a string.
For any string:
<li>All instances of 'KPI' must become "key performance indicators" </li>
<li>All instances of 'EOD' must become "the end of the day" </li>
<li>All instances of 'TBD' must become "to be decided"</li>
<li>All instances of 'WAH' must become "work at home"</li>
<li>All instances of 'IAM' must become "in a meeting"</li>
<li>All instances of 'OOO' must become "out of office"</li>
<li>All instances of 'NRN' must become "no reply necessary"</li>
<li>All instances of 'CTA' must become "call to action"</li>
<li>All instances of 'SWOT' must become "strengths, weaknesses, opportunities and threats"</li>
<br>If there are any unknown acronyms in the string, Laura wants you to return <b>only</b> the message:</br>
<li>'[acronym] is an acronym. I do not like acronyms. Please remove them from your email.'</li>
<br>So if the acronym in question was 'BRB', you would return the string:</br>
<li>'BRB is an acronym. I do not like acronyms. Please remove them from your email.'</li>
<br>If there is more than one unknown acronym in the string, return <b>only the first</b> in your answer.</br>
If all acronyms can be replaced with full words according to the above, however, return <b>only</b> the altered string.
If this is the case, ensure that sentences still start with capital letters. '!' or '?' will not be used.
|
algorithms
|
import re
from functools import reduce
_ACRONYMS = {
'KPI': 'key performance indicators',
'EOD': 'the end of the day',
'EOP': 'the end of the day', # snafu in the tests?
'TBD': 'to be decided',
'WAH': 'work at home',
'IAM': 'in a meeting',
'OOO': 'out of office',
'NRN': 'no reply necessary',
'CTA': 'call to action',
'SWOT': 'strengths, weaknesses, opportunities and threats'}
_ACRONYM_PATTERN = re . compile(r'\b[A-Z]{3,}\b')
_CAPITAL_PATTERN = re . compile(r'(?:\. |^)([a-z])')
def _CAPITAL_FIX(match): return '{}' . format(match . group(0). upper())
def acronym_buster(message):
message = reduce(lambda msg, item: msg . replace(
* item), _ACRONYMS . items(), message)
try:
acro = next(_ACRONYM_PATTERN . finditer(message)). group(0)
return '{} is an acronym. I do not like acronyms. Please remove them from your email.' . format(acro)
except StopIteration:
return _CAPITAL_PATTERN . sub(_CAPITAL_FIX, message)
|
Acronym Buster
|
58397ee871df657929000209
|
[
"Regular Expressions",
"Parsing",
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/58397ee871df657929000209
|
6 kyu
|
1)
Given some text, count each alphabetic character's occurrence in it, regardless of the case.
2)
Let's suppose you have to use an old terminal window to represent the occurrencies of each character in a text-based horizontal bar graph. The terminal has a maximum width, provided as parameter (`max_units_on_screen`), and you have to abide by it.
For example, if the maximum width is 80, your longest bar in the graph will be scaled to this size and all the others have to be represented and scaled proportionally to this size.
Every unit of the bar will be represented by the character `#`.
See examples below for typical output format.
3)
The bars of the graph have to be sorted by number of occurrencies (from biggest to lowest, before getting scaled), then by alphabetic order of the letter (from a to z). Approximation of decimal numbers will happen on the lowest integer (for example: `57.1`, `57.2`, `57.68`, `57.999` will all get reduced to `57` )
Example
Input:
```
count_and_print_graph("just a short text", 4)
```
Output:
```
t:####
s:##
a:#
e:#
h:#
j:#
o:#
r:#
u:#
x:#
```
Example 2
Input:
```
count_and_print_graph("just a short text", 23)
```
Output:
```
t:#######################
s:###########
a:#####
e:#####
h:#####
j:#####
o:#####
r:#####
u:#####
x:#####
```
|
reference
|
from collections import Counter
import re
def count_and_print_graph(text, max_units_on_screen):
counts = Counter(re . sub("[^a-z]", "", text . lower()))
adjust = counts . most_common(1)[0][1] / max_units_on_screen
return "\n" . join([x[0] + ":" + "#" * int(x[1] / adjust) for x in sorted(counts . items(), key=lambda x: (- x[1], x[0]))])
|
Character Counter and Bars Graph
|
5826773bfad36332bf0002f9
|
[
"ASCII Art",
"Arrays",
"Fundamentals"
] |
https://www.codewars.com/kata/5826773bfad36332bf0002f9
|
6 kyu
|
## The Story
Green Lantern's long hours of study and practice with his ring have really paid off -- his skills, focus, and control have improved so much that now he can even use his ring to update and redesign his web site. Earlier today he was focusing his will and a beam from his ring upon the Justice League web server, while intensely brainstorming and visualizing in minute detail different looks and ideas for his web site, and when he finished and reloaded his home page, he was absolutely thrilled to see that among other things it now displayed
~~~~
In brightest day, in blackest night,
There's nothing cooler than my site!
~~~~
in his favorite font in very large blinking <font color="Lime">green letters</font>.
The problem is, Green Lantern's ring has no power over anything <font color="Yellow">yellow</font>, so if he's experimenting with his web site and accidentally changes some text or background color to yellow, he will no longer be able to make any changes to those parts of the content or presentation (because he doesn't actually know any HTML, CSS, programming languages, frameworks, etc.) until he gets a more knowledgable friend to edit the code for him.
## Your Mission
You can help Green Lantern by writing a function that will replace any color property values that are too yellow with shades of green or blue-green. Presumably at a later time the two of you will be doing some testing to find out at exactly which RGB values yellow stops being yellow and starts being off-white, orange, brown, etc. as far as his ring is concerned, but here's the plan to get version 1.0 up and running as soon as possible:
Your function will receive either an HTML color name or a six-digit hex color code. (You're not going to bother with other types of color codes just now because you don't think they will come up.) If the color is too yellow, your function needs to return a green or blue-green shade instead, but if it is not too yellow, it needs to return the original color name or hex color code unchanged.
### HTML Color Names
(If don't know what HTML color names are, take a look at <a href="http://www.w3schools.com/colors/colors_names.asp">this HTML colors names reference</a>.)
For HMTL color names, you are going to start out trying a pretty strict definition of yellow, replacing any of the following colors as specified:
~~~~
Gold => ForestGreen
Khaki => LimeGreen
LemonChiffon => PaleGreen
LightGoldenRodYellow => SpringGreen
LightYellow => MintCream
PaleGoldenRod => LightGreen
Yellow => Lime
~~~~
HTML color names are case-insensitive, so your function will need to be able to identify the above yellow shades regardless of the cases used, but should output the green shades as capitalized above.
Some examples:
```
"lemonchiffon" "PaleGreen"
"GOLD" "ForestGreen"
"pAlEgOlDeNrOd" "LightGreen"
"BlueViolet" "BlueViolet"
```
### Hex Color Codes
(If you don't know what six-digit hex color codes are, take a look at <a href="https://en.wikipedia.org/wiki/Web_colors#Hex_triplet">this Wikipedia description</a>. Basically the six digits are made up of three two-digit numbers in base 16, known as <a href="https://en.wikipedia.org/wiki/Hexadecimal">hexidecimal</a> or hex, from 00 to FF (equivalent to 255 in base 10, also known as decimal), with the first two-digit number specifying the color's red value, the second the green value, and the third blue.)
With six-digit color hex codes, you are going to start out going really overboard, interpreting as "yellow" any hex code where the red (R) value and the green (G) value are each greater than the blue (B) value. When you find one of these "yellow" hex codes, your function will take the three hex values and rearrange them that the largest goes to G, the middle goes to B, and the smallest to R.
For example, with the six-digit hex color code `#FFD700`, which has an R value of hex FF (decimal 255), a G value of hex D7 (decimal 215), and a B value of hex 00 (decimal 0), as the R and G values are each larger than the B value, you would return it as `#00FFD7` -- the FF reassigned to G, the D7 to B, and the 00 to R.
Hex color codes are also case-insensitive, but your function should output them in the same case they were received in, just for consistency with whatever style is being used.
Some examples:
```
"#000000" "#000000"
"#b8860b" "#0bb886"
"#8FBC8F" "#8FBC8F"
"#C71585" "#C71585"
```
|
reference
|
def yellow_be_gone(s):
d = {'gold': 'ForestGreen', 'khaki': 'LimeGreen', 'lemonchiffon': 'PaleGreen', 'lightgoldenrodyellow': 'SpringGreen',
'lightyellow': 'MintCream', 'palegoldenrod': 'LightGreen', 'yellow': 'Lime'}
if s[0] == '#':
R, G, B = s[1: 3], s[3: 5], s[5:]
if B < G and B < R:
R, B, G = sorted([R, G, B])
s = '#' + R + G + B
return d . get(s . lower(), s)
|
Help Green Lantern with his web site
|
57e6bcbd684e570c6700021c
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/57e6bcbd684e570c6700021c
|
6 kyu
|
Build a function `sumNestedNumbers`/`sum_nested_numbers` that finds the sum of all numbers in a series of nested arrays raised to the power of their respective nesting levels. Numbers in the outer most array should be raised to the power of 1.
For example,
```javascript
sumNestedNumbers([1, [2], 3, [4, [5]]])
```
```php
sum_nested_numbers([1, [2], 3, [4, [5]]]);
```
should return `1 + 2*2 + 3 + 4*4 + 5*5*5 === 149`
|
reference
|
def sum_nested_numbers(a, depth=1):
return sum(sum_nested_numbers(e, depth + 1) if type(e) == list else e * * depth for e in a)
|
Sum of nested numbers
|
5845e6a7ae92e294f4000315
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5845e6a7ae92e294f4000315
|
6 kyu
|
Have you finished [this one](https://www.codewars.com/kata/590938089ff3d186cb00004c)? Now there is a complex version:
### Task
Given the prefix sums of some array `A`, return suffix sums for the same array.
Array of prefix sums is defined as:
```
B[0] = A[0]
B[1] = A[0] + A[1]
B[2] = A[0] + A[1] + A[2]
...
B[n - 1] = A[0] + A[1] + ... + A[n - 1]
```
Array of suffix sums is defined as:
```
B[0] = A[0] + A[1] + A[2] + ... + A[n - 1]
B[1] = A[1] + A[2] + ... + A[n - 1]
...
B[n - 2] = A[n - 2] + A[n - 1]
B[n - 1] = A[n - 1]
```
### Input/Output
- `[input]` integer array `prefixSums`
prefix sums of the orginal array.
`1 ≤ prefixSums.length ≤ 10^4,`
`-10^5 ≤ prefixSums[i] ≤ 10^5.`
- `[output]` an integer array
suffix sums of the orginal array.
### Example
For `prefixSums = [1, 3, 6, 10, 15]`,
the output should be `[15, 14, 12, 9, 5]`.
You may verify that the initial array A is `[1, 2, 3, 4, 5]` (just try to calculate the prefix sums of it).
Then following the rules, you can calculate the suffix sums of `A`.
|
algorithms
|
def prefix_sums_to_suffix_sums(prefix_sums):
return [prefix_sums[- 1] - (i and prefix_sums[i - 1]) for i, s in enumerate(prefix_sums)]
|
Simple Fun #250: Prefix Sums To Suffix Sums
|
590c4c342ad5cd6a8700005c
|
[
"Algorithms"
] |
https://www.codewars.com/kata/590c4c342ad5cd6a8700005c
|
6 kyu
|
# Task
A person is moving along a straight line. Initially he is at point `A`. He goes to point `B` from `A` with speed equal to `1 meter per second`. Immediately after reaching `B` he turns around and heads to `A` from `B` with the same speed. After reaching point `A` he turns around once again and heads to `B`. etc.
We need an algorithm that identifies the location of the person at any given moment in time(argument `t`).
It's guaranteed that `A` and `B` are two different points.
# Input/Output
`[input]` integer `a`
Coordinate of point `A` (in meters).
1 ≤ a ≤ 10^9.
`[input]` integer `b`
Coordinate of point `B` (in meters).
`1 ≤ b ≤ 10^9,`
`b ≠ a.`
`[input]` integer `t`
A positive integer representing time (in seconds).
`3 ≤ t ≤ 10^9.`
`[output]` an integer
Coordinate of the person `t` seconds after he left `A`.
# Example
For `a = 2, b = 4 and t = 3`, the output should be 3.
```
t-->From A to B 0 1 2
3 <--B back to A
A | B
line --> .--.--.--.--.--.--.--.--.
0 1 2 3 4 5 6 7 8
```
For `a = 1, b = 10 and t = 8`, the output should be 9.
```
t-->From A to B 0 1 2 3 4 5 6 7 8
A | B
line --> .--.--.--.--.--.--.--.--.--.--.--.
0 1 2 3 4 5 6 7 8 9 10 11
```
|
reference
|
def to_and_from(a, b, t):
times, rem = divmod(t, b - a)
if not times % 2:
return a + rem
return b - rem
|
Simple Fun #247: To And From
|
590c3173cd3b99c467000a26
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/590c3173cd3b99c467000a26
|
6 kyu
|
# Task
Your friend has invited you to watch a tennis match at a local sports club. Since tennis isn't your favorite sport, you get bored right at the start of the first game and start looking for something to keep yourself entertained. Noticing the scoreboard, you realize you don't even know how many points have been won since the game started, so you decided to calculate this number. Given the current score, your goal is to find the number of points won in the current game.
If you are not familiar with tennis rules, here's a short description of its scoring system. Score calling is unique in tennis: each point has a corresponding call that is different from its point value. The table of points won and corresponding calls is given below.
```
+----------------------+--------------------+
| Number of points won | Corresponding call |
+----------------------+--------------------+
| 0 | "love" |
+----------------------+--------------------+
| 1 | "15" |
+----------------------+--------------------+
| 2 | "30" |
+----------------------+--------------------+
| 3 | "40" |
+----------------------+--------------------+
```
There's an additional rule to remember: `when players are tied by one or two points, the score is described as "15-all" and "30-all", respectively.`
It's guaranteed that no more than 5 points have been won so far, and the game is not over yet. It is also guaranteed that at least one point has been won.
# Input/Output
`[input]` string `score`
A string in the format `<p1>-<p2>` representing a valid score, where `<p1>` is the first player's score, and `<p2>` is the second player's score.
`[output]` an integer
The number of points won so far.
# Example
For `score = "15-40"`, the output should be 4.
The first player won `1` point, and the second `3`, so `1 + 3 = 4` points have been won.
For `score = "30-all"`, the output should be 4.
The players have won `2` points each.
|
reference
|
def tennis_game_points(score):
arr = ["love", "15", "30", "40"]
[a, b] = score . split("-")
return arr . index(a) + (arr . index(a) if b == "all" else arr . index(b))
|
Simple Fun #238: Tennis Game Points
|
590942d4efde93886900185a
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/590942d4efde93886900185a
|
7 kyu
|
Given an input of an array of digits, return the array with each digit incremented by its position in the array: the first digit will be incremented by 1, the second digit by 2, etc. Make sure to **start counting your positions from 1** ( and not 0 ).
Your result can only contain single digit numbers, so if adding a digit with its position gives you a multiple-digit number, only the last digit of the number should be returned.
#### Notes:
* return an empty array if your array is empty
* arrays will only contain numbers so don't worry about checking that
#### Examples:
```
[1, 2, 3] --> [2, 4, 6] # [1+1, 2+2, 3+3]
[4, 6, 9, 1, 3] --> [5, 8, 2, 5, 8] # [4+1, 6+2, 9+3, 1+4, 3+5]
# 9+3 = 12 --> 2
```
|
reference
|
def incrementer(nums):
return [(v + i) % 10 for i, v in enumerate(nums, 1)]
|
Incrementer
|
590e03aef55cab099a0002e8
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/590e03aef55cab099a0002e8
|
7 kyu
|
#Permutation position
In this kata you will have to permutate through a string of lowercase letters, each permutation will start at ```a``` and you must calculate how many iterations it takes to reach the current permutation.
##examples
```
input: 'a'
result: 1
input: 'c'
result: 3
input: 'z'
result: 26
input: 'foo'
result: 3759
input: 'aba'
result: 27
input: 'abb'
result: 28
```
|
reference
|
trans_table = str . maketrans('abcdefghijklmnopqrstuvwxyz',
'0123456789abcdefghijklmnop')
def permutation_position(perm):
return int(perm . translate(trans_table), 26) + 1
|
Permutation position
|
57630df805fea67b290009a3
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/57630df805fea67b290009a3
|
6 kyu
|
Create a function that calculates all possible diagonals of a given (square) matrix.
Diagonals must be laid out from top to bottom
> Matrix = array of `n` length whose elements are `n` length arrays of integers.
2x2 example:
```javascript
diagonals( [
[ 1, 2 ],
[ 3, 4 ]
] );
returns -> [ [ 1 ], [ 2, 3 ], [ 4 ], [ 2 ], [ 1, 4 ], [ 3 ] ]
it is valid too -> [ [ 1, 4 ], [ 3 ], [ 2 ], [ 2 , 3 ], [ 1 ], [ 4 ] ] //Order of the returned array does not matter
it is invalid -> [ [ 1 ], [ 3, 2 ], [ 4 ], [ 2 ], [ 1, 4 ], [ 3 ] ] //Order of each diagonal must be preserved
```
3x3 example:
```javascript
diagonals( [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
] );
returns ->
[ [ 1 ],
[ 2, 4 ],
[ 3, 5, 7 ],
[ 6, 8 ],
[ 9 ],
[ 3 ],
[ 2, 6 ],
[ 1, 5, 9 ],
[ 4, 8 ],
[ 7 ] ]
```
The tests verify that the implementation is efficient (1000x1000 matrix are used in tests).
|
algorithms
|
def diagonals(matrix):
def skewed(left, right):
tilted = [[None] * l + row + [None] * r for l,
row, r in zip(left, matrix, right)]
return [[x for x in row if x is not None] for row in zip(* tilted)]
left, right = range(len(matrix)), range(len(matrix) - 1, - 1, - 1)
return matrix if len(matrix) < 2 else skewed(left, right) + skewed(right, left)
|
Diagonals
|
5592dd43a9cd0e43a800019e
|
[
"Matrix",
"Algorithms"
] |
https://www.codewars.com/kata/5592dd43a9cd0e43a800019e
|
5 kyu
|
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" />
# A History Lesson
<b>Soundex</b> is an interesting phonetic algorithm developed nearly 100 years ago for indexing names as they are pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling.
Reference: https://en.wikipedia.org/wiki/Soundex
<hr>
# Preface
I first read about Soundex over 30 years ago. At the time it seemed to me almost like A.I. that you could just type in somebody's name the way it sounded and there was still a pretty good chance it could match the correct person record. That was about the same year as the first "Terminator" movie so it was easy for me to put 2 and 2 together and conclude that Arnie must have had some kind of futuristic Soundex chip in his titanium skull helping him to locate ```Serah Coner```... or was it ```Sarh Connor```... or maybe ```Sayra Cunnarr```...
:-)
<hr>
# Task
In this Kata you will encode strings using a Soundex variation called "American Soundex" using the following (case insensitive) steps:
* Save the first letter. Remove all occurrences of ```h``` and ```w``` except first letter.
* Replace all consonants (include the first letter) with digits as follows:
* ```b```, ```f```, ```p```, ```v``` = 1
* ```c```, ```g```, ```j```, ```k```, ```q```, ```s```, ```x```, ```z``` = 2
* ```d```, ```t``` = 3
* ```l``` = 4
* ```m```, ```n``` = 5
* ```r``` = 6
* Replace all adjacent same digits with one digit.
* Remove all occurrences of ```a```, ```e```, ```i```, ```o```, ```u```, ```y``` except first letter.
* If first symbol is a digit replace it with letter saved on step 1.
* Append 3 zeros if result contains less than 3 digits. Remove all except first letter and 3 digits after it
## Input
A space separated string of one or more names. E.g.
```Sarah Connor```
## Output
Space separated string of equivalent <b>Soundex</b> codes (the first character of each code must be uppercase). E.g.
```S600 C560```
|
algorithms
|
import re
REPLACMENTS = ["BFPV", "CGJKQSXZ", "DT", "L", "MN", "R"]
ER1, ER2 = "HW", "AEIOUY"
TABLE_ERASE1 = str . maketrans("", "", ER1)
TABLE_NUMS = str . maketrans('' . join(REPLACMENTS), '' . join(
str(n) * len(elt) for n, elt in enumerate(REPLACMENTS, 1)))
TABLE_ERASE2 = str . maketrans("", "", ER2)
def formatSoundex(w):
s = w[0] * (w[0] in ER1 + ER2) + re . sub(r'(\d)\1*', r'\1',
w . translate(TABLE_ERASE1). translate(TABLE_NUMS)). translate(TABLE_ERASE2)
return ((w[0] if s[0]. isdigit() else s[0]) + s[1:] + "000")[: 4]
def soundex(name):
return ' ' . join(formatSoundex(w . upper()) for w in name . split(" "))
|
Soundex
|
587319230e9cf305bb000098
|
[
"Algorithms"
] |
https://www.codewars.com/kata/587319230e9cf305bb000098
|
5 kyu
|
# Introduction
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">Slot machine (American English), informally fruit machine (British English), puggy (Scottish English slang), the slots (Canadian and American English), poker machine (or pokies in slang) (Australian English and New Zealand English) or simply slot (American English), is a casino gambling machine with three or more reels which spin when a button is pushed. Slot machines are also known as one-armed bandits because they were originally operated by one lever on the side of the machine as distinct from a button on the front panel, and because of their ability to leave the player in debt and impoverished. Many modern machines are still equipped with a legacy lever in addition to the button. (Source <a href="https://en.wikipedia.org/wiki/Slot_machine">Wikipedia</a>)
</pre>
<center><img src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/fruit.jpg"></center>
# Task
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">
You will be given three reels of different images and told at which index the reels stop. From this information your job is to return the score of the resulted reels.
</pre>
# Rules
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">
1. There are always exactly <font color="#A1A85E">three</font> reels<br>
2. Each reel has <font color="#A1A85E">10</font> different items.<br>
3. The three reel inputs may be different.<br>
4. The spin array represents the <font color="#A1A85E">index</font> of where the reels finish.<br>
5. The three spin inputs may be different<br>
6. Three of the same is worth more than two of the same<br>
7. Two of the same plus one <font color="#A1A85E">"Wild"</font> is double the score.<br>
8. No matching items returns <font color="#A1A85E">0</font>.
</pre>
# Scoring
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="400"><table width="400" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="100" height="40" align="center" valign="middle"><center>Item</center></td>
<td width="100" align="center" valign="middle"><center>Three of the same</center></td>
<td width="100" align="center" valign="middle"><center>Two of the same</center></td>
<td width="100" align="center" valign="middle"><center>Two of the same plus one Wild</center></td>
</tr>
<tr>
<td width="100"><center>Wild</center></td>
<td width="100"><center>100</center></td>
<td width="100"><center>10</center></td>
<td width="100"><center>N/A</center></td>
</tr>
<tr>
<td width="100"><center>Star</center></td>
<td width="100"><center>90</center></td>
<td width="100"><center>9</center></td>
<td width="100"><center>18</center></td>
</tr>
<tr>
<td width="100"><center>Bell</center></td>
<td width="100"><center>80</center></td>
<td width="100"><center>8</center></td>
<td width="100"><center>16</center></td>
</tr>
<tr>
<td width="100"><center>Shell</center></td>
<td width="100"><center>70</center></td>
<td width="100"><center>7</center></td>
<td width="100"><center>14</center></td>
</tr>
<tr>
<td width="100"><center>Seven</center></td>
<td width="100"><center>60</center></td>
<td width="100"><center>6</center></td>
<td width="100"><center>12</center></td>
</tr>
<tr>
<td width="100"><center>Cherry</center></td>
<td width="100"><center>50</center></td>
<td width="100"><center>5</center></td>
<td width="100"><center>10</center></td>
</tr>
<tr>
<td width="100"><center>Bar</center></td>
<td width="100"><center>40</center></td>
<td width="100"><center>4</center></td>
<td width="100"><center>8</center></td>
</tr>
<tr>
<td width="100"><center>King</center></td>
<td width="100"><center>30</center></td>
<td width="100"><center>3</center></td>
<td width="100"><center>6</center></td>
</tr>
<tr>
<td width="100"><center>Queen</center></td>
<td width="100"><center>20</center></td>
<td width="100"><center>2</center></td>
<td width="100"><center>4</center></td>
</tr>
<tr>
<td width="100"><center>Jack</center></td>
<td width="100"><center>10</center></td>
<td width="100"><center>1</center></td>
<td width="100"><center>2</center></td>
</tr>
</table></td>
<td> </td>
</tr>
</table>
</pre>
# Returns
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">
Return an integer of the <font color="#A1A85E">score</font>.
</pre>
# Example
## Initialise
```ruby
reel1 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]
reel2 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]
reel3 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]
spin = [5,5,5]
result = fruit([reel1,reel2,reel3],spin)
```
```python
reel1 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]
reel2 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]
reel3 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]
spin = [5,5,5]
result = fruit([reel1,reel2,reel3],spin)
```
```javascript
reel1 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"];
reel2 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"];
reel3 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"];
spin = [5,5,5];
result = fruit([reel1,reel2,reel3],spin);
```
```csharp
Kata kata = new Kata();
string[] reel1 = new string[] { "Wild", "Star", "Bell", "Shell", "Seven", "Cherry", "Bar", "King", "Queen", "Jack" };
string[] reel2 = new string[] { "Wild", "Star", "Bell", "Shell", "Seven", "Cherry", "Bar", "King", "Queen", "Jack" };
string[] reel3 = new string[] { "Wild", "Star", "Bell", "Shell", "Seven", "Cherry", "Bar", "King", "Queen", "Jack" };
List<string[]> reels = new List<string[]> { reel1, reel2, reel3 };
int[] spins = new int[] { 5, 5, 5 };
int result = kata.fruit(reels, spins);
```
```haskell
reel1 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]
reel2 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]
reel3 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]
spin = [5,5,5]
result = fruit [reel1,reel2,reel3] spin
```
```c
reel1 = {"Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"}
reel2 = {"Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"}
reel3 = {"Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"}
spin = {5,5,5}
result = fruit({reel1, reel2, reel3}, spin)
```
```cpp
reel1 = {"Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"}
reel2 = {"Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"}
reel3 = {"Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"}
spin = {5,5,5}
result = fruit({reel1, reel2, reel3}, spin)
```
```java
reel1 = {"Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"}
reel2 = {"Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"}
reel3 = {"Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"}
spin = {5,5,5}
result = fruit({reel1, reel2, reel3}, spin)
```
## Scoring
```haskell
reel1!!5 == "Cherry"
reel2!!5 == "Cherry"
reel3!!5 == "Cherry"
Cherry + Cherry + Cherry == 50
```
```ruby
reel1[5] == "Cherry"
reel2[5] == "Cherry"
reel3[5] == "Cherry"
Cherry + Cherry + Cherry == 50
```
```python
reel1[5] == "Cherry"
reel2[5] == "Cherry"
reel3[5] == "Cherry"
Cherry + Cherry + Cherry == 50
```
```javascript
reel1[5] == "Cherry"
reel2[5] == "Cherry"
reel3[5] == "Cherry"
Cherry + Cherry + Cherry == 50
```
```csharp
reel1[5] == "Cherry"
reel2[5] == "Cherry"
reel3[5] == "Cherry"
Cherry + Cherry + Cherry == 50
```
```scrytal
reel1[5] == "Cherry"
reel2[5] == "Cherry"
reel3[5] == "Cherry"
Cherry + Cherry + Cherry == 50
```
```c
reel1[5] == "Cherry"
reel2[5] == "Cherry"
reel3[5] == "Cherry"
Cherry + Cherry + Cherry == 50
```
```cpp
reel1[5] == "Cherry"
reel2[5] == "Cherry"
reel3[5] == "Cherry"
Cherry + Cherry + Cherry == 50
```
```java
reel1[5] == "Cherry"
reel2[5] == "Cherry"
reel3[5] == "Cherry"
Cherry + Cherry + Cherry == 50
```
## Return
```
result == 50
```
Good luck and enjoy!<br>
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58663693b359c4a6560001d6" target="_blank">Maze Runner</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58693bbfd7da144164000d05" target="_blank">Scooby Doo Puzzle</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/7KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/586a1af1c66d18ad81000134" target="_blank">Driving License</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/586c0909c1923fdb89002031" target="_blank">Connect 4</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/586e6d4cb98de09e3800014f" target="_blank">Vending Machine</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/587136ba2eefcb92a9000027" target="_blank">Snakes and Ladders</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58a848258a6909dd35000003" target="_blank">Mastermind</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58b2c5de4cf8b90723000051" target="_blank">Guess Who?</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58f5c63f1e26ecda7e000029" target="_blank">Am I safe to drive?</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58f5c63f1e26ecda7e000029" target="_blank">Mexican Wave</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58fdcc51b4f81a0b1e00003e" target="_blank">Pigs in a Pen</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/590300eb378a9282ba000095" target="_blank">Hungry Hippos</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/5904be220881cb68be00007d" target="_blank">Plenty of Fish in the Pond</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/590adadea658017d90000039" target="_blank">Fruit Machine</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/591eab1d192fe0435e000014" target="_blank">Car Park Escape</a></span>
|
reference
|
def fruit(reels, spins):
fruits = {"Wild": 10, "Star": 9, "Bell": 8, "Shell": 7, "Seven": 6,
"Cherry": 5, "Bar": 4, "King": 3, "Queen": 2, "Jack": 1}
spin = sorted(reels[i][spins[i]] for i in range(3))
matches = len(set(spin))
if matches == 1:
return fruits[spin[0]] * 10
if matches == 2:
return fruits[spin[0]] * 2 if spin[2] == "Wild" else fruits[spin[1]]
return 0
|
Fruit Machine
|
590adadea658017d90000039
|
[
"Arrays",
"Games",
"Fundamentals"
] |
https://www.codewars.com/kata/590adadea658017d90000039
|
6 kyu
|
# Task
Consider an array of integers `a`. Let `min(a)` be its minimal element, and let `avg(a)` be its mean.
Define the center of the array `a` as array `b` such that:
```
- b is formed from a by erasing some of its elements.
- For each i, |b[i] - avg(a)| < min(a).
- b has the maximum number of elements among all the arrays
satisfying the above requirements.
```
Given an array of integers, return its center.
# Input/Output
`[input]` integer array `a`
Unsorted non-empty array of integers.
`2 ≤ a.length ≤ 50,`
`1 ≤ a[i] ≤ 350.`
`[output]` an integer array
# Example
For `a = [8, 3, 4, 5, 2, 8]`, the output should be `[4, 5]`.
Here `min(a) = 2, avg(a) = 5`.
For `a = [1, 3, 2, 1]`, the output should be `[1, 2, 1]`.
Here `min(a) = 1, avg(a) = 1.75`.
|
algorithms
|
def array_center(lst):
return [i for i in lst if abs(i - sum(lst) * 1.0 / len(lst)) < min(lst)]
|
Simple Fun #246: Array Center
|
590bdaa251ab8267b800005b
|
[
"Algorithms"
] |
https://www.codewars.com/kata/590bdaa251ab8267b800005b
|
7 kyu
|
A family of <a href="https://en.wikipedia.org/wiki/Laughing_kookaburra">kookaburras</a> are in my backyard.
I can't see them all, but I can hear them!
# How many kookaburras are there?
<img src="https://i.imgur.com/JyeBAJH.png" style='width:60%'/>
## Hint
The trick to counting kookaburras is to listen carefully
* The males sound like ```HaHaHa```...
* The females sound like ```hahaha```...
* And they always alternate male/female
## Examples
* `ha` = female => 1
* `Ha` = male => 1
* `Haha` = male + female => 2
* `haHa` = female + male => 2
* `hahahahaha` = female => 1
* `hahahahahaHaHaHa` = female + male => 2
* `HaHaHahahaHaHa` = male + female + male => 3
<hr>
^ Kata Note : No validation is necessary; only valid input will be passed :-)
|
algorithms
|
import re
def kooka_counter(laughing):
return len(re . findall(r'(ha)+|(Ha)+', laughing))
|
Kooka-Counter
|
58e8cad9fd89ea0c6c000258
|
[
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/58e8cad9fd89ea0c6c000258
|
7 kyu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.