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 |
---|---|---|---|---|---|---|---|
## Background
Starting with the closed interval `$[0,1]$`, the Cantor ternary set is constructed by iteratively applying the operation "remove the middle thirds", by which we mean removing the open interval `$(\frac{2a + b}{3}, \frac{a + 2b}{3})$` from each remaining closed interval `$[a,b]$`. If `$C_n$` denotes the result after `$n$` iterations, then `$C_0 = [0,1]$`, `$C_1 = [0, \frac{1}{3}] \cup [\frac{2}{3}, 1]$` and `$C_2 = [0,\frac{1}{9}] \cup [\frac{2}{9},\frac{1}{3}] \cup [\frac{2}{3}, \frac{7}{9}] \cup [\frac{8}{9},1]$`.
To be precise, the Cantor ternary set, `$C$`, is the result after infinitely many iterations. In other words, `$C$` is the intersection of all the sets `$C_n$`.
## Task
Given a rational number (i.e. a fraction) `$q$` and a non-negative integer `$n$`, decide whether `$q$` is in `$C_n$`. More precisely, you must write a function whose parameters are two positive integers `num` and `den` and an integer `n`. Your function must return `True` or `False` depending on whether the rational number `num / den` is in `$C_n$` or not.
For example:
```
* num = 1, den = 3, n = 100 => return True
```
because the number `$\frac{1}{3}$` is in `$C_{100}$` (in fact, `$\frac{1}{3}$` is in `$C_n$` for every `$n$`).
`num` and `den` will be less than `10e8` and `n` will be less than `1000`.
Go make Cantor proud! | algorithms | def is_in_cantor(num, den, n):
if num < 0 or num > den:
return False
for i in range(n):
num *= 3
if num > den and num < den * 2:
return False
num %= den
return True
| The Cantor ternary set | 60b744478e8d62003d327e6a | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/60b744478e8d62003d327e6a | 6 kyu |
Returns the commom directory path for specified array of full filenames.
```
@param {array} pathes
@return {string}
```
Examples:
```
['/web/images/image1.png', '/web/images/image2.png'] => '/web/images/'
['/web/assets/style.css', '/web/scripts/app.js', 'home/setting.conf'] => ''
['/web/assets/style.css', '/.bin/mocha', '/read.me'] => '/'
['/web/favicon.ico', '/web-scripts/dump', '/webalizer/logs'] => '/'
```
(c)RSS | games | def get_common_directory_path(pathes):
res = ''
for cs in zip(* pathes):
if len(set(cs)) == 1:
res += cs[0]
else:
break
arr = res . split('/')[: - 1]
if not arr:
return ''
return '/' . join(arr) + '/'
| Common directory path | 597f334f1fe82a950500004b | [
"Strings",
"Puzzles"
] | https://www.codewars.com/kata/597f334f1fe82a950500004b | 6 kyu |
Regular Tic-Tac-Toe is boring.
That's why in this Kata you will be playing Tic-Tac-Toe in **3D** using a 4 x 4 x 4 matrix!
<img src="https://i.imgur.com/NlG3wai.png" title="source: imgur.com" />
# Kata Task
Play the game. Work out who wins.
Return a string
* `O wins after <n> moves`
* `X wins after <n> moves`
* `No winner`
# Rules
* Player `O` always goes first
* Input `moves` is list/array/tuple of `[x,y,z]` (zero based)
* Each player takes a turn until you find a winner, or there are no moves left
* Four of the same symbols in a row wins
* There may be more moves provided than are necessary to finish the game - that is for you to figure out
<hr style='border-bottom 1px solid white'>
<span style='color:orange'>
Good Luck!<br/>
DM
</span> | reference | WINS = [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15),
(16, 17, 18, 19), (20, 21, 22, 23), (24, 25, 26, 27), (28, 29, 30, 31),
(32, 33, 34, 35), (36, 37, 38, 39), (40, 41, 42, 43), (44, 45, 46, 47),
(48, 49, 50, 51), (52, 53, 54, 55), (56, 57, 58, 59), (60, 61, 62, 63),
(0, 4, 8, 12), (1, 5, 9, 13), (2, 6, 10, 14), (3, 7, 11, 15),
(16, 20, 24, 28), (17, 21, 25, 29), (18, 22, 26, 30), (19, 23, 27, 31),
(32, 36, 40, 44), (33, 37, 41, 45), (34, 38, 42, 46), (35, 39, 43, 47),
(48, 52, 56, 60), (49, 53, 57, 61), (50, 54, 58, 62), (51, 55, 59, 63),
(0, 16, 32, 48), (1, 17, 33, 49), (2, 18, 34, 50), (3, 19, 35, 51),
(4, 20, 36, 52), (5, 21, 37, 53), (6, 22, 38, 54), (7, 23, 39, 55),
(8, 24, 40, 56), (9, 25, 41, 57), (10, 26, 42, 58), (11, 27, 43, 59),
(12, 28, 44, 60), (13, 29, 45, 61), (14, 30, 46, 62), (15, 31, 47, 63),
(0, 20, 40, 60), (1, 21, 41, 61), (2, 22, 42, 62), (3, 23, 43, 63),
(3, 18, 33, 48), (7, 22, 37, 52), (11, 26, 41, 56), (15, 30, 45, 60),
(0, 17, 34, 51), (4, 21, 38, 55), (8, 25, 42, 59), (12, 29, 46, 63),
(12, 24, 36, 48), (13, 25, 37, 49), (14, 26, 38, 50), (15, 27, 39, 51),
(3, 6, 9, 12), (19, 22, 25, 28), (35, 38, 41, 44), (51, 54, 57, 60),
(0, 5, 10, 15), (16, 21, 26, 31), (32, 37, 42, 47), (48, 53, 58, 63),
(0, 21, 42, 63), (3, 22, 41, 60), (12, 25, 38, 51), (15, 26, 37, 48)]
BOARD_MOVES_POSITION = {(0, 0, 0): 0, (1, 0, 0): 1, (2, 0, 0): 2, (3, 0, 0): 3,
(0, 1, 0): 4, (1, 1, 0): 5, (2, 1, 0): 6, (3, 1, 0): 7,
(0, 2, 0): 8, (1, 2, 0): 9, (2, 2, 0): 10, (3, 2, 0): 11,
(0, 3, 0): 12, (1, 3, 0): 13, (2, 3, 0): 14, (3, 3, 0): 15,
(0, 0, 1): 16, (1, 0, 1): 17, (2, 0, 1): 18, (3, 0, 1): 19,
(0, 1, 1): 20, (1, 1, 1): 21, (2, 1, 1): 22, (3, 1, 1): 23,
(0, 2, 1): 24, (1, 2, 1): 25, (2, 2, 1): 26, (3, 2, 1): 27,
(0, 3, 1): 28, (1, 3, 1): 29, (2, 3, 1): 30, (3, 3, 1): 31,
(0, 0, 2): 32, (1, 0, 2): 33, (2, 0, 2): 34, (3, 0, 2): 35,
(0, 1, 2): 36, (1, 1, 2): 37, (2, 1, 2): 38, (3, 1, 2): 39,
(0, 2, 2): 40, (1, 2, 2): 41, (2, 2, 2): 42, (3, 2, 2): 43,
(0, 3, 2): 44, (1, 3, 2): 45, (2, 3, 2): 46, (3, 3, 2): 47,
(0, 0, 3): 48, (1, 0, 3): 49, (2, 0, 3): 50, (3, 0, 3): 51,
(0, 1, 3): 52, (1, 1, 3): 53, (2, 1, 3): 54, (3, 1, 3): 55,
(0, 2, 3): 56, (1, 2, 3): 57, (2, 2, 3): 58, (3, 2, 3): 59,
(0, 3, 3): 60, (1, 3, 3): 61, (2, 3, 3): 62, (3, 3, 3): 63}
def move_to_position(move):
try:
return BOARD_MOVES_POSITION[tuple(move)]
except KeyError:
None
def legal_move(board, player, move):
place = move_to_position(move)
if place is None:
return False
else:
board[place] = player
return True
def play_OX_3D(moves):
board = dict()
for index, move in enumerate(moves):
player = "O" if (index % 2) == 0 else "X"
if not legal_move(board, player, move):
return "No winner"
set_of_player_positions = set(
key for (key, value) in board . items() if value == player)
for winning_moves in WINS:
if set(winning_moves). issubset(set_of_player_positions):
return f" { player } wins after { len ( board )} moves"
return "No winner"
| Tic-Tac-Toe (3D) | 5aa67541373c2e69a20000c9 | [
"Fundamentals"
] | https://www.codewars.com/kata/5aa67541373c2e69a20000c9 | 5 kyu |
# VIN Checker
In this Kata you should write a function to validate VINs, Vehicle Identification Numbers. Valid VINs are exactly 17 characters long, its composed of capital letters (except "I","O" and "Q") and digits. The 9th character is a MODULUS 11 check digit. Here is how it works:
## 1. Letters are converted to numbers
Following the table bellow, letters are converted to numbers. "I","O" and "Q" are invalid characters.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1 2 3 4 5 6 7 8 1 2 3 4 5 7 9 2 3 4 5 6 7 8 9
Ex.: VIN **5YJ3E1EA7HF000337** becomes **58135151786000337**.
## 2. Each number is multiplied by a weight
The weights are the following: **[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2]**.
Ex.:
VIN: 5 Y J 3 E 1 E A 7 H F 0 0 0 3 3 7
DECODED: 5 8 1 3 5 1 5 1 7 8 6 0 0 0 3 3 7
WEIGHTS: 8 7 6 5 4 3 2 10 0 9 8 7 6 5 4 3 2
PRODUCT: 40 56 6 15 20 3 10 10 0 72 48 0 0 0 12 9 14
## 3. All products are summed up
Ex.:
40+56+6+15+20+3+10+10+0+72+48+0+0+0+12+9+14 = 315
## 4. The modulus 11 of the sum is taken
Ex.:
315 mod 11 = 7
## 5. Check 9th character
If the 9th character matches the modulus 11, the VIN is valid.
Ex.:
5YJ3E1EA7HF000337 is a valid VIN, 9th character is 7
### Note
If the modulus 11 of the sum is equal to 10, then the digit is "X".
Ex.:
5YJ3E1EAXHF000347 is a valid VIN.
### Input Validation
Input validation is part of the Kata, VINs with lenghts different than 17 characters or containing invalid characters should return `False` as well.
### Online VIN Checker
[Click here](https://vpic.nhtsa.dot.gov/decoder/CheckDigit/Index/5YJ3E1EA7HF000337) to open an online VIN Checker if you want to better understand how it works. | algorithms | TRANS = str . maketrans("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z",
"1 2 3 4 5 6 7 8 1 2 3 4 5 7 9 2 3 4 5 6 7 8 9")
WEIGHTS = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2]
def check_vin(vin):
try:
return len(vin) == 17 and vin[8] == "0123456789X" [sum(int(c) * w for c, w in zip(vin . translate(TRANS), WEIGHTS)) % 11]
except:
return False
| VIN Checker | 60a54750138eac0031eb98e1 | [
"Strings",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/60a54750138eac0031eb98e1 | 6 kyu |
### Description
Consider some _subject_, who has some initial _momentum_ and is travelling through an array (_powerups_).
_momentum_ is an integer that represents the "distance" the _subject_ can travel through the array. Each index travelled requires one unit of _momentum_. (The _subject_ starts outside of the array, so it requires `1` _momentum_ to get to index `0`).
_powerups_ is an array of integers which the _subject_ is travelling through. At each index, the value there is added to the subject's total _momentum_.
If at any point through the array, the subject's _momentum_ is below `1`, the _subject_ stops there, and does not successfully make it through. If the _subject_ does make it to the last index of the array, with at least `1` _momentum_ remaining (required to leave the array), it has successfully reached the "other side".
**Examples:**
* `momentum = 3` and `powerups = [0,0,0]` - No success (it finished in the last index).
* `momentum = 3` and `powerups = [0,1,0]` - Success
### Resume
You are given a list of _momentum_ `listOfMomentum` and a list of _powerups_ `listOfPowerups`(a 2D list of numbers). You have to check it for each pair of `listOfMomentum[index]` and `listOfPowerups[index]`.
Return indexes of sublists where there was enough _momentum_.
### Notes
* The sublists in `listOfPowerups` can be of a different length.
* `listOfMomentum` will be of same length as `listOfPowerups`.
* `listOfMomentum` and sublists of `listOfPowerups` only contain integers from `0` to `9`.
* There can be duplicated numbers.
* The numbers in the result must be _in order_.
**Example for:**
`listOfMomentum = [3, 2, 1, 0]`  and
`listOfPowerups = [[1, 0, 0], [0, 2, 0, 0], [0, 9], [8, 8]`
```
listOfMomentum[0] = 3
listOfPowerups[0] = [1, 0, 0]
listOfMomentum[1] = 2
listOfPowerups[1] = [0, 2, 0, 0]
listOfMomentum[2] = 1
listOfPowerups[2] = [0, 9]
listOfMomentum[3] = 0
listOfPowerups[3] = [8, 8]
```
So, the output will be `[0]`
If you like this kata, check out another one: [Survivors Ep.5](https://www.codewars.com/kata/60a58520c42fb60055546ce5)
| reference | from itertools import accumulate
def survivors(ms, pss):
return [i
for i, (m, pss) in enumerate(zip(ms, pss))
if all(m > 0 for m in accumulate(pss, lambda m, p: m - 1 + p, initial=m))]
| Survivors Ep.4 | 60a516d70759d1000d532029 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/60a516d70759d1000d532029 | 6 kyu |
Given a list of strings (of letters and spaces), and a list of numbers:
Considering the list of strings as a 2D character array, the idea is to remove from each column, starting from bottom, as many letters as indicated in the list of numbers. Then return the remaining letters in any order as a string.
* If there aren't enough letters, just remove those you can.
* The strings in the list will all be of the same length.
* The list of numbers will be of the same length as the strings in the list of strings.
* Strings will contain only lowercase letters and spaces.
* There can be duplicated letters and numbers.
### Example:
strings
```
["abc",
" z ",
" a "]
```
numbers
```
[0,4,1]
```
the output would be `"a"`.
---
If you like this kata, check out another one: [Survivors Ep.4](https://www.codewars.com/kata/60a516d70759d1000d532029) | reference | def last_survivors(arr, nums):
return '' . join(map(shrink, zip(* arr), nums))
def shrink(col, n):
return '' . join(col). replace(' ', '')[: - n or len(col)]
| Last Survivors Ep.3 | 60a2d7f50eee95000d34f414 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/60a2d7f50eee95000d34f414 | 6 kyu |
Given a number, find the permutation with the smallest absolute value (no leading zeros).
```python
-20 => -20
-32 => -23
0 => 0
10 => 10
29394 => 23499
```
The input will always be an integer. | reference | def min_permutation(n):
f = n < 0
s = "" . join(sorted(str(abs(n))))
n = s . count("0")
s = s . replace("0", "")
return int(s[: 1] + "0" * n + s[1:]) * (- 1 if f else 1)
| Smallest Permutation | 5fefee21b64cc2000dbfa875 | [
"Fundamentals"
] | https://www.codewars.com/kata/5fefee21b64cc2000dbfa875 | 6 kyu |
You are given a string of letters and an array of numbers.
The numbers indicate positions of letters that must be removed, in order, starting from the beginning of the array.
After each removal the size of the string decreases (there is no empty space).
Return the only letter left.
Example:
~~~if-not:java
```
let str = "zbk", arr = [0, 1]
str = "bk", arr = [1]
str = "b", arr = []
return 'b'
```
~~~
~~~if:java
```java
str = "zbk", arr = {0, 1}
str = "bk", arr = {1}
str = "b", arr = {}
return "b"
```
~~~
#### Notes
* The given string will never be empty.
* The length of the array is always one less than the length of the string.
* All numbers are valid.
* There can be duplicate letters and numbers.
If you like this kata, check out the next one: [Last Survivors Ep.2](https://www.codewars.com/kata/60a1aac7d5a5fc0046c89651)
| reference | def last_survivor(letters, coords):
for x in coords:
letters = letters[0: x] + letters[x + 1:]
return letters
| Last Survivor | 609eee71109f860006c377d1 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/609eee71109f860006c377d1 | 7 kyu |
Substitute two equal letters by the next letter of the alphabet (two letters convert to one):
"aa" => "b", "bb" => "c", .. "zz" => "a".
The equal letters do _not_ have to be adjacent.
Repeat this operation until there are no possible substitutions left.
Return a string.
Example:
let str = "zzzab"
str = "azab"
str = "bzb"
str = "cz"
return "cz"
#### Notes
* The order of letters in the result is not important.
* The letters `"zz"` transform into `"a"`.
* There will only be lowercase letters.
If you like this kata, check out another one: [Last Survivor Ep.3](https://www.codewars.com/kata/60a2d7f50eee95000d34f414) | reference | from re import sub
def last_survivors(s):
while len(set(s)) != len(s):
s = sub(r'(.)(.*)\1', lambda x: chr((ord(x . group(1)) - 96) %
26 + 97) + x . group(2), s)
return s
| Last Survivors Ep.2 | 60a1aac7d5a5fc0046c89651 | [
"Fundamentals",
"Arrays",
"Regular Expressions"
] | https://www.codewars.com/kata/60a1aac7d5a5fc0046c89651 | 6 kyu |
### Overview
Many people know that Apple uses the letter "i" in almost all of its devices to emphasize its personality.
And so John, a programmer at Apple, was given the task of making a program that would add that letter to every word. Let's help him do it, too.
### Task:
Your task is to make a function that takes the value of **word** and returns it with an "i" at the beginning of the word. For example we get the word "Phone", so we must return "iPhone". But we have a few rules:
1. The word should not begin with the letter "I", for example **Inspire**.
2. The number of vowels should not be greater than or equal to the number of consonants, for example **East** or **Peace**. ("y" is considered a consonant)
3. The first letter should not be lowercase, for example **road**.
If the word does not meet the rules, we return "Invalid word". | reference | vowel = set("aeiouAEIOU"). __contains__
def i(word):
if not word or word[0]. islower() or word[0] == 'I' or 2 * sum(map(vowel, word)) >= len(word):
return "Invalid word"
return 'i' + word
| I'm everywhere! | 6097a9f20d32c2000d0bdb98 | [
"Fundamentals"
] | https://www.codewars.com/kata/6097a9f20d32c2000d0bdb98 | 7 kyu |
Your job is to create a class called `Song`.
A new `Song` will take two parameters, `title` and `artist`.
```javascript
const mountMoose = new Song('Mount Moose', 'The Snazzy Moose');
mountMoose.title => 'Mount Moose'
mountMoose.artist => 'The Snazzy Moose'
```
```python
mount_moose = Song('Mount Moose', 'The Snazzy Moose')
mount_moose.title => 'Mount Moose'
mount_moose.artist => 'The Snazzy Moose'
```
```java
Song mountMoose = new Song("Mount Moose", "The Snazzy Moose");
mountMoose.getTitle() => "Mount Moose";
mountMoose.getArtist() => "The Snazzy Moose";
```
You will also have to create an instance method named `howMany()` (or how_many()).
The method takes an array of people who have listened to the song that day. The output should be how many new listeners the song gained on that day out of all listeners. Names should be treated in a case-insensitive manner, i.e. "John" is the same as "john".
### Example
```javascript
const mountMoose = new Song('Mount Moose', 'The Snazzy Moose');
// day 1 (or test 1)
mountMoose.howMany(['John', 'Fred', 'BOb', 'carl', 'RyAn']); => 5
// These are all new since they are the first listeners.
// day 2
mountMoose.howMany(['JoHn', 'Luke', 'AmAndA']); => 2
// Luke and Amanda are new, john already listened to it the previous day
```
```python
mount_moose = Song('Mount Moose', 'The Snazzy Moose')
# day 1 (or test 1)
mount_moose.how_many(['John', 'Fred', 'BOb', 'carl', 'RyAn']) => 5
# These are all new since they are the first listeners.
# day 2
mount_moose.how_many(['JoHn', 'Luke', 'AmAndA']); => 2
# Luke and Amanda are new, john already listened to it the previous day
```
```java
Song mountMoose = new Song("Mount Moose", "The Snazzy Moose");
// day 1 (or test 1)
mountMoose.howMany(new ArrayList<String>(Arrays.asList("John", "Fred", "BOb", "carl", "RyAn"))); => 5
// These are all new since they are the first listeners.
// day 2
mountMoose.howMany(new ArrayList<String>(Arrays.asList("JoHn", "Luke", "AmAndA"))); => 2
// Luke and Amanda are new, john already listened to it the previous day
```
Also if the same person listened to it more than once a day it should only count them once.
### Example
```javascript
const mountMoose = new Song('Mount Moose', 'The Snazzy Moose');
// day 1
mountMoose.howMany(['John', 'joHN', 'carl']); => 2
```
```python
mount_moose = Song('Mount Moose', 'The Snazzy Moose')
# day 1
mount_moose.how_many(['John', 'joHN', 'carl']) => 2
```
```java
Song mountMoose = new Song("Mount Moose", "The Snazzy Moose");
// day 1
mountMoose.howMany(new ArrayList<String>(Arrays.asList("John", "joHN", "carl"))); => 2
```
Good luck! | reference | class Song:
def __init__(self, title, artist):
self . title = title
self . artist = artist
self . _seen = set()
def how_many(self, people):
tmp = set(map(str . lower, people))
res = len(tmp - self . _seen)
self . _seen . update(tmp)
return res
| What a "Classy" Song | 6089c7992df556001253ba7d | [
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/6089c7992df556001253ba7d | 7 kyu |
### Overview
Have you ever wondered how a user interface handles key presses?
So today you have the opportunity to create it.
### Task:
The keyboard handler is a function which receives three parameters as input:
1. **Key** - the entered character on the keyboard.
2. **isCaps** (or **is_caps**) - boolean variable responsible for the enabled 'Caps Lock'. (by default false)
3. **isShift** (or **is_shift**) - boolean variable which is responsible for whether 'Shift' is pressed. (by default false)
Your task to write a function that returns the entered character.
#### Requirements for obtaining the 'key' variable:
* Alphabetical characters must be a lowercase (e.x. 'a', not 'A')
* It must be a character (e.x '2', not 2 or not [1,2,3])
* It must be of unit length (e.x. 'a', not 'abc')
If the value does not satisfy the condition, return 'KeyError'
For example:
```javascript
handler('a', true) // should return 'A' (because Caps-Lock)
handler('1', true) // should return '1' (because Сaps-Lock doesn't work here)
handler('a', false, true) // should return 'A' (because Shift)
handler('1', false, true) // should return '!'
handler('') // should return 'KeyError'
handler('A') // should return 'KeyError'
handler( 3 ) // should return 'KeyError'
handler('abc') // should return 'KeyError'
```
**In this kata we use en-US QWERTY layout. (The characters we are working with are shown on a white background)**
<img src="https://i.ibb.co/vvvCRXC/qwerty.png" height="1920" width="800"> | algorithms | def handler(key, isCaps=False, isShift=False):
if not isinstance(key, str) or len(key) != 1 or key . isupper():
return 'KeyError'
num = "1234567890-=[];'\/.,`"
unNum = '!@#$%^&*()_+{}:"|?><~'
if key . isalpha() and (isCaps != isShift):
return key . upper()
if not key . isalpha() and isShift:
return key . translate(str . maketrans(num, unNum))
return key
| Keyboard handler | 609d17f9838b2c0036b10e89 | [
"Algorithms",
"Logic"
] | https://www.codewars.com/kata/609d17f9838b2c0036b10e89 | 7 kyu |
In Lambda Calculus, lists can be represented as their right fold. A right fold <sup>[wiki](https://en.wikipedia.org/wiki/Fold_(higher-order_function))</sup> takes a combining function and an initial value, and returns a single combined value for the whole list, eg.:
```
< x y z > = λ c n . c x (c y (c z n))
```
~~~if:javascript,
in JavaScript syntax:
```javascript
[ x, y, z ] = c => n => c(x)(c(y)(c(z)(n))) ;
```
~~~
~~~if:haskell,
in Haskell syntax:
```haskell
infixr _ `c`
[ x, y, z ] = \ c n -> x `c` y `c` z `c` n
```
~~~
~~~if:python,
in Python syntax:
```python
[ x, y, z ] = lambda c: lambda n: c(x)(c(y)(c(z)(n)))
```
~~~
A list is not just the data in it; it also encapsulates operations on it. This representation encodes both a list's data and all possible operations on it, because _any_ operation on a list can, with the right combining function and initial value, be expressed as a right fold ( even a left fold. but we're not going there .. today ).
Booleans can be represented as a function that chooses between two arguments.
Both these representations can be given type in System F <sup>[wiki](https://en.wikipedia.org/wiki/System_F)</sup> .
This kata will use those encodings.
### Task
Write functions `cons` and `snoc`. Both take an element and a list and return a new list with the element added to the list, in first and last position respectively.
Write function `map`. It takes a transforming function and a list and returns a new list with every element transformed.
Finally, write function `filter`. It takes a predicate and a list and returns a new, filtered list. ( A predicate is a function that takes a value and returns a Boolean. )
~~~if:javascript,
You can define constants in Lambda Calculus syntax only: variables, function expressions, and function calls. Declare your definitions with `const`. Function expressions must use fat arrow syntax ( `x =>` ). You can define and use helper constants. Recursion is not restricted.
~~~
~~~if:lambdacalc,
### Encodings
Lists: `Church`
Booleans: `Church`
Purity: `LetRec`
No number encoding is used; lists are agnostic to the type of their elements ( it just has to be consistent ). Lists may actually contain native JS numbers.
~~~
~~~if:haskell,
You can define constants in Lambda Calculus syntax only: variables, abstractions and applications. Do not include type signatures ( they will be inferred ). Abstractions must use anonymous function syntax ( `\ x ->` ). You can define and use helper constants. Recursion is not restricted.
~~~
~~~if:python,
You can define constants in Lambda Calculus syntax only: variables, function expressions, and function calls. Function expressions must use lambda notation ( `lambda x:` ). You can define and use helper constants. Recursion is not restricted.
~~~
### `Preloaded`
```javascript
False = t => f => f // Church Boolean
True = t => f => t // Church Boolean
nil = c => n => n // constant: the empty list
isEmpty = xs => xs ( _ => _ => False ) (True) // returns a Church Boolean indicating if a list is empty
head = xs => xs ( x => _ => x ) (undefined) // returns the first element of a list // list must not be empty
tail = xs => something quite clever // returns a list without its first element // list must not be empty
```
```lambdacalc
False = \ t f . f # Church Boolean
True = \ t f . t # Church Boolean
nil = \ c n . n # constant: the empty list
is-empty = \ xs . xs ( \ _ _ . False ) True # returns a Church Boolean indicating if a list is empty
head = \ xs . xs ( \ x _ . x ) () # returns the first element of a list # list must not be empty
tail = \ xs . something quite clever # returns a list without its first element # list must not be empty
```
```haskell
false = \ t f -> f -- Church Boolean
true = \ t f -> t -- Church Boolean
nil = \ c n -> n -- constant: the empty list
isEmpty = \ xs -> xs ( \ _ _ -> false ) true -- returns a Church Boolean indicating if a list is empty
head = \ xs -> xs ( \ x _ -> x ) undefined -- returns the first element of a list -- list must not be empty
tail = \ xs -> something quite clever -- returns a list without its first element -- list must not be empty
```
```python
# Church Booleans
false = lambda t: lambda f: f
true = lambda t: lambda f: t
# constant: the empty list
nil = lambda c: lambda n: n
# returns a Church Boolean indicating if a list is empty
is_empty = lambda xs: xs (lambda _: lambda _: false) (true)
# returns the first element of a non-empty list
head = lambda xs: xs (lambda x: lambda _: x) (None)
# returns a non-empty list without its first element
tail = lambda xs: something quite clever
```
### Examples
```javascript
cons ( 1 ) ( nil ) => < 1 >
cons ( 2 ) (< 1 >) => < 2 1 >
snoc ( 1 ) ( nil ) => < 1 >
snoc ( 2 ) (< 1 >) => < 1 2 >
map (sqr) (< 1 2 >) => < 1 4 >
filter (odd) (< 1 2 >) => < 1 >
```
```haskell
cons 1 nil -> < 1 >
cons 2 < 1 > -> < 2 1 >
snoc 1 nil -> < 1 >
snoc 2 < 1 > -> < 1 2 >
map (^2) < 1 2 > -> < 1 4 >
filter odd < 1 2 > -> < 1 >
```
```python
cons ( 1 ) ( nil ) => < 1 >
cons ( 2 ) (< 1 >) => < 2 1 >
snoc ( 1 ) ( nil ) => < 1 >
snoc ( 2 ) (< 1 >) => < 1 2 >
map (sqr) (< 1 2 >) => < 1 4 >
filter (odd) (< 1 2 >) => < 1 >
```
### Notes
`get` and `set` are definitely possible. Implementing those, however, means either using encoded numerals or dealing with numerical arithmetic and comparison operators, which is beyond the scope of this kata. For a real challenge, solve [class List](https://www.codewars.com/kata/class-list) ( JS only ) using this encoding. | algorithms | def cons(a): return lambda b: lambda c: lambda d: c(a)(b(c)(d))
def snoc(a): return lambda b: lambda c: lambda d: b(c)(c(a)(d))
def map(a): return lambda b: lambda c: lambda d: b(
lambda e: lambda f: c(a(e))(f))(d)
def filter(a): return lambda b: lambda c: lambda d: b(
lambda e: lambda f: a(e)(c(e)(f))(f))(d)
| Lambda Calculus: Lists as folds I | 5fb44fbd98799a0021dca93a | [
"Algorithms"
] | https://www.codewars.com/kata/5fb44fbd98799a0021dca93a | 5 kyu |
This is my republished first kata(with issues fixed!), hope you guys will enjoy it!
For input, you will be given a string in the form `"(mx+n)(px+q)"` where the character `x`
can be any single lowercase alphabet from a-z, while `m`, `n`, `p` and `q` are integers(can be negative).
## Task
* Return a string in the format `ax^2+bx+c` where a, b and c are integers, eg. `5x^2-6x+8`
* If `a` or `b` is 1, the '1' in front of the variable should be omitted. eg. `x^2+x-20`
* If `a` or `b` is -1, only the minus sign `-` should be shown, eg. `-x^2-x+6`
## Examples:
```java
KataSolution.quadraticBuilder("(x+2)(x+3)"); //return "x^2+5x+6"
KataSolution.quadraticBuilder("(x-2)(x+7)"); //return "x^2+5x-14"
KataSolution.quadraticBuilder("(3y+2)(y+5)"); //return "3y^2+17y+10"
KataSolution.quadraticBuilder("(-h-7)(4h+3)"); //return "-4h^2-31h-21"
```
```python
quadratic_builder("(x+2)(x+3)") #return "x^2+5x+6"
quadratic_builder("(x-2)(x+7)") #return "x^2+5x-14"
quadratic_builder("(3y+2)(y+5)") #return "3y^2+17y+10"
quadratic_builder("(-h-7)(4h+3)") #return "-4h^2-31h-21"
```
Good luck and have fun! | reference | import re
def quadratic_builder(expression):
# replace -x with -1x in the expression
expression = re . sub("-([a-z])", r"-1\1", expression)
# extract constants and variable name
m, x, n, p, _, q = re . findall("""
\( # opening bracket
(-?\d*) # constant (m)
(\D) # variable (x)
([+-]\d*) # constant (n)
\) # closing bracket
\( # opening bracket
(-?\d*) # constant (p)
(\D) # variable (x)
([+-]\d*) # constant (q)
\) # closing bracket
""", expression, flags=re . VERBOSE). pop()
m, n, p, q = map(int, [m or 1, n, p or 1, q])
# calculate constants of the result
a, b, c = m * p, m * q + n * p, n * q
# construct output
A = f" { a }{ x } ^2" if a != 0 else ""
B = f" { b : + }{ x } " if b != 0 else ""
C = f" { c : + } " if c != 0 else ""
# remove 1s
result = re . sub(r"(\b|\+|-)1" + x, r"\1" + x, A + B + C)
return result
| Build a quadratic equation | 60a9148187cfaf002562ceb8 | [
"Mathematics",
"Strings",
"Algebra",
"Fundamentals"
] | https://www.codewars.com/kata/60a9148187cfaf002562ceb8 | 5 kyu |
Re-write the initial function below so that it is `31` characters or less:
```python
def f(iterable, integer):
length = len(iterable)
if length > integer:
return length
else:
return 0
```
This simple function takes an input iterable and an integer. If the length of the iterable is larger than the integer it returns that length. Otherwise it returns zero. All inputs will be valid and and all iterables will have a defined length. | games | def f(a, b): return (0, z: = len(a))[z > b]
| [Code Golf] Optional Walrus? | 60a82776de1604000e29eb50 | [
"Restricted",
"Puzzles"
] | https://www.codewars.com/kata/60a82776de1604000e29eb50 | 6 kyu |
### Task:
You need to write a function ```grid``` that returns an alphabetical grid of size NxN, where a = 0, b = 1, c = 2....
### Examples:
grid(4)
```
a b c d
b c d e
c d e f
d e f g
```
grid(10)
```
a b c d e f g h i j
b c d e f g h i j k
c d e f g h i j k l
d e f g h i j k l m
e f g h i j k l m n
f g h i j k l m n o
g h i j k l m n o p
h i j k l m n o p q
i j k l m n o p q r
j k l m n o p q r s
```
### Notes:
* After "z" comes "a"
* If function receive N < 0 should return:
```javascript,kotlin
null
```
```python
None
```
```cpp
""
```
```c
""
```
```cobol
""
``` | algorithms | def grid(N):
if N < 0:
return None
abc = 'abcdefghijklmnopqrstuvwxyz' * 8
val = []
for i in range(N):
arr = list(abc[i: N + i])
out = ' ' . join(arr)
val . append(out)
return '\n' . join(val)
| Alphabetical Grid | 60a94f1443f8730025d1744b | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/60a94f1443f8730025d1744b | 7 kyu |
Your music theory class just gave you a homework where you have to find the keys for a bunch of melodies. You decided to be lazy and create a key detection program to do the work for you.
Each melody in this assignment is supposed to be strictly derived from a major scale. There are twelve major scales each of which starts from a differnt one of the twelve musical notes. The twelve musical notes are, in ascending order:
`C, C#, D, D#, E, F, F#, G, G#, A, A#, B`
(For simplicity, we only use sharps( # ) and not flats( b ))
A major scale has seven unique notes and follows a specific intervalic pattern.
For instance, the ascending C major scale with notes C,D,E,F,G,A and B follows this pattern:
<pre>
<code>Notes C - D - E - F - G - A - B - C
Distance 2 2 1 2 2 2 1</code></pre>
The number indicated below each set of two notes shows the distance of the two notes. Between C and D, you have distance of 2 because you skip C#, but between E and F the distance is only 1.
The same pattern (2-2-1-2-2-2-1) occurs in every major scale.
E major scale, which starts on the note E, goes:
<pre>
<code>Notes E - F# - G# - A - B - C# - D# - E
Distance 2 2 1 2 2 2 1</code></pre>
Your task is to create a function that takes a melody as a string and if the melody uses all the seven notes of a major scale, but no other notes, returns a string:
`"? major scale"`
Where `?` is the starting note of the scale (or the "key center").
For instance, the input melody `"C#D#FF#D#FF#G#A#C"` returns `"C# major scale"`.
Beware! A melody doesn't always start on the first note of a scale.
For example, `"D#BC#ABG#AF#E"` should return `"E major scale"`.
If the melody is not derived from any of the major scales, return:
`"No major scale"`
Note:
<pre>
- Input contains only -> 'C','D','E','F','G','A','B', or '#' (no lower case)
- No other letters, space, number or special characters are included
- Even if a melody misses only one note from a scale, return "No major scale"(for instance, "CDEFGA" is not a complete C major scale)
- Note names E# and B# are invalid, and input with these should return "No major scale"
- Also invalid to have two sharps in a row (##), if this happens return "No major scale"</pre>
- Also invalid to have two sharps in a row (##), if this happens, return "No major scale"
- Input string that starts with a sharp should also return "No major scale"
</pre>
| reference | from itertools import accumulate
import re
DEFAULT = 'No'
NOTES = 'C C# D D# E F F# G G# A A# B' . split()
MAJOR_SCHEME = (0, 2, 2, 1, 2, 2, 2, 1)
SPLITTER = re . compile('|' . join(
sorted(NOTES, key=len, reverse=True)) + '|.')
CHORDS_DCT = {frozenset(NOTES[(i + delta) % 12] for delta in accumulate(MAJOR_SCHEME)): root
for i, root in enumerate(NOTES)}
def major_scale(melody):
result = CHORDS_DCT . get(frozenset(SPLITTER . findall(melody)), DEFAULT)
return f" { result } major scale"
| Music Fun #1 - Major Scale | 5c1b25bc85042749e9000043 | [
"Algorithms",
"Strings",
"Parsing",
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/5c1b25bc85042749e9000043 | 6 kyu |
Implement a function which creates a **[radix tree](https://en.wikipedia.org/wiki/Radix_tree)** ( a space-optimized trie \[prefix tree\] )
* in which each node that is the only child is merged with its parent ( unless a word from the input ends there )
* from a given list of words
* using dictionaries ( aka hash tables, hash maps, maps, or objects )
* where:
* The dictionary keys are the nodes.
* Leaf nodes are empty dictionaries.
* The value for empty input is an empty dictionary.
* Words are all lowercase or empty strings.
* Words can contain duplicates.
~~~if:haskell,
* Nodes can be in any order.
~~~
~~~if:rust
Due to the recursive nature of the HashMap, we need to wrap it in a new type. It is preloaded for you and takes the following shape:
```rust
#[derive(Debug, PartialEq)]
struct RadixTree(HashMap<String, Self>);
/// These are convenience methods used for tests creation, but you
/// are free to use them yourself if you find a reason to.
impl RadixTree {
pub fn new<I: IntoIterator<Item=(&'static str, Self)>>(words: I) -> Self {
Self(HashMap::from_iter(
words.into_iter().map(|(k, v)| (String::from(k), v)),
))
}
pub fn empty() -> Self {
Self(HashMap::new())
}
}
```
`Debug` output omits the type name for readability (see examples)
~~~
### Examples:
```python
>>> radix_tree()
{}
>>> radix_tree("")
{}
>>> radix_tree("", "")
{}
>>> radix_tree("radix", "tree")
{"radix": {}, "tree": {}}
>>> radix_tree("ape", "apple")
{"ap": {"e": {}, "ple": {}}}
>>> radix_tree("apple", "applet", "apple", "ape")
{"ap": {"ple": {"t": {}}, "e": {}}}
>>> radix_tree("romane", "romanus", "romulus", "rubens", "rubicon", "rubicundus")
{"r": {"om": {"an": {"e": {}, "us": {}}, "ulus": {}},
"ub": {"ens": {}, "ic": {"on": {}, "undus": {}}}}}
>>> radix_tree("appleabcd", "apple")
{"apple": {"abcd": {}}}
```
```javascript
>>> radixTree()
{}
>>> radixTree("")
{}
>>> radixTree("", "")
{}
>>> radixTree("radix", "tree")
{ radix: {}, tree: {} }
>>> radixTree("ape", "apple")
{ ap: { e: {}, ple: {} } }
>>> radixTree("apple", "applet", "apple", "ape")
{ ap: { ple: { t: {} }, e: {} } }
>>> radixTree("romane", "romanus", "romulus", "rubens", "rubicon", "rubicundus")
{ r: { om: { an: { e: {}, us: {} }, ulus: {} }
, ub: { ens: {}, ic: { on: {}, undus: {} } }
} }
```
```haskell
-- Note that the dictionary format is a standard assoclist, but `newtype`d because of type recursion.
-- This type is Preloaded, and its Eq instance does not require equal ordering for equality.
> radixTree []
Dict []
> radixTree [""]
Dict []
> radixTree ["", ""]
Dict []
> radixTree ["radix", "tree"]
Dict [ ("radix", Dict []), ("tree", Dict []) ]
> radixTree ["ape", "apple"]
Dict [ ("ap", Dict [ ("e", Dict []), ("ple", Dict []) ]) ]
> radixTree ["apple", "applet", "apple", "ape"]
Dict [ ("ap", Dict [ ("ple", Dict [ ("t", Dict []) ]), ("e", Dict []) ]) ]
> radixTree ["romane", "romanus", "romulus", "rubens", "rubicon", "rubicundus"]
Dict [ ("r", Dict [ ("om", Dict [ ("an", Dict [ ("e", Dict []), ("us", Dict []) ]), ("ulus", Dict []) ])
, ("ub", Dict [ ("ens", Dict []), ("ic", Dict [ ("on", Dict []), ("undus", Dict []) ]) ])
]) ]
> radixTree ["appleabcd", "apple"]
Dict [ ("apple", Dict [ ("abcd", Dict []) ]) ]
```
```java
Solution.radixTree()
// returns {}
Solution.radixTree("")
// returns {}
Solution.radixTree("", "")
// returns {}
Solution.radixTree("radix", "tree")
// returns {radix={}, tree={}}
Solution.radixTree("ape", "apple")
// returns {ap={e={}, ple={}}}
Solution.radixTree("apple", "applet", "apple", "ape")
// returns {ap={ple={t={}}, e={}}}
Solution.radixTree("romane", "romanus", "romulus", "rubens", "rubicon", "rubicundus")
// returns {r={om={an={e={}, us={}}, ulus={}}, ub={ens={}, ic={on={}, undus={}}}}}
Solution.radixTree("appleabcd", "apple")
// returns {apple={abcd={}}}
```
```kotlin
Solution.radixTree()
// returns {}
Solution.radixTree("")
// returns {}
Solution.radixTree("", "")
// returns {}
Solution.radixTree("radix", "tree")
// returns {radix={}, tree={}}
Solution.radixTree("ape", "apple")
// returns {ap={e={}, ple={}}}
Solution.radixTree("apple", "applet", "apple", "ape")
// returns {ap={ple={t={}}, e={}}}
Solution.radixTree("romane", "romanus", "romulus", "rubens", "rubicon", "rubicundus")
// returns {r={om={an={e={}, us={}}, ulus={}}, ub={ens={}, ic={on={}, undus={}}}}}
Solution.radixTree("appleabcd", "apple")
// returns {apple={abcd={}}}
```
```rust
// Note: {} is a RadixTree
radix_tree(&[])
// returns {}
radix_tree(&[""])
// returns {}
radix_tree(&["", ""])
// returns {}
radix_tree(&["radix", "tree"])
// returns {"radix": {}, "tree": {}}
radix_tree(&["ape", "apple"])
// returns {"ap": {"e": {}, "ple": {}}}
radix_tree(&["apple", "applet", "apple", "ape"])
// returns {"ap": {"ple": {"t": {}}, "e": {}}}
radix_tree(&["romane", "romanus", "romulus", "rubens", "rubicon", "rubicundus"])
// returns {"r": {"om": {"an": {"e": {}, "us": {}}, "ulus": {}},
// "ub": {"ens": {}, "ic": {"on": {}, "undus": {}}}}}
radix_tree(&["appleabcd", "apple"])
// returns {"apple": {"abcd": {}}}
``` | algorithms | from itertools import groupby
from operator import itemgetter
from os . path import commonprefix
first = itemgetter(0)
def radix_tree(* words):
words = [w for w in words if w]
result = {}
for key, grp in groupby(sorted(words), key=first):
lst = list(grp)
prefix = commonprefix(lst)
result[prefix] = radix_tree(* (w[len(prefix):] for w in lst))
return result
| Radix Tree | 5c9d62cbf1613a001af5b067 | [
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/5c9d62cbf1613a001af5b067 | 6 kyu |
# Markdown 101: Code Format Corrector
## Description
We are writing the document `README.md` for our [github](https://github.com/) but we have forgotten to format correctly the code.
According to this [documentation](https://guides.github.com/features/mastering-markdown/) and this [cheat sheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code), a group of code lines must be surrounded by: ` ``` `
## Task
Your function must insert new lines in the text containing only ` ``` ` in the next two cases:
1. Before the first line of consecutive code lines
2. After the last line of consecutive code lines
## Code lines:
* `>>>` or `&` beginning a line mean "code".
* `\` at the end of a line means continuation of the current type of line.
## Examples
### Example 1
One empty lines after code ending with `\`
````
& code \
& code \
& code
````
Should be:
````
```
& code \
& code \
& code
```
````
Because the empty line is considered code and the forth line is code.
### Example 2
Two empty lines after code ending with `\`
````
& code \
& code \
& code
````
Should be:
````
```
& code \
& code \
```
```
& code
```
````
Because the first empty line is considered code but the second emply line does not follow a code line ending with `\`.
| reference | def markdown_code_corrector(s):
out, inBlk, cont = [], 0, 0
for l in s . split('\n'):
isCode = l . startswith(('&', '>>>'))
if not inBlk and isCode or inBlk and not isCode and not cont:
out . append("```")
out . append(l)
inBlk = isCode or inBlk and cont
cont = l . endswith('\\')
if inBlk:
out . append("```")
return '\n' . join(out)
| Markdown 101: Code Format Corrector | 5e9ed1864f12ec003281e761 | [
"Strings",
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/5e9ed1864f12ec003281e761 | 6 kyu |
### Task
Write a function that receives a non-negative integer `n ( n >= 0 )` and returns the next higher multiple of five of that number, obtained by concatenating the ***shortest possible*** binary string to the end of this number's binary representation.
### Examples
```python
1. next_multiple_of_five(8)
```
```javascript
1. nextMultipleOfFive(8)
```
```haskell
1. nextMultipleOfFive 8
```
**Steps:**
* 8 to binary == '1000'
* concatenate shortest possible string '11' to obtain '1000' + '11' == '100011'
* '100011' to decimal == 35 => the answer
('001' would do the job too, but '11' is the shortest string here)
```python
2. next_multiple_of_five(5)
```
```javascript
2. nextMultipleOfFive(5)
```
```haskell
2. nextMultipleOfFive 5
```
**Steps:**
* 5 to binary =='101'
* concatenate shortest possible string '0' to obtain '101' + '0' == '1010'
* '1010' to decimal == 10
(5 is already a multiple of 5, obviously, but we're looking for the next multiple of 5)
### Note
* Numbers up to `1e10` will be tested, so you need to come up with something smart. | algorithms | PROVIDERS = (
lambda n: n * 2 or 5,
lambda n: n * 4 + 1,
lambda n: n * 2 + 1,
lambda n: n * 4 + 3,
lambda n: n * 8 + 3,
)
def next_multiple_of_five(n):
return PROVIDERS[n % 5](n)
| Next multiple of 5 | 604f8591bf2f020007e5d23d | [
"Algorithms",
"Logic",
"Performance"
] | https://www.codewars.com/kata/604f8591bf2f020007e5d23d | 6 kyu |
Your goal in this kata is to implement an algorithm, which increases `number` in the way explained below, and returns the result.
Input data: `number, iterations, step`.
Stage 1:
We get the: `number:143726`, `iterations: 16`, `step:3`
And make increment operations in a special way
Position: We start from `1` position and increment `4`th num, besause `step` is `3`
`s` - start position
`+` - current increased position
Position: `s - - - - -` => `- - - + - -`
Number: `1 4 3 7 2 6` => `1 4 3 8 2 6`
Stage 2: repeat stage 1 :)
Position: `- - - s - -` => `+ - - - - -`
Number: `1 4 3 8 2 6` => `2 4 3 8 2 6`
You must remember: if your number overflow into a longer number, the current position gets shifted to the right
`9 9 9` => `- - p` - before overflow position be at `3`rd digit
`1 0 0 0` => `- - - p` - after overflow position be at `4`th digit
Note:
`9 => 10`
`799 => 800` (if you increase second `9`) or `809` (if you increase first `9`)
`99000 => 100000` (if you increase second `9`) or `109000` (if you increase first `9`) | algorithms | def increment(number, iterations, spacer):
step = len(str(number)) - 1
for i in range(iterations):
step = (step - spacer) % len(str(number))
number = number + 10 * * (step)
return number
| Increment with iterations | 5ecc16daa200d2000165c5b1 | [
"Algorithms"
] | https://www.codewars.com/kata/5ecc16daa200d2000165c5b1 | 6 kyu |
A group of horses just ran past Farmer Thomas, and he would like to figure out how many horses were there. However, Farmer Thomas has a bad eye sight, and cannot really see the horses that are now distant. He did remember the sound of their galloping though, and he wants your help in figuring out how many horses (and the length of their legs) were in that group.
Each horse will make a thumping noise every step as its hooves hit the ground. Farmer Thomas has recorded the sound as strings like this (the following record is 15 seconds long):
```
000100010001000
```
where each number represents how many thumps he heard in that second.
However, there's a catch; horses with longer legs take bigger steps, resulting in longer intervals between thumps. Specifically, a horse with leg length `n` will thump every `n` seconds.
A single horse with leg length `2` will sound like:
```
01010101010101
```
The same rule applies when there are multiple horses. Two horses with leg length 2 and 3 sound like:
```
0111020111
```
Note that the sixth digit is `2` since both horses thump in that second.
## Input
A string of any length that represents the sound of the horses' galloping (as described above).
## Output
An array of length equivalent to the amount of horses where each element represents the leg length of a horse.
For example, this input
```
0111020111
```
should return `[2, 3]`.
## Notes
- There could be multiple horses with the same leg length. `0020020020020` is the sound of `2` horses, both of which have leg length of `3`.
- The thump cycle of all horses is synchronized at the start of the sound string. This means that you don't have to worry about phase offsets.
- The length of the sound string is always greater than or equal the longest leg length (meaning that every horse will jump at least once in the string).
- Your output will be sorted in the tests for comparison purpose (your answer doesn't need to be sorted).
### Constraints
- `len(sound_str)` <= `1000`
- `len(horses)` <= `9` (random tests)
- `len(horses)` <= `10` (trivial tests) | algorithms | def count_horses(sound_str):
res = []
lst = list(sound_str)
while set(lst) != {'0'}:
for j in range(len(lst)):
if lst[j] != '0':
res . append(j + 1)
for k in range(j, len(lst), j + 1):
lst[k] = str(int(lst[k]) - 1)
break
return res
| Counting Horses | 5f799eb13e8a260015f58944 | [
"Algorithms"
] | https://www.codewars.com/kata/5f799eb13e8a260015f58944 | 6 kyu |
### Checkerboard Resolution
In this kata we will be counting the the black squares on a special checkerboard. It is special because it has a `resolution` which determines how the black and white squares are laid out.
The `resolution` refers to the dimensions of squares of a single colour. See below for an example with dimensions `11x6`:
With `resolution = 1`:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1102 602" style="background-color:white" width="600">
<title>Resolution = 1</title>
<g fill="#241d28">
<rect x="101" y="1" width="100" height="100"/>
<rect x="301" y="1" width="100" height="100"/>
<rect x="501" y="1" width="100" height="100"/>
<rect x="701" y="1" width="100" height="100"/>
<rect x="901" y="1" width="100" height="100"/>
<rect x="1" y="101" width="100" height="100"/>
<rect x="201" y="101" width="100" height="100"/>
<rect x="401" y="101" width="100" height="100"/>
<rect x="601" y="101" width="100" height="100"/>
<rect x="801" y="101" width="100" height="100"/>
<rect x="1001" y="101" width="100" height="100"/>
<rect x="101" y="201" width="100" height="100"/>
<rect x="301" y="201" width="100" height="100"/>
<rect x="501" y="201" width="100" height="100"/>
<rect x="701" y="201" width="100" height="100"/>
<rect x="901" y="201" width="100" height="100"/>
<rect x="1" y="301" width="100" height="100"/>
<rect x="201" y="301" width="100" height="100"/>
<rect x="401" y="301" width="100" height="100"/>
<rect x="601" y="301" width="100" height="100"/>
<rect x="801" y="301" width="100" height="100"/>
<rect x="1001" y="301" width="100" height="100"/>
<rect x="101" y="401" width="100" height="100"/>
<rect x="301" y="401" width="100" height="100"/>
<rect x="501" y="401" width="100" height="100"/>
<rect x="701" y="401" width="100" height="100"/>
<rect x="901" y="401" width="100" height="100"/>
<rect x="1" y="501" width="100" height="100"/>
<rect x="201" y="501" width="100" height="100"/>
<rect x="401" y="501" width="100" height="100"/>
<rect x="601" y="501" width="100" height="100"/>
<rect x="801" y="501" width="100" height="100"/>
<rect x="1001" y="501" width="100" height="100"/>
</g>
<g fill="none" stroke="#447cbf" stroke-width="2">
<line x1="1001" y1="1" x2="1001" y2="601"/>
<line x1="901" y1="1" x2="901" y2="601"/>
<line x1="801" y1="1" x2="801" y2="601"/>
<line x1="701" y1="1" x2="701" y2="601"/>
<line x1="601" y1="1" x2="601" y2="601"/>
<line x1="501" y1="1" x2="501" y2="601"/>
<line x1="401" y1="1" x2="401" y2="601"/>
<line x1="301" y1="1" x2="301" y2="601"/>
<line x1="1101" y1="1" x2="1101" y2="601"/>
<line x1="1" y1="1" x2="1" y2="601"/>
<line x1="201" y1="1" x2="201" y2="601"/>
<line x1="101" y1="1" x2="101" y2="601"/>
<line x1="1" y1="1" x2="1101" y2="1"/>
<line x1="1" y1="101" x2="1101" y2="101"/>
<line x1="1" y1="201" x2="1101" y2="201"/>
<line x1="1" y1="301" x2="1101" y2="301"/>
<line x1="1" y1="401" x2="1101" y2="401"/>
<line x1="1" y1="501" x2="1101" y2="501"/>
<line x1="1" y1="601" x2="1101" y2="601"/>
</g>
</svg>
`Number of black squares = 33`
And now with `resolution = 2`:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1102 602" style="background-color:white" width="600">
<title>Resolution = 2</title>
<g fill="#241d28">
<rect x="201" y="1" width="200" height="200"/>
<rect x="601" y="1" width="200" height="200"/>
<rect x="1001" y="1" width="100" height="200"/>
<rect x="1" y="201" width="200" height="200"/>
<rect x="401" y="201" width="200" height="200"/>
<rect x="801" y="201" width="200" height="200"/>
<rect x="201" y="401" width="200" height="200"/>
<rect x="601" y="401" width="200" height="200"/>
<rect x="1001" y="401" width="100" height="200"/>
</g>
<g fill="none" stroke="#447cbf" stroke-width="2">
<line x1="1001" y1="1" x2="1001" y2="601"/>
<line x1="901" y1="1" x2="901" y2="601"/>
<line x1="801" y1="1" x2="801" y2="601"/>
<line x1="701" y1="1" x2="701" y2="601"/>
<line x1="601" y1="1" x2="601" y2="601"/>
<line x1="501" y1="1" x2="501" y2="601"/>
<line x1="401" y1="1" x2="401" y2="601"/>
<line x1="301" y1="1" x2="301" y2="601"/>
<line x1="1101" y1="1" x2="1101" y2="601"/>
<line x1="1" y1="1" x2="1" y2="601"/>
<line x1="201" y1="1" x2="201" y2="601"/>
<line x1="101" y1="1" x2="101" y2="601"/>
<line x1="1" y1="1" x2="1101" y2="1"/>
<line x1="1" y1="101" x2="1101" y2="101"/>
<line x1="1" y1="201" x2="1101" y2="201"/>
<line x1="1" y1="301" x2="1101" y2="301"/>
<line x1="1" y1="401" x2="1101" y2="401"/>
<line x1="1" y1="501" x2="1101" y2="501"/>
<line x1="1" y1="601" x2="1101" y2="601"/>
</g>
</svg>
`Number of black squares = 32`
And one more example, `resolution = 5`:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1102 602" style="background-color:white" width="600">
<title>Resolution = 5</title>
<g fill="#241d28">
<rect x="501" y="1" width="500" height="500"/>
<rect x="1" y="501" width="500" height="100"/>
<rect x="1001" y="501" width="100" height="100"/>
</g>
<g fill="none" stroke="#447cbf" stroke-width="2">
<line x1="1001" y1="1" x2="1001" y2="601"/>
<line x1="901" y1="1" x2="901" y2="601"/>
<line x1="801" y1="1" x2="801" y2="601"/>
<line x1="701" y1="1" x2="701" y2="601"/>
<line x1="601" y1="1" x2="601" y2="601"/>
<line x1="501" y1="1" x2="501" y2="601"/>
<line x1="401" y1="1" x2="401" y2="601"/>
<line x1="301" y1="1" x2="301" y2="601"/>
<line x1="1101" y1="1" x2="1101" y2="601"/>
<line x1="1" y1="1" x2="1" y2="601"/>
<line x1="201" y1="1" x2="201" y2="601"/>
<line x1="101" y1="1" x2="101" y2="601"/>
<line x1="1" y1="1" x2="1101" y2="1"/>
<line x1="1" y1="101" x2="1101" y2="101"/>
<line x1="1" y1="201" x2="1101" y2="201"/>
<line x1="1" y1="301" x2="1101" y2="301"/>
<line x1="1" y1="401" x2="1101" y2="401"/>
<line x1="1" y1="501" x2="1101" y2="501"/>
<line x1="1" y1="601" x2="1101" y2="601"/>
</g>
</svg>
`Number of black squares = 31`
<sub>*Credit to awesomead for the pretty images!*</sub>
As you may have noticed the top left square is **always white**, and we are counting the **individual** black squares on the board.
#### Task
You are required to write a function that will take in three parameters:
- `width` -> The width of the board
- `height` -> The height of the board
- `resolution` -> The size of the coloured squares on the checkerboard (as shown above)
And returns the total count of all individual black squares.
#### Additional Info
~~~if-not:lambdacalc
- All inputs will be valid
- `0 <= width <= 10**32`
- `0 <= height <= 10**32`
- `1 <= resolution <= 10**32`
~~~
~~~if:lambdacalc
- All inputs will be valid
- `0 <= width <= 10**8`
- `0 <= height <= 10**8`
- `1 <= resolution <= 10**8`
#### Encodings:
- Numbers: `BinaryScott`
- Purity: `LetRec`
~~~
Good luck! | algorithms | def count_checkerboard(w, h, r):
nW, rW = divmod(w, r)
nH, rH = divmod(h, r)
rect = nW * nH / / 2 * r * * 2 # full rectangle
# right vertical strip (except corner)
rStrip = (nH + nW % 2) / / 2 * r * rW
# bottom horizontal strip (except corner)
bStrip = (nW + nH % 2) / / 2 * r * rH
# bottom right corner: black only if parity of nH and nW are different
corner = (nH ^ nW) % 2 * rH * rW
return rect + rStrip + bStrip + corner
| Checkerboard Resolution | 60576b180aef19001bce494d | [
"Performance",
"Algorithms",
"Matrix"
] | https://www.codewars.com/kata/60576b180aef19001bce494d | 6 kyu |
Given a natural number n, we want to know in how many ways we may express these numbers as product of other numbers.
For example the number
```python
18 = 2 x 9 = 3 x 6 = 2 x 3 x 3 # (we do not consider the product 18 x 1), (3 ways)
```
See this example a bit more complicated,
```python
60 = 2 x 30 = 3 x 20 = 4 x 15 = 5 x 12 = 6 x 10 = 2 x 2 x 15 = 2 x 3 x 10 = 2 x 5 x 6 = 3 x 4 x 5 = 2 x 2 x 3 x 5 (10 ways)
```
We need the function ```prod_int_part()```, that receives a number n, and ouputs the amount of total different products with all the products of max length sorted in this way:
1) each product will be expressed in a list of its factors in incresing order from left to right
2) if there is more than one list-product, these lists should be ordered by the value of the first term, if two lists have the same term equal thay should be ordered by the value of the second term.
Let's see some cases:
```python
prod_int_part(18) == [3, [2, 3, 3]]
prod_int_part(60) == [10, [2, 2, 3, 5]
```
If we have only one list-product with the maximum length, there is no use to have it with two nested braces, so the result will be like this case:
```python
prod_int_part(54) == [6, [2, 3, 3, 3]]
```
Now, let's see examples when ```n``` cannot be partitioned:
```python
prod_int_part(37) == [0, []]
prod_int_part(61) == [0, []]
```
Enjoy it!!
| reference | def prod_int_part(n, min_=2):
total, fac = 0, []
for d in range(min_, int(n * * .5) + 1):
if not n % d:
count, sub = prod_int_part(n / / d, d)
total += count + 1
if not count:
sub = [n / / d]
if not fac:
fac = [d] + sub
return [total, fac]
| Product Partitions I | 56135a61f8b29814340000cd | [
"Fundamentals",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/56135a61f8b29814340000cd | 6 kyu |
<b>Unicode Transformation Format – 8-bit</b>
</br>As the name suggests <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a> was designed to encode data in a stream of bytes.
It works by splitting the bits up in multiples of eight. This is achieved by inserting headers to mark in how many bytes the bits were split. If the bits need to be split in two, the header `110` is added as prefix leaving five bits of the byte for the rest of the data. Followed by a continuation byte.
A continuation byte always start with `10` leaving six bits for data.
For a three-way split: the header `1110` is added with two continuation bytes and for four: `11110` with three continuation bytes. The number of ones at the start of the first byte denotes the number of bytes the data was split in.
# Task
Your task is to write two functions:
```if:python
1. `to_utf8_binary`: which encodes a string to a bitstring using UTF-8 encoding.
2. `from_utf8_binary`: which does the reverse.
```
```if:javascript
1. `toUTF8binary`: which encodes a string to a bitstring (a string consisting entirely of `0`s and `1`s) using UTF-8 encoding.
2. `fromUTF8binary`: which does the reverse.
<b>Note :</b> Remember that JavaScript uses [UTF-16](https://en.wikipedia.org/wiki/UTF-16) as its character encoding !
```
- Layout of UTF-8 byte sequences:
```
# BYTES FIRST CODE POINT LAST CODE POINT BYTE 1 BYTE 2 BYTE 3 BYTE 4
1 0 127 0xxxxxxx
2 128 2047 110xxxxx 10xxxxxx
3 2048 65535 1110xxxx 10xxxxxx 10xxxxxx
4 65536 1114111 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
```
# Examples
```
ENCODE
A -> 1000001 -> 01000001
八 -> 101000101101011 -> 1110-0101 10-000101 10-101011
DECODE
110-00010 10-100111 -> 10100111 -> §
11110-000 10-010000 10-001010 10-001100 -> 10000001010001100 -> 𐊌
```
* Spaces and hyphens just for clarity
- https://en.wikipedia.org/wiki/UTF-8#Encoding | algorithms | from textwrap import wrap
def to_utf8_binary(string):
return '' . join(format(x, 'b'). rjust(8, '0') for x in bytearray(string, 'utf-8'))
def from_utf8_binary(bitstring):
return bytearray([int(t, 2) for t in wrap(bitstring, 8)]). decode()
| Utf-8: Binary Encoding | 5f5fffc4f6b3390029a6b277 | [
"Unicode",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5f5fffc4f6b3390029a6b277 | 6 kyu |
It's about time your hacking skills paid off! You've come across proprietary code for a slot machine (see below), and as it turns out, the program uses a pseudorandom number generator that isn't very random. Now you've realized the potential to win big!
Your session starts with a bankroll of `36.00` dollars. You will be passed a function to `play` the slot game. The only option your code has is how much to wager, any whole dollar amount from `1` to available funds. Calling `play` will pull the lever to do just that, returning the reel symbols in view (including those peeking above and below center) and your updated balance.
In order to beat the casino, you'll probably want to know how the game works. The mechanics are described at a high-level here, but the complete code shown below is also included with the test case. You should't need to change that code, just your solution. Remember, your job as the player is to bet high when you're about to win.
This is a simple one-line game where the 3 reels spin and stop at random positions. If all 3 symbols across the middle match, the one-armed bandit pays out big time! Just 2 matching symbols anywhere on the center line will award a smaller prize. Otherwise, 3 mismatched symbols award half the wager, which is an overall loss.
Play continues until the session terminates (e.g. due to an invalid wager), you run out of time or money (the return to player averages just 98% per spin), or the millionaire casino owner goes broke. To beat this kata, you'll have to strike it rich, and then repeat your success as proof. It's too bad the money isn't real!
```python
state = None
def pseudorandom():
global state, random_seed
if state is None:
# initialize RNG with seed
state = (random_seed & 0x7FFF) + 1
# determine the next pseudorandom number
state ^= state >> 6
state ^= state << 8
state &= 0x7FFF
state ^= state >> 5
return state
def reel(position):
# return the 5 symbols on the reel strip around this position
reel_strip = (
'', '#', '', '$', '', '%', '', '&', '', '$',
'', '$', '', '&', '', '#', '', '%', '', '%',
'', '$', '', '#', '', '&', '', '&', '', '%', '', '#'
)
symbol = lambda row: reel_strip[(position + row) % 32]
return [symbol(row) for row in (-2, -1, 0, 1, 2)]
def spin():
# spin each reel and return a 2D array of the symbols that landed
random = pseudorandom()
stop3 = random & 0x1F
random >>= 5
stop2 = random & 0x1F
random >>= 5
stop1 = random & 0x1F
return [reel(stop1), reel(stop2), reel(stop3)]
def evaluate(view):
# determine the payout based on the 2D array of symbols in view
payline = [column[2] for column in view]
for symbol in payline:
count = payline.count(symbol)
if count > 1:
paytable = {
3: {'$': 100, '#': 50, '&': 30, '%': 21, '': 0},
2: {'$': 5, '#': 3.50, '&': 2.75, '%': 2.50, '': 0}
}
return paytable[count][symbol]
return 0.50 if all(payline) else 0 # consolation prize or loss
def play(wager):
# stake a bet at the given wager amount to play the game
global bankroll, threshold
assert type(wager) is int and 0 < wager <= bankroll, f'Bad wager: {wager}'
view = spin()
bankroll += (-1 + evaluate(view)) * wager # cost plus award
if bankroll < 1.00 or bankroll >= threshold:
raise FutureWarning # end the session
return view, bankroll
```
| games | def session(play): play . __globals__['threshold'] = 0
| Rob the one-armed bandit | 601ae2a5f6d6bb0012947f27 | [
"Puzzles",
"Algorithms",
"Cryptography"
] | https://www.codewars.com/kata/601ae2a5f6d6bb0012947f27 | 6 kyu |
**set!** is a card game where you compete with other players, to find out who can find a _set_ of cards first.
Your task is to write a function that checks if a collection of three input cards qualifies as a set.
### The cards
Every card has one, two or three symbols in it. A symbol has three distinct features:
- Shape (either `diamond`, `snake` or `capsule`)
- Colour (either `green`, `blue` or `red`)
- Pattern (either `blank`, `striped` or `solid`)

(Image is taken as fair use from Wikipedia.)
### What's a set?
A set *always* consists of three cards. The set is considered valid if, and only if, every property of the card is either the same as the other two cards, or distinct from the other two. Properties include the three features mentioned above plus the quantity of symbols.
### Input & Output
You will receive an four arrays, containing the properties of the cards. One array, containing the quantity of symbols, will be numeric, the others will contain strings.
It's safe to assume that any card provided will always satisfy the properties outlined above. For example, there will be no card passed with 5 symbols, or with a circle shape.
Your task is to return a boolean, indicating if the given input properties qualify as a valid set - `true` if they do `false` if not. | algorithms | def is_valid_set(* props):
return all(len(set(x)) != 2 for x in props)
| Is it a Set? | 5fddfbe6a65636001cc4fcd2 | [
"Games",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/5fddfbe6a65636001cc4fcd2 | 6 kyu |
A [Leyland number](https://en.wikipedia.org/wiki/Leyland_number) is a number of the form `$x^y + y^x$` where `$x$` and `$y$` are integers greater than 1.
The first few such numbers are:
* `$8 = 2^2 + 2^2$`
* `$17 = 2^3 + 3^2$`
* `$32 = 2^4 + 4^2$`
* `$54 = 3^3 + 3^3$`
Return all Leyland numbers up to 10<sup>12</sup> as a list, in ascending order.
```if:python,ruby
Your code can be maximum 80 characters long.
```
---
### My other katas
If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-)
#### *Translations are welcome!* | games | r = range(2, 40)
def f(): return sorted({x * * y + y * * x for x in r for y in r})[: 121]
| [Code Golf] Leyland Numbers | 6021ab77b00bf1000dd276d3 | [
"Restricted",
"Puzzles"
] | https://www.codewars.com/kata/6021ab77b00bf1000dd276d3 | 6 kyu |
# Task
You are given string <code>s</code>.
For example:
```python
s = "aebecda"
```
Your task is to shuffle and divide this line into the lowest number of palindromes so that the <b>length</b> of the <b>smallest</b> palindrome in the chosen division is the <b>largest</b> amongst all the smallest palindromes across all possible divisions. Return this length.
In the above example this can be done as follows:
```python
s = "aba | c | ede"
```
So the answer is 1.
Here's another example:
```python
s = "eutxutuatgextu" -> "xttattx | uuegeuu" -> lowest(s) = 7
```
Another division for the previous example could be:
```python
"ttatt | xuuegeuux" -> lowest(s) = 5
```
But the length of the smallest palindrome <code>5</code> in this division is lower than the one in the initial division <code>7</code>.
Your task is to write the function lowest(s) that returns one number - answer.
# Constraints
<code>100</code> tests where <code>len(s) = 10</code>
<code>100</code> tests where <code>len(s) = 1000</code>
<code>100</code> tests where <code>len(s) = 10000</code>
<code>100</code> tests where <code>0 ≤ len(s) ≤ 10000</code>
If you do not know what a palindrome is:
https://examples.yourdictionary.com/palindrome-examples.html
# Examples
```python
s = "aebecda" -> "aba | c | ede" -> lowest(s) = 1
s = "eutxutuatgextu" -> "xttattx | uuegeuu" -> lowest(s) = 7
s = "abbddc" -> "bab | dcd" -> lowest(s) = 3
s = "abcd" -> "a | b | c | d" -> lowest(s) = 1
s = "aabbccdd" -> "abcddcba" -> lowest(s) = 8
s = "" -> "" -> lowest(s) = 0
```
Good luck :D | algorithms | from collections import Counter
def lowest(s):
if not s:
return 0
cnt = Counter(s)
pairs, seeds = map(sum, zip(* (divmod(n, 2) for n in cnt . values())))
return len(s) if not seeds else pairs / / seeds * 2 + 1
| Divide into palindromes | 5f8219c1ae0eb800291c50c1 | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/5f8219c1ae0eb800291c50c1 | 6 kyu |
Have you heard about <b>Megamind</b>? <b>Megamind</b> and <b>Metro Man</b> are two aliens who came to earth. <b>Megamind</b> wanted to destroy the earth, while <b>Metro Man</b> wanted to stop him and protect mankind. After a lot of fighting, <b>Megamind</b> finally threw <b>Metro Man</b> up into the sky. <b>Metro Man</b> was defeated and was never seen again. <b>Megamind</b> wanted to be a super villain. He believed that the difference between a villain and a super villain is nothing but presentation. <b>Megamind</b> became bored, as he had nobody or nothing to fight against since <b>Metro Man</b> was gone. So, he wanted to create another hero against whom he would fight for recreation. But accidentally, another villain named <b>Hal Stewart</b> was created in the process, who also wanted to destroy the earth. Also, at some point <b>Megamind</b> had fallen in love with a pretty girl named <b>Roxanne Ritchi</b>. This changed him into a new man. Now he wants to stop <b>Hal Stewart</b> for the sake of his love. So, the ultimate fight starts now.
* Megamind has unlimited supply of guns named <b>Magic-48</b>. Each of these guns has `shots` rounds of magic spells.
* Megamind has perfect aim. If he shoots a magic spell it will definitely hit Hal Stewart. Once hit, it decreases the energy level of Hal Stewart by `dps` units.
* However, since there are exactly `shots` rounds of magic spells in each of these guns, he may need to swap an old gun with a fully loaded one. This takes some time. Let’s call it swapping period.
* Since Hal Stewart is a mutant, he has regeneration power. His energy level increases by `regen` unit during a swapping period.
* Hal Stewart will be defeated immediately once his energy level becomes zero or negative.
* Hal Stewart initially has the energy level of `hp` and Megamind has a fully loaded gun in his hand.
* Given the values of `hp`, `dps`, `shots` and `regen`, find the minimum number of times Megamind needs to shoot to defeat Hal Stewart. If it is not possible to defeat him, return `-1` instead.
# Example
Suppose, `hp` = 13, `dps` = 4, `shots` = 3 and `regen` = 1. There are 3 rounds of spells in the gun. Megamind shoots all of them. Hal Stewart’s energy level decreases by 12 units, and thus his energy level becomes 1. Since Megamind’s gun is now empty, he will get a new gun and thus it’s a swapping period. At this time, Hal Stewart’s energy level will increase by 1 unit and will become 2. However, when Megamind shoots the next spell, Hal’s energy level will drop by 4 units and will become −2, thus defeating him. So it takes 4 shoots in total to defeat Hal Stewart. However, in this same example if Hal’s regeneration power was 50 instead of 1, it would have been impossible to defeat Hal.
| reference | from math import ceil
def mega_mind(hp, dps, shots, regen):
if dps * shots >= hp:
return ceil(hp / dps)
if dps * shots <= regen:
return - 1
number_of_regenerations = ceil((hp - dps * shots) / (dps * shots - regen))
return ceil((hp + regen * number_of_regenerations) / dps)
| Megamind | 5baf21542d15ec9453000147 | [
"Fundamentals",
"Games"
] | https://www.codewars.com/kata/5baf21542d15ec9453000147 | 6 kyu |
# Scenario
With **_Cereal crops_** like wheat or rice, before we can eat the grain kernel, we need to remove that inedible hull, or *to separate the wheat from the chaff*.
___
# Task
**_Given_** a *sequence of n integers* , **_separate_** *the negative numbers (chaff) from positive ones (wheat).* 
___
# Notes
* **_Sequence size_** is _at least_ **_3_**
* **_Return_** *a new sequence*, such that **_negative numbers (chaff) come first, then positive ones (wheat)_**.
* In Java , *you're not allowed to modify the input Array/list/Vector*
* **_Have no fear_** , *it is guaranteed that there will be no zeroes* . 
* **_Repetition_** of numbers in *the input sequence could occur* , so **_duplications are included when separating_**.
* If a misplaced *positive* number is found in the front part of the sequence, replace it with the last misplaced negative number (the one found near the end of the input). The second misplaced positive number should be swapped with the second last misplaced negative number. *Negative numbers found at the head (begining) of the sequence* , **_should be kept in place_** .
____
# Input >> Output Examples:
```
wheatFromChaff ({7, -8, 1 ,-2}) ==> return ({-2, -8, 1, 7})
```
## **_Explanation_**:
* **_Since_** `7 ` is a **_positive number_** , it should not be located at the beginnig so it needs to be swapped with the **last negative number** `-2`.
____
```
wheatFromChaff ({-31, -5, 11 , -42, -22, -46, -4, -28 }) ==> return ({-31, -5,- 28, -42, -22, -46 , -4, 11})
```
## **_Explanation_**:
* **_Since_**, `{-31, -5} ` are **_negative numbers_** *found at the head (begining) of the sequence* , *so we keep them in place* .
* Since `11` is a positive number, it's replaced by the last negative which is `-28` , and so on till sepration is complete.
____
```
wheatFromChaff ({-25, -48, -29, -25, 1, 49, -32, -19, -46, 1}) ==> return ({-25, -48, -29, -25, -46, -19, -32, 49, 1, 1})
```
## **_Explanation_**:
* **_Since_** `{-25, -48, -29, -25} ` are **_negative numbers_** *found at the head (begining) of the input* , *so we keep them in place* .
* Since `1` is a positive number, it's replaced by the last negative which is `-46` , and so on till sepration is complete.
* Remeber, *duplications are included when separating* , that's why the number `1` appeared twice at the end of the output.
____
# Tune Your Code , There are 250 Assertions , 100.000 element For Each .
# Only O(N) Complexity Solutions Will pass .
____
____
____
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [Bizarre Sorting-katas](https://www.codewars.com/collections/bizarre-sorting-katas)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcome
## Enjoy Learning !!
# Zizou
| reference | def wheat_from_chaff(values):
i, j = 0, len(values) - 1
while True:
while i < j and values[i] < 0:
i += 1
while i < j and values[j] > 0:
j -= 1
if i >= j:
return values
values[i], values[j] = values[j], values[i]
| Separate The Wheat From The Chaff | 5bdcd20478d24e664d00002c | [
"Fundamentals",
"Arrays",
"Performance"
] | https://www.codewars.com/kata/5bdcd20478d24e664d00002c | 6 kyu |
Convert the 8-bit grayscale input image (2D-list) into an ASCII-representation.
```
_____/\\\\\\\\\________/\\\\\\\\\\\__________/\\\\\\\\\__/\\\\\\\\\\\__/\\\\\\\\\\\_
___/\\\\\\\\\\\\\____/\\\/////////\\\_____/\\\////////__\/////\\\///__\/////\\\///__
__/\\\/////////\\\__\//\\\______\///____/\\\/_______________\/\\\_________\/\\\_____
_\/\\\_______\/\\\___\////\\\__________/\\\_________________\/\\\_________\/\\\_____
_\/\\\\\\\\\\\\\\\______\////\\\______\/\\\_________________\/\\\_________\/\\\_____
_\/\\\/////////\\\_________\////\\\___\//\\\________________\/\\\_________\/\\\_____
_\/\\\_______\/\\\__/\\\______\//\\\___\///\\\______________\/\\\_________\/\\\_____
_\/\\\_______\/\\\_\///\\\\\\\\\\\/______\////\\\\\\\\\__/\\\\\\\\\\\__/\\\\\\\\\\\_
_\///________\///____\///////////___________\/////////__\///////////__\///////////__
```
_(Example ASCII-art)_
For every component in the image output a character corresponding to its intensity.
Specifically, you are supposed to normalize the input values (of dynamic range 0 - 255) down to a dynamic range of the number of glyphs (0 - 8). For simplicity your implementation should use flooring (integer division) in order to make all values (0 ~ 8) integers, ie.
```
0 → 0.000 → 0
10 → ~ 0.313 → 0
254 → ~ 7.968 → 7
255 → 8.000 → 8
```
Your symbols (_glyphs_) for representing pixel intensities:
```python
GLYPHS = " .,:;xyYX"
```
The _normalization_ is linear (and floored), meaning with an input value of 180 and 9 glyphs, glyph #5 (0-indexed) is ```x```, meaning ```180 → 'x'```.
Each scanline (_row_) in the image should be represented by a newline ```\n``` in the output string. Ie. a single string, not a list of strings.
__Note:__ Your ASCII-art generator is best suited for bright text on dark background. | algorithms | def image2ascii(image):
return '\n' . join('' . join(glyphs[(v * 8) / / 255] for v in r) for r in image)
| Grayscale ASCII-art | 5c22954a58251f1fdc000008 | [
"ASCII Art",
"Algorithms"
] | https://www.codewars.com/kata/5c22954a58251f1fdc000008 | 6 kyu |
This kata is a slightly harder version of [Gravity Flip](https://www.codewars.com/kata/5f70c883e10f9e0001c89673). It is recommended to do that first.
Bob is bored in his physics lessons yet again, and this time, he's brought a more complex gravity-changing box with him. It's 3D, with small cubes arranged in a matrix of `n`×`m` columns. It can change gravity to go in a certain direction, which can be `'L'`, `'R'`, `'D'`, and `'U'` (left, right, down, and up).
Given the initial configuration of the cubes inside of the box as a 2D array, determine how the cubes are arranged after Bob switches the gravity.
See the sample tests for examples. | games | import numpy as np
dir = {
'L': lambda a: np . sort(a)[:, :: - 1],
'R': lambda a: np . sort(a),
'U': lambda a: np . sort(a, axis=0)[:: - 1, :],
'D': lambda a: np . sort(a, axis=0)
}
def flip(d, a):
return dir[d](np . array(a)). tolist()
| Gravity Flip (3D version) | 5f849ab530b05d00145b9495 | [
"Puzzles",
"Arrays"
] | https://www.codewars.com/kata/5f849ab530b05d00145b9495 | 6 kyu |
Remove the parentheses
=
In this kata you are given a string for example:
```python
"example(unwanted thing)example"
```
Your task is to remove everything inside the parentheses as well as the parentheses themselves.
The example above would return:
```python
"exampleexample"
```
## Notes
* Other than parentheses only letters and spaces can occur in the string. Don't worry about other brackets like ```"[]"``` and ```"{}"``` as these will never appear.
* There can be multiple parentheses.
* The parentheses can be nested. | reference | def remove_parentheses(s):
lvl, out = 0, []
for c in s:
lvl += c == '('
if not lvl:
out . append(c)
lvl -= c == ')'
return '' . join(out)
| Remove the parentheses | 5f7c38eb54307c002a2b8cc8 | [
"Strings",
"Algorithms",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/5f7c38eb54307c002a2b8cc8 | 6 kyu |
Given time in 24-hour format, convert it to words.
```
For example:
13:00 = one o'clock
13:09 = nine minutes past one
13:15 = quarter past one
13:29 = twenty nine minutes past one
13:30 = half past one
13:31 = twenty nine minutes to two
13:45 = quarter to two
00:48 = twelve minutes to one
00:08 = eight minutes past midnight
12:00 = twelve o'clock
00:00 = midnight
Note: If minutes == 0, use 'o'clock'. If minutes <= 30, use 'past', and for minutes > 30, use 'to'.
```
More examples in test cases. Good luck! | reference | def solve(time):
def number(n):
if n > 20:
return "twenty {}" . format(number(n - 20))
return [
None, "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen", "twenty"][n]
hours, minutes = (int(s) for s in time . split(':'))
if minutes <= 30:
direction = "past"
else:
hours = (hours + 1) % 24
direction = "to"
minutes = 60 - minutes
hour = number((hours + 11) % 12 + 1) if hours else "midnight"
if minutes == 0:
return "{} o'clock" . format(hour) if hours else hour
if minutes == 15:
return "quarter {} {}" . format(direction, hour)
if minutes == 30:
return "half past {}" . format(hour)
return "{} minute{} {} {}" . format(
number(minutes), "" if minutes == 1 else "s", direction, hour)
| Read the time | 5c2b4182ac111c05cf388858 | [
"Fundamentals"
] | https://www.codewars.com/kata/5c2b4182ac111c05cf388858 | 6 kyu |
## Description
As the title already told you, you have to parse a IPv6 hex string in a weird way. For each block in the string you have to parse its characters as if they were separate hexadecimal values, add them up, and join the results into a string.
Here's an example of an IPv6 string: `1B1D:AF01:3847:F8C4:20E9:0111:DFEA:AAAA`. And here's how you'd convert its first block to an integer: `"1B1D" => 0x1 + 0xB + 0x1 + 0xD = 26`. After all the blocks have been processed in the same way, the results should be joined together: ``"26" + "26" + "22" + "39" + "25" + "3" + "52" + "40"`` -> ``"262622392535240"``
**Note**: some character other than colon (`:`) may be used in the input string, but it is guaranteed that hexadecimal digits will never be used as separators.
#### Examples
```
"1111:1111:1111:1111:1111:1111:1111:1111" => "4" + "4" + "4" + "4" + "4" + "4" + "4" + "4" => "44444444"
"1111-1111-1111-1111-1111-1111-1111-1111" => "4" + "4" + "4" + "4" + "4" + "4" + "4" + "4" => "44444444"
"ABCD_1111_ABCD_1111_ABCD_1111_ABCD_1111" => "46" + "4" + "46" + "4" + "46" + "4" + "46" + "4" => 464464464464
```
Happy coding! | algorithms | def parse_IPv6(iPv6):
return '' . join(str(sum(int(c, 16) for c in s)) for s in iPv6 . split(iPv6[4]))
| Weird IPv6 hex string parsing | 5f5bc8a04e485f002d85b303 | [
"Parsing",
"Algorithms"
] | https://www.codewars.com/kata/5f5bc8a04e485f002d85b303 | 6 kyu |
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The <a href="https://en.wikipedia.org/wiki/Pied_Piper_of_Hamelin">Pied Piper</a> has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidean distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
<pre style='background:black'>
↗ P
<span style='color:red'>↘</span> ↖
↑
↗
</pre>
---
ex2 - has 7 deaf rats
<pre style='background:black'>
<span style='color:red'>↗</span>
P <span style='color:red'>↓</span> ↖ <span style='color:red'>↑</span>
← <span style='color:red'>↓</span>
↖ ↙ ↙
<span style='color:red'>↓ ↓ ↓</span>
</pre> | reference | from math import hypot
DIRS = {'←': (0, - 1), '↑': (- 1, 0), '→': (0, 1), '↓': (1, 0),
'↖': (- 1, - 1), '↗': (- 1, 1), '↘': (1, 1), '↙': (1, - 1)}
def count_deaf_rats(town):
pipper = next((x, y) for x, r in enumerate(town)
for y, c in enumerate(r) if c == 'P')
return sum(isDeaf(pipper, x, y, * DIRS[c])
for x, r in enumerate(town) for y, c in enumerate(r)
if c in DIRS)
def isDeaf(pipper, x, y, dx, dy):
dCurrent, dNext = (hypot(* (a - b for a, b in zip(pipper, pos)))
for pos in ((x, y), (x + dx, y + dy)))
return dCurrent < dNext
| The Deaf Rats of Hamelin (2D) | 5c1448e08a2d87eda400005f | [
"Fundamentals"
] | https://www.codewars.com/kata/5c1448e08a2d87eda400005f | 6 kyu |
### Lazy Decorator Function
You have decided to play a prank on your programmer friend.
You want to make his code "Lazy". And not in the good way. You want his functions to only run normally every _nth_ run, otherwise doing nothing.
To do this, you are going to write a function decorator `@lazy(n)` where `n` is the frequency of 'normal' runs. For example, if `n == 4`, then after the first successful run, the next three calls to this function will do nothing, and then the 5th run will run normally again. (The first run should always be successful, except for `n == -1` which is always lazy).
However, if `n` is a negative number, then the frequency is inverted (ie. `@lazy(-4)` means that only every 4th run is lazy, the rest are normal.).
If `n == 1`, then the function should always be normal, and if `n == -1` then the function should always be lazy. `n == 0` will never be tested.
**Note:** When the lazy function 'does nothing', that means it immediately returns `None`. No lines of the 'normal' function should be run at all.
**Example Code**
```python
@lazy(4)
def half(x):
return x/2
print(half(10)) # 5 <- Remember, First run should be normal
print(half(77)) # None
print(half(63)) # None
print(half(2)) # None
print(half(38)) # 19 <- Every nth run (in this case 4) after the first should also be normal
@lazy(-3)
def output_str(s):
print(s)
output_str('Foo') # Foo <- Starts normal
output_str('Bar') # Bar
output_str('Pikachu') # Nothing printed <- Every nth run is lazy
output_str('Gla') # Gla
``` | reference | def lazy(n):
step = - 1
def inner(func):
def wrapper(* args, * * kwargs):
nonlocal step
step += 1
if n > 0 and step % n:
return None
elif n < 0 and not (step + 1) % n:
return None
else:
return func(* args, * * kwargs)
return wrapper
return inner
| A different kind of 'Lazy' function. | 601d457ce00e9a002ccb7403 | [
"Decorator"
] | https://www.codewars.com/kata/601d457ce00e9a002ccb7403 | 6 kyu |
# Unpack delicious sausages!
A food delivery truck carrying boxes of delicious sausages has arrived and it's your job to unpack them and put them in the store's display counter.
The truck is filled with boxes of goods. Among the goods, there are various types of sausages. Straight sausages ```I```, curvy sausages ```)```, even twirly sausages ```@``` and many more.
The safest way to tell any type of sausage apart from other goods is by the packaging ```[]```, used exclusively by sausages. Make sure to ignore other goods, those will be taken care of by someone else.
Once you have unpacked all the sausages, just lay them out in the display counter *(string)* in the same order in which they came in boxes with one space ```" "``` in-between every sausage. Oh, and watch out for spoiled or damaged sausage packs, did I tell you about those?
The sausages are always packed in fours and each pack contains only one sausage type, so whenever there is any irregularity, the sausages are probably spoiled or damaged and the whole pack should be thrown out!
Now we're getting to the best part - your reward! Instead of money, you'll be paid in something far better - sausages! Every fifth undamaged processed pack of sausages doesn't go to the counter, instead it's yours to keep. Don't go spending it all at once!
If the truck arrives completely empty, only with empty boxes or only with goods that are not sausages, the display counter will simply stay empty ```""```. Unlike truck and boxes that may be empty, every existing product is a non-empty string.
## Example:
**Input** (truck with 5 boxes containing 11 products):
```python
[("(-)", "[IIII]", "[))))]"), ("IuI", "[llll]"), ("[@@@@]", "UwU", "[IlII]"), ("IuI", "[))))]", "x"), ()]
"Truck is a list, boxes are tuples, packages of goods are strings"
```
```javascript
[ [ "(-)", "[IIII]", "[))))]" ], [ "IuI", "[llll]" ], [ "[@@@@]", "UwU", "[IlII]" ], [ "IuI", "[))))]", "x" ], [] ]
"Truck is an array, packages are arrays, packages of goods are strings"
```
```rust
vec![vec!["(-)", "[IIII]", "[))))]"], vec!["IuI", "[llll]"], vec!["[@@@@]", "UwU", "[IlII]"], vec!["IuI", "[))))]", "x"], vec![]]
"Truck is a Vec, packages are Vec's, packages of goods are &str"
```
**Output** (four sets of sausages):
```"I I I I ) ) ) ) l l l l @ @ @ @"```
**Explanation:**
- The last box is empty and is therefore ignored
- Packages with products that are not sausages are ignored - ```"(-)", "IuI", "UwU", "IuI", "x"```
- One damaged package gets thrown out - ```"[IlII]"```
- Fifth undamaged package is used as your reward and is therefore excluded from the output: ```"[))))]"```
- More examples of input and expected output can be seen in the example test cases
| reference | def unpack_sausages(truck):
display = ""
counter = 0
for box in truck:
for pack in box:
if pack[0] == "[" and pack[- 1] == "]":
contents = pack[1: - 1]
if len(contents) == 4 and len(set(contents)) == 1:
counter += 1
if counter % 5:
display += contents
return " " . join(display)
| Unpack delicious sausages! | 5fa6d9e9454977000fb0c1f8 | [
"Data Structures",
"Fundamentals"
] | https://www.codewars.com/kata/5fa6d9e9454977000fb0c1f8 | 6 kyu |
<!-- Hexagon Beam Max Sum -->
<p>In this kata, your task is to find the maximum sum of any straight "beam" on a hexagonal grid, where its cell values are determined by a finite integer sequence <code>seq</code>.<br/><br/>
In this context, a beam is a linear sequence of cells in any of the 3 pairs of opposing sides of a hexagon. We'll refer to the sum of a beam's integer values as the "beam value".<br/>Refer to the example below for further clarification.</p>
<h2 style='color:#f88'>Input</h2>
<p>Your function will receive two arguments:</p>
<ul>
<li><code>n</code> : the length of each side of the hexagonal grid, where <code>2 <= n < 100</code></li>
<li><code>seq</code> : a finite sequence of (positive and/or nonpositive) integers with a length >= 1<br/>The sequence is used to populate the cells of the grid and should be repeated as necessary.<br/>The sequence type will be dependent on the language (e.g. array for JavaScript, tuple for Python, etc.).</li>
</ul>
<h2 style='color:#f88'>Output</h2>
<p>Your function should return the largest beam value as an integer.</p>
<h2 style='color:#f88'>Test Example</h2>
<img src='https://i.imgur.com/9cL0hjt.png'/><br/>
<pre><code>In our test example, we have the following arguments:
n = 4
seq = [2, 4, 6, 8]
Below is the hexagonal grid determined by our example arguments;
the sequence repeats itself from left to right, then top to bottom.
2 4 6 8
2 4 6 8 2
4 6 8 2 4 6
8 2 4 6 8 2 4
6 8 2 4 6 8
2 4 6 8 2
4 6 8 2
The three diagrams below illustrate the "beams" in the hexagonal grid above.
In the grid on the left, the horizontal beams are highlighted by their likewise colors,
and the value of each beam is given to its right.
In the center grid, the beams highlighted go from upper-right to bottom-left (and vice-versa).
In the grid on the right, the beams highlighted go from upper-left to bottom-right (and vice-versa).
<span style='color:#00ff00'> 2 4 6 8</span> -> 20 <span style='color:#00ff00'> 2</span> <span style='color:#00f0f0'>4</span> <span style='color:#f0f000'>6</span> <span style='color:#ff3030'>8</span> <span style='color:#ff3030'> 2</span> <span style='color:#9090ff'>4</span> <span style='color:#f000f0'>6</span> <span style='color:#a0a0a0'>8</span>
<span style='color:#00f0f0'> 2 4 6 8 2</span> -> 22 <span style='color:#00ff00'> 2</span> <span style='color:#00f0f0'>4</span> <span style='color:#f0f000'>6</span> <span style='color:#ff3030'>8</span> <span style='color:#9090ff'>2</span> <span style='color:#f0f000'> 2</span> <span style='color:#ff3030'>4</span> <span style='color:#9090ff'>6</span> <span style='color:#f000f0'>8</span> <span style='color:#a0a0a0'>2</span>
<span style='color:#f0f000'> 4 6 8 2 4 6</span> -> 30 <span style='color:#00ff00'> 4</span> <span style='color:#00f0f0'>6</span> <span style='color:#f0f000'>8</span> <span style='color:#ff3030'>2</span> <span style='color:#9090ff'>4</span> <span style='color:#f000f0'>6</span> <span style='color:#00f0f0'> 4</span> <span style='color:#f0f000'>6</span> <span style='color:#ff3030'>8</span> <span style='color:#9090ff'>2</span> <span style='color:#f000f0'>4</span> <span style='color:#a0a0a0'>6</span>
<span style='color:#ff3030'>8 2 4 6 8 2 4</span> -> 34 <span style='color:#00ff00'>8</span> <span style='color:#00f0f0'>2</span> <span style='color:#f0f000'>4</span> <span style='color:#ff3030'>6</span> <span style='color:#9090ff'>8</span> <span style='color:#f000f0'>2</span> <span style='color:#a0a0a0'>4</span> <span style='color:#00ff00'>8</span> <span style='color:#00f0f0'>2</span> <span style='color:#f0f000'>4</span> <span style='color:#ff3030'>6</span> <span style='color:#9090ff'>8</span> <span style='color:#f000f0'>2</span> <span style='color:#a0a0a0'>4</span>
<span style='color:#9090ff'> 6 8 2 4 6 8</span> -> 34 <span style='color:#00f0f0'> 6</span> <span style='color:#f0f000'>8</span> <span style='color:#ff3030'>2</span> <span style='color:#9090ff'>4</span> <span style='color:#f000f0'>6</span> <span style='color:#a0a0a0'>8</span> <span style='color:#00ff00'> 6</span> <span style='color:#00f0f0'>8</span> <span style='color:#f0f000'>2</span> <span style='color:#ff3030'>4</span> <span style='color:#9090ff'>6</span> <span style='color:#f000f0'>8</span>
<span style='color:#f000f0'> 2 4 6 8 2</span> -> 22 <span style='color:#f0f000'> 2</span> <span style='color:#ff3030'>4</span> <span style='color:#9090ff'>6</span> <span style='color:#f000f0'>8</span> <span style='color:#a0a0a0'>2</span> <span style='color:#00ff00'> 2</span> <span style='color:#00f0f0'>4</span> <span style='color:#f0f000'>6</span> <span style='color:#ff3030'>8</span> <span style='color:#9090ff'>2</span>
<span style='color:#a0a0a0'> 4 6 8 2</span> -> 20 <span style='color:#ff3030'> 4</span> <span style='color:#9090ff'>6</span> <span style='color:#f000f0'>8</span> <span style='color:#a0a0a0'>2</span> <span style='color:#00ff00'> 4</span> <span style='color:#00f0f0'>6</span> <span style='color:#f0f000'>8</span> <span style='color:#ff3030'>2</span>
The maximum beam value in our example is 34.
</code></pre>
<h2 style='color:#f88'>Test Specifications</h2>
<ul>
<li>All inputs will be valid</li>
<li>Full Test Suite: <code>12</code> fixed tests and <code>100</code> random tests</li>
<li>For JavaScript, <code>module</code> and <code>require</code> are disabled [NOTE: if you would like to suggest a module that you think should be permitted for JS, please leave a note in the Discourse section]</li>
</ul>
<p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p>
| algorithms | from itertools import cycle, chain
def max_hexagon_beam(n, seq):
h = 2 * n - 1
seq = cycle(seq)
sums = [[0] * h for _ in range(3)] # [horz, diagUp, diagDown]
for r in range(h):
for c, v in zip(range(n + r if r < n else h + n - 1 - r), seq):
idxs = (r, c + max(0, r - n + 1), c + max(0, n - 1 - r))
for i, j in enumerate(idxs):
sums[i][j] += v
return max(chain . from_iterable(sums))
| Hexagon Beam Max Sum | 5ecc1d68c6029000017d8aaf | [
"Puzzles",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5ecc1d68c6029000017d8aaf | 6 kyu |
## Task
Let's say we have a positive integer, `$n$`. You have to find the smallest possible positive integer that when multiplied by `$n$`, becomes a perfect power of integer `$k$`. A perfect power of `$k$` is any positive integer that can be represented as `$a^k$`. For example if `$k = 2$`, then `$36$` is a perfect power of `$k$`, but `$27$` isn't.
## Examples
```python
n, k = 100, 3 return 10, #because 10*100 becomes 1000, and 1000 = 10**3
n, k = 36, 2 return 1, #because 36 is already a perfect square 6**2
n, k = 72, 4 return 18, #because 18*72 = 1296 = 6**4
```
```ruby
[n, k] = [100, 3] return 10, #because 10*100 becomes 1000, and 1000 = 10**3
[n, k] = [36, 2] return 1, #because 36 is already a perfect square 6**2
[n, k] = [72, 4] return 18, #because 18*72 = 1296 = 6**4
```
**Notes:**
+ `$k, n \in \mathbb{N} $` and `$ 1 \lt n \lt 10^6,\text{ } 1 \lt k \lt 10 $`
+ However, the output may be way larger than `$10^6$`.
If you have trouble seeing the numbers, refresh your page ;-) Please rate this kata. All translations are welcome.
ABOVE: [If you see this:](https://imgur.com/TKY59S4), refresh your page. | algorithms | def mul_power(n, k):
a = 1
for p in range(2, int(n * * .5) + 1):
if not n % p:
m = 0
while not n % p:
n / /= p
m += 1
a *= p * * (- m % k)
if n > 1:
a *= n * * (k - 1)
return a
| Multiply by a number, so it becomes a perfect power | 5ee98cf315741d00104499e5 | [
"Mathematics",
"Algebra",
"Algorithms"
] | https://www.codewars.com/kata/5ee98cf315741d00104499e5 | 6 kyu |
[IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) is a standard for representing floating-point numbers (i.e. numbers that can have a fractional part and emulate real numbers).
Its use is currently ubiquitous in both software (programming languages implementations) and hardware (Floating Point Units ([FPU](https://en.wikipedia.org/wiki/Floating-point_unit)) chips embedded in processors).
The 2 most widely used IEEE 754 formats are called the single precision (SP, encoded on 32 bits) and double precision (DP, encoded on 64 bits) formats.
* In `C/C++`, these correspond respectively to the types `float` and `double`, in virtually every implementation that supports floating-point numbers
* The default `Python` implementation, `CPython`, is written in `C` and represents Python `float`s internally as `C` `double`s, and thus as IEEE 754 DP
* In `JavaScript`, all `Number`s are IEEE 754 DP values.
* In `Rust`, these correspond respectively to the types `f32` and `f64`.
* In `Java`, these correspond respectively to the types `float` and `double`.
___
As you can see on the images below, IEEE 754 numbers are divided into 3 fields :
* a sign bit;
* an exponent encoded on 8 (SP) or 11 (DP) bits;
* a mantissa (also called significand) encoded on 23 (SP) or 52 (DP) bits.
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/Float_example.svg/1920px-Float_example.svg.png" style="background-color:white" alt="The IEEE 754 single-precision encoding scheme" title = "The IEEE 754 single-precision encoding scheme">
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a9/IEEE_754_Double_Floating_Point_Format.svg" style="background-color:white" alt="The IEEE 754 double-precision encoding scheme" title = "The IEEE 754 double-precision encoding scheme">
___
Your task is to write a function that takes as input a floating point number, and returns the binary IEEE 754 encoding of this number as a string, with fields separated by spaces for readability.
If your programming language supports both SP and DP, you will have 2 functions to write, one for each type.
___
## Example
* Single Precision
```
input:
15.875
output:
"0 10000010 11111100000000000000000"
```
* Double Precision
```
input:
15.875
output:
"0 10000000010 1111110000000000000000000000000000000000000000000000"
```
___
## Note
If you find yourself writing overly complex code, you are probably on the wrong path. Your solution should only be concerned with the bit-pattern of the number, without dealing with its value.
___
## Related Katas
If you want to solve the same problem with a different approach, try :
* [Float to Binary Conversion](https://www.codewars.com/kata/540ddb07716ab397e1000797) (in Javascript)
This kata was inspired by this very interesting C kata :
* [C Puzzle: Extract Field from a Double Value](https://www.codewars.com/kata/59e5f1b77905df91aa000024)
My kata about classifying floating-point numbers:
* [Classify a floating point number](https://www.codewars.com/kata/5f1ab7bd5af35f000f4ff875)
| reference | from struct import pack
s = "{:08b}" . format
def float_to_IEEE_754(f: float) - > str:
binary = '' . join(map(s, pack('!d', f)))
return ' ' . join((binary[0], binary[1: 12], binary[12:]))
| IEEE 754 floating point numbers | 5efcaedf95d7110017896ced | [
"Binary",
"Fundamentals"
] | https://www.codewars.com/kata/5efcaedf95d7110017896ced | 6 kyu |
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a9/IEEE_754_Double_Floating_Point_Format.svg" style="background-color:white" alt="The IEEE 754 double-precision encoding scheme" title = "The IEEE 754 double-precision encoding scheme">
___
The following table describes the different types of [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) numbers.
It is valid for both single-precision (SP, 32 bits) and double-precision (DP, 64 bits).
<table>
<tr>
<th>Type</th>
<th>Sign</th>
<th>Exponent</th>
<th>Mantissa</th>
</tr>
<tr>
<td>Infinity</td>
<td>Any</td>
<td>All 1s</td>
<td>All 0s</td>
</tr>
<tr>
<td>Quiet NaN</td>
<td>Any</td>
<td>All 1s</td>
<td>Starts with a 1</td>
</tr>
<tr>
<td>Signaling NaN</td>
<td>Any</td>
<td>All 1s</td>
<td>Starts with a 0 and contains at least one 1</td>
</tr>
<tr>
<td>Zero</td>
<td>Any</td>
<td>All 0s</td>
<td>All 0s</td>
</tr>
<tr>
<td>Denormalized numbers</td>
<td>Any</td>
<td>All 0s</td>
<td>At least one 1</td>
</tr>
<tr>
<td>Normalized numbers</td>
<td>Any</td>
<td>At least one 1 and one 0</td>
<td>Any</td>
</tr>
</table>
___
## Note about NaN
A `NaN` (Not a Number) is a special value that indicates an asbence of a valid number, or an erroneous operation, such as division by `0`. There are 2 types of `NaN`s: a *signalling* `NaN` is supposed to trigger a runtime error, while a *quiet* `NaN` does not by itself result in a a program error.
## Task
```if:c
An `enum` representing these possible types has been preloaded for you. You must return the correct type of the `double` received as parameter. On Codewars and many other plaforms, ```double```s are encoded as IEEE 754 double precision (64 bits).
```
```if:python
A `FloatType` enum representing these possible types has been preloaded for you. You must return the correct type of the `float` received as parameter. On Codewars and many other plaforms, ```float```s are encoded as IEEE 754 double precision (64 bits).
~~~
class FloatType ():
POSITIVE_DENORMALIZED = auto()
NEGATIVE_DENORMALIZED = auto()
POSITIVE_NORMALIZED = auto()
NEGATIVE_NORMALIZED = auto()
POSITIVE_INFINITY = auto()
NEGATIVE_INFINITY = auto()
POSITIVE_ZERO = auto()
NEGATIVE_ZERO = auto()
POSITIVE_QUIET_NAN = auto()
NEGATIVE_QUIET_NAN = auto()
POSITIVE_SIGNALING_NAN = auto()
NEGATIVE_SIGNALING_NAN = auto()
~~~~
```
```if:javascript
An object ```FloatTypeEnum``` with properties enumerating these possible types has been preloaded for you. You must return the type of the `Number` received as parameter by returning the correct object property.
In JavaScript, ```Numbers``` are encoded as IEEE 754 double precision (64 bits).
```
```if:java
A class `FloatTypeEnum` with properties enumerating these possible types has been preloaded for you. You must return the type of the `double` received as parameter by returning the correct object property. In Java, `double`s are encoded as IEEE 754 double precision (64 bits).
~~~java
public enum FloatTypeEnum {
POSITIVE_DENORMALIZED,
NEGATIVE_DENORMALIZED,
POSITIVE_NORMALIZED,
NEGATIVE_NORMALIZED,
POSITIVE_INFINITY,
NEGATIVE_INFINITY,
POSITIVE_ZERO,
NEGATIVE_ZERO,
POSITIVE_QUIET_NAN,
NEGATIVE_QUIET_NAN,
POSITIVE_SIGNALING_NAN,
NEGATIVE_SIGNALING_NAN;
}
~~~
```
___
## Note
You may want to solve this kata first :
* [IEEE 754 floating point numbers](https://www.codewars.com/kata/5efcaedf95d7110017896ced) | reference | import struct
class FloatType (NoValue):
POSITIVE_DENORMALIZED = auto()
NEGATIVE_DENORMALIZED = auto()
POSITIVE_NORMALIZED = auto()
NEGATIVE_NORMALIZED = auto()
POSITIVE_INFINITY = auto()
NEGATIVE_INFINITY = auto()
POSITIVE_ZERO = auto()
NEGATIVE_ZERO = auto()
POSITIVE_QUIET_NAN = auto()
NEGATIVE_QUIET_NAN = auto()
POSITIVE_SIGNALING_NAN = auto()
NEGATIVE_SIGNALING_NAN = auto()
def category (exponent, mantissa):
return (
"quiet_nan" if mantissa [0 ] else
"signaling_nan" if any (mantissa ) else
"infinity"
) if all(exponent) else (
"normalized" if any (exponent ) else
"denormalized" if any (mantissa ) else
"zero"
)
def get_float_type (number: float) - > FloatType :
bits = format (struct . unpack ("Q" , struct . pack ("d" , number ))[ 0 ], "064b" )
sign, exponent , mantissa = bits [: 1 ], bits [1 : 12 ], bits [12 :]
name = category ([b == "1" for b in exponent], [b == "1" for b in mantissa ])
return FloatType[f" { 'positive' if sign == '0' else 'negative' } _ { name } " . upper ()]
| Classify a floating point number | 5f1ab7bd5af35f000f4ff875 | [
"Binary",
"Fundamentals"
] | https://www.codewars.com/kata/5f1ab7bd5af35f000f4ff875 | 6 kyu |
## Text printing like <span style="color:#6899D3">Portal 2</span> end credits
Now you finished this brilliant game and wanna create some simillar that you saw after.
### Task:
Create function, <span style="color: #D6F870">that take song text</span> and then return <span style="color: #D6F870">symbols step by step out</span> like it computer console printing.
You have song as an array:
```javascript
//lyrics.length >= 0 && lyrics[any].length >= 0
const lyrics = [
[
'Well here we are again',
...
'Ive been shockingly nice'
],
[
'You want your freedom?',
...
'Thats what Im counting on'
]
]
```
```python
# lyrics.length >= 0 and lyrics[any].length >= 0
lyrics = [
[
'Well here we are again',
...
'Ive been shockingly nice'
],
[
'You want your freedom?',
...
'Thats what Im counting on'
]
]
```
<span style="color:#FD3F49">You need print it symbol by symbol</span> into current paragraph array of strings(outer array - it's resulting array), <span style="color:#FD3F49">each emerging paragraph part</span> added into resulting array:
```javascript
[['W_']] //1 step
[['We_']] //2 step
[['Wel_']] //3 step
```
```python
[['W_']] # 1 step
[['We_']] # 2 step
[['Wel_']] # 3 step
```
When string end, you need keep it and start create new string into this paragraph:
```javascript
[['Well here we are again', 'I_']] //1 step
[['Well here we are again', 'It_']] //2 step
[['Well here we are again', 'Its_']] //3 step
```
```python
[['Well here we are again', 'I_']] # 1 step
[['Well here we are again', 'It_']] # 2 step
[['Well here we are again', 'Its_']] # 3 step
```
<span style="color:#FD3F49">Attention</span>, after <span style="color:#FD3F49">any print</span> you need show "_" symbol(exepted full strings).
When paragraph end, you start new paragraph:
```javascript
//you can mind about it like new print page
[
[ 'Well here we are again',
'Its always such a pleasure',
'Remember when you tried',
'To kill me twice?',
'Oh how we laughed and laughed',
'Except I wasnt laughing',
'Under the circumstances',
'Ive been shockingly nice_' ], //1 step
[ 'Y_' ], //2 step
[ 'Yo_' ], //3 step
[ 'You_' ] //4 step etc.
],
```
```python
# you can mind about it like new print page
[
[
'Well here we are again',
'Its always such a pleasure',
'Remember when you tried',
'To kill me twice?',
'Oh how we laughed and laughed',
'Except I wasnt laughing',
'Under the circumstances',
'Ive been shockingly nice_'
], # 1 step
['Y_'], # 2 step
['Yo_'], # 3 step
['You_'] # 4 step etc.
],
```
### Test example:
```javascript
lyricsPrint(['Hey','you'],['Good','luck']) =>
[
[ 'H_' ],
[ 'He_' ],
[ 'Hey_' ],
[ 'Hey', 'y_' ],
[ 'Hey', 'yo_' ],
[ 'Hey', 'you_' ],
[ 'G_' ],
[ 'Go_' ],
[ 'Goo_' ],
[ 'Good_' ],
[ 'Good', 'l_' ],
[ 'Good', 'lu_' ],
[ 'Good', 'luc_' ],
[ 'Good', 'luck_' ]
]
```
```python
lyrics_print([['Hey','you'],['Good','luck']]) =>
[
['H_'],
['He_'],
['Hey_'],
['Hey', 'y_'],
['Hey', 'yo_'],
['Hey', 'you_'],
['G_'],
['Go_'],
['Goo_'],
['Good_'],
['Good', 'l_'],
['Good', 'lu_'],
['Good', 'luc_'],
['Good', 'luck_']
]
```
Inspired by https://www.youtube.com/watch?v=dVVZaZ8yO6o | algorithms | def lyrics_print(lyrics):
return [lyric[: i] + [f" { w [: j + 1 ]} _"] for lyric in lyrics for i, w in enumerate(lyric) for j in range(len(w))]
| Portal 2: End credits song. Text printing. | 608673cf4b69590030fee8d6 | [
"Algorithms"
] | https://www.codewars.com/kata/608673cf4b69590030fee8d6 | 6 kyu |
You're a buyer/seller and your buisness is at stake... You ___need___ to make profit... Or at least, you need to lose the least amount of money!
Knowing a list of prices for buy/sell operations, you need to pick two of them. Buy/sell market is evolving across time and the list represent this evolution. First, you need to buy one item, then sell it later. Find the best profit you can do.
### Example:
Given an array of prices `[3, 10, 8, 4]`, the best profit you could make would be `7` because you buy at `3` first, then sell at `10`.
# Input:
A list of prices (integers), of length 2 or more.
# Output:
The result of the best buy/sell operation, as an integer.
### Note:
Be aware you'll face lists with several thousands of elements, so think about performance. | algorithms | def max_profit(prices):
m = best = float('-inf')
for v in reversed(prices):
m, best = max(m, best - v), max(best, v)
return m
| Best Stock Profit in Single Sale | 58f174ed7e9b1f32b40000ec | [
"Algorithms"
] | https://www.codewars.com/kata/58f174ed7e9b1f32b40000ec | 6 kyu |
<b>Task</b>
Given the following arguments and examples, could you figure out my operator?
```
a: integer (0 <= a) -> left operand
n: integer (0 <= n <= 4) -> Somehow used by my operator, but I can't remember exactly how, sorry!
b: integer (0 <= b) -> right operand
* for this kata: all values will be small (no performance or no overflow issues)
* n has an upper limit of 4 for this kata, but could go to +inf mathematically, theoretically
```
<b>Examples</b>
```
operator(1, 0, 2) = 3
operator(2, 0, 2) = 3
operator(2, 1, 2) = 4
operator(2, 2, 2) = 4
operator(2, 3, 2) = 4
operator(2, 4, 2) = 4
operator(2, 2, 3) = 6
operator(2, 3, 3) = 8
```
<b>Trivia</b>
```
a) if you don't see it, you might find out more by clicking <i>Attempt</i>
b) the operator is described on wikipedia as a generalized operator that can be
implemented using only recursion and incrementation; due to limitations in
optimization of tail recursion of most programming languages, you may need
to use a combination of different operators to get the job done
```
---
Good luck! | games | from functools import reduce
def operator(a, n, b):
if n == 0:
return 1 + b
if n == 1:
return a + b
if n == 2:
return a * b
if n == 3:
return a * * b
return reduce(lambda x, _: a * * x, [1] * (b + 1))
| Guess Operator | 60512be8bbc51a000a83d767 | [
"Algorithms",
"Puzzles",
"Mathematics"
] | https://www.codewars.com/kata/60512be8bbc51a000a83d767 | 6 kyu |
# Task
You are a lifelong fan of your local football club, and proud to say you rarely miss a game. Even though you're a superfan, you still hate boring games. Luckily, boring games often end in a draw, at which point the winner is determined by a penalty shoot-out, which brings some excitement to the viewing experience. Once, in the middle of a penalty shoot-out, you decided to count the lowest total number of shots required to determine the winner. So, given the number of shots each team has already made and the current score, `how soon` can the game end?
If you are not familiar with penalty shoot-out rules, here they are:
`Teams take turns to kick from the penalty mark until each has taken five kicks. However, if one side has scored more successful kicks than the other could possibly reach with all of its remaining kicks, the shoot-out immediately ends regardless of the number of kicks remaining.`
`If at the end of these five rounds of kicks the teams have scored an equal number of successful kicks, additional rounds of one kick each will be used until the tie is broken.`
# Input/Output
`[input]` integer `shots`
An integer, the number of shots each team has made thus far.
`0 ≤ shots ≤ 100.`
`[input]` integer array `score`
An array of two integers, where score[0] is the current score of the first team and score[1] - of the second team.
`score.length = 2,`
`0 ≤ score[i] ≤ shots.`
`[output]` an integer
The minimal possible total number of shots required to determine the winner.
# Example
For `shots = 2 and score = [1, 2]`, the output should be `3`.
The possible 3 shots can be:
```
shot1: the first team misses the penalty
shot2: the second team scores
shot3: the first one misses again```
then, score will be [1, 3]. As the first team can't get 2 more points in the last remaining shot until the end of the initial five rounds, the winner is determined.
For `shots = 10 and score = [10, 10]`, the output should be `2`.
If one of the teams misses the penalty and the other one scores, the game ends.
For `shots = 4 and score = [4, 0]`, the output should be `0`.
First team already wins, so no shots are needed. | games | def penaltyShots(shots, score):
sa, sb = score
return (abs(sa - sb) <= 1) + (sa == sb) if shots >= 5 else max(6 - shots - abs(sa - sb), 0)
| Simple Fun #229: Penalty Shots | 59073712f98c4718b5000022 | [
"Puzzles"
] | https://www.codewars.com/kata/59073712f98c4718b5000022 | 6 kyu |
# Penguin Olympics: Swimming Race Disaster
The situation...
- The fastest penguins in the world have just swum for the ultimate prize in professional penguin swimming.
- The cameras that were capturing the race stopped recording half way through.
- The athletes, and the fans are in disarray waiting for the results.
The challenge...
Given the last recorded frame of the race, and an array of penguin athletes, work out the gold, silver and bronze medal positions.
The rules...
- Assume all penguins swim at the same speed, when swimming through the same kind of water (waves or smooth water).
- Waves (`~`) take twice as long to swim through as smooth water (`-`).
- Penguins (`p` or `P`) are racing from left to right.
- There can be any number of lanes, and the race can be any length.
- All Lanes in a single race will be the same length.
- Penguin names are in the same order as the lanes.
- Return a string in this format: `"GOLD: <name-1>, SILVER: <name-2>, BRONZE: <name-3>"`
- There will always be an equal amount of penguins and lanes.
- There will always be a top three (no draws).
Examples...
```
Snapshot:
|----p---~---------|
|----p---~~--------|
|----p---~~~-------|
Penguins:
["Derek", "Francis", "Bob"]
Expected Output:
"GOLD: Derek, SILVER: Francis, BRONZE: Bob"
```
```
Snapshot:
|-~~------------~--P-------|
|~~--~P------------~-------|
|--------~-P---------------|
|--------~-P----~~~--------|
Penguins:
["Joline", "Abigail", "Jane", "Gerry"]
Expected Output:
"GOLD: Joline, SILVER: Jane, BRONZE: Gerry"
```
| games | def score(line):
try:
pos = line . index('p')
except ValueError:
pos = line . index('P')
left = line[pos + 1: - 1]
return len(left) + left . count('~')
def calculate_winners(snapshot, penguins):
res = sorted((score(line), name)
for line, name in zip(snapshot . splitlines(), penguins))
return f"GOLD: { res [ 0 ][ 1 ]} , SILVER: { res [ 1 ][ 1 ]} , BRONZE: { res [ 2 ][ 1 ]} "
| Penguin Olympics: Swimming Race Disaster | 6022c97dac16b0001c0e7ccc | [
"Puzzles"
] | https://www.codewars.com/kata/6022c97dac16b0001c0e7ccc | 6 kyu |
In this Kata you will be given an array (or another language-appropriate collection) representing contestant ranks. You must eliminate contestant in series of rounds comparing consecutive pairs of ranks and store all initial and intermediate results in an array.
During one round, the lowest rank of a pair is eliminated while the highest proceeds to the next round. This goes on until one contestant only is left. If the number of contestants is odd, the last one of the current array becomes the first of the next round.
At the end of the competition, return the results of all the rounds in the form of array of arrays.
### Example:
```
input = [9, 5, 4, 7, 6, 3, 8, 2];
output = [
[9, 5, 4, 7, 6, 3, 8, 2], // first round is initial input
[9, 7, 6, 8], // results of 9 vs 5, 4 vs 7, 6 vs 3, and 8 vs 2
[9, 8], // results of 9 vs 7 and 6 vs 8
[9] // results of 9 vs 8
];
```
Notes:
- Array length will alway be >= 2 and <= 100
- Elements of the array will always be >=1 and <= 100
- Input must not be altered.
| reference | def tourney(lst):
out = [lst]
while len(lst) > 1:
lst = [lst[- 1]] * (len(lst) % 2) + [* map(max, lst[:: 2], lst[1:: 2])]
out . append(lst)
return out
| Elimination Tournament | 5f631ed489e0e101a70c70a0 | [
"Arrays",
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5f631ed489e0e101a70c70a0 | 6 kyu |
The Evil King of Numbers wants to conquer all space in the Digital World. For that reason, His Evilness declared war on Letters, which actually stay in the Alphabet Fragmentation. You were nominated the Great Arbiter and must provide results of battles to the technology God 3 in 1, Llib Setag-Kram Grebrekcuz-Nole Ksum.
### Description
`armyLetters` consists of letters from `'a'` to `'z'` and `armyNumbers` consists of digits from `'1'` to `'9'`. The power of a letter is its position in the Latin alphabet, so the letter `'a'` has power `1`, `'b'` has `2`, .. `'z'` has `26`. The power of a digit is its value, so `'1'` has power `1`, `'2'` has `2`, .. `'9'` has `9`.
`armyLetters` fights from its end; `armyNumbers` fights from its beginning.
Per round, one letter from `armyLetters` attacks one digit and does damage equal to its power, and one digit from `armyNumbers` attacks _two_ letters and does damage equal to its power _to both_. Characters with 0 or lower power disappear.
Rounds of battle continue until at least one army has completely disappeared.
### Output
* If either or both armies are empty at the start of hostilities, return `"Peace"`.
* At the end of the war, return `"Draw"` if both armies died, or the final state of the winning army (as a `String`).
### How the attacks happen
For example, we have `"abc"` and `"12"`.
The rightmost letter of `"abc"` is `'c'`, which has power `3`, and the leftmost digit of `"12"` is `'1'`.
`'c'` attacks `'1'` and at the same time `'1'` attacks two last letters of `"abc"`.
String `"abc"` becomes `"aab"` because `'1'` attacks the last two letters: `'c'` (power `3`) subtracts `1` and `'b'` subtracts `1`;
`'1'` was attacked and eliminated by `'c'` because its power became _less than or equal to zero_.
After this round we have `"aab"` and `"2"`; repeat until only one non-empty string is left and return it.
In this case the winner is `"a"`.
### Notes
There are no zeros in numbers.
There are no uppercase letters.
### More examples
```javascript
let armyLetters = 'g', armyNumbers = '2222';
armyLetters = 'e', armyNumbers = '222';
armyLetters = 'c', armyNumbers = '22';
armyLetters = 'a', armyNumbers = '2';
armyLetters = '', armyNumbers = '1';
return '1'; // armyNumbers
```
```haskell
armyLetters = "g" ; armyNumbers = "2222"
armyLetters -> "e" ; armyNumbers -> "222"
armyLetters -> "c" ; armyNumbers -> "22"
armyLetters -> "a" ; armyNumbers -> "2"
armyLetters -> "" ; armyNumbers -> "1"
return "1" -- armyNumbers
```
```python
army_letters, army_numbers = 'g', '2222'
army_letters, army_numbers = 'e', '222'
army_letters, army_numbers = 'c', '22'
army_letters, army_numbers = 'a', '2'
army_letters, army_numbers = '', '1'
return '1' # army_numbers
```
```javascript
let armyLetters = 'g', armyNumbers = '99';
armyLetters = '', armyNumbers = '29';
return '29'; // armyNumbers
```
```haskell
armyLetters = "g" ; armyNumbers = "99"
armyLetters -> "" ; armyNumbers -> "29"
return "29" -- armyNumbers
```
```python
army_letters, army_numbers = 'g', '99'
army_letters, army_numbers = '', '29'
return '29' # army_numbers
```
```javascript
let armyLetters = 'g', armyNumbers = '23';
armyLetters = 'e', armyNumbers = '3';
armyLetters = 'b', armyNumbers = '';
return 'b'; //armyLetters
```
```haskell
armyLetters = "g" ; armyNumbers = "23"
armyLetters -> "e" ; armyNumbers -> "3"
armyLetters -> "b" ; armyNumbers -> ""
return "b" -- armyLetters
```
```python
army_letters, army_numbers = 'g', '23'
army_letters, army_numbers = 'e', '3'
army_letters, army_numbers = 'b', ''
return 'b' # army_letters
```
```javascript
let armyLetters = 'ebj', armyNumbers = '45';
armyLetters = 'ef', armyNumbers = '5';
armyLetters = 'a', armyNumbers = '';
return 'a'; // armyLetters
```
Have fun and please don't forget to vote and rank this kata!
If you like this kata, check out the other one: [Last Survivor](https://www.codewars.com/kata/609eee71109f860006c377d1)
| reference | def battle_codes(chars, nums):
if not chars or not nums:
return 'Peace'
chars = [ord(c) - 96 for c in chars]
nums = [* map(int, nums[:: - 1])]
while chars and nums:
c, n = chars[- 1], nums[- 1]
chars[- 1], nums[- 1] = c - n, n - c
if len(chars) > 1:
chars[- 2] -= n
if chars[- 2] < 1:
chars . pop(- 2)
if nums[- 1] < 1:
nums . pop()
if chars[- 1] < 1:
chars . pop()
return '' . join(chars and (chr(c + 96) for c in chars) or map(str, nums[:: - 1])) or 'Draw'
| The Great Digital Conflict | 605150ba96ff8c000b6e3df8 | [
"Fundamentals"
] | https://www.codewars.com/kata/605150ba96ff8c000b6e3df8 | 6 kyu |
*You don't need python knowledge to complete this kata*
You've waited weeks for this moment. Finally an NSA agent has opened the malware you planted on their system.
Now you can execute code remotly.
It looks like you're on a Linux machine. Your goal is to root the box and return the content of root.txt
You don't have a complete remote shell, you can only run a few commands.
You got access on multiple machines, the boxNr shows you, on which machine you are currently.
Return the command you want to execute:
```python
# example
return "help"
```
It prints for example
```
available commands: whoami, pwd, cd, ls, help
```
Another example:
```python
# example2
return "whoami"
```
It prints for example
```
root
```
Some hints:
1. If you want to execute more commands in a row, it works exactly like in bash.
2. Pipes aren't working
3. The available commands aren't always the same
4. Just because the name of a command is the same here as in bash, it doesn't mean that it works the same
5. Your goal is to hack the NSA, therefore you are allowed to run things on your local machine. You don't have to run everything on codewars.
| games | import crypt
def runShell(boxNr):
print(boxNr)
if boxNr == 1:
# return "cd /root; cat root.txt"
return 'CodeWars{7594357083475890320019dsfsdjfl32423hjkasd9834haksdSKJAHD32423khdf}'
elif boxNr == 2:
hash = crypt . crypt('a', '$1$root')
cmds = ['cd /etc',
'ls -l',
'cat passwd',
'echo root:' + hash + ':0:0::/root:/bin/bash > passwd',
'su root a',
'cd /root',
'ls -l',
'cat root.txt']
# return ';'.join(cmds)
return 'CodeWars{jfklsfjljlk&8632847dhfkjds876fDKJFHD(F&/KHKJDF}'
elif boxNr == 3:
# return "ls -la; cat .hidden_password_for_root.txt; cat root.txt fil3pa44word"
return 'CodeWars{fdjslfd2433SKAJF(/&Dfkhk3h4kfsd786234kjf}'
| Hack the NSA | 5f0795c6e45bc600247ab794 | [
"Puzzles"
] | https://www.codewars.com/kata/5f0795c6e45bc600247ab794 | 5 kyu |
Given is a md5 hash of a five digits long PIN. It is given as string.
Md5 is a function to hash your password:
"password123" ===> "482c811da5d5b4bc6d497ffa98491e38"
Why is this useful?
Hash functions like md5 can create a hash from string in a short time and it is impossible to find out the password, if you only got the hash. The only way is cracking it, means try every combination, hash it and compare it with the hash you want to crack. (There are also other ways of attacking md5 but that's another story)
Every Website and OS is storing their passwords as hashes, so if a hacker gets access to the database, he can do nothing, as long the password is safe enough.
<a href="https://en.wikipedia.org/wiki/Hash_function#:~:text=A%20hash%20function%20is%20any,table%20called%20a%20hash%20table." target="_blank">What is a hash?</a>
<a href="https://en.wikipedia.org/wiki/MD5" target="_blank">What is md5?</a>
Note: Many languages have build in tools to hash md5. If not, you can write your own md5 function or google for an example.
<a href="https://www.codewars.com/kata/password-hashes" target="_blank">Here</a> is another kata on generating md5 hashes!
Your task is to return the cracked PIN as string.
This is a little fun kata, to show you, how weak PINs are and how important a bruteforce protection is, if you create your own login.
If you liked this kata, <a href="https://www.codewars.com/kata/59146f7b4670ba520900000a" target="_blank">here</a> is an extension with short passwords!
Some of my other katas:
<br>
<a href="https://www.codewars.com/kata/5ef9ca8b76be6d001d5e1c3e" target="_blank">Error Correction #1 - Hamming Code</a>
<br>
<a href="https://www.codewars.com/kata/5f0795c6e45bc600247ab794" target="_blank">Hack the NSA</a>
<br>
<a href="https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f" target="_blank">Decode the QR-Code</a>
| algorithms | import hashlib
def crack(hash):
for i in range(100000):
if hashlib . md5(str(i). zfill(5). encode()). hexdigest() == hash:
return str(i). zfill(5)
| Crack the PIN | 5efae11e2d12df00331f91a6 | [
"Algorithms",
"Cryptography"
] | https://www.codewars.com/kata/5efae11e2d12df00331f91a6 | 6 kyu |
*Translations appreciated*
## Background information
The Hamming Code is used to correct errors, so-called bit flips, in data transmissions. Later in the description follows a detailed explanation of how it works. <br>
In this Kata we will implement the Hamming Code with bit length 3; this has some advantages and disadvantages:
- **[ + ]** It's simple to implement
- **[ + ]** Compared to other versions of hamming code, we can correct more mistakes
- **[ - ]** The size of the input triples
## Task 1: Encode function
Implement the encode function, using the following steps:
* convert every letter of the text to its ASCII value; (ASCII value of space is 32)
* convert ASCII values to 8-bit binary;
* triple every bit;
* concatenate the result;
For example:
```c
input: "hey"
--> 104, 101, 121 // ASCII values
--> 01101000, 01100101, 01111001 // binary
--> 000111111000111000000000 000111111000000111000111 000111111111111000000111 // tripled
--> "000111111000111000000000000111111000000111000111000111111111111000000111" // concatenated
```
## Task 2: Decode function:
Check if any errors happened and correct them. Errors will be only bit flips, and not a loss of bits:
- ```111``` --> ```101``` : this can and will happen
- ```111``` --> ```11``` : this cannot happen
**Note**: the length of the input string is also always divisible by 24 so that you can convert it to an ASCII value.
Steps:
* Split the input into groups of three characters;
* Check if an error occurred: replace each group with the character that occurs most often, e.g. `010` --> `0`, `110` --> `1`, etc;
* Take each group of 8 characters and convert that binary number;
* Convert the binary values to decimal (ASCII);
* Convert the ASCII values to characters and concatenate the result
For example:
```c
input: "100111111000111001000010000111111000000111001111000111110110111000010111"
--> 100, 111, 111, 000, 111, 001, ... // triples
--> 0, 1, 1, 0, 1, 0, ... // corrected bits
--> 01101000, 01100101, 01111001 // bytes
--> 104, 101, 121 // ASCII values
--> "hey"
```
~~~if:shell
<br>
In <b>bash</b> you get two arguments, first one is "encode" or "decode" whether you should encode or decode and the second argument is the plain text or the encoded bits.
<br>
~~~
If you liked this kata, please try out some of my other katas:
<br>
<a href="https://www.codewars.com/kata/5efae11e2d12df00331f91a6" target="_blank">Crack the PIN</a>
<br>
<a href="https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f" target="_blank">Decode the QR-Code</a>
<br>
<a href="https://www.codewars.com/kata/5f0795c6e45bc600247ab794" target="_blank">Hack the NSA</a>
| algorithms | def encode(stg):
return "" . join(digit * 3 for char in stg for digit in f" { ord ( char ):0 8 b } ")
def decode(binary):
reduced = (get_digit(triplet) for triplet in chunks(binary, 3))
return "" . join(get_char(byte) for byte in chunks("" . join(reduced), 8))
def chunks(seq, size):
return (seq[i: i + size] for i in range(0, len(seq), size))
def get_digit(triplet):
return max(triplet, key=triplet . count)
def get_char(byte):
return chr(int(byte, 2))
| Error correction #1 - Hamming Code | 5ef9ca8b76be6d001d5e1c3e | [
"Algorithms",
"Bits"
] | https://www.codewars.com/kata/5ef9ca8b76be6d001d5e1c3e | 6 kyu |
Consider the following well known rules:
- To determine if a number is divisible by 37, we take numbers in groups of three digits from the right and check if the sum of these groups is divisible by 37. Example: 4567901119 is divisible by 37 because 37 * 123456787 = 4567901119. Now: 4 + 567 + 901 + 119 = 1591 = 37 * 43. Let's call this a "3-sum" prime because we use groups of 3 digits and sum them.
- To determine if a number is divisible by 3, we take numbers in groups of 1 digit and add them. If the sum of the groups is divisible by 3, then the original number is also divisible by 3. For example: 3 * 123 = 369 => 3 + 6 + 9 = 18, which is divisible by 3. Let's call '3' a "1-sum" prime because we take groups of 1 digit and sum them.
- For 41, we take numbers in groups of five digits from the right and check if the sum of these groups is divisible by 41. This is a "5-sum" prime.
- 239 is a "7-sum" prime (groups of 7)
Let's look at another type of prime:
- For 11, we need to add all digits by alternating their signs from the right.
Example: 1358016 is divisible by 11 because 11 * 123456 = 1358016 => 6-1+0-8+5-3+1 = 0, which is divible by 11. Let's call this a "1-altsum" prime
- For 7, we need to group the digits into threes from the right and add all groups by alternating their signs.
Example: 7 * 1234567891234 = 8641975238638 => 638 - 238 + 975 - 641 + 8 = 742/7 = 106.
- 7 is a "3-altsum" prime because we use groups of threes. 47 is a "23-altsum" (groups of 23), while 73 is a "4-altsum" prime (groups of 4).
You will be given a prime number `p` and your task is to find the smallest positive integer `n` such that `p’s` divisibility testing is `n-sum` or `n-altsum`.
For example:
```
solve(3) = "1-sum"
solve(7) = "3-altsum"
```
Primes will not exceed `50,000,000`. More examples in test cases.
You can get some insight from [Fermat's little theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem).
Good luck! | reference | import math
def divisors(p):
a = [1]
for i in range(2, int(math . sqrt(p)) + 1):
if p % i == 0:
a . extend([i, p / / i])
a . extend([p])
return list(set(a))
def solve(p):
for d in sorted(divisors(p - 1)):
if pow(10, d, p) == 1:
return '{}-sum' . format(d)
break
elif pow(10, d, p) == p - 1:
return '{}-altsum' . format(d)
break
| Divisible by primes | 5cfe4465ac68b86026b09c77 | [
"Fundamentals"
] | https://www.codewars.com/kata/5cfe4465ac68b86026b09c77 | 6 kyu |
## Task
Given a string, add the fewest number of characters possible from the front or back to make it a palindrome.
## Example
For the input `cdcab`, the output should be `bacdcab`
## Input/Output
Input is a string consisting of lowercase latin letters with length 3 <= str.length <= 10
The output is a palindrome string satisfying the task.
For s = `ab` either solution (`aba` or `bab`) will be accepted. | algorithms | def build_palindrome(s):
for n in range(len(s), - 1, - 1):
if s[: n] == s[: n][:: - 1]:
return s[n:][:: - 1] + s
if s[- n:] == s[- n:][:: - 1]:
return s + s[: - n][:: - 1]
| Palindrome Builder | 58efb6ef0849132bf000008f | [
"Algorithms"
] | https://www.codewars.com/kata/58efb6ef0849132bf000008f | 6 kyu |
### Story
In the fictional country of Bugliem, you can ask for a custom licence plate on your car, provided that it meets the followoing criteria:
* it's 2-8 characters long
* it contains only letters `A-Z`, numbers `0-9`, and dashes `-`
* letters and numbers are separated by a dash
* it doesn't start or end with a dash, and it doesn't have consecutive dashes
* it's not made up of numbers only
You also have to pay 1000 local units to obtain one, although this will not be tested.
### Task
To make the life of the local authorities easier (and get your driving record cleaned), you need to implement a function that accepts an ascii input string, and returns the number plate if possible.
You have to replace all special characters and spaces with dashes (consecutive characters should be replaced with a single dash), and truncate the result to maximum 8 characters (if longer). If the result complies with the above criteria, return it capitalized; otherwise return `"not possible"`.
### Examples
```
"mercedes" --> "MERCEDES"
"anter69" --> "ANTER-69"
"1st" --> "1-ST"
"~c0d3w4rs~" --> "C-0-D-3"
"I'm cool!" --> "I-M-COOL"
"1337" --> "not possible"
```
---
### My other katas
If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-)
#### *Translations are welcome!* | algorithms | import re
def licence_plate(s):
plate = '-' . join(re . findall(r'[A-Z]+|\d+',
s . upper()))[: 8]. rstrip('-')
return plate if len(plate) > 1 and not plate . isdigit() else 'not possible'
| Custom Licence Plate | 5bc64f48eba26e79df000031 | [
"Algorithms"
] | https://www.codewars.com/kata/5bc64f48eba26e79df000031 | 6 kyu |
# Introduction
A new casino has come to Las Vegas, but this casino does not want to have human staff, but they want to implement a series of computer systems that automate the process. After looking for references and recommendations, the administrative team has decided to hire you to develop these systems.
Your assignment is to complete the function that draws cards for the dealer, and returns the players who have won.
## Rules
* Each table will consist of 3 players, `"Player 1"`, `"Player 2"`, `"Player 3"`
* Players play against the croupier (dealer) only, not against other players.
* Each card has its value: the numerals are worth whatever their number indicates; `"J"`, `"Q"` and `"K"` are worth `10`; `"A"` may be worth `11 or 1`, always trying to keep the highest score possible.
* If any player exceeds `21` points, they lose.
* The croupier must draw from a deck until it's hand scores `17` or more points.
* A player has a blackjack when they have 2 cards, one worth `10`, and an `"A"`
* If the player has a blackjack, then they win, **unless** the croupier also has a blackjack.
* When the croupier draws a card, the croupier draws the first card from a deck.
**Notes:**
* The inputs will never be null.
* All letters are in uppercase
## Examples
* Player 1: `"J", "A"` (21, blackjack)
* Player 2: `"10", "5", "6"` (21)
* Player 3: `"3", "6", "A", "3", "A", "K"` (24)
* Croupier: `"9", "7"` (16)
* Deck: `"5", "4", "K", "2"`
Since the dealer has less than 17 points, it must draw a card:
* Croupier: `"9", "7", "5"` (21)
* Deck: `"4", "K", "2"`
Now comparing hands:
* Player 1 scores 21, croupier scores 21, but Player 1 has Black Jack, so Player 1 won
* Player 2 scores 21, croupier scores 21, draw
* Player 3 scores 24, Player 3 exceeded 21, so he lost
~~~if:javascript
So return `"Player 1"`
~~~
~~~if-not:javascript
So return `["Player 1"]`
~~~
*And another example:*
* Player 1: `"10", "K"` (20)
* Player 2: `"10", "2", "6"` (18)
* Player 3: `"8", "8", "5"` (21)
* Croupier: `"5", "10"` (15)
* Deck: `"A" , "3" , "K" , "2"`
Since the dealer has less than 17 points, it must draw more cards:
* Croupier: `"5", "10", "A", "3"` (19)
* Deck: `"K", "2"`
Now comparing hands:
* Player 1 scores 20, croupier scores 19, Player 1 won
* Player 2 scores 18, croupier scores 19, Player 2 lost
* Player 3 scores 21, croupier scores 19, Player 3 won
~~~if:javascript
So return `"Player 1, Player 3"`
~~~
~~~if-not:javascript
So return `["Player 1", "Player 3"]`
~~~ | algorithms | def score(hand):
score = sum(int(c) if c . isdigit() else 11 if c ==
"A" else 10 for c in hand)
aces = hand . count("A")
for _ in range(aces):
if score > 21:
score -= 10
return "BJ" if score == 21 and len(hand) == 2 else score if score <= 21 else 0
def winners(player1, player2, player3, dealer, deck):
p1, p2, p3, house = map(score, (player1, player2, player3, dealer))
if house == "BJ":
return []
deck = deck[:: - 1]
while 0 < house < 17 and deck:
dealer . append(deck . pop())
house = score(dealer)
return (["Player 1"] * (p1 == "BJ" or p1 > house) +
["Player 2"] * (p2 == "BJ" or p2 > house) +
["Player 3"] * (p3 == "BJ" or p3 > house) +
[])
| Card Games: Black Jack | 5bebcbf2832c3acc870000f6 | [
"Games",
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5bebcbf2832c3acc870000f6 | 6 kyu |
## Task
You will receive a string consisting of lowercase letters, uppercase letters and digits as input. Your task is to return this string as blocks separated by dashes (`"-"`). The elements of a block should be sorted with respect to the hierarchy listed below, and each block cannot contain multiple instances of the same character. Elements should be put into the first suitable block.
The hierarchy is:
1. lowercase letters (`a - z`), in alphabetical order
2. uppercase letters (`A - Z`), in alphabetical order
3. digits (`0 - 9`), in ascending order
## Examples
* `"21AxBz" -> "xzAB12"` - since input does not contain repeating characters, you only need 1 block
* `"abacad" -> "abcd-a-a"` - character "a" repeats 3 times, thus 3 blocks are needed
* `"" -> ""` - an empty input should result in an empty output
* `"hbh420sUUW222IWOxndjn93cdop69NICEep832" -> "bcdehjnopsxCEINOUW0234689-dhnpIUW239-2-2-2"` - a more sophisticated example
Good luck! | reference | from collections import Counter
def blocks(s):
def sort(c): return (c . isdigit(), c . isupper(), c)
answer, counter = [], Counter(s)
while counter:
block = '' . join(sorted(counter, key=sort))
answer . append(block)
counter = counter - Counter(block)
return '-' . join(answer)
| Return String As Sorted Blocks | 5e0f6a3a2964c800238ca87d | [
"Strings",
"Algorithms",
"Sorting"
] | https://www.codewars.com/kata/5e0f6a3a2964c800238ca87d | 6 kyu |
In this kata, you have an input string and you should check whether it is a valid message. To decide that, you need to split the string by the numbers, and then compare the numbers with the number of characters in the following substring.
For example `"3hey5hello2hi"` should be split into `3, hey, 5, hello, 2, hi` and the function should return `true`, because `"hey"` is 3 characters, `"hello"` is 5, and `"hi"` is 2; as the numbers and the character counts match, the result is `true`.
**Notes:**
* Messages are composed of only letters and digits
* Numbers may have multiple digits: e.g. `"4code13hellocodewars"` is a valid message
* Every number must match the number of character in the following substring, otherwise the message is invalid: e.g. `"hello5"` and `"2hi2"` are invalid
* If the message is an empty string, you should return `true`
| algorithms | import re
def is_a_valid_message(message):
return all(n and int(n) == len(s) for n, s in re . findall("(\d*)(\D*)", message)[: - 1])
| Message Validator | 5fc7d2d2682ff3000e1a3fbc | [
"Algorithms"
] | https://www.codewars.com/kata/5fc7d2d2682ff3000e1a3fbc | 6 kyu |
<h2>Introduction</h2>
Let’s assume that when you register a car you are assigned two numbers:
1. Customer ID – number between `0` and `17558423` inclusively. It is assigned to car buyers in the following order: the first customer receives an ID of `0`, the second customer receives an ID of `1`, the third - `2`, and so on;
2. A Number Plate – 6-character combination composed of the __series__ - three Latin lowercase letters from a to z; and the __serial number__ - three digits from 0 to 9. __Example:__ `aaa001, xyz123, tok469`;
Each Number Plate is related to the given Customer ID. For example:
Customer ID of 0: `aaa001`
Customer ID of 21: `aaa022`
Customer ID of 169: `aaa170`
<h2>Your Task</h2>
Write a function
```if:python,ruby,crystal,rust,c,riscv
`find_the_number_plate`
```
```if:javascript,java,d,coffeescript,typescript
`findTheNumberPlate`
```
```if:go
`FindTheNumberPlate`
```
which takes the Customer ID as an argument, calculates the Number Plate corresponding to this ID and returns it as a string;
<h3>Rules</h3>
1. The serial number changes first. For each 3-letter series it goes through 001 to 999, such as:
`aaa001, aaa002, aaa003, ......, aaa998, aaa999`
2. The leftmost letter in the series switches alphabetically each time after the serial number has moved through 001 to 999 inclusively;
```
aaa001...aaa999
```
_at this point the leftmost letter will switch alphabetically, while the serial number repeats the same cycle again;_
```
baa001...baa999,
...... ,
zaa001...zaa999
```
3. The middle letter switches alphabetically each time after the leftmost letter has moved through a to z and the __z**__ series has moved through 001 to 999.
```
zaa001...zaa999
```
_at this point the middle letter will switch alphabetically, while the leftmost letter and the serial number repeat the same cycle again;_
```
aba001...aba999,
bba001...bba999,
......,
zza001...zza999
```
4. The rightmost letter switches alphabetically each time after the middle letter has moved through a to z and the __zz*__ series has moved through 001 to 999.
```
zza001...zza999
```
_at this point the rightmost letter will switch alphabetically, while the middle letter, the leftmost letter, and the serial number repeat the same cycle again;_
```
aab001...aab999,
bab001...bab999,
......,
zab001...zab999,
abb001...abb999,
bbb001...bbb999,
......,
zbb001...zbb999,
acb001...acb999,
......,
zzz001...zzz999
```
<h3>Note</h3>
If the serial number has less than 3 digits, the missing places should be adjusted with zeroes.
__i.e:__ `12` should equal `012`; `4` should equal `004`.
Once again, the customer ID starts with 0.
<h3>Good luck!</h3>
| algorithms | def find_the_number_plate(customer_id):
q, r = divmod(customer_id, 999)
q, a = divmod(q, 26)
c, b = divmod(q, 26)
return f" { chr ( a + 97 )}{ chr ( b + 97 )}{ chr ( c + 97 )}{ r + 1 :0 3 d } "
| Car Number Plate Calculator | 5f25f475420f1b002412bb1f | [
"Algorithms",
"Logic",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5f25f475420f1b002412bb1f | 6 kyu |
Two moving objects A and B are moving accross the same orbit (those can be anything: two planets, two satellites, two spaceships,two flying saucers, or spiderman with batman if you prefer).
If the two objects start to move from the same point and the orbit is circular, write a function that gives the time the two objects will meet again, given the time the objects A and B need to go through a full orbit, Ta and Tb respectively, and the radius of the orbit r.
As there can't be negative time, the sign of Ta and Tb, is an indication of the direction in which the object moving: positive for clockwise and negative for anti-clockwise.
The function will return a string that gives the time, in two decimal points.
Ta and Tb will have the same unit of measurement so you should not expect it in the solution.
Hint: Use angular velocity "w" rather than the classical "u". | reference | def meeting_time(Ta, Tb, r):
if Ta == 0:
return "{:.2f}" . format(abs(Tb))
elif Tb == 0:
return "{:.2f}" . format(abs(Ta))
else:
return "{:.2f}" . format(abs(Ta * Tb / (Tb - Ta)))
| Basic physics problem - Space -Kinematics | 58dc420210d162048a000085 | [
"Fundamentals",
"Physics",
"Algorithms"
] | https://www.codewars.com/kata/58dc420210d162048a000085 | 6 kyu |
You are given a certain array of positive and negative integers which elements occur only once (all of them different from 0), a certain number known as target, ```t, t ≠ 0```, and a number ```k, k > 0.```
You should find the amount of combinations, which numbers are not contiguous elements of the given array and which sums (adding up their numbers) are in the range ```[t - k, t + k] (extremes included)```
```python
array = [-4, 2, 1, 6, 4, -3, -1]
t = 5
k = 2
find_comb_noncontig(array, t, k) == 11
# The combinations are [6], [4], [2, 4], [1, 4], [6, -3], [6, -1], [4, -1], [2, 6, -3], [2, 6, -1], [2, 4, -1], [1, 4, -1]
# all of their sums are in the range [3, 7]
```
It is possible that no combinations may be found fulfilling these constraints.
```python
array = [-4, 2, 1, 6, 4, -3, -1]
t = -30
k = 3
find_comb_noncontig(array, t, k) == 0
```
Enjoy it!! | reference | def find_comb_noncontig(arr, t, k):
comb_sum = []
for r, x in enumerate(arr, - 1):
comb_sum . append([x] + [x + y for l in range(r) for y in comb_sum[l]])
return sum(t - k <= z <= t + k for row in comb_sum for z in row)
| Find Amount of Certain Combinations than its Sum of Elements Are Within a Given Range | 5713338968e0cf779b00096e | [
"Fundamentals",
"Mathematics",
"Data Structures",
"Algorithms",
"Logic"
] | https://www.codewars.com/kata/5713338968e0cf779b00096e | 6 kyu |
A binary operation `op` is called associative if
`op(a, op(b, c)) = op(op(a, b), c)`
for example:
`(1 + 2) + 8 = 1 + (2 + 8)`
`(A * B) * C = A * (B * C)` where `A, B, C` are matrices with sizes `N x M, M x K, K x L`
## Task
Inputs:
- `arr` - array of objects with type `T` and size `n` (1..100 000)
- `op` - associative operation `(T, T) -> T`
- `ranges` - array of boundaries represented as `[start, end]` and size `m` (1..100 000)
For each range you need to find the result of applying `op` to all elements between the boundaries (start inclusive, end exclusive).
for example:
```
arr = [1, 0, 7, 8, 1]
range = [1, 4]
op = +
result = 0 + 7 + 8 = 15
```
Output:
- Array of results for the respective ranges.
## Notes
The time complexity is expected to be `O((n + m) * log n) * T(op)` or better.
Start always less than end.
Start and end always in range from `0` to `n`. | algorithms | def compute_ranges(arr, op, rs):
"""
Efficient and easy segment trees
http://codeforces.com/blog/entry/18051
"""
def f(a, b):
if a is None:
return b
if b is None:
return a
return op(a, b)
def query(l, r):
resL = resR = None
l += n
r += n
while l < r:
if l & 1:
resL = f(resL, tree[l])
l += 1
if r & 1:
r -= 1
resR = f(tree[r], resR)
l >>= 1
r >>= 1
return f(resL, resR)
n = len(arr)
tree = n * [None] + arr
for i in range(n - 1, 0, - 1):
tree[i] = f(tree[i << 1], tree[i << 1 | 1])
return [query(l, r) for l, r in rs]
| Associative Operation on Range | 608cc9666513cc00192a67a9 | [
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/608cc9666513cc00192a67a9 | 4 kyu |
Same as https://www.codewars.com/kata/605e61435c2b250040deccf2, but code golf.
### Task
You've been given an analogue clock, but rather than the standard 12 hours it can display any number of hours.
Given an hour return the time to the second during which the minute and hour hands on an analogue clock would be aligned, in `"h:mm:ss"` format (if the actual time is in between two seconds, choose the smaller time value). If no time exists for that hour return an empty string.
###### Input
- **`hour`** *(integer)*: hour during which hands would be aligned; range: 1–`hours_on_the_clock`
- **`hours_on_the_clock`** *(integer)*: number of hours on the clock; range: 2–99
###### Output
*string*:
- time (`"h:mm:ss"`) of hands alignment, `hour`:00:00 <= time < `hour+1`:00:00, if such time exists
- empty string otherwise
### Restrictions
```if:python
Your code should be shorter than **85 bytes**.
*World record: 78 bytes*
*Personal best: 80 bytes*
``` | reference | # 78 :D
def time_hands_cross(a, b): return f" { a } :%02d:%02d" % divmod(a % b * 3600 / / ~ - b, 60) * (a != ~ - b)
| Clock hands cross [Code Golf] | 6004cb552b8bc80017fe26b1 | [
"Restricted",
"Fundamentals"
] | https://www.codewars.com/kata/6004cb552b8bc80017fe26b1 | 6 kyu |
# Scraping Wikipedia Links From Wikipedia Articles
You will create a function that accepts the url of a Wikipedia article as an argument. This function will return a dictionary of keys as titles of articles (given by the title attribute of anchor tags), and values as URLs of articles. The dictionary will only contain items that are links to other Wikipedia articles.
You will be scraping only through the div with the id "bodyContent" to do this (the content of the article on the webpage).
The values of the dictionary will be full links, not relative links:
e.g. ```'https://en.wikipedia.org/wiki/Easter_Island'``` as opposed to ```'/wiki/Easter_Island'```
<span style="color:#FF6969; font-weight:bold;">Anchor tags with links to images, help pages, categories of articles, special pages, etc will not be present in the returned dictionary; only true Wikipedia articles will be present. This means any article that has an href in the form of /wiki/ followed by any of the strings in the following list are not to be included.</span>
```
Namespaces not to be included:
["User:", "Wikipedia:", "WP:", "Project:", "WT:", "Project_talk", "Wikipedia_talk:",
"Image:", "Image_talk:","File:", "MediaWiki:", "Template:", "Help:", "Category:",
"Portal:", "Draft:", "TimedText:", "Module:", "Special:", "Template_talk:", "Talk:",
"File:", "File_talk:"]
```
I've found that occasionally, the random Wikipedia article generator gives an article that is too long/has too many anchor tags in it, meaning your code will inevitably time out. If that is the case, try runnning it once or twice more. | reference | import re
import bs4
import requests
HOST = 'https://en.wikipedia.org'
EXCLUDING_NAMESPACES = re . compile(f"^/wiki/(?!\w+:)")
def wikiscraping(url):
body = bs4 . BeautifulSoup(requests . get(
url). text). find('div', id='bodyContent')
links = body . find_all('a', href=EXCLUDING_NAMESPACES)
return {link . get('title'): HOST + link . get('href') for link in links}
| Web Scraping: Find Every Link to Another Wikipedia Article in a Wikipedia Article | 5ecb44975864da0012572d5c | [
"Web Scraping",
"Fundamentals"
] | https://www.codewars.com/kata/5ecb44975864da0012572d5c | 6 kyu |
Credits go to the fantastic Numberphile YouTube channel for the inspiration behind this kata - the specific video for it can be found here: https://www.youtube.com/watch?v=tP-Ipsat90c&t=545s
Your challenge in this Kata is to code a function ```check_sequence``` that checks a sequence of coin flip results for specific 'streak' patterns of Heads and Tails. Streaks are consecutive occurences of results -- a streak of length 3 would be ```'HHH'``` or ```'TTT'```.
Given a sequence such as ```'HTHHHHTTH'```, an integer ```l```, and integer ```n```, we want to check the existence of STRICTLY ```n```-number of streaks that are STRICTLY of length ```l``` in the sequence.
By STRICTLY of a certain length, we mean that those streaks are not greater than or less than that length ```l```. For instance, sequences such as 'HHHH' or 'TTTT' are streaks of length 4, and do not count as streaks of length 3, 2, or 1 even though those streaks might be contained within them.
Likewise, we are looking for STRICTLY ```n``` occurences of streaks of a given length -- NOT more or less than the value of N.
The function ```check_sequence``` should return ```True``` if the sequence conforms to this pattern, or ```False``` otherwise.
For example, ```check_sequence('HTHHHTTH', 3, 1)``` should return ```True```, because there is ```1``` streak of exactly length ```3``` ('HHH'). Likewise, ```check_sequence('HTHHHTTTHHHHT', 3, 2)``` should return ```True``` because there exists ```2``` streaks of exactly length ```3``` ('HHH' and 'TTT').
Test cases are a mix of static cases and randomly generated cases. For the randomly generated cases:
1. Coin flip sequences (e.g. 'HTHHT') are from character lengths of 5 to 70 inclusive
2. L can take any integer value from 2 to 8 inclusive
3. N can take any integer value from 1 to 8 inclusive
Best of luck! | algorithms | def check_sequence(seq, L, N):
return sum(1 for r in seq . replace('HT', 'H T'). replace('TH', 'T H'). split() if len(r) == L) == N
| Streaky Patterns in Coin Flips | 5c1ac4f002c59c725900003f | [
"Strings",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/5c1ac4f002c59c725900003f | 7 kyu |
<h1>Task</h1>
<p>You get a Boolean expression and the values of its variables as input.
Your task is to calculate this Boolean expression with a given set of variable values.</p>
<h1>Details</h1>
<ul>
<li>The input expression consists of variables represented by uppercase letters A-F and operations "&" (logical AND) and "|" (logical OR). </li>
<li>Parentheses and other operations are missing from the expression.</li>
<li>Variables can be repeated and placed in any order.</li>
<li>The expression contains at least one variable</li>
<li>Variable values are represented as a dictionary {name: value}.</li>
<ul>
<h1>Example</h1>
```python
calculate("A & B & C", {"A": 0, "B": 1, "C": 0}) # returns 0
# A & B & C = 0 & 1 & 0 = 0
calculate("B & A | C", {"A": 1, "B": 0, "C": 1}) # returns 1
# B & A | C = 0 & 1 | 1 = 0 | 1 = 1
```
| reference | calculate = eval
| Boolean Trilogy #2: Calculate Boolean Expression (Easy) | 5f8070c834659f00325b5313 | [
"Fundamentals"
] | https://www.codewars.com/kata/5f8070c834659f00325b5313 | 7 kyu |
You will be given a string with sets of characters, (i.e. words), seperated by between one and four spaces (inclusive).
Looking at the first letter of each word (case insensitive-`"A"` and `"a"` should be treated the same), you need to determine whether it falls into the positive/first half of the alphabet (`"a"`-`"m"`) or the negative/second half (`"n"`-`"z"`).
Return `True/true` if there are more (or equal) positive words than negative words, `False/false` otherwise.
```
"A big brown fox caught a bad rabbit" => True/true
"Xylophones can obtain Xenon." => False/false
``` | reference | def connotation(s):
lst = s . upper(). split()
return sum('A' <= w[0] <= 'M' for w in lst) >= len(lst) / 2
| Negative Connotation | 5ef0456fcd067000321baffa | [
"Fundamentals"
] | https://www.codewars.com/kata/5ef0456fcd067000321baffa | 7 kyu |
# Task
In Python 3.5 a new module called [typing](https://docs.python.org/3/library/typing.html) was introduced which provides type hints. In this kata you will need to implement `to_type_hint` which needs to return (a best match of) such a type hint for some input.
# Examples
### Numeric Types (int, float, complex):
```python
# Return the type itself:
to_type_hint(2) => int
to_type_hint(1.0) => float
to_type_hint(3+5j) => complex
```
### Some other types:
```python
to_type_hint(None) => None
to_type_hint(True) => bool
to_type_hint(False) => bool
to_type_hint("123") => str
```
### Lists, set, frozensets, deques:
```python
# If the object contains no elements, return its type
to_type(deque()) => deque
# If all elements within have same type:
to_type_hint([1, 2, 3]) => List[int]
to_type_hint({1, 3, 4}) => Set[int]
to_type_hint(deque([1])) => Deque[int]
to_type_hint(frozenset([3, 5, 7])) => FrozenSet[int]
# Different types of elements within:
to_type_hint([True, 2, 3.0, 3]) => List[Union[bool, int, float]]
to_type_hint({"1", 2, 3}) => Set[Union[str, int]]
to_type_hint(deque([2, 3.0])) => Deque[Union[int, float]]
```
### Tuples
```python
# Less than four elements, return a Tuple with each type:
to_type_hint(()) => Tuple[()]
to_type_hint((42,)) => Tuple[int,]
to_type_hint((1, 2)) => Tuple[int, int]
to_type_hint((1, "2", 3)) => Tuple[int, str, int]
# With more than three elements, use the literal ellipsis to specify a variable length tuple
to_type_hint((1, 2, 3, 4)) => Tuple[int, ...] # All elements in tuple are same type
to_type_hint((1, "2", 3, 4.0)) => Tuple[Union[int, str, float], ...]
```
### Dictionaries
```python
to_type({}) => dict
to_type_hint({1: 2, 3: 4}) => Dict[int, int]
to_type_hint({"a": 1, "b": 2}) => Dict[str, int]
to_type_hint({"a": 2, "b": 3.0, 2: None}) => Dict[Union[str, int], Union[int, float, None]]
```
### Nested types
```python
# Input types may be nested:
to_type_hint([1, [1, 2], [[1, 2], 3]]) => List[Union[int, List[int], List[Union[List[int], int]]]]
to_type_hint(([1, 2], [])) => Tuple[List[int], list]
```
Notes:
- Other types that are not mentioned above, will not be tested (e.g. generator, iterator, function, range, etc.)
- The order of types in a `Union` does not matter | algorithms | from collections import deque
from typing import *
def f(t): return Union[tuple(to_type_hint(x) for x in t)]
d = {
list: List,
set: Set,
deque: Deque,
frozenset: FrozenSet
}
def to_type_hint(t):
v = t . __class__
if t is None:
return
if v is tuple:
w = tuple(to_type_hint(x) for x in t)
return Tuple[w if len(t) <= 3 else (to_type_hint(t[0]), ...) if len(set(w)) == 1 else (Union[w], ...)]
elif t and v is dict:
return Dict[f(t . keys()), f(t . values())]
elif t and v in d:
return d[v][f(t)]
return v
| Hint a Type | 5ed7625f548425001205e290 | [
"Recursion",
"Algorithms"
] | https://www.codewars.com/kata/5ed7625f548425001205e290 | 6 kyu |
## Problem
Complete the function that takes an odd integer (`0 < n < 1000000`) which is the difference between two consecutive perfect squares, and return these squares as a string in the format `"bigger-smaller"`
## Examples
```
9 --> "25-16"
5 --> "9-4"
7 --> "16-9"
``` | algorithms | def find_squares(n):
m = (n - 1) / / 2
return f' {( m + 1 ) * * 2 } - { m * * 2 } '
| Find the Squares | 60908bc1d5811f0025474291 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/60908bc1d5811f0025474291 | 7 kyu |
The date is March 24, 2437 and the the Earth has been nearly completely destroyed by the actions of its inhabitants. Our last hope in this disaster lies in a shabby time machine built from old toasters and used microwave parts.
The World Time Agency requires you to travel back in time to prevent disaster. You are ordered to "remove" certain babies from the timeline.
Historical newspapers and records provide the Date, Month, and Year for each mission. Unfortunately the time machine takes input only as the number of days to travel back in time. It is your job to calculate how many days you will need to travel back from today's date (March 24, 2437) for each mission.
For example, if a historical newspaper says a dangerous baby was born on:
Date = 21, Month = 3, Year = 2437
Then your function must compute that it was 3 Days ago.
Another example would be that a baby born on Date = 24, Month = 3, Year = 2436 would have been born 365 days ago.
You will not have time travel past the year 0.
Note that while this is a fairly simple task, it is complicated by the fact that newspapers used the Julian calendar instead of the current Gregorian calendar prior to September 14, 1752. In 1752, it was declared that Sep 2, 1752 was proceeded immediately by September 14, 1752, entirely omitting September 3-13. Furthermore, the rules for leap years changed on that date.
After 1752, leap years are on any year divisible by four, except for years which are divisible by 100. An exception to that exception is that years divisible by 400 are always leap years. For example, 1803, 1900, 2001, 2019, and 2100 are not leap years, but 1804, 2000 and 2020 are leap years.
However in the Julian calander prior to and including 1752, leap years were on every year divisible by 4, without the exception of years divisible by 100. The years 1752, 1700, 1600, and 0 were all leap years.
Good luck agent, the world depends on you!
Note: It is not required, but if you find it helpful to visualize the switch from the Julian to the Gregorian calendar, please see these links:
Please observe that much of September 1752 is missing here: https://www.timeanddate.com/calendar/?year=1752&country=1
Please observe that 1700 is a leap year here: https://www.timeanddate.com/calendar/?year=1700&country=1 | algorithms | import datetime
def days(date, month, year):
x = datetime . datetime(year, month, date)
y = datetime . datetime(2437, 3, 24)
delta = y - x
t = delta . days
if year < 1752 or (year == 1752 and month < 9) or (year == 1752 and month == 9 and date < 14):
t -= 11
if year < 1752:
y = year / / 4 * 4 + 4
for i in range(y, 1752, 4):
if i % 100 == 0 and i % 400 != 0:
t += 1
return t
| Secret Agent Time Travel Calculations | 5c1556f37f0627f75b0000d5 | [
"Date Time",
"Algorithms"
] | https://www.codewars.com/kata/5c1556f37f0627f75b0000d5 | 5 kyu |
Your task is to write a function which counts the number of squares contained in an ASCII art picture.
The input pictures contain rectangles---some of them squares---drawn with the characters `-`, `|`, and `+`, where `-` and `|` are used to represent horizontal and vertical sides, and `+` is used to represent corners and intersections. Each picture may contain multiple, possibly overlapping, rectangles.
A simple example input looks like this:
+--+ +----+
| | | | +-+
| | +----+ | |
+--+ +-+
There are two squares and one rectangle in this picture, so your function should return 2 for this input.
The following picture does not contain any squares, so the answer for this one is 0:
+------+
| |
+------+
Here is another, more complex input:
+---+
| |
| +-+-+
| | | |
+-+-+ |
| |
+---+
The answer for this one is 3: two big squares, and a smaller square formed by the intersection of the two bigger ones. Similarly, the answer for the following picture is 5:
+-+-+
| | |
+-+-+
| | |
+-+-+
A more complex one below, with a lot of entangledrectangles, but there is one single square in there
+---+ * +---+ Those 3 are
| | * | | superposed:
| | * | | +--+
+--+|+--+ * | | +--+ +--+ +--+
+--++| | * +---+ | | | |
+--+-+--+ * +--+ +--+ +-+ +--+
| | * +--+ | |
| | * | |
+-+ * +-+
Note that there is no 3x3 square right in the middle of the shape, because there is no intersection/`+` on the top border of that "square to be".
You are going to implement a function `count_squares()` which takes an ASCII art picture as input and returns the number of squares the picture shows. The input to that function is an array of strings, where each string corresponds to a line of the ASCII art picture. Each string is guaranteed to contain only the characters `-`, `|`, `+`, and `` `` (space).
The smallest valid square has a side length of 2 and is represented by four `+` characters arranged in a square; a single `+` character is not considered a square.
Have fun! | games | import re
def count_squares(lines):
h, w = len(lines), max(map(len, lines))
grid = "\t" . join(line . ljust(w) for line in lines)
return sum(
len(re . findall(r"(?=\+[-+]{%d}\+.{%d}(?:[|+].{%d}[|+].{%d}){%d}\+[-+]{%d}\+)"
% (i, w + 1 - i - 2, i, w + 1 - i - 2, i, i), grid))
for i in range(0, min(w, h) - 1)
)
| Counting ASCII Art Squares | 5bf71b94e50d1b00590000fe | [
"Geometry",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5bf71b94e50d1b00590000fe | 6 kyu |
<!--Transforming Maze Solver-->
The objective of this kata will be to guide a ball through an `m` x `n` rectangular maze. This maze is special in that:
- all the cells rotate `90` degrees clockwise, in unison, at each interval
- each cell can have anywhere from `0` to `4` walls
<p>Your goal is to write a function that returns a path that requires the fewest intervals for the ball to get from its starting position to a specified destination.</p>
<h2 style='color:#f88'>Input</h2>
<p>Your function will receive one argument — an <code>m</code> x <code>n</code> matrix.</p>
<h2 style='color:#f88'>Output</h2>
<p>Your function must return a path as an array/list of strings. Each string in the array will:</p>
<ul>
<li>consist only of the letters <code>N</code>, <code>W</code>, <code>S</code>, and <code>E</code> representing the directions <code>north</code>, <code>west</code>, <code>south</code>, and <code>east</code>, respectively</li>
<li>represent the path of the ball at each interval (based on its index position in the array)</li>
</ul>
<p>Also note that empty strings are permitted in the output array.<br/>
If there is no possible solution, return <code>null</code> or <code>None</code>.</p>
<h2 style='color:#f88'>Maze Mechanics</h2>
<p>Each cell in the maze is given as an integer, ranging from <code>0</code> to <code>15</code>. This number, when translated to binary form, represents the walls of the corresponding cell. That is, a <code>1</code> means there is a wall and a <code>0</code> means there is no wall. The order of the walls is north, west, south, and east.</p>
<p>For example, a cell with the value <code>7</code> is <code>0111</code> in binary. This means it has 3 walls — initially on the west, south, and east sides. Since there is no wall on the north side of the cell, it can be entered from that side at time interval <code>0</code> (assuming that the adjacent cell to its north does not have a south wall).</p>
<p>A cell with the value <code>5</code> (<code>0101</code> in binary) can be entered from its north and south sides at interval <code>0</code>. At the next interval, it rotates <code>90</code> degrees clockwise and can then only be entered from its west and east sides (<code>1010</code>).</p>
<p>A cell with the value <code>15</code> is enclosed on all sides (<code>1111</code> in binary) and therefore can never be entered. Likewise, a cell with a value of <code>0</code> can always be entered from any side.</p>
<p><b style='color:#8df'>There will be</b> <code>2</code> <b style='color:#8df'>cells that will not be given in the form of an integer.</b> Assume that these cells have no walls (the equivalent of a <code>0</code> cell):</p>
<ul>
<li>The ball's starting position, given as the letter <code>B</code> (Java,Kotlin:<code>-1</code>)</li>
<li>The destination, given as the letter <code>X</code> (Java,Kotlin:<code>-2</code>)</li>
</ul>
<h2 style='color:#f88'>Test Example</h2>
<img src='https://i.imgur.com/N1D2rcI.png'/>
<p>The image above shows the state of the maze and starting position of the ball at each each interval; the order is given in the bottom right square.<br/>
The green shaded area shows the available cells the ball can move to at each interval, but the bold number shows where it ends up (for our example solution)
</p>
```python
example = (
( 4, 2, 5, 4),
( 4, 15, 11, 1),
('B', 9, 6, 8),
( 12, 7, 7,'X')
)
maze_solver(example) # ['NNE','EE','S','SS']
```
```javascript
let example = [
[ 4, 2, 5, 4],
[ 4, 15, 11, 1],
['B', 9, 6, 8],
[ 12, 7, 7,'X']
];
mazeSolver(example) // ['NNE','EE','S','SS']
```
```kotlin
val example = arrayOf(
intArrayOf( 4, 2, 5, 4),
intArrayOf( 4, 15, 11, 1),
intArrayOf( -1, 9, 6, 8),
intArrayOf( 12, 7, 7, -2)
)
mazeSolver(example) == arrayOf("NNE", "EE", "S", "SS") // one possible solution
```
```rust
let example = vec![
vec![ 4, 2, 5, 4],
vec![ 4, 15, 11, 1],
vec![ -1, 9, 6, 8],
vec![ 12, 7, 7, -2]
];
maze_solver(&example); // ["NNE", "EE", "S", "SS"] <- one possible solution
```
<h2 style='color:#f88'>Technical Details</h2>
<ul>
<li>The width and length of the matrix will range between <code>4</code> and <code>25</code> in either direction</li>
<li>The ball's starting position will always be on the west side and the exit will always be on the east side of the maze</li>
<li>For the sake of efficiency, the ball must not enter the same cell more than once per interval</li>
<li>Full Test Suite: <code>10</code> fixed tests, and <code>110</code> random tests for Python,Kotlin,Rust / <code>100</code> random tests for JavaScript / <code>200</code> random tests for Java</li>
<li>Each test case may have <code>0</code> or more possible solutions</li>
<li>Inputs will always be valid</li>
<li>Use Python 3+ for the Python translation</li>
<li>For JavaScript, <code>require</code> has been disabled and most built-in prototypes have been frozen (prototype methods can be added to <code>Array</code>, <code>Function</code>, and <code>Set</code>)</li>
</ul>
<p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p> | games | from itertools import count
def getRevStep(step): return ((step << 2) + (step >> 2)) & 15
CONFIG = ((8, - 1, 0, 'N'), (4, 0, - 1, 'W'), (2, 1, 0, 'S'), (1, 0, 1, 'E'))
SWARM = [tuple((step, getRevStep(step), dx, dy, dir) for step, dx, dy, dir in CONFIG if not step & n)
for n in range(16)]
def maze_solver(arr):
for x, row in enumerate(arr):
for y, v in enumerate(row):
if v == 'B':
ball = (x, y)
elif v == 'X':
end = (x, y)
bag = {ball}
lX, lY = len(arr), len(arr[0])
paths = [[[] for _ in range(lY)] for _ in range(lX)]
lastModifiedBagGen = - 1
for nIter in count(0):
for x, y in bag:
paths[x][y]. append('') # "wait there"
oldBagLen = len(bag)
while 1:
addToBag = set()
for x, y in bag:
doors = 0 if isinstance(arr[x][y], str) else arr[x][y]
for step, revStep, dx, dy, dir in SWARM[doors]:
a, b = x + dx, y + dy
if (0 <= a < lX and 0 <= b < lY # in board
and len(paths[a][b]) <= nIter # "No! Don't go there again!"
and (isinstance(arr[a][b], str) or not revStep & arr[a][b])): # target tile allows travel too
addToBag . add((a, b))
paths[a][b] = paths[x][y][:]
paths[a][b][- 1] += dir
if end == (a, b):
return paths[a][b]
if not addToBag:
break
bag |= addToBag
if oldBagLen != len(bag):
lastModifiedBagGen = nIter
elif nIter - lastModifiedBagGen > 4:
return None
arr = [[((n << 1) + (n >> 3)) & 15 if isinstance(n, int) else n for n in row]
for row in arr] # Rotate all tiles colckwise
| Transforming Maze Solver | 5b86a6d7a4dcc13cd900000b | [
"Algorithms",
"Arrays",
"Performance",
"Puzzles"
] | https://www.codewars.com/kata/5b86a6d7a4dcc13cd900000b | 2 kyu |
# Generate All Possible Matches
Your mission is to list all possible match flows with scores up to k (k is a parameter).
Meaning the first to reach k points wins the match.
For examples, Table Tennis (Ping-pong) is a game with 11-point system (up to 11).
In this kata your mission is to write a function getting a positive integer value `k>0`
and it should return all possible match flows up to score of k. Players' scores can increment by one only.
NOTE: Pay attention to the order of possible matches.
## Order of matches
If we take `k=2` example we can draw the following tree describing all possible matches:
```
0:0
/ \
/ \
/ \
/ \
1:0 0:1
/ \ / \
/ \ / \
2:0 1:1 1:1 0:2
/ \ / \
/ \ / \
2:1 1:2 2:1 1:2
```
The required order of matches is actually all the paths from root to leaves, from left to right.
In every node we go to the left option and then the right one.
### Example 1
There are 2 possible matches up to score of `k=1`:
`[['0:0', '1:0'], ['0:0', '0:1']]`
### Example 2
There are 6 possible matches up to score of `k=2`:
`[['0:0', '1:0', '2:0'], ['0:0', '1:0', '1:1', '2:1'], ['0:0', '1:0', '1:1', '1:2'], ['0:0', '0:1', '1:1', '2:1'], ['0:0', '0:1', '1:1', '1:2'], ['0:0', '0:1', '0:2']]`
## Constraints
Your solution will be tested for `1<=k<=10`
Good Luck!
| reference | def generate_all_possible_matches(n=1):
def rec(a, b, p):
p . append(f' { a } : { b } ')
if n == a or n == b:
yield p[:]
else:
yield from rec(a + 1, b, p)
yield from rec(a, b + 1, p)
p . pop()
return list(rec(0, 0, []))
| Generate All Possible Matches | 605721e922624800435689e8 | [
"Recursion",
"Fundamentals"
] | https://www.codewars.com/kata/605721e922624800435689e8 | 6 kyu |
_That's terrible! Some evil korrigans have abducted you during your sleep and threw you into a maze of thorns in the scrubland D:
But have no worry, as long as you're asleep your mind is floating freely in the sky above your body._
> **Seeing the whole maze from above in your sleep, can you remember the list of movements you'll have to do to get out when you awake?**
---
**Input**
---
---
You are given the whole maze `maze` as a 2D grid, more specifically in your language:
```if:ruby,javascript,python
an array of strings
```
```if:java
a `char[][]`
```
```if:ruby,javascript,python,java
`maze[0][0]` is the top left-hand corner
```
```if:c
a `Maze*` (a struct with three fields: `unsigned height`, `unsigned width`, `char **grid`)
Each line is '\0' terminated, but the array of lines is not.
`maze->grid[0][0]` is the top left-hand corner.
```
```if:java,javascript,ruby
`maze[maze.length - 1][maze[0].length - 1]` is the bottom right-hand corner
```
```if:python
`maze[len(maze) - 1][len(maze[0]) - 1]` is the bottom right-hand corner
```
```if:c
`maze->grid[maze->height - 1][maze->width - 1]` is the bottom right-hand corner.
```
Inside this 2D grid:
- `' '` is some walkable space
- `'#'` is a thorn bush (you can't pass through)
- `'^'`, `'<'`, `'v'` or `'>'` is your sleeping body facing respectively the top, left, bottom or right side of the map.
---
**Output**
---
---
Write the function `escape` that returns the list/array of moves you need to do relatively to the direction you're facing in order to escape the maze (you won't be able to see the map when you wake up). as an array of the following instructions:
- `'F'` move one step forward
- `'L'` turn left
- `'R'` turn right
- `'B'` turn back
> Note: `'L'`,`'R'`, and `'B'` **ONLY** perform a rotation and will not move your body
```if:javascript,ruby,python,java
If the maze has no exit, return an empty array.
```
```if:c
If the maze has no exit, return `NULL`.
```
* This is a real maze, there is no "escape" point. Just reach the edge of the map and you're free!
* You don't explicitely HAVE to find the shortest possible route, but you're quite likely to timeout if you don't **;P**
* Aside from having no escape route the mazes will all be valid (they all contain one and only one "body" character and no other characters than the body, `"#"` and `" "`. Besides, the map will always be rectangular, you don't have to check that either) | reference | from collections import deque
from numpy import cross, dot
MOVES = ((1, 0), (- 1, 0), (0, 1), (0, - 1))
DIRS = ('v', '^', '>', '<')
def escape(maze):
start = x, y = next((x, y) for x, row in enumerate(maze)
for y, c in enumerate(row) if c not in '# ')
X, Y, dir = len(maze), len(maze[0]), MOVES[DIRS . index(maze[x][y])]
q, seens = deque([(start, dir)]), {}
if not x or x == X - 1 or not y or y == Y - 1:
return [] # Already at the end, do nothing
noPath = True
while q:
(x, y), dir = q . popleft()
for dx, dy in MOVES:
xx, yy = pos = (x + dx, y + dy)
if 0 <= xx < X and 0 <= yy < Y and maze[xx][yy] == ' ' and pos not in seens:
q . append((pos, (dx, dy)))
# data: (origin position, direction before origin, direction after origin)
seens[pos] = ((x, y), dir, (dx, dy))
if not xx or xx == X - 1 or not yy or yy == Y - 1: # Escaped!
q, noPath = [], False # reset the queue to stop it, "from the for loop"
break
if noPath:
return [] # No path, no chocolate...
path = []
while pos != start:
pos, dir, nextDir = seens[pos]
# scalar prouct > 0 <=> go ahead, otherwise, turn back
scal = dot(dir, nextDir)
# cross product > 0 <=> turn left, otherwise, turn right
prod = cross(dir, nextDir)
if scal:
# dot != 0 => both directions are colinear
path . append('FB' if scal < 0 else 'F')
else:
# orthogonal directions, take a turn
path . append('FL' if prod > 0 else 'FR')
return list('' . join(path)[:: - 1])
| Escape the maze | 5877027d885d4f6144000404 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5877027d885d4f6144000404 | 4 kyu |
If you're old enough, you might remember buying your first mobile phone, one of the old ones with no touchscreen, and sending your first text message with excitement in your eyes. Maybe you still have one lying in a drawer somewhere.
Let's try to remember the good old days and what it was like to send text messages with such devices. A lot of them had different layouts, most notably for special characters and spaces, so for simplicity we'll be using a fictional model with 3x4 key layout shown below:
```
-------------------------
| 1 | 2 | 3 | <-- hold a key to type a number
| .,?! | abc | def | <-- press a key to type a letter
-------------------------
| 4 | 5 | 6 | <-- Top row
| ghi | jkl | mno | <-- Bottom row
-------------------------
| 7 | 8 | 9 |
| pqrs | tuv | wxyz |
-------------------------
| * | 0 | # | <-- hold for *, 0 or #
| '-+= | space | case | <-- press # to switch between upper/lower case
-------------------------
```
# The task
You got your thumb ready to go, so you'll receive a ```message``` and your job is to figure out which keys you need to press to output the given message with ***the lowest number of clicks possible***.
Return the result as a string of key inputs from top row (refer to diagram above).
***Take your time*** to study the rules below.
# How it works
### Result
Output string contains inputs that are shown at the **top** row of a key's layout. (`0-9*#`)
### Typing letters
To type letters, press a button repeatedly to cycle through the possible characters (bottom row of a key's layout). Pressing is represented by key's top row element repeated `n` times, where n is the position of character on that particular key. Examples:
- ```2``` => 'a', ```9999``` => 'z', ```111``` => '?', ```***``` => '+'
### Typing numbers
To type numbers ```0-9``` and special characters ```*#``` - hold that key. Holding is represented by a number, followed by a dash. Examples:
- ```3-``` => '3', ```5-5-5-``` => '555'
### Uppercase / Lowercase
Initially the case is `lowercase`. To ***toggle*** between lowercase and uppercase letters, use the ```#``` symbol. Case switching should only be considered when next character is alphabetic (`a-z`). Examples:
- ```#2#9999``` => 'Az' (remember, it's a toggle)
- ```27-#2255``` => 'a7BK' (do not switch before '7')
### Waiting for next character
If you have 2 or more characters in a sequence that reside on the same button (refer to layout, bottom row), you have to ***wait*** before pressing the same button again.
Waiting is represented by adding a **space** between 2 (or more) such characters. Example:
- ```44 444 44 444``` => 'hihi'
**Exceptions**: No need to wait **after holding** any key, even if next character resides on same button (```4-4``` => '4g'), or if there's a case switch between 2 characters on same button (```#5#55``` => 'Jk').
# Example
To put it all together, let's go over an example.
Say you want to type this message - ```'Def Con 1!'```:
- Switch to uppercase with ```#``` and press ```3``` (```#3 => D```) (input is now in uppercase mode)
- Switch to lowercase and press ```3``` twice (```#33 => e```). (Note that there is no **waiting** because of case switching)
- Next character ```f``` is on button ```3``` again, and has the same case (lowercase input and lowercase character), so you have to wait to type again (```' 333' => f```).
- In a similar manner type the second word (space is located on number ```0```). ```0#222#666 660 => ' Con '```
- Finish off by holding ```1``` as ```1-``` and typing ```!``` as ```1111``` (```'1-1111' = 1!```). Note that after holding a key you don't need to wait to press another key.
## Result:
```if:python,cpp,c,ruby
`send_message("Def Con 1!") => "#3#33 3330#222#666 6601-1111"`
```
```if:javascript,haskell,java,php,typescript,cfml
`sendMessage("Def Con 1!") => "#3#33 3330#222#666 6601-1111" `
```
```if:csharp
`Kata.SendMessage("Def Con 1!") => "#3#33 3330#222#666 6601-1111"`
```
```if:prolog
`send_message("Def Con 1!", "#3#33 3330#222#666 6601-1111").`
```
```if:pascal
SendMessage("Def Con 1!") => "#3#33 3330#222#666 6601-1111"
```
```if:cfml
***Note for CFML: be careful with '#'. To output it, you should use '##'.***
```
More examples are provided in sample test suite.
All inputs will be valid strings and only consist of characters from the key layout table.
### Good luck!
Also check out other cool katas that inspired this one:
- [Multi-tap Keypad Text Entry on an Old Mobile Phone by mroth](https://www.codewars.com/kata/multi-tap-keypad-text-entry-on-an-old-mobile-phone)
- [Mobile Display Keystrokes by zruF](https://www.codewars.com/kata/mobile-display-keystrokes)
- [Thinking & Testing : Mobile phone simulator by myjinxin2015](https://www.codewars.com/kata/thinking-and-testing-mobile-phone-simulator) | algorithms | HOLDERS = '12345678910*#'
TOME = {c: n * str(i) for i, seq in enumerate(' /.,?!/abc/def/ghi/jkl/mno/pqrs/tuv/wxyz' . split('/'))
for n, c in enumerate(seq, 1)}
TOME . update({c: c + '-' for c in HOLDERS})
TOME . update({c: n * '*' for n, c in enumerate("'-+=", 1)})
def send_message(s):
isUp, out = 0, []
def press(seq):
if out and out[- 1][- 1] == seq[0]:
seq = ' ' + seq
out . append(seq)
for c in s:
if c . isalpha() and isUp != c . isupper():
press('#')
isUp ^= 1
press(TOME[c . lower()])
return '' . join(out)
| Texting with an old-school mobile phone | 5ca24526b534ce0018a137b5 | [
"Fundamentals",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5ca24526b534ce0018a137b5 | 6 kyu |
Let's say we have a number, `num`. Find the number of values of `n` such that: there exists `n` consecutive **positive** values that sum up to `num`. A positive number is `> 0`. `n` can also be 1.
```python
#Examples
num = 1
#1
return 1
num = 15
#15, (7, 8), (4, 5, 6), (1, 2, 3, 4, 5)
return 4
num = 48
#48, (15, 16, 17)
return 2
num = 97
#97, (48, 49)
return 2
```
```java
//Examples
int num = 1;
//1
return 1;
int num = 15;
//15, (7, 8), (4, 5, 6), (1, 2, 3, 4, 5)
return 4;
int num = 48;
//48, (15, 16, 17)
return 2;
int num = 97;
//97, (48, 49)
return 2;
```
The upper limit is `$10^8$` | algorithms | def consecutive_sum(num):
upper_limit = 1
while True:
if upper_limit * (upper_limit + 1) / / 2 > num:
break
upper_limit += 1
return sum([1 if i % 2 and not num % i else 1 if not i % 2 and num % i == i / / 2 else 0 for i in range(1, upper_limit)])
| Consecutive Sum | 5f120a13e63b6a0016f1c9d5 | [
"Mathematics"
] | https://www.codewars.com/kata/5f120a13e63b6a0016f1c9d5 | null |
In this Kata your task is to check the possibility to solve the 'Knight's tour problem' for the desk of the current size.
A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square exactly once. If the knight ends on a square that is one knight's move away from the beginning square (so that it could tour the board again immediately, following the same path), the tour is closed; otherwise, it is open.
In this Kata we will think only about open tours.
## Input
`n`, `m` - desk size.
`0 < n < 10.`
`0 < m < 10.`
## Output
``` if:python
Return `True` if a tour exist for the current desk. Otherwise return `False`.
```
```if-not:python
Return `true` if a tour exist for the current desk.
Otherwise return `false`
```
| algorithms | def check(n, m):
return n * m >= 20 or f" { min ( n , m )}{ max ( n , m )} " == "34"
| Knight's tour problem on (N x M) desk | 5fc836f5a167260008dfad7f | [
"Algorithms"
] | https://www.codewars.com/kata/5fc836f5a167260008dfad7f | 7 kyu |
It's been a tough week at work and you are stuggling to get out of bed in the morning.
While waiting at the bus stop you realise that if you could time your arrival to the nearest minute you could get valuable extra minutes in bed.
There is a bus that goes to your office every 15 minute, the first bus is at `06:00`, and the last bus is at `00:00`.
Given that it takes 5 minutes to walk from your front door to the bus stop, implement a function that when given the curent time will tell you much time is left, before you must leave to catch the next bus.
## Examples
```
"05:00" => 55
"10:00" => 10
"12:10" => 0
"12:11" => 14
```
### Notes
1. Return the number of minutes till the next bus
2. Input will be formatted as `HH:MM` (24-hour clock)
3. The input time might be after the buses have stopped running, i.e. after `00:00` | reference | def bus_timer(current_time):
h, m = map(int, current_time . split(":"))
current_time = 60 * h + m
if current_time >= 1436 or current_time <= 355:
return (355 - current_time) % 1440
else:
return (10 - current_time) % 15
| Bus Timer | 5736378e3f3dfd5a820000cb | [
"Parsing",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5736378e3f3dfd5a820000cb | 7 kyu |
### Task
Return the length of the given month in the given year.
```if:python,ruby
Your code can be maximum `90` characters long.
```
---
### My other katas
If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-)
#### *Translations are welcome!* | games | from calendar import _monthlen as last_day
| [Code Golf] Length of Month | 5fc4e46867a010002b4b5f70 | [
"Restricted",
"Date Time",
"Puzzles"
] | https://www.codewars.com/kata/5fc4e46867a010002b4b5f70 | 7 kyu |
Write a function which maps a function over the lists in a list:
```ruby
def grid_map inp,&block
# applies the &block to all nested elements
```
```haskell
gridMap :: (a -> b) -> [[a]] -> [[b]]
```
```python
def grid_map(inp, op)
# which performs op(element) for all elements of inp
```
```javascript
function gridMap(fn,xss) { return [[]]; }
```
```java
public static <T,R> R[][] gridMap(Function<T,R> fn, T[][] list)
```
Example 1:
```ruby
x = [[1,2,3],
[4,5,6]]
grid_map(x) { |n| n + 1 }
#-- returns [[2,3,4],[5,6,7]]
grid_map(x) { |n| n ** 2 }
#-- returns [[1,4,9],[16,25,36]]
```
```haskell
x = [[1,2,3],
[4,5,6]]
gridMap (+1) x
-- returns [[2,3,4],[5,6,7]]
gridMap (^2) x
-- returns [[1,4,9],[16,25,36]]
```
```python
x = [[1,2,3],
[4,5,6]]
grid_map(x, lambda x: x + 1)
-- returns [[2,3,4],[5,6,7]]
grid_map(x, lambda x: x ** 2)
-- returns [[1,4,9],[16,25,36]]
```
```javascript
const xss = [ [1,2,3]
, [4,5,6]
];
gridMap( x => x+1 , xss ) => [[2,3,4],[5,6,7]]
gridMap( x => x**2 , xss ) => [[1,4,9],[16,25,36]]
```
```java
int[][] x = {{1,2,3},
{4,5,6}};
gridMap(e -> e + 1, x); // {{2,3,4},{5,6,7}}
gridMap(e -> e * e, x); // {{1,4,9},{16,25,36}}
```
Example 2
```ruby
x = [['h', 'E', 'l', 'l', 'O'], ['w', 'O', 'r', 'L', 'd']]
grid_map(x) { |c| c.upcase }
#-- returns [["H", "E", "L", "L", "O"], ["W", "O", "R", "L", "D"]]
```
```haskell
import Data.Char
x = ["hEllO", "wOrLd"]
gridMap toUpper x
-- returns ["HELLO, WORLD"]
```
```python
x = [['h', 'E', 'l', 'l', 'O'], ['w', 'O', 'r', 'L', 'd']]
grid_map(x, lambda x: x.upper())
-- returns [['H', 'E', 'L', 'L', 'O'], ['W', 'O', 'R', 'L', 'D']]
```
```javascript
const xss = [['h','E','l','l','O'],['w','O','r','L','d']];
gridMap( x => x.toUpperCase() , xss ) => [['H','E','L','L','O'],['W','O','R','L','D']]
```
```java
char[][] x = {{'h','E','l','l','O'},{'w','O','r','L','d'}};
gridMap(e -> Character.toUpperCase(e), x); // {{'H','E','L','L','O'},{'W','O','R','L','D'}}
``` | reference | def grid_map(lst, op):
return [[* map(op, x)] for x in lst]
| Map over a list of lists | 606b43f4adea6e00425dff42 | [
"Fundamentals",
"Lists"
] | https://www.codewars.com/kata/606b43f4adea6e00425dff42 | 7 kyu |
## Task
In this kata you will be given a list consisting of unique elements except for one thing that appears twice.
Your task is to output a list of everything inbetween both occurrences of this element in the list.
## Examples:
```python
[0, 1, 2, 3, 4, 5, 6, 1, 7, 8] => [2, 3, 4, 5, 6]
['None', 'Hello', 'Example', 'hello', 'None', 'Extra'] => ['Hello', 'Example', 'hello']
[0, 0] => []
[True, False, True] => [False]
['e', 'x', 'a', 'm', 'p', 'l', 'e'] => ['x', 'a', 'm', 'p', 'l']
```
```haskell
[0, 1, 2, 3, 4, 5, 6, 1, 7, 8] -> [2, 3, 4, 5, 6]
["None", "Hello", "Example", "hello", "None", "Extra"] -> ["Hello", "Example", "hello"]
[0, 0] -> []
[True, False, True] -> [False]
"example" -> "xampl"
```
```javascript
[0, 1, 2, 3, 4, 5, 6, 1, 7, 8] => [2, 3, 4, 5, 6]
["None", "Hello", "Example", "hello", "None", "Extra"] => ["Hello", "Example", "hello"]
[0, 0] => []
[true, false, true] => [false]
"example" => "xampl"
```
## Notes
* All elements will be the same datatype.
~~~if:python
* All used elements will be hashable.
~~~
~~~if:javascript
* All used elements will be primitive.
~~~ | reference | def duplicate_sandwich(arr):
start, end = [i for i, x in enumerate(arr) if arr . count(x) > 1]
return arr[start + 1: end]
| Duplicate sandwich | 5f8a15c06dbd530016be0c19 | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/5f8a15c06dbd530016be0c19 | 7 kyu |
# Description
There is a narrow hallway in which people can go right and left only. When two people meet in the hallway, by tradition they must salute each other. People move at the same speed left and right.
Your task is to write a function that, given a string representation of people moving in the hallway, will count the number of salutes that will occur.
**Note**: `2` salutes occur when people meet, one to the other and vice versa.
# Input
People moving right will be represented by `>`; people moving left will be represented by `<`. An example input would be `>--<--->->`. The `-` character represents empty space, which you need not worry about.
# Examples
Input: `>----->-----<--<`
Output: `8`
Explanation: Both guys moving right will meet both guys moving left.
Hence a total of `4` meetings will occur and `8` salutes will occur.
Input: `<---<--->----<`
Output: `2`
Explanation: Only one meeting occurs. | reference | def count_salutes(hallway: str) - > int:
right = 0
salutes = 0
for p in hallway:
if p == '>':
right += 1
if p == '<':
salutes += 2 * right
return salutes
| Count salutes | 605ae9e1d2be8a0023b494ed | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/605ae9e1d2be8a0023b494ed | 7 kyu |
Given: a sequence of different type of values (number, string, boolean). You should return an object with a separate properties for each of types presented in input. Each property should contain an array of corresponding values.
- keep order of values like in input array
- if type is not presented in input, no corresponding property are expected
So, for this input:
```javascript
['a', 1, 2, false, 'b']
```
```python
['a', 1, 2, False, 'b']
```
expected output is:
```javascript
{
number: [1, 2],
string: ['a', 'b'],
boolean: [false]
}
```
```python
{
int: [1, 2],
str: ['a', 'b'],
bool: [False]
}
``` | reference | def separate_types(seq):
result = {}
for element in seq:
if type(element) not in result:
result[type(element)] = [element]
else:
result[type(element)]. append(element)
return result
| Separate basic types | 60113ded99cef9000e309be3 | [
"Fundamentals"
] | https://www.codewars.com/kata/60113ded99cef9000e309be3 | 7 kyu |
You are given an n by n ( square ) grid of characters, for example:
```python
[['m', 'y', 'e'],
['x', 'a', 'm'],
['p', 'l', 'e']]
```
You are also given a list of integers as input, for example:
```python
[1, 3, 5, 8]
```
You have to find the characters in these indexes of the grid if you think of the indexes as:
```python
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
```
Remember that the indexes start from one and not zero.
Then you output a string like this:
```python
"meal"
```
All inputs will be valid. | reference | def grid_index(grid, indexes):
flat = sum(grid, [])
return "" . join(flat[i - 1] for i in indexes)
| Grid index | 5f5802bf4c2cc4001a6f859e | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/5f5802bf4c2cc4001a6f859e | 7 kyu |
## Theory
In Boolean algebra, any Boolean function takes the value 0 or 1 (True or False) and depends on Boolean variables, which also have two values 0 and 1. Any Boolean function can be placed in canonical disjunctive normal form (CDNF). CDNF is a conjunction of minterms - expressions that are true only on a single set of variable values. Only 3 logical operations are involved in a CDNF record: `*` (logical AND), `+` (logical OR), and `~` (logical negation).
## Task
You get a truth table representing a Boolean function and must return its Canonical normal form (CDNF) as a string, using the following formatting/rules:
* Variable names are always in order: `"x1"`, `"x2"`, ..., `"xn"`.
* The number of logical variables is between `1` and `5`.
* Output only terms where the result is true.
* If the variable `xi` has the value "false" in the term, then it is written "~xi" in the output, otherwise "xi".
* It is guaranteed that all truth tables are correctly built.
## Construction CDNF
CDNF is based on the truth table, and only those rows in which the function value is true are taken.
In this kata, the truth table is a two-dimensional array whose elements are lists that store the value of the i-th Boolean variable in the i-th position and the value of the Boolean function in the last position.
For example, for the function `x1 + x2 * x3` (hence `x1 OR x2 AND x3`), with `n` being the number of logical variables (here,`n=3`), the truth table will have `2**n` rows with `n+1` columns, and will look like this:
```python
truth_table = [
# [x1,x2,x3,result]
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 1, 1, 1], # Minterm (~x1 * x2 * x3)
[1, 0, 0, 1], # Minterm (x1 * ~x2 * ~x3)
[1, 0, 1, 1], # Minterm (x1 * ~x2 * x3)
[1, 1, 0, 1], # Minterm (x1 * x2 * ~x3)
[1, 1, 1, 1], # Minterm (x1 * x2 * x3)
]
```
```javascript
truthTable = [
//[x1,x2,x3,result]
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 1, 1, 1], // Minterm (~x1 * x2 * x3)
[1, 0, 0, 1], // Minterm (x1 * ~x2 * ~x3)
[1, 0, 1, 1], // Minterm (x1 * ~x2 * x3)
[1, 1, 0, 1], // Minterm (x1 * x2 * ~x3)
[1, 1, 1, 1], // Minterm (x1 * x2 * x3)
]
```
And you shall return:
```code
"(~x1 * x2 * x3) + (x1 * ~x2 * ~x3) + (x1 * ~x2 * x3) + (x1 * x2 * ~x3) + (x1 * x2 * x3)"
```
More examples in the Examples Test Cases.
---
If you nead more information:
* [About CDNF](https://en.m.wikipedia.org/wiki/Canonical_normal_form)
* [Truth table and logical operations](https://en.m.wikipedia.org/wiki/Truth_table)
_Good luck!_ | algorithms | def cdnf(truth_table):
return ' + ' . join(f'( { buildRow ( r [: - 1 ]) } )' for r in truth_table if r[- 1])
def buildRow(r):
return ' * ' . join(f' { "~" * ( not b ) } x { i } ' for i, b in enumerate(r, 1))
| Boolean Trilogy #1: CDNF | 5f76c4779164bf001d52c141 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5f76c4779164bf001d52c141 | 7 kyu |
My PC got infected by a strange virus. It only infects my text files and replaces random letters by `*`, `li*e th*s` `(like this)`.
Fortunately, I discovered that the virus hides my censored letters inside root directory.
It will be very tedious to recover all these files manually, so your goal is to implement `uncensor` function that does the hard work automatically.
### Examples
```
uncensor("*h*s *s v*ry *tr*ng*", "Tiiesae") ➜ "This is very strange"
uncensor("A**Z*N*", "MAIG") ➜ "AMAZING"
uncensor("xyz", "") ➜ "xyz"
```
### Notes
- Expect all discovered letters to be given in the correct order.
- Discovered letters will match the number of censored ones.
- Any character can be censored. | games | def uncensor(infected, discovered):
return infected . replace('*', '{}'). format(* discovered)
| Ce*s*r*d Strings | 5ff6060ed14f4100106d8e6f | [
"Puzzles",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5ff6060ed14f4100106d8e6f | 7 kyu |
### Task
Given an array of numbers and an index, return either the index of the smallest number that is larger than the element at the given index, or `-1` if there is no such index ( or, where applicable, `Nothing` or a similarly empty value ).
### Notes
Multiple correct answers may be possible. In this case, return any one of them.
The given index will be inside the given array.
The given array will, therefore, never be empty.
### Example
```javascript
leastLarger( [4, 1, 3, 5, 6], 0 ) => 3
leastLarger( [4, 1, 3, 5, 6], 4 ) => -1
```
```haskell
leastLarger [4, 1, 3, 5, 6] 0 -> Just 3
leastLarger [4, 1, 3, 5, 6] 4 -> Nothing
```
```c
least_larger({4, 1, 3, 5, 6}, 5, 0) == 3;
least_larger({4, 1, 3, 5, 6}, 5, 4) == -1;
```
```python
least_larger( [4, 1, 3, 5, 6], 0 ) -> 3
least_larger( [4, 1, 3, 5, 6], 4 ) -> -1
```
```prolog
least_larger( [4, 1, 3, 5, 6], 0, 3 ).
least_larger( [4, 1, 3, 5, 6], 4, -1 ).
```
```ruby
least_larger( [4, 1, 3, 5, 6], 0 ) = 3
least_larger( [4, 1, 3, 5, 6], 4 ) = -1
```
```go
leastLarger( [] int {4, 1, 3, 5, 6}, 0 ) = 3
leastLarger( [] int {4, 1, 3, 5, 6}, 4 ) = -1
```
```java
leastLarger( new int [] {4, 1, 3, 5, 6}, 0 ) = 3
leastLarger( new int [] {4, 1, 3, 5, 6}, 4 ) = -1
```
```csharp
Kata.LeastLarger(new[] { 4, 1, 3, 5, 6 }, 0) == 3
Kata.LeastLarger(new[] { 4, 1, 3, 5, 6 }, 4) == -1
```
```cobol
LeastLarger( [4, 1, 3, 5, 6], 1 ) = 4
LeastLarger( [4, 1, 3, 5, 6], 5 ) = 0
```
```lambdacalc
least-larger : List Number -> Number -> Option Number
least-larger < 4 1 3 5 6 > 0 . Some 3
least-larger < 4 1 3 5 6 > 4 . None
# use numEncoding Scott
# provide the following for input / output:
nil ~ [] : List a
cons ~ (:) : a -> List a -> List a
option ~ maybe : z -> (a -> z) -> Option a -> z
```
```factor
{ 4 1 3 5 6 } 0 ?least-larger ! 3
{ 4 1 3 5 6 } 4 ?least-larger ! f
```
```julia
leastlarger([4, 1, 3, 5, 6], 1) --> 4
leastlarger([4, 1, 3, 5, 6], 5) --> nothing
```
```rust
least_larger(&[4, 1, 3, 5, 6], 0) // returns Some(3)
least_larger(&[4, 1, 3, 5, 6], 4) // returns None
```
```go
LeastLarger([]int{4, 1, 3, 5, 6}, 0) // returns 3
LeastLarger([]int{4, 1, 3, 5, 6}, 4) // returns -1
```
```d
leastLarger( [4, 1, 3, 5, 6], 0 ) => 3
leastLarger( [4, 1, 3, 5, 6], 4 ) => -1
```
```cpp
least_larger({ 4, 1, 3, 5, 6 }, 0) == 3
least_larger({ 4, 1, 3, 5, 6 }, 4) == -1
``` | algorithms | def least_larger(a, i):
b = [x for x in a if x > a[i]]
return a . index(min(b)) if b else - 1
| Least Larger | 5f8341f6d030dc002a69d7e4 | [
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/5f8341f6d030dc002a69d7e4 | 7 kyu |
# Four Seven
```if:python
Simple kata, simple rules: your function should accept the inputs `4` and `7`. If `4` is entered, the function should return `7`. If `7` is entered, the function should return `4`. Anything else entered as input should return a false-y value such as `False`, `0`, `[]`, `""`. There's only one catch, your function cannot include if statements (or the eval function due to the fact that you can get around the if requirement using it).
There are some *very* simple ways of answering this problem, but I encourage you to try and be as creative as possible.
Good Luck!
```
```if:java,csharp
Simple kata, simple rules: your function should accept the inputs `4` and `7`. If `4` is entered, the function should return `7`. If `7` is entered, the function should return `4`. Anything else entered as input should return `0`. There's only one catch, your function cannot include if statements, switch statements, or the ternary operator.
There are some *very* simple ways of answering this problem, but I encourage you to try and be as creative as possible.
Good Luck!
```
```if:php,javascript
Simple kata, simple rules: your function should accept the inputs `4` and `7`. If `4` is entered, the function should return `7`. If `7` is entered, the function should return `4`. Anything else entered as input should return `0`. There's only one catch, your function cannot include if statements, switch statements, or the ternary operator (or the eval function due to the fact that you can get around the if requirement using it).
There are some *very* simple ways of answering this problem, but I encourage you to try and be as creative as possible.
Good Luck!
```
```if:lambdacalc
Simple kata, simple rules: your function should accept the inputs `4` and `7`. If `4` is entered, the function should return `7`. If `7` is entered, the function should return `4`. Anything else entered as input should return `0`. There's only one catch. This is Lambda Calculus. You have to make any if, case, switch or guard expressions yourself.
( This kata uses Church numerals. )
There are some *very* simple ways of answering this problem, but I encourage you to try and be as creative as possible.
Good Luck!
```
```if:haskell
Simple kata, simple rules: your function should accept the inputs `4` and `7`. If `4` is entered, the function should return `Just 7`. If `7` is entered, the function should return `Just 4`. Anything else entered as input should return `Nothing`. There's only one catch, your function cannot include if expressions, case expressions, or guards.
There are some *very* simple ways of answering this problem, but I encourage you to try and be as creative as possible.
Good Luck!
``` | games | def solution(n):
return {4: 7, 7: 4}. get(n)
| Four/Seven | 5ff50f64c0afc50008861bf0 | [
"Puzzles"
] | https://www.codewars.com/kata/5ff50f64c0afc50008861bf0 | 7 kyu |
Given the integer `n` return odd numbers as they are, but subtract 1 from even numbers.
**Note:**
~~~if:python,ruby
Your solution should be 36 or less characters long.
~~~
~~~if:javascript
Your solution should be 22 or less characters long.
~~~
### Examples
```
Input = 2
Output = 1
Input = 13
Output = 13
Input = 46
Output = 45
``` | algorithms | def always_odd(n): return n - (n % 2 == 0)
| [Code Golf] Return Odd No Matter What | 5f882dcc272e7a00287743f5 | [
"Fundamentals",
"Restricted",
"Algorithms"
] | https://www.codewars.com/kata/5f882dcc272e7a00287743f5 | 7 kyu |
You are given a list of unique integers `arr`, and two integers `a` and `b`. Your task is to find out whether or not `a` and `b` appear consecutively in `arr`, and return a boolean value (`True` if `a` and `b` are consecutive, `False` otherwise).
It is guaranteed that `a` and `b` are both present in `arr`.
~~~if:lambdacalc
### Encodings
purity: `LetRec`
numEncoding: `BinaryScott`
export constructors `nil, cons` for your `List` encoding, and deconstructor `if` for your `Boolean` encoding.
~~~ | reference | def consecutive(A, a, b):
return abs(A . index(a) - A . index(b)) == 1
| Consecutive items | 5f6d533e1475f30001e47514 | [
"Fundamentals"
] | https://www.codewars.com/kata/5f6d533e1475f30001e47514 | 7 kyu |
## Task
Implement a function that takes an unsigned 32 bit integer as input and sorts its bytes in descending order, returning the resulting (unsigned 32 bit) integer.
An alternative way to state the problem is as follows: The number given as input is made up of four bytes. Reorder these bytes so that the resulting (unsigned 32 bit) integer is as large as possible.
## Example
```
Input: 3735928559
3735928559 is 0xdeadbeef in hexadecimal representation and 11011110 10101101 10111110 11101111
in binary representation.
After sorting the bytes in descending order the resulting unsigned 32 bit integer is 4024352429
in decimal representation, which is 0xefdebead in hexadecimal and 11101111 11011110 10111110 10101101
in binary.
Output should be: 4024352429
``` | reference | def sort_bytes(number):
return int . from_bytes(sorted(number . to_bytes(4, 'little')), 'little')
| Sort the Bytes | 6076d4edc7bf5d0041b31dcf | [
"Algorithms",
"Fundamentals",
"Sorting"
] | https://www.codewars.com/kata/6076d4edc7bf5d0041b31dcf | 7 kyu |
The <b><i>status</b></i> of each element of an array of integers can be determined by its position in the array and the value of the other elements in the array. The status of an element <i><b>E</b></i> in an array of size <i><b>N</b></i> is determined by adding the position <i><b>P</b></i>, 0 <= <i><b>P</b></i> < <i><b>N</b></i>, of the element in the array to the number of array elements in the array that are less than <i><b>E</b></i>.
For example, consider the array containing the integers: ```6 9 3 8 2 3 1```. The status of the element ```8``` is 8 because its position is 3 and there are 5 elements in the array that are less than 8.
You will return the elements of the original array from low to high status order. In the event there is a tie for status of two or more elements, you will output them in order of appearance in the array.
EXAMPLE:
```Java
status([6, 9, 3, 8, 2, 3, 1]) = [6, 3, 2, 1, 9, 3, 8]
``` | algorithms | def status(nums):
cnts = {n: len(nums) - i for i,
n in enumerate(sorted(nums, reverse=True), 1)}
def itemStatus(it): return it[0] + cnts[it[1]]
return [v for _, v in sorted(enumerate(nums), key=itemStatus)]
| Status Arrays | 601c18c1d92283000ec86f2b | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/601c18c1d92283000ec86f2b | 7 kyu |
# Task
You have a list of integers. The task is to return the maximum sum of the elements located between two negative elements. No negative element should be present in the sum.
If there is no such sum: `-1` for Python, C++, JavaScript, Java, CoffeeScript and COBOL, `Nothing` for Haskell, `None` for Rust.
## Example 1
```
[4, -1, 6, -2, 3, 5, -7, 7] -> 8
^ ^ ^
```
Sum between `-1` and `-2` is `6`, between `-2` and `-7` is 3 + 5 = `8`.
It's also not `14` (between `-1` and `-7`), because this includes a negative number (`-2`).
## Example 2
```
[4, -1, -2] -> 0
^ ^
```
There is nothing between `-1` and `-2`, so return `0`. | algorithms | from itertools import dropwhile
def max_sum_between_two_negatives(arr):
top = c = - 1
for v in dropwhile((0). __le__, arr):
if v < 0:
top, c = max(top, c), 0
else:
c += v
return top
| Max sum between two negatives | 6066ae080168ff0032c4107a | [
"Algorithms"
] | https://www.codewars.com/kata/6066ae080168ff0032c4107a | 7 kyu |
All clocks can have their times changed, so when a clock is going too fast or slow, the time can be changed to be correct again. Bob has a 24-hour clock (so `2:00 PM` will be `14:00` instead), on which there are two buttons -- the `H` button and the `M` button, which increase the hour and minute, respectively, by one. Given the list of buttons Bob presses and the starting time, figure out what time Bob set his clock to.
Some details:
- When the minute reaches 60 it resets to 0 **without changing the hour**
- Hours do not have leading zeros, only minutes do
- The hour for midnight should be 24; 0 is not used as an hour
It is guaranteed that:
- There are no more than 59 `'M'`s and 23 `'H'`s that Bob presses
- The time given as the starting time will always be a valid 24-hr time
Examples:
```
set_clock("9:21", ['M', 'M', 'M', 'M', 'H', 'H', 'M']) => "11:26"
set_clock("16:54", ['M', 'M', 'H', 'M', 'M', 'H', 'H', 'H', 'M', 'H', 'H', 'M', 'H', 'H']) => "24:00"
```
| reference | def set_clock(time, buttons):
h, m = map(int, time . split(':'))
h += buttons . count('H')
m += buttons . count('M')
return f' { h % 24 or 24 } : { m % 60 :0 2 } '
| Set the Clock | 5fbfc2c0dce9ec000de691e3 | [
"Puzzles",
"Fundamentals"
] | https://www.codewars.com/kata/5fbfc2c0dce9ec000de691e3 | 7 kyu |
## Task
Your task is to write a function called ```valid_spacing()``` or ```validSpacing()``` which checks if a string has valid spacing. The function should return either ```true``` or ```false``` (or the corresponding value in each language).
For this kata, the definition of valid spacing is one space between words, and no leading or trailing spaces. Words can be any consecutive sequence of non space characters. Below are some examples of what the function should return:
```
* 'Hello world' => true
* ' Hello world' => false
* 'Hello world ' => false
* 'Hello world' => false
* 'Hello' => true
Even though there are no spaces, it is still valid because none are needed:
* 'Helloworld' => true
* 'Helloworld ' => false
* ' ' => false
* '' => true
```
*Note - there will be no punctuation or digits in the input string, only letters.*
| reference | def valid_spacing(s):
return s == ' ' . join(s . split())
| Valid Spacing | 5f77d62851f6bc0033616bd8 | [
"Fundamentals"
] | https://www.codewars.com/kata/5f77d62851f6bc0033616bd8 | 7 kyu |
# Tap Code Translation
[Tap code](https://en.wikipedia.org/wiki/Tap_code) is a way to communicate using a series of taps and pauses for each letter. In this kata, we will use dots `.` for the taps and whitespaces for the pauses.
The number of taps needed for each letter matches its coordinates in the following polybius square (note the `c/k` position). Then you "tap" the row, a pause, then the column. Each letter is separated from others with a pause too.
```
1 2 3 4 5
1 A B C\K D E
2 F G H I J
3 L M N O P
4 Q R S T U
5 V W X Y Z
```
### Input:
A lowercase string of a single word (no whitespaces or punctuation, only letters).
### Output:
The encoded string as taps and pauses.
### Examples
```
text = "dot"
"D" = (1, 4) = ". ...."
"O" = (3, 4) = "... ...."
"T" = (4, 4) = ".... ...."
output: ". .... ... .... .... ...."
"example" -> ". ..... ..... ... . . ... .. ... ..... ... . . ....."
"more" -> "... .. ... .... .... .. . ....."
```
Happy coding! | algorithms | def tap_code_translation(text):
dots = {'a': '. .', 'b': '. ..', 'c': '. ...', 'd': '. ....', 'e': '. .....', 'f': '.. .', 'g': '.. ..', 'h': '.. ...', 'i': '.. ....', 'j': '.. .....', 'k': '. ...', 'l': '... .', 'm': '... ..', 'n': '... ...',
'o': '... ....', 'p': '... .....', 'q': '.... .', 'r': '.... ..', 's': '.... ...', 't': '.... ....', 'u': '.... .....', 'v': '..... .', 'w': '..... ..', 'x': '..... ...', 'y': '..... ....', 'z': '..... .....'}
return ' ' . join([dots[i] for i in text])
| Tap Code Translation | 605f5d33f38ca800322cb18f | [
"Algorithms",
"Strings",
"Cryptography",
"Security"
] | https://www.codewars.com/kata/605f5d33f38ca800322cb18f | 7 kyu |
In a certain kingdom, strange mathematics is taught at school. Its main difference from ordinary mathematics is that the numbers in it are not ordered in ascending order, but lexicographically, as in a dictionary (first by the first digit, then, if the first digit is equal, by the second, and so on). In addition, we do not consider an infinite set of natural numbers, but only the first `n` numbers.
So, for example, if `n = 11`, then the numbers in strange mathematics are ordered as follows:
`1, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9.`
Help your students to learn this science: write a function that receives two integer numbers: `n` (total amount of numbers in strange mathematics) and `k` (number from sequence) and returns the location of a given number `k` in the order defined in strange mathematics.
For example, if `n = 11` and `k = 2`, the function should return `4` as the answer.
**Input**: `1 <= n <= 100 000` , `1 <= k <= n`.
**Output**: position of the number `k` in sequence of the first `n` natural numbers in lexicographic order. Numbering starts with 1.
#### Examples:
```python
strange_math(11, 2) == 4
strange_math(15, 5) == 11
strange_math(15, 15) == 7
```
```javascript
strangeMath(11, 2) === 4
strangeMath(15, 5) === 11
strangeMath(15, 15) === 7
``` | reference | def strange_math(n, k):
return sorted(range(n + 1), key=str). index(k)
| Strange mathematics | 604517d65b464d000d51381f | [
"Sorting",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/604517d65b464d000d51381f | 7 kyu |
Uh oh, Someone at the office has dropped all these sequences on the floor and forgotten to label them with their correct bases.
We have to fix this before the boss gets back or we're all going to be fired!
This is what your years of coding have been leading up to, now is your time to shine!
## Task
You will have to create a function which takes in a sequence of numbers in **random order** and you will have to return the correct base of those numbers.
The base is the number of unique digits. For example, a base 10 number can have 10 unique digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and a base 2 number (Binary) can have 2 unique digits: 0 and 1.
## Constraints
The sequence will always be 10 numbers long and we know that the base is going to be between 2 and 10 inclusive so no need to worry about any letters. When sorted, the sequence is made up of consecutive numbers.
## Examples
```
[ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ] --> 10
[ "1", "2", "3", "4", "5", "6", "10", "11", "12", "13" ] --> 7
```
**Good luck!**
| games | def base_finder(seq):
return len(set('' . join(seq)))
| Bases Everywhere | 5f47e79e18330d001a195b55 | [
"Puzzles"
] | https://www.codewars.com/kata/5f47e79e18330d001a195b55 | 7 kyu |
<h1>Hit the target</h1>
given a matrix <code>n x n</code> (2-7), determine if the arrow is directed to the target (x). <br>
There will be only 1 arrow '>' and 1 target 'x'<br>
An empty spot will be denoted by a space " ", the target with a cross "x", and the scope ">"
<h2>Examples:</h2>
given matrix 4x4: <br>
<code>[<br>
[' ', ' ', ' ', ' '],<br>
[' ', ' ', ' ', ' '], --> return true<br>
[' ', '>', ' ', 'x'],<br>
[' ', ' ', ' ', ' ']<br>
] </code><br>
given matrix 4x4: <br>
<code>[<br>
[' ', ' ', ' ', ' '],<br>
[' ', '>', ' ', ' '], --> return false<br>
[' ', ' ', ' ', 'x'],<br>
[' ', ' ', ' ', ' ']<br>
] </code><br>
given matrix 4x4: <br>
<code>[<br>
[' ', ' ', ' ', ' '],<br>
[' ', 'x', '>', ' '], --> return false<br>
[' ', '', ' ', ' '],<br>
[' ', ' ', ' ', ' ']<br>
] </code>
In this example, only a 4x4 matrix was used, the problem will have matrices of dimensions from 2 to 7<br>
Happy hacking as they say! | reference | def solution(mtrx):
for row in mtrx:
if ">" in row and "x" in row:
return row . index(">") < row . index("x")
return False
| Game Hit the target | 5ffc226ce1666a002bf023d2 | [
"Games",
"Matrix",
"Arrays",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5ffc226ce1666a002bf023d2 | 7 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.