description
stringlengths 38
154k
| category
stringclasses 5
values | solutions
stringlengths 13
289k
| name
stringlengths 3
179
| id
stringlengths 24
24
| tags
listlengths 0
13
| url
stringlengths 54
54
| rank_name
stringclasses 8
values |
|---|---|---|---|---|---|---|---|
# Task
Two teams are playing a game of tennis. The team sizes are the same and each player from the first team plays against the corresponding player from the second team.

Each player has a certain power level. If a player has a higher power level than her opponent, she is guaranteed to win and her team would get 1 point for that win while the opponents get a 0.
You are the coach of the first team and you know the power levels of all the players before the game starts. You want to rearrange the players in your team to earn the highest possible total score.
# Input/Output
- `[input]` integer array `team1`
The power levels of the players in the first team. Teams have less than `100` players and each power level is less than `100`.
- [input] integer array `team2`
Array of the same length as team1, the power levels of the players of the second team.
- `[output]` an integer
The maximum number of points the first team can get.
# Example
For `team1 = [3,2,4] and team2 = [1,2,3]`, the output should be `3`.
If you don't rearrange the players in the first team, it will get `2 points`, since `3 > 1, 2 = 2 and 4 > 3`.
However, if you rearrange the order of the players to `[2, 3, 4]`, the first team will get `3 points`.
|
reference
|
def maximize_points(team1, team2):
team1 . sort()
team2 . sort()
ans = 0
for p2 in team2[:: - 1]:
if p2 < max(team1):
team1 . remove(max(team1))
ans += 1
return ans
|
Simple Fun #210: Maximize Points
|
58fec262184b6dc30800000d
|
[
"Algorithms",
"Fundamentals"
] |
https://www.codewars.com/kata/58fec262184b6dc30800000d
|
6 kyu
|
In this Kata you have to find the factors of <code>integer</code> down to the <code>limit</code> including the limiting number. There will be no negative numbers. Return the result as an array of numbers in ascending order.
If the <code>limit</code> is more than the <code>integer</code>, return an empty list
As a challenge, see if you can do it in one line
|
reference
|
def factors(integer, limit):
return [x for x in range(limit, integer + 1) if integer % x == 0]
|
Find Factors Down to Limit
|
58f6024e1e26ec376900004f
|
[
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/58f6024e1e26ec376900004f
|
7 kyu
|
# Task
You are given a decimal number `n` as a **string**. Transform it into an array of numbers (given as **strings** again), such that each number has only one nonzero digit and their sum equals n.
Each number in the output array should be written without any leading and trailing zeros.
# Input/Output
- `[input]` string `n`
A non-negative number.
`1 ≤ n.length ≤ 30.`
- `[output]` a string array
Elements in the array should be sorted in descending order.
# Example
For `n = "7970521.5544"` the output should be:
```
["7000000",
"900000",
"70000",
"500",
"20",
"1",
".5",
".05",
".004",
".0004"]
```
For `n = "7496314"`, the output should be:
```
["7000000",
"400000",
"90000",
"6000",
"300",
"10",
"4"]
```
For `n = "0"`, the output should be `[]`
|
algorithms
|
def split_exp(n):
dot = n . find('.')
if dot == - 1:
dot = len(n)
return [d + "0" * (dot - i - 1) if i < dot else ".{}{}" . format("0" * (i - dot - 1), d)
for i, d in enumerate(n) if i != dot and d != '0']
|
Simple Fun #205: Split Exp
|
58fd9f6213b00172ce0000c9
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58fd9f6213b00172ce0000c9
|
7 kyu
|
# Task
You are given three integers `l, d and x`. Your task is:
```
• determine the minimal integer n
such that l ≤ n ≤ d, and the sum of its digits equals x.
• determine the maximal integer m
such that l ≤ m ≤ d, and the sum of its digits equals x.
```
It is guaranteed that such numbers always exist.
# Input/Output
- `[input]` integer `l`
- `[input]` integer `d`
`1 ≤ l ≤ d ≤ 10000.`
- `[input]` integer `x`
`1 ≤ x ≤ 36`
- `[output]` an integer array
Array of two elements, where the first element is `n`, and the second one is `m`.
# Example
For `l = 500, d = 505, x = 10`, the output should be `[505, 505]`.
For `l = 100, d = 200, x = 10`, the output should be `[109, 190]`.
|
reference
|
def min_and_max(l, d, x):
for n in range(l, d + 1):
if sum(map(int, str(n))) == x:
break
for m in range(d, l - 1, - 1):
if sum(map(int, str(m))) == x:
break
return [n, m]
|
Simple Fun #202: Min And Max
|
58fd52b59a9f65c398000096
|
[
"Algorithms",
"Fundamentals"
] |
https://www.codewars.com/kata/58fd52b59a9f65c398000096
|
7 kyu
|
# Task
You're given a two-dimensional array of integers `matrix`. Your task is to determine the smallest non-negative integer that is not present in this array.
# Input/Output
- `[input]` 2D integer array `matrix`
A non-empty rectangular matrix.
`1 ≤ matrix.length ≤ 10`
`1 ≤ matrix[0].length ≤ 10`
- `[output]` an integer
The smallest non-negative integer that is not present in matrix.
# Example
For
```
matrix = [
[0, 2],
[5, 1]]```
the result should be `3`
0,1,2,`(3)`...5
|
reference
|
def smallest_integer(matrix):
nums = set(sum(matrix, []))
n = 0
while n in nums:
n += 1
return n
|
Simple Fun #204: Smallest Integer
|
58fd96a59a9f65c2e900008d
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/58fd96a59a9f65c2e900008d
|
7 kyu
|
# Task
Mirko has been moving up in the world of basketball. He started as a mere spectator, but has already reached the coveted position of the national team coach!
Mirco is now facing a difficult task: selecting five primary players for the upcoming match against Tajikistan. Since Mirko is incredibly lazy, he doesn't bother remembering players' names, let alone their actual skills. That's why he has settled on selecting five players who share the same first letter of their surnames, so that he can remember them easier. If there are no five players sharing the first letter of their surnames, Mirko will simply forfeit the game!
Your task is to find the first letters Mirko's players' surnames can begin with(In alphabetical order), or return `"forfeit"` if Mirko can't gather a team.
# Input/Output
- `[input]` string array `players`
Array of players' surnames, consisting only of lowercase English letters.
- `[output]` a string
A **sorted** string of possible first letters, or "forfeit" if it's impossible to gather a team.
# Example
For `players = ["michael","jordan","lebron","james","kobe","bryant"]`, the output should be `"forfeit"`.
For
```
players = ["babic","keksic","boric","bukic",
"sarmic","balic","kruzic","hrenovkic",
"beslic","boksic","krafnic","pecivic",
"klavirkovic","kukumaric","sunkic","kolacic",
"kovacic","prijestolonasljednikovic"]
```
the output should be "bk".
|
reference
|
from collections import Counter
def strange_coach(players):
return '' . join(
sorted(i for i, j in
Counter(map(lambda x: x[0], players)). most_common()
if j >= 5)) or 'forfeit'
|
Simple Fun #203: Strange Coach
|
58fd91af13b0012e8e000010
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/58fd91af13b0012e8e000010
|
7 kyu
|
### Help Kiyo きよ solve her problems LCM Fun!
Kiyo has been given a series of problems and she needs your help to
solve them!
You will be given a two-dimensional array such as the one below.
```
a =
[
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9]
]
Remove everything but odd integers from each sub-array.
Sum the remaining odd integers of each sub-array.
Sum of odds ( a[0] = 1 + 3 + 5 + 7 + 9 ) = 25
Find the Least common multiple of the arrays.
(25, 25, 25, 25, 25, 25, 25, 25, 25)
^ ^
| |
a[0]-----------------------------a[8]
example : lcm( 25, 25, 25, 25, 25, 25, 25, 25, 25 ) = 25
example : lcm( 37, 29, 19, 38, 31, 28, 15, 24, 9 ) = 1592632440
```
Integers are between 0 and 9. Sub-array size is always 9. The number of sub-arrays varies between 9 and 18.
Watch out for non-integers mixed in the arrays. If all arrays are empty return 0.
https://en.wikipedia.org/wiki/Least_common_multiple
|
reference
|
from math import lcm
def kiyo_lcm(a):
return lcm(* (sum(v for v in r if isinstance(v, int) and v % 2) for r in a))
|
Help Kiyo きよ solve her problems LCM Fun!
|
5872bb7faa04282110000124
|
[
"Algorithms",
"Data Structures",
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/5872bb7faa04282110000124
|
6 kyu
|
Create a program that will take in a string as input and, if there are duplicates of more than two alphabetical characters in the string, returns the string with all the extra characters in a bracket.
For example, the input "aaaabbcdefffffffg" should return "aa[aa]bbcdeff[fffff]g"
Please also ensure that the input is a string, and return "Please enter a valid string" if it is not.
|
algorithms
|
import re
def string_parse(string):
return re . sub(r'(.)\1(\1+)', r'\1\1[\2]', string) if isinstance(string, str) else 'Please enter a valid string'
|
Bracket Duplicates
|
5411c4205f3a7fd3f90009ea
|
[
"Strings",
"Regular Expressions",
"Algorithms"
] |
https://www.codewars.com/kata/5411c4205f3a7fd3f90009ea
|
6 kyu
|
No Story
No Description
Only by Thinking and Testing
Look at result of testcase, guess the code!
# #Series:<br>
<a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br>
<a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br>
<a href="http://www.codewars.com/kata/56d931ecc443d475d5000003">03:True or False</a><br>
<a href="http://www.codewars.com/kata/56d93f249c844788bc000002">04:Something capitalized</a><br>
<a href="http://www.codewars.com/kata/56d949281b5fdc7666000004">05:Uniq or not Uniq</a> <br>
<a href="http://www.codewars.com/kata/56d98b555492513acf00077d">06:Spatiotemporal index</a><br>
<a href="http://www.codewars.com/kata/56d9b46113f38864b8000c5a">07:Math of Primary School</a><br>
<a href="http://www.codewars.com/kata/56d9c274c550b4a5c2000d92">08:Math of Middle school</a><br>
<a href="http://www.codewars.com/kata/56d9cfd3f3928b4edd000021">09:From nothingness To nothingness</a><br>
<a href="http://www.codewars.com/kata/56dae2913cb6f5d428000f77">10:Not perfect? Throw away!</a> <br>
<a href="http://www.codewars.com/kata/56db19703cb6f5ec3e001393">11:Welcome to take the bus</a><br>
<a href="http://www.codewars.com/kata/56dc41173e5dd65179001167">12:A happy day will come</a><br>
<a href="http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356">13:Sum of 15(Hetu Luosliu)</a><br>
<a href="http://www.codewars.com/kata/56dd3dd94c9055a413000b22">14:Nebula or Vortex</a><br>
<a href="http://www.codewars.com/kata/56dd927e4c9055f8470013a5">15:Sport Star</a><br>
<a href="http://www.codewars.com/kata/56de38c1c54a9248dd0006e4">16:Falsetto Rap Concert</a><br>
<a href="http://www.codewars.com/kata/56de4d58301c1156170008ff">17:Wind whispers</a><br>
<a href="http://www.codewars.com/kata/56de82fb9905a1c3e6000b52">18:Mobile phone simulator</a><br>
<a href="http://www.codewars.com/kata/56dfce76b832927775000027">19:Join but not join</a><br>
<a href="http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7">20:I hate big and small</a><br>
<a href="http://www.codewars.com/kata/56e0e065ef93568edb000731">21:I want to become diabetic ;-)</a><br>
<a href="http://www.codewars.com/kata/56e0f1dc09eb083b07000028">22:How many blocks?</a><br>
<a href="http://www.codewars.com/kata/56e1161fef93568228000aad">23:Operator hidden in a string</a><br>
<a href="http://www.codewars.com/kata/56e127d4ef93568228000be2">24:Substring Magic</a><br>
<a href="http://www.codewars.com/kata/56eccc08b9d9274c300019b9">25:Report about something</a><br>
<a href="http://www.codewars.com/kata/56ee0448588cbb60740013b9">26:Retention and discard I</a><br>
<a href="http://www.codewars.com/kata/56eee006ff32e1b5b0000c32">27:Retention and discard II</a><br>
<a href="http://www.codewars.com/kata/56eff1e64794404a720002d2">28:How many "word"?</a><br>
<a href="http://www.codewars.com/kata/56f167455b913928a8000c49">29:Hail and Waterfall</a><br>
<a href="http://www.codewars.com/kata/56f214580cd8bc66a5001a0f">30:Love Forever</a><br>
<a href="http://www.codewars.com/kata/56f25b17e40b7014170002bd">31:Digital swimming pool</a><br>
<a href="http://www.codewars.com/kata/56f4202199b3861b880013e0">32:Archery contest</a><br>
<a href="http://www.codewars.com/kata/56f606236b88de2103000267">33:The repair of parchment</a><br>
<a href="http://www.codewars.com/kata/56f6b4369400f51c8e000d64">34:Who are you?</a><br>
<a href="http://www.codewars.com/kata/56f7eb14f749ba513b0009c3">35:Safe position</a><br>
<br>
# #Special recommendation
Another series, innovative and interesting, medium difficulty. People who like to challenge, can try these kata:
<a href="http://www.codewars.com/kata/56c85eebfd8fc02551000281">Play Tetris : Shape anastomosis</a><br>
<a href="http://www.codewars.com/kata/56cd5d09aa4ac772e3000323">Play FlappyBird : Advance Bravely</a><br>
|
games
|
def testit(stg):
try:
return eval("" . join(str(ord(c) - 96) if i % 2 == 0 else "+-*/" [(ord(c) - 1) % 4] for i, c in enumerate(stg)))
except SyntaxError:
return
|
Thinking & Testing : Operator hidden in a string
|
56e1161fef93568228000aad
|
[
"Puzzles",
"Games"
] |
https://www.codewars.com/kata/56e1161fef93568228000aad
|
6 kyu
|
## Background - the Collatz Conjecture:
Imagine you are given a positive integer, `n`, then:
* if `n` is even, calculate: `n / 2`
* if `n` is odd, calculate: `3 * n + 1`
Repeat until your answer is `1`. The Collatz conjecture states that performing this operation repeatedly, you will always eventually reach `1`.
You can try creating Collatz sequences with [this](http://www.codewars.com/kata/5286b2e162056fd0cb000c20) kata. For further information, see the [wiki page](https://en.wikipedia.org/wiki/Collatz_conjecture).
## Now! Your task:
**Given an array of positive integers, return the integer whose Collatz sequence is the longest.**
Example:
```javascript
longestCollatz([2, 4, 3])===3;
```
```python
longest_collatz([2, 4, 3])==3
```
```ruby
longest_collatz([2, 4, 3])==3
```
Explanation: The Collatz sequence for `2` has a length of `1`, the sequence for `4` has a length of `2`, and the sequence for `3` has a length of `7`. So from our array, the integer `3` is the one with the longest Collatz sequence.
Hence, your function should return `3`.
## Note:
There may be more than one answer, i.e. two or more integers produce the longest Collatz sequence, because they happen to have sequences of the same length. **In this case, your function should return the integer that appears first in the array.**
Example:
Given an array: `[2, 5, 32]`, both `5` and `32` have Collatz sequences of length 5. These are also the longest sequences from our array.
In this case, our function returns `5`, because `5` comes before `32` in our array.
|
reference
|
def collatz_length(nm):
cntr = 0
while nm != 1:
nm = 3 * nm + 1 if nm % 2 else nm / / 2
cntr += 1
return cntr
def longest_collatz(input_array):
return max(input_array, key=collatz_length)
|
Integer with the longest Collatz sequence
|
57acc8c3e298a7ae4e0007e3
|
[
"Algorithms",
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/57acc8c3e298a7ae4e0007e3
|
6 kyu
|
## Preface
A collatz sequence, starting with a positive integer<i>n</i>, is found by repeatedly applying the following function to <i>n</i> until <i>n</i> == 1 :
`$f(n) =
\begin{cases}
n/2, \text{ if $n$ is even} \\
3n+1, \text{ if $n$ is odd}
\end{cases}$`
----
A more detailed description of the collatz conjecture may be found [on Wikipedia](http://en.wikipedia.org/wiki/Collatz_conjecture).
## The Problem
Create a function `collatz` that returns a collatz sequence string starting with the positive integer argument passed into the function, in the following form:
"X<sub>0</sub>->X<sub>1</sub>->...->X<sub>N</sub>"
Where X<sub>i</sub> is each iteration of the sequence and N is the length of the sequence.
## Sample Input
```
Input: 4
Output: "4->2->1"
Input: 3
Output: "3->10->5->16->8->4->2->1"
```
Don't worry about invalid input. Arguments passed into the function are guaranteed to be valid integers >= 1.
|
algorithms
|
def collatz_step(n):
if n % 2 == 0:
return n / / 2
else:
return n * 3 + 1
def collatz_seq(n):
while n != 1:
yield n
n = collatz_step(n)
yield 1
def collatz(n):
return '->' . join(str(x) for x in collatz_seq(n))
|
Collatz
|
5286b2e162056fd0cb000c20
|
[
"Number Theory",
"Algorithms"
] |
https://www.codewars.com/kata/5286b2e162056fd0cb000c20
|
6 kyu
|
Write a generator `sequence_gen` ( `sequenceGen` in JavaScript) that, given the first terms of a sequence will generate a (potentially) infinite amount of terms, where each subsequent term is the sum of the previous `x` terms where `x` is the amount of initial arguments (examples of such sequences are the Fibonacci, Tribonacci and Lucas number sequences).
##Examples
```python
fib = sequence_gen(0, 1)
next(fib) = 0 # first term (provided)
next(fib) = 1 # second term (provided)
next(fib) = 1 # third term (sum of first and second terms)
next(fib) = 2 # fourth term (sum of second and third terms)
next(fib) = 3 # fifth term (sum of third and fourth terms)
next(fib) = 5 # sixth term (sum of fourth and fifth terms)
next(fib) = 8 # seventh term (sum of fifth and sixth terms)
trib = sequence_gen(0,1,1)
next(trib) = 0 # first term (provided)
next(trib) = 1 # second term (provided)
next(trib) = 1 # third term (provided)
next(trib) = 2 # fourth term (sum of first, second and third terms)
next(trib) = 4 # fifth term (sum of second, third and fourth terms)
next(trib) = 7 # sixth term (sum of third, fourth and fifth terms)
lucas = sequence_gen(2,1)
[next(lucas) for _ in range(10)] = [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
```
```javascript
fib = sequenceGen(0, 1)
fib.next().value = 0 // first term (provided)
fib.next().value = 1 // second term (provided)
fib.next().value = 1 // third term (sum of first and second terms)
fib.next().value = 2 // fourth term (sum of second and third terms)
fib.next().value = 3 // fifth term (sum of third and fourth terms)
fib.next().value = 5 // sixth term (sum of fourth and fifth terms)
fib.next().value = 8 // seventh term (sum of fifth and sixth terms)
trib = sequenceGen(0,1,1)
trib.next().value = 0 // first term (provided)
trib.next().value = 1 // second term (provided)
trib.next().value = 1 // third term (provided)
trib.next().value = 2 // fourth term (sum of first, second and third terms)
trib.next().value = 4 // fifth term (sum of second, third and fourth terms)
trib.next().value = 7 // sixth term (sum of third, fourth and fifth terms)
lucas = sequenceGen(2,1);
arr = [];
for(i = 0;i < 10;i++){
arr.push(lucas.next().value);
}
arr === [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
```
```ruby
fib = sequence_gen(0, 1) # returns an Enumerator
fib.next = 0 # first term (provided)
fib.next = 1 # second term (provided)
fib.next = 1 # third term (sum of first and second terms)
fib.next = 2 # fourth term (sum of second and third terms)
fib.next = 3 # fifth term (sum of third and fourth terms)
fib.next = 5 # sixth term (sum of fourth and fifth terms)
fib.next = 8 # seventh term (sum of fifth and sixth terms)
trib = sequence_gen(0,1,1) # returns an Enumerator
trib.next = 0 # first term (provided)
trib.next = 1 # second term (provided)
trib.next = 1 # third term (provided)
trib.next = 2 # fourth term (sum of first, second and third terms)
trib.next = 4 # fifth term (sum of second, third and fourth terms)
trib.next = 7 # sixth term (sum of third, fourth and fifth terms)
lucas = sequence_gen(2,1) # returns an Enumerator
lucas.take(10) = [2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
```
**Note:** You can assume you will get at least one argument and any arguments given will be valid (positive or negative integers) so no error checking is needed.
**Note for Ruby users: ** `sequence_gen` should return an Enumerator object.
Any feedback/suggestions would much appreciated.
|
reference
|
def sequence_gen(* args):
values = list(args)
while True:
yield values[0]
values = values[1:] + [sum(values)]
|
Sequence generator
|
55eee789637477c94200008e
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/55eee789637477c94200008e
|
6 kyu
|
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
Given two array of integers(`arr1`,`arr2`). Your task is going to find a pair of numbers(an element in arr1, and another element in arr2), their difference is as big as possible(absolute value); Again, you should to find a pair of numbers, their difference is as small as possible. Return the maximum and minimum difference values by an array: `[ max difference, min difference ]`
For example:
```
Given arr1 = [3,10,5], arr2 = [20,7,15,8]
should return [17,2] because 20 - 3 = 17, 10 - 8 = 2
```
# Note:
- arr1 and arr2 contains only integers(positive, negative or 0);
- arr1 and arr2 may have different lengths, they always has at least one element;
- All inputs are valid.
- This is a simple version, if you want some challenges, [try the challenge version](https://www.codewars.com/kata/583c592928a0c0449d000099).
# Some Examples
```
maxAndMin([3,10,5],[20,7,15,8]) === [17,2]
maxAndMin([3],[20]) === [17,17]
maxAndMin([3,10,5],[3,10,5]) === [7,0]
maxAndMin([1,2,3,4,5],[6,7,8,9,10]) === [9,1]
```
|
reference
|
def max_and_min(arr1, arr2):
diffs = [abs(x - y) for x in arr1 for y in arr2]
return [max(diffs), min(diffs)]
|
The maximum and minimum difference -- Simple version
|
583c5469977933319f000403
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/583c5469977933319f000403
|
6 kyu
|
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
Given two array of integers(`arr1`,`arr2`). Your task is going to find a pair of numbers(an element in arr1, and another element in arr2), their difference is as big as possible(absolute value); Again, you should to find a pair of numbers, their difference is as small as possible. Return the maximum and minimum difference values by an array: `[ max difference, min difference ]`
For example:
```
Given arr1 = [3,10,5], arr2 = [20,7,15,8]
should return [17,2] because 20 - 3 = 17, 10 - 8 = 2
```
# Note:
- arr1 and arr2 contains only integers(positive, negative or 0);
- arr1 and arr2 may have different lengths, they always has at least one element;
- All inputs are valid.
- This is a challenge version, Please optimize your algorithm to avoid time out ;-)
- If you feel difficult, please [try the simple version](https://www.codewars.com/kata/583c5469977933319f000403).
# About testcases
- Basic test: 5 testcases
- Random test1: 100 testcases, arr1 and arr2 contains 1-20 elements
- Random test2: 300 testcases, arr1 and arr2 contains 10000 elements
# Some Examples
```javascript
maxAndMin([3,10,5],[20,7,15,8]) === [17,2]
maxAndMin([3],[20]) === [17,17]
maxAndMin([3,10,5],[3,10,5]) === [7,0]
maxAndMin([1,2,3,4,5],[6,7,8,9,10]) === [9,1]
```
```python
max_and_min([3,10,5],[20,7,15,8]) # -> (17,2)
max_and_min([3],[20]) # -> (17,17)
max_and_min([3,10,5],[3,10,5]) # -> (7,0)
max_and_min([1,2,3,4,5],[6,7,8,9,10]) # -> (9,1)
```
|
algorithms
|
def max_and_min(seq1, seq2):
# your code here
seq1 . sort()
seq2 . sort()
if abs(seq1[- 1] - seq2[0]) > abs(seq1[0] - seq2[- 1]):
max_difference = abs(seq1[- 1] - seq2[0])
else:
max_difference = abs(seq1[0] - seq2[- 1])
i, j = 0, 0
while i < len(seq1) and j < len(seq2):
d = abs(seq1[i] - seq2[j])
if i == 0 and j == 0:
min_difference = d
else:
if d < min_difference:
min_difference = d
if seq1[i] < seq2[j]:
i += 1
elif seq1[i] > seq2[j]:
j += 1
else:
break
return max_difference, min_difference
|
The maximum and minimum difference -- Challenge version
|
583c592928a0c0449d000099
|
[
"Algorithms"
] |
https://www.codewars.com/kata/583c592928a0c0449d000099
|
5 kyu
|
<b><a href="https://en.wikipedia.org/wiki/Hofstadter_sequence">Hofstadter sequences</a></b> are a family of related integer sequences, among which the first ones were described by an American professor <a href="https://en.wikipedia.org/wiki/Douglas_Hofstadter">Douglas Hofstadter</a> in his book <a href="https://en.wikipedia.org/wiki/G%C3%B6del,_Escher,_Bach">Gödel, Escher, Bach</a>.
### Task
Today we will be implementing the rather chaotic recursive sequence of integers called <b>Hofstadter Q</b>.<br>
<b>The Hofstadter Q</b> is defined as:<br><br>
<img style="background:white;padding:5px;" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/1477baacadb4a3c0f00a1159ded4e8815972f415"><br>
As the author states in the aforementioned book:<br><br><blockquote>It is reminiscent of the Fibonacci definition in that each new value is a sum of two
previous values-but not of the immediately previous two values. Instead, the two
immediately previous values tell how far to count back to obtain the numbers to be added
to make the new value.</blockquote>
The function produces the starting sequence:
`1, 1, 2, 3, 3, 4, 5, 5, 6 . . .`
<b>Test info:</b> 100 random tests, <b>n</b> is always positive<br><br>
Good luck!
|
algorithms
|
def hofstadter_Q(n):
try:
return hofstadter_Q . seq[n]
except IndexError:
ans = hofstadter_Q(n - hofstadter_Q(n - 1)) + \
hofstadter_Q(n - hofstadter_Q(n - 2))
hofstadter_Q . seq . append(ans)
return ans
hofstadter_Q . seq = [None, 1, 1]
|
Hofstadter Q
|
5897cdc26551af891c000124
|
[
"Recursion",
"Algorithms"
] |
https://www.codewars.com/kata/5897cdc26551af891c000124
|
6 kyu
|
# Task
Miss X has only two combs in her possession, both of which are old and miss a tooth or two. She also has many purses of different length, in which she carries the combs. The only way they fit is horizontally and without overlapping. Given teeth' positions on both combs, find the minimum length of the purse she needs to take them with her.
It is guaranteed that there is at least one tooth at each end of the comb.
- Note, that the combs can not be rotated/reversed.
# Example
For `comb1 = "*..*" and comb2 = "*.*"`, the output should be `5`
Although it is possible to place the combs like on the first picture, the best way to do this is either picture 2 or picture 3.

# Input/Output
- `[input]` string `comb1`
A comb is represented as a string. If there is an asterisk ('*') in the ith position, there is a tooth there. Otherwise there is a dot ('.'), which means there is a missing tooth on the comb.
Constraints: 1 ≤ comb1.length ≤ 10.
- `[input]` string `comb2`
The second comb is represented in the same way as the first one.
Constraints: 1 ≤ comb2.length ≤ 10.
- `[output]` an integer
The minimum length of a purse Miss X needs.
|
games
|
def combs(a, b):
return min(mesh(a, b), mesh(b, a))
def mesh(a, b):
for i in range(len(a)):
for j, k in zip(a[i:], b):
if j + k == '**':
break
else:
return max(i + len(b), len(a))
return len(a) + len(b)
|
Simple Fun #53: Combs
|
58898b50b832f8046a0000ec
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58898b50b832f8046a0000ec
|
5 kyu
|
## Task
Pac-Man got lucky today! Due to minor performance issue all his enemies have frozen. Too bad Pac-Man is not brave enough to face them right now, so he doesn't want any enemy to see him.
Given a gamefield of size `N` x `N`, Pac-Man's position(`PM`) and his enemies' positions(`enemies`), your task is to count the number of coins he can collect without being seen.
An enemy can see a Pac-Man if they are standing on the same row or column.
It is guaranteed that no enemy can see Pac-Man on the starting position. There is a coin on each empty square (i.e. where there is no Pac-Man or enemy).
## Example
For `N = 4, PM = [3, 0], enemies = [[1, 2]]`, the result should be `3`.
```
Let O represent coins, P - Pac-Man and E - enemy.
OOOO
OOEO
OOOO
POOO
```
Pac-Man cannot cross row 1 and column 2.
He can only collect coins from points `(2, 0), (2, 1) and (3, 1)`, like this:
```
x is the points that Pac-Man can collect the coins.
OOOO
OOEO
xxOO
PxOO
```
## Input/Output
- `[input]` integer `N`
The field size.
- `[input]` integer array `PM`
Pac-Man's position (pair of integers)
- `[input]` 2D integer array `enemies`
Enemies' positions (array of pairs)
- `[output]` an integer
Number of coins Pac-Man can collect.
# More PacMan Katas
- [Play PacMan: Devour all](https://www.codewars.com/kata/575c29d5fcee86cb8b000136)
- [Play PacMan 2: The way home](https://www.codewars.com/kata/575ed46e23891f67d90000d8)
|
algorithms
|
def pac_man(size, pacman, enemies):
px, py = pacman
mx, my, Mx, My = - 1, - 1, size, size
for x, y in enemies:
if x < px and x > mx:
mx = x
if y < py and y > my:
my = y
if x > px and x < Mx:
Mx = x
if y > py and y < My:
My = y
return (Mx - mx - 1) * (My - my - 1) - 1
|
Simple Fun #155: Pac-Man
|
58ad0e0a154165a1c80000ea
|
[
"Algorithms",
"Puzzles"
] |
https://www.codewars.com/kata/58ad0e0a154165a1c80000ea
|
5 kyu
|
## Task
Compute the [Mobius function](https://en.wikipedia.org/wiki/M%C3%B6bius_function) `$\mu (n)$` for a given value of `n`.
For a given `n`, the Mobius function is equal to:
- `0` if `n` is divisible by the square of any prime number. For example `n` = `4, 8, 9` are all divisible by the square of at least one prime number.
- `1` if `n` is **not** divisible by the square of any prime numbers, **and** has an **even number of prime factors**. For example `n` = `6, 10, 21` satisfy these conditions (e.g. `21 = 3 * 7` so it has an even number (2) of distinct prime factors and is not divisible by the square of any prime numbers).
- `-1` otherwise. For example `n` = `3, 5, 7, 30`.
## Input/Output
You will be given an integer `n`; you must return an integer - the Mobius function of `n`.
**Performance requirements:**
`2 <= n <= 1e12`
|
games
|
def mobius(n):
sP, p = set(), 2
while n > 1 and p <= n * * .5:
while not n % p:
if p in sP:
return 0
sP . add(p)
n / /= p
p += 1 + (p != 2)
return (- 1) * * ((len(sP) + (n != 1)) % 2)
|
Simple Fun #142: Mobius function
|
58aa5d32c9eb04d90b000107
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58aa5d32c9eb04d90b000107
|
6 kyu
|
## The story you are about to hear is true
Our cat, <a href="https://www.flickr.com/photos/tachyon/tags/balor/">Balor</a>, sadly died of cancer in 2015.
While he was alive, the three neighborhood cats <a href="https://www.flickr.com/photos/tachyon/tags/lou/">Lou</a>, <a href="https://www.flickr.com/photos/tachyon/tags/mustachecat/">Mustache Cat</a>, and <a href="https://www.flickr.com/photos/tachyon/tags/raoul/">Raoul</a> all recognized our house and yard as Balor's territory, and would behave respectfully towards him and each other when they would visit.
But after Balor died, gradually each of these three neighborhood cats began trying to claim his territory as their own, trying to drive the others away by growling, yowling, snarling, chasing, and even fighting, when one came too close to another, and no human was right there to distract or extract one of them before the situation could escalate.
It is sad that these otherwise-affectionate animals, who had spent many afternoons peacefully sitting and/or lying near Balor and each other on our deck or around our yard, would turn on each other like that. However, sometimes, if they are far enough away from each other, especially on a warm day when all they really want to do is pick a spot in the sun and lie in it, they will ignore each other, and once again there will be a <a href="https://www.google.com/search?q=Peaceable+Kingdom&source=lnms&tbm=isch">Peaceable Kingdom</a>.
## Your Mission
In this, the first and simplest of a planned trilogy of cat katas :-), all you have to do is determine whether the distances between any visiting cats are large enough to make for a peaceful afternoon, or whether there is about to be an altercation someone will need to deal with by carrying one of them into the house or squirting them with water or what have you.
As input your function will receive a list of strings representing the yard as a grid, and an integer representing the minimum distance needed to prevent problems (considering the cats' current states of sleepiness). A point with no cat in it will be represented by a "-" dash. Lou, Mustache Cat, and Raoul will be represented by an upper case L, M, and R respectively. At any particular time all three cats may be in the yard, or maybe two, one, or even none.
If the number of cats in the yard is one or none, or if the distances between all cats are at least the minimum distance, your function should return True/true/TRUE (depending on what language you're using), but if there are two or three cats, and the distance between at least two of them is smaller than the minimum distance, your function should return False/false/FALSE.
## Some examples
(The yard will be larger in the random test cases, but a smaller yard is easier to see and fit into the instructions here.)
In this first example, there is only one cat, so your function should return True.
```
["------------",
"------------",
"-L----------",
"------------",
"------------",
"------------"], 10
```
In this second example, Mustache Cat is at the point yard[1][3] and Raoul is at the point yard[4][7] -- a distance of 5, so because the distance between these two points is smaller than the specified minimum distance of 6, there will be trouble, and your function should return False.
```
["------------",
"---M--------",
"------------",
"------------",
"-------R----",
"------------"], 6
```
In this third example, Lou is at yard[0][11], Raoul is at yard[1][2], and Mustache Cat at yard[5][2]. The distance between Lou and Raoul is 9.05538513814, the distance between Raoul and Mustache Cat is 4, and the distance between Mustache Cat and Lou is 10.295630141 -- all greater than or equal to the specified minimum distance of 4, so the three cats will nap peacefully, and your function should return True.
```
["-----------L",
"--R---------",
"------------",
"------------",
"------------",
"--M---------"], 4
```
Have fun!
|
reference
|
from itertools import combinations
from math import hypot
def peaceful_yard(yard, d):
cats = ((i, j) for i, r in enumerate(yard)
for j, c in enumerate(r) if c in 'LMR')
return all(hypot(q[0] - p[0], q[1] - p[1]) >= d for p, q in combinations(cats, 2))
|
Cat Kata, Part 1
|
5869848f2d52095be20001d1
|
[
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/5869848f2d52095be20001d1
|
6 kyu
|
You are asked to write a simple cypher that rotates every character (in range [a-zA-Z], special chars will be ignored by the cipher) by 13 chars. As an addition to the original ROT13 cipher, this cypher will also cypher numerical digits ([0-9]) with 5 chars.
Example:
"The quick brown fox jumps over the 2 lazy dogs"
will be cyphered to:
"Gur dhvpx oebja sbk whzcf bire gur 7 ynml qbtf"
Your task is to write a ROT13.5 (ROT135) method that accepts a string and encrypts it.
Decrypting is performed by using the same method, but by passing the encrypted string again.
Note: when an empty string is passed, the result is also empty.
When passing your succesful algorithm, some random tests will also be applied. Have fun!
|
algorithms
|
trans = "abcdefghijklmnopqrstuvwxyz" * 2
trans += trans . upper() + "0123456789" * 2
def ROT135(input):
output = []
for c in input:
if c . isalpha():
c = trans[trans . index(c) + 13]
elif c . isdigit():
c = trans[trans . index(c) + 5]
output . append(c)
return "" . join(output)
|
Simple ROT13.5 cypher
|
5894986e2ddc8f6805000036
|
[
"Algorithms",
"Fundamentals",
"Ciphers",
"Cryptography"
] |
https://www.codewars.com/kata/5894986e2ddc8f6805000036
|
6 kyu
|
# Task
Consider a sequence of numbers a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub>, in which an element is equal to the sum of squared digits of the previous element. The sequence ends once an element that has already been in the sequence appears again.
Given the first element `a0`, find the length of the sequence.
# Example
For a0 = 16, the output should be `9`
Here's how elements of the sequence are constructed:
a0 = 16
a1 = 1<sup>2</sup> + 6<sup>2</sup> = 37
a2 = 3<sup>2</sup> + 7<sup>2</sup> = 58
a3 = 5<sup>2</sup> + 8<sup>2</sup> = 89
a4 = 8<sup>2</sup> + 9<sup>2</sup> = 145
a5 = 1<sup>2</sup> + 4<sup>2</sup> + 5<sup>2</sup> = 42
a6 = 4<sup>2</sup> + 2<sup>2</sup> = 20
a7 = 2<sup>2</sup> + 0<sup>2</sup> = 4
a8 = 4<sup>2</sup> = 16, which has already occurred before (a0)
Thus, there are 9 elements in the sequence.
For a0 = 103, the output should be `4`
The sequence goes as follows: 103 -> 10 -> 1 -> 1, 4 elements altogether.
# Input/Output
- `[input]` integer `a0`
First element of a sequence, positive integer.
Constraints: 1 ≤ a0 ≤ 650.
- `[output]` an integer
|
games
|
def square_digits_sequence(n):
a, seq = n, set()
while a not in seq:
seq . add(a)
a = sum(int(d) * * 2 for d in str(a))
return len(seq) + 1
|
Simple Fun #23: Square Digits Sequence
|
5886d65e427c27afeb0000c1
|
[
"Puzzles"
] |
https://www.codewars.com/kata/5886d65e427c27afeb0000c1
|
6 kyu
|
# Task
You've intercepted an encrypted message, and you are really curious about its contents. You were able to find out that the message initially contained only lowercase English letters, and was encrypted with the following cipher:
Let all letters from 'a' to 'z' correspond to the numbers from 0 to 25, respectively.
The number corresponding to the ith letter of the encrypted message is then equal to the sum of numbers corresponding to the first i letters of the initial unencrypted message modulo 26.
Now that you know how the message was encrypted, implement the algorithm to decipher it.
# Example
For `message = "taiaiaertkixquxjnfxxdh", `
the output should be `"thisisencryptedmessage"`.
The initial message `"thisisencryptedmessage"` was encrypted as follows:
```
letter 0: t -> 19 -> t;
letter 1: th -> (19 + 7) % 26 -> 0 -> a;
letter 2: thi -> (19 + 7 + 8) % 26 -> 8 -> i;
etc.
```
# Input/Output
- `[input]` string `message`
An encrypted string containing only lowercase English letters.
Constraints: `1 ≤ message.length ≤ 200.`
- `[output]` a string
A decrypted message.
|
games
|
from itertools import pairwise, chain
def cipher26(message):
return '' . join(chr((y - x) % 26 + 97) for x, y in pairwise(chain([97], map(ord, message))))
|
Simple Fun #46: Cipher26
|
588847702ffea657ba00001b
|
[
"Puzzles"
] |
https://www.codewars.com/kata/588847702ffea657ba00001b
|
6 kyu
|
# Task
Suppose there are `n` people standing in a circle and they are numbered 1 through n in order.
Person 1 starts off with a sword and kills person 2. He then passes the sword to the next person still standing, in this case person 3. Person 3 then uses the sword to kill person 4, and passes it to person 5. This pattern continues around and around the circle until just one person remains.
What is the number of this person?
# Example:
For `n = 5`, the result should be `3`.
```
1 kills 2, passes to 3.
3 kills 4, passes to 5.
5 kills 1, passes to 3.
3 kills 5 and wins.```
# Input/Output
- `[input]` integer `n`
The number of people. 1 through n standing in a circle.
`1 <= n <= 1e9`
- `[output]` an integer
The index of the last person standing.
|
games
|
def circle_slash(n):
return int(bin(n)[3:] + '1', 2)
|
Simple Fun #140: Circle Slash
|
58a6ac309b5762b7aa000030
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58a6ac309b5762b7aa000030
|
6 kyu
|
Your task is to find all the elements of an array that are non consecutive.
A number is non consecutive if it is not exactly one larger than the previous element in the array. The first element gets a pass and is never considered non consecutive.
~~~if:javascript,haskell,swift
Create a function named `allNonConsecutive`
~~~
~~~if:python,rust
Create a function name `all_non_consecutive`
~~~
E.g., if we have an array `[1,2,3,4,6,7,8,15,16]` then `6` and `15` are non-consecutive.
~~~if:javascript,python
You should return the results as an array of objects with two values `i: <the index of the non-consecutive number>` and `n: <the non-consecutive number>`.
~~~
~~~if:haskell,swift,rust
You should return the results as an array of tuples with two values: the index of the non-consecutive number and the non-consecutive number.
~~~
E.g., for the above array the result should be:
```javascript
[
{i: 4, n:6},
{i: 7, n:15}
]
```
```python
[
{'i': 4, 'n': 6},
{'i': 7, 'n': 15}
]
```
```haskell
[ ( 4, 6 )
, ( 7, 15 )
]
```
```swift
[
( 4, 6 ),
( 7, 15 )
]
```
```rust
[
( 4, 6 ),
( 7, 15 )
]
```
If the whole array is consecutive or has one element then return an empty array.
The array elements will all be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive and/or negetive and the gap could be larger than one.
If you like this kata, maybe try this one next: https://www.codewars.com/kata/represent-array-of-numbers-as-ranges
|
reference
|
def all_non_consecutive(a):
return [{"i": i, "n": y} for i, (x, y) in enumerate(zip(a, a[1:]), 1) if x != y - 1]
|
Find all non-consecutive numbers
|
58f8b35fda19c0c79400020f
|
[
"Arrays",
"Fundamentals"
] |
https://www.codewars.com/kata/58f8b35fda19c0c79400020f
|
7 kyu
|
Your task in this Kata is to emulate text justify right in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width.
Here are the rules:
- Use spaces to fill in the gaps on the left side of the words.
- Each line should contain as many words as possible.
- Use '\n' to separate lines.
- Gap between words can't differ by more than one space.
- Lines should end with a word not a space.
- '\n' is not included in the length of a line.
- Last line should not contain '\n'
Example with width=30:
```
Bacon ipsum dolor amet
excepteur ut kevin burgdoggen,
shankle cupim dolor officia
ground round id ullamco
deserunt nisi. Commodo tail
qui salami, brisket boudin
tri-tip. Labore flank laboris,
cow enim proident aliqua sed
hamburger consequat. Sed
consequat ut non bresaola
capicola shoulder excepteur
veniam, bacon kevin. Pastrami
shank laborum est excepteur
non eiusmod bresaola flank in
nostrud. Corned beef ex pig do
kevin filet mignon in irure
deserunt ipsum qui duis short
loin. Beef ribs dolore
meatball officia rump fugiat
in enim corned beef non est.
```
If you enjoyed this one and want more of a challenge try https://www.codewars.com/kata/text-align-justify/python
If you like bacon ipsum https://baconipsum.com
|
algorithms
|
import textwrap
def align_right(text, width):
return "\n" . join([l . rjust(width, ' ') for l in textwrap . wrap(text, width)])
|
Text align right
|
583601518d3b9b8d3b0000c9
|
[
"Algorithms",
"Strings"
] |
https://www.codewars.com/kata/583601518d3b9b8d3b0000c9
|
6 kyu
|
# Task
Given a sorted array of integers `A`, find such an integer x that the value of `abs(A[0] - x) + abs(A[1] - x) + ... + abs(A[A.length - 1] - x)`
is the smallest possible (here abs denotes the `absolute value`).
If there are several possible answers, output the smallest one.
# Example
For `A = [2, 4, 7]`, the output should be `4`.
# Input/Output
- `[input]` integer array `A`
A non-empty array of integers, sorted in ascending order.
Constraints:
`1 ≤ A.length ≤ 200,`
`-1000000 ≤ A[i] ≤ 1000000.`
- `[output]` an integer
|
games
|
from statistics import median_low as absolute_values_sum_minimization
|
Simple Fun #72: Absolute Values Sum Minimization
|
589414918afa367b4800015c
|
[
"Puzzles"
] |
https://www.codewars.com/kata/589414918afa367b4800015c
|
6 kyu
|
#Detail
[Countdown](https://en.wikipedia.org/wiki/Countdown_(game_show) is a British game show with number and word puzzles. The letters round consists of the contestant picking 9 shuffled letters - either picking from the vowel pile or the consonant pile. The contestants are given 30 seconds to try to come up with the longest English word they can think of with the available letters - letters can not be used more than once unless there is another of the same character.
#Task
Given an uppercase 9 letter string, ```letters```, find the longest word that can be made with some or all of the letters. The preloaded array ```words``` (or ```$words``` in Ruby) contains a bunch of uppercase words that you will have to loop through. Only return the longest word; if there is more than one, return the words of the same lengths in alphabetical order. If there are no words that can be made from the letters given, return ```None/nil/null```.
##Examples
```
letters = "ZZZZZZZZZ"
longest word = None
letters = "POVMERKIA",
longest word = ["VAMPIRE"]
letters = "DVAVPALEM"
longest word = ["VAMPED", "VALVED", "PALMED"]
```
|
reference
|
def longest_word(letters):
unscrambled = []
for word in words:
if set(word). issubset(set(letters)) and all(word . count(l) <= letters . count(l) for l in set(letters)):
unscrambled . append(word)
return [x for x in unscrambled if len(x) == max(map(len, unscrambled))] or None
|
Countdown - Longest Word
|
57a4c85de298a795210002da
|
[
"Strings",
"Arrays",
"Fundamentals"
] |
https://www.codewars.com/kata/57a4c85de298a795210002da
|
6 kyu
|
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/56ffd817140fcc0c3900099b)
## Task
Your apple has a virus, and the infection is spreading.
The ```apple``` is a two-dimensional array, containing strings ```"V"``` (virus) and ```"A"``` (uninfected parts). For each hour, the infection spreads one space up, down, left and right.
Input: 2D array ```apple``` and number ```n``` (n >= 0).
Output: 2D array showing the ```apple``` after ```n``` hours.
### Series:
- [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9)
- [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008)
- [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009)
- [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1)
- [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3)
- [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e)
- [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4)
- [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947)
- [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1)
- [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b)
- [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba)
- [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba)
- [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742)
- [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c)
- [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048)
- [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633)
- [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a)
- [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594)
- [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9)
- [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001)
- [Tidy up the room](http://www.codewars.com/kata/5703ace6e55d30d3e0001029)
- [Waiting for a Bus](http://www.codewars.com/kata/57070eff924f343280000015)
|
games
|
def infect_apple(apple, n):
A = {(r, c): v for r, row in enumerate(apple) for c, v in enumerate(row)}
for _ in range(n):
for n in {(r, c) for r, c in A if any(A . get((r + rr, c + cc), '') == 'V' for rr, cc in [(1, 0), (- 1, 0), (0, 1), (0, - 1)])}:
A[n] = 'V'
return [[A[(r, c)] for c in range(len(apple[0]))] for r in range(len(apple))]
|
Coding 3min: Virus in Apple
|
5700af83d1acef83fd000048
|
[
"Puzzles",
"Games"
] |
https://www.codewars.com/kata/5700af83d1acef83fd000048
|
6 kyu
|
Let's do a simple approximation of the integral of a continuous function.
In this kata, we will implement: *left_riemann(f, n, a, b)*
In the test, we will pass a function that takes a single float argument to compute the value of the function. Your job is to approximate the integral of that function on the closed interval [a,b] with n rectangles. You will use the left hand rule. For a better explanation of the assigment visit the wikipedia page on riemann sums linked below:
*http://en.wikipedia.org/wiki/Riemann_sum*
- f will always take a single float argument
- f will always be a "nice" function, don't worry about NaN
- n will always be a natural number (0, N]
- b > a
- and n will be chosen appropriately given the length of [a, b] (as in I will not have step sizes smaller than machine epsilon)
|
reference
|
def left_riemann(f, n: int, a: float, b: float) - > float:
dx = (b - a) / n
return dx * sum(f(a + i * dx) for i in range(n))
|
riemann sums I (left side rule)
|
5562ab5d6dca8009f7000050
|
[
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/5562ab5d6dca8009f7000050
|
6 kyu
|
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
Give you two number `m`(a positive integer with 5 digits) and `n`(a positive odd integer >= 3), make a `n*n` matrix pattern using the digits of `m`:
```
Main diagonal and Vice diagonal fill in the first digit
At this time the matrix is divided into four triangular areas
The top area fill in the second digit
The bottom area fill in the third digit
The left area fill in the fourth digit
The right area fill in the fifth digit
```
like this:
```
When m = 12345 and n = 5, the matrix is:
1 2 2 2 1
4 1 2 1 5
4 4 1 5 5
4 1 3 1 5
1 3 3 3 1
```
Note: The result is a multiline string; Each row separated by "\n"; Each digit separated by a space; All inputs are valid.
# Some examples:
```
makeMatrix(67890,3) should return:
6 7 6
9 6 0
6 8 6
makeMatrix(13579,7) should return:
1 3 3 3 3 3 1
7 1 3 3 3 1 9
7 7 1 3 1 9 9
7 7 7 1 9 9 9
7 7 1 5 1 9 9
7 1 5 5 5 1 9
1 5 5 5 5 5 1
```
|
games
|
def make_matrix(m: int, n: int) - > str:
m = str(m)
matrix = []
for i in range(n):
st = []
for j in range(n):
if i == j or i + j == n - 1:
st . append(m[0])
elif i + j > n - 1 and i > j:
st . append(m[2])
elif i + j < n - 1 and i > j: # ok
st . append(m[3])
elif i + j > n - 1 and i < j: # ok
st . append(m[4])
else:
st . append(m[1])
st = ' ' . join(st) + '\n'
matrix . append(st)
return '' . join(matrix)[: - 1]
|
Complete the matrix pattern
|
582c01ad3fd1cc5736000348
|
[
"Puzzles",
"Algorithms",
"Matrix"
] |
https://www.codewars.com/kata/582c01ad3fd1cc5736000348
|
6 kyu
|
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
Give you two number `rows` , `columns` and a string `str`. Returns a `rows x columns` table pattern and fill in the `str`(each grid fill in a char, the length of str is always less than or equals to the total numbers of grids):
```
If rows = 4 and columns = 4, str = "Hello World!"
The pattern should be a 4x4 table like this:
+---+---+---+---+
| H | e | l | l | From left to right
+---+---+---+---+
| o | | W | o | and from top to bottom
+---+---+---+---+
| r | l | d | ! | each row separated by "\n"
+---+---+---+---+
| | | | |
+---+---+---+---+
```
# Some examples:
```
pattern(3, 3, "codewars") should return:
+---+---+---+
| c | o | d |
+---+---+---+
| e | w | a |
+---+---+---+
| r | s | |
+---+---+---+
pattern(4, 3, "Nice pattern") should return:
+---+---+---+
| N | i | c |
+---+---+---+
| e | | p |
+---+---+---+
| a | t | t |
+---+---+---+
| e | r | n |
+---+---+---+
pattern(3, 4, "Nice pattern") should return:
+---+---+---+---+
| N | i | c | e |
+---+---+---+---+
| | p | a | t |
+---+---+---+---+
| t | e | r | n |
+---+---+---+---+
```
|
games
|
def pattern(rows, cols, s):
txt, border, row = iter(s), '+' + '---+' * cols, '|' + ' {} |' * cols
def linerAndSep(
_): return f" { row . format ( * ( next ( txt , ' ' ) for _ in range ( cols )) ) } \n { border } "
return f' { border } \n' + '\n' . join(map(linerAndSep, range(rows)))
|
Complete the table pattern
|
5827e2efc983ca6f230000e0
|
[
"ASCII Art",
"Puzzles"
] |
https://www.codewars.com/kata/5827e2efc983ca6f230000e0
|
6 kyu
|
Figure out and complete the very pointless function.
[THIS KATA HAS BEEN RETIRED. I WOULD DELETE IT BUT IT SEEMS ONLY ADMIN CAN DO IT.]
|
games
|
def pointless(* args):
return "rickastley"
|
What is the point? [THIS KATA HAS BEEN RETIRED. ATTEMPT AT OWN PERIL]
|
55ed10a402a0c6e3c3000021
|
[
"Puzzles",
"Games"
] |
https://www.codewars.com/kata/55ed10a402a0c6e3c3000021
|
6 kyu
|
Given an array, return the reversed version of the array (a different kind of reverse though), you reverse portions of the array, you'll be given a length argument which represents the length of each portion you are to reverse.
E.g
```javascript
selReverse([1,2,3,4,5,6], 2)
//=> [2,1, 4,3, 6,5]
```
if after reversing some portions of the array and the length of the remaining portion in the array is not up to the length argument, just reverse them.
```javascript
selReverse([2,4,6,8,10,12,14,16], 3)
//=> [6,4,2, 12,10,8, 16,14]
```
`selReverse(array, length)`
- array - array to reverse
- length - length of each portion to reverse
Note : if the length argument exceeds the array length, reverse all of them, if the length argument is zero do not reverse at all.
|
algorithms
|
def sel_reverse(arr, l):
return [elt for i in range(0, len(arr), l) for elt in arr[i: i + l][:: - 1]] if l != 0 else arr
|
Selective Array Reversing
|
58f6000bc0ec6451960000fd
|
[
"Algorithms",
"Logic",
"Arrays"
] |
https://www.codewars.com/kata/58f6000bc0ec6451960000fd
|
6 kyu
|
In programming you know the use of the logical negation operator (**!**), it reverses the meaning of a condition.
```javascript
!false = true
!!false = false
```
Your task is to complete the function 'negationValue()' that takes a string of negations with a value and returns what the value would be if those negations were applied to it.
```javascript
negationValue("!", false); //=> true
negationValue("!!!!!", true); //=> false
negationValue("!!", []); //=> true
```
```python
negation_value("!", False) #=> True
negation_value("!!!!!", True) #=> False
negation_value("!!", []) #=> False
```
```julia
negationvalue("!", false) #=> true
negationvalue("!!!!!", true) #=> false
```
```dart
negationValue("!", false); //=> true
negationValue("!!!!!", true); //=> false
```
```php
negationValue("!", false); //=> true
negationValue("!!!!!", true); //=> false
negationValue("!!", []); //=> false
```
Do not use the `eval()` function or the `Function()` constructor in JavaScript.
Note: Always return a boolean value, even if there're no negations.
|
reference
|
def negation_value(s, x):
return len(s) % 2 ^ bool(x)
|
Negation of a Value
|
58f6f87a55d759439b000073
|
[
"Logic",
"Algorithms",
"Fundamentals"
] |
https://www.codewars.com/kata/58f6f87a55d759439b000073
|
7 kyu
|
Kontti language is a finnish word play game.
You add `-kontti` to the end of each word and then swap their characters until and including the first vowel ("aeiouy");
For example the word `tame` becomes `kome-tantti`; `fruity` becomes `koity-fruntti` and so on.
If no vowel is present, the word stays the same.
Write a string method that turns a sentence into kontti language!
|
reference
|
import re
def kontti(s):
return " " . join([re . sub("([^aeiouy]*[aeiouy])(.*)", r"ko\2-\1ntti", w, flags=re . I) for w in s . split()])
|
Kontti Language
|
570e1271e5c9a0cf2f000d11
|
[
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/570e1271e5c9a0cf2f000d11
|
6 kyu
|
# Task
A lock has `n` buttons in it, numbered from `1 to n`. To open the lock, you have to press all buttons in some order, i.e. a key to the lock is a permutation of the first `n` integers. If you push the right button in the right order, it will be pressed into the lock. Otherwise all pressed buttons will pop out. When all buttons are pressed into the lock, it opens.
Your task is to calculate the number of times you've got to push buttons in order to open the lock in the `worst-case scenario`.
# Example
For `n = 3`, the result should be `7`.
```
Let's assume the right order is 3-2-1.
In the worst-case scenario, we press the buttons:
Press 1, wrong, button 1 pop out
Press 2, wrong, button 2 pop out
Press 3, right, button 3 pressed in
Press 1, wrong, button 1,3 pop out
Press 3, right, button 3 pressed in
Press 2, right, button 2 pressed in
Press 1, right, button 1 pressed in
We pressed button total 7 times.```
For `n = 4`, the result should be `14`.
```
Let's assume the right order is 4-3-2-1.
In the worst-case scenario, we press the buttons:
Press 1, wrong, button 1 pop out
Press 2, wrong, button 2 pop out
Press 3, wrong, button 3 pop out
Press 4, right, button 4 pressed in
Press 1, wrong, button 1,4 pop out
Press 4, right, button 4 pressed in
Press 2, wrong, button 2,4 pop out
Press 4, right, button 4 pressed in
Press 3, right, button 3 pressed in
Press 1, wrong, button 1,3,4 pop out
Press 4, right, button 4 pressed in
Press 3, right, button 3 pressed in
Press 2, right, button 2 pressed in
Press 1, right, button 1 pressed in
We pressed button total 14 times.```
# Input/Output
- `[input]` integer `n`
The number of buttons in the lock.
`0 < n ≤ 2000`
- `[output]` an integer
The number of times you've got to push buttons in the `worst-case scenario`.
|
games
|
def press_button(n):
return (n * n + 5) * n / 6
|
Simple Fun #169: Press Button
|
58b3bb9347117f4aa7000096
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58b3bb9347117f4aa7000096
|
6 kyu
|
Our AAA company is in need of some software to help with logistics: you will be given the width and height of a map, a list of x coordinates and a list of y coordinates of the supply points, starting to count from the top left corner of the map as 0.
Your goal is to return a two dimensional array/list with every item having the value of the distance of the square itself from the closest supply point expressed as a simple integer.
Quick examples:
```python
logistic_map(3,3,[0],[0])
#returns
#[[0,1,2],
# [1,2,3],
# [2,3,4]]
logistic_map(5,2,[0,4],[0,0])
#returns
#[[0,1,2,1,0],
# [1,2,3,2,1]]
```
```ruby
logistic_map(3,3,[0],[0])
#returns
#[[0,1,2],
# [1,2,3],
# [2,3,4]]
logistic_map(5,2,[0,4],[0,0])
#returns
#[[0,1,2,1,0],
# [1,2,3,2,1]]
```
```javascript
logisticMap(3,3,[0],[0])
//returns
//[[0,1,2],
// [1,2,3],
// [2,3,4]]
logisticMap(5,2,[0,4],[0,0])
//returns
//[[0,1,2,1,0],
// [1,2,3,2,1]]
```
```csharp
LogisticMap(3,3,{0},{0})
//returns
//{{0,1,2},
// {1,2,3},
// {2,3,4}}
LogisticMap(5,2,{0,4},{0,0})
//returns
//{{0,1,2,1,0},
// {1,2,3,2,1}}
```
```dart
logisticMap(3,3,[0],[0])
//returns
//[[0,1,2],
// [1,2,3],
// [2,3,4]]
logisticMap(5,2,[0,4],[0,0])
//returns
//[[0,1,2,1,0],
// [1,2,3,2,1]]
```
Remember that our company is operating with trucks, not drones, so you can simply use <a href="https://en.wikipedia.org/wiki/Taxicab_geometry">Manhattan distance</a>. If supply points are present, they are going to be within the boundaries of the map; if no supply point is present on the map, just return `None`/`nil`/`null` in every cell.
```python
logistic_map(2,2,[],[])
#returns
#[[None,None],
# [None,None]]
```
```ruby
logistic_map(2,2,[],[])
#returns
#[[None,None],
# [None,None]]
```
```javascript
logisticMap(2,2,[],[])
//returns
//[[None,None],
// [None,None]]
```
```csharp
LogisticMap(2,2,{},{})
//returns
//{{-1,-1},
// {-1,-1}}
```
```dart
logisticMap(2,2,[],[])
//returns
//[[null,null],
// [null,null]]
```
**Note:** this one is taken (and a bit complicated) from a problem a real world AAA company [whose name I won't tell here] used in their interview. It was done by a friend of mine. It is nothing that difficult and I assume it is their own version of the FizzBuzz problem, but consider candidates were given about 30 mins to solve it.
|
algorithms
|
def manhattan_dist(x1, y1, x2, y2):
return abs(x1 - x2) + abs(y1 - y2)
def logistic_map(width, height, xs, ys):
field = [[None] * width for _ in range(height)]
if xs and ys:
for row in range(height):
for col in range(width):
field[row][col] = min(manhattan_dist(col, row, xi, yi)
for xi, yi in zip(xs, ys))
return field
|
Logistic Map
|
5779624bae28070489000146
|
[
"Graph Theory",
"Matrix",
"Arrays",
"Lists",
"Algorithms"
] |
https://www.codewars.com/kata/5779624bae28070489000146
|
6 kyu
|
MongoDB is a noSQL database which uses the concept of a document, rather than a table as in SQL. Its popularity is growing.
As in any database, you can create, read, update, and delete elements. But in constrast to SQL, when you create an element, a new field `_id` is created. This field is unique and contains some information about the time the element was created, id of the process that created it, and so on. More information can be found in the [MongoDB documentation](http://docs.mongodb.org/manual/reference/object-id/) (which you have to read in order to implement this Kata).
So let us implement the following helper which will have 2 methods:
- one which verifies that the string is a valid Mongo ID string, and
- one which finds the timestamp from a MongoID string
*Note:*
If you take a close look at a Codewars URL, you will notice each kata's id (the `XXX` in `http://www.codewars.com/dojo/katas/XXX/train/javascript`) is really similar to MongoDB's ids, which brings us to the conjecture that this is the database powering Codewars.
## Examples
The verification method will return `true` if an element provided is a valid Mongo string and `false` otherwise:
```javascript
Mongo.isValid('507f1f77bcf86cd799439011') // true
Mongo.isValid('507f1f77bcf86cz799439011') // false
Mongo.isValid('507f1f77bcf86cd79943901') // false
Mongo.isValid('111111111111111111111111') // true
Mongo.isValid(111111111111111111111111) // false
Mongo.isValid('507f1f77bcf86cD799439011') // false (we arbitrarily only allow lowercase letters)
```
```python
Mongo.is_valid('507f1f77bcf86cd799439011') # True
Mongo.is_valid('507f1f77bcf86cz799439011') # False
Mongo.is_valid('507f1f77bcf86cd79943901') # False
Mongo.is_valid('111111111111111111111111') # True
Mongo.is_valid(111111111111111111111111) # False
Mongo.is_valid('507f1f77bcf86cD799439011') # False (we arbitrarily only allow lowercase letters)
```
```ruby
Mongo.is_valid('507f1f77bcf86cd799439011') # true
Mongo.is_valid('507f1f77bcf86cz799439011') # false
Mongo.is_valid('507f1f77bcf86cd79943901') # false
Mongo.is_valid('111111111111111111111111') # true
Mongo.is_valid(111111111111111111111111) # false
Mongo.is_valid('507f1f77bcf86cD799439011') # false (we arbitrarily only allow lowercase letters)
```
The timestamp method will return a date/time object from the timestamp of the Mongo string and false otherwise:
```javascript
// Mongo.getTimestamp should return a Date object
Mongo.getTimestamp('507f1f77bcf86cd799439011') // Wed Oct 17 2012 21:13:27 GMT-0700 (Pacific Daylight Time)
Mongo.getTimestamp('507f1f77bcf86cz799439011') // false
Mongo.getTimestamp('507f1f77bcf86cd79943901') // false
Mongo.getTimestamp('111111111111111111111111') // Sun Jan 28 1979 00:25:53 GMT-0800 (Pacific Standard Time)
Mongo.getTimestamp(111111111111111111111111) // false
```
```python
# Mongo.get_timestamp should return a datetime object
Mongo.get_timestamp('507f1f77bcf86cd799439011') # Wed Oct 17 2012 21:13:27 GMT-0700 (Pacific Daylight Time)
Mongo.get_timestamp('507f1f77bcf86cz799439011') # False
Mongo.get_timestamp('507f1f77bcf86cd79943901') # False
Mongo.get_timestamp('111111111111111111111111') # Sun Jan 28 1979 00:25:53 GMT-0800 (Pacific Standard Time)
Mongo.get_timestamp(111111111111111111111111) # False
```
```ruby
# Mongo.get_timestamp should return a datetime object
Mongo.get_timestamp('507f1f77bcf86cd799439011') # Wed Oct 17 2012 21:13:27 GMT-0700 (Pacific Daylight Time)
Mongo.get_timestamp('507f1f77bcf86cz799439011') # false
Mongo.get_timestamp('507f1f77bcf86cd79943901') # false
Mongo.get_timestamp('111111111111111111111111') # Sun Jan 28 1979 00:25:53 GMT-0800 (Pacific Standard Time)
Mongo.get_timestamp(111111111111111111111111) # false
```
When you will implement this correctly, you will not only get some points, but also would be able to check creation time of all the kata here :-)
|
reference
|
from datetime import datetime
import re
class Mongo (object):
@ classmethod
def is_valid(cls, s):
return isinstance(s, str) and bool(re . match(r'[0-9a-f]{24}$', s))
@ classmethod
def get_timestamp(cls, s):
return cls . is_valid(s) and datetime . fromtimestamp(int(s[: 8], 16))
|
Mongodb ObjectID
|
52fefe6cb0091856db00030e
|
[
"MongoDB",
"Regular Expressions",
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/52fefe6cb0091856db00030e
|
5 kyu
|
Primes that have only odd digits are pure odd digits primes, obvious but necessary definition.
Examples of pure odd digit primes are: 11, 13, 17, 19, 31...
If a prime has only one even digit does not belong to pure odd digits prime, no matter the amount of odd digits that may have.
Create a function, only_oddDigPrimes(), that receive any positive integer n, and output a list like the one below:
[number pure odd digit primes below n, largest pure odd digit prime smaller than n, smallest pure odd digit prime higher than n]
Let's see some cases:
```python
only_oddDigPrimes(20) ----> [7, 19, 31]
///7, beacause we have seven pure odd digit primes below 20 and are 3, 5, 7, 11, 13, 17, 19
19, because is the nearest prime of this type to 20
31, is the first pure odd digit that we encounter after 20///
only_oddDigPrimes(40) ----> [9, 37, 53]
```
In the case that n, the given value, is a pure odd prime, should be counted with the found primes and search for the immediately below and the immediately after.
Happy coding!!
|
reference
|
from bisect import bisect_right as bisect
ODDS, n = set("13579"), 150000
sieve, PODP = [0] * (n + 1), []
for i in range(2, n + 1):
if not sieve[i]:
for j in range(i * * 2, n + 1, i):
sieve[j] = 1
if set(str(i)) <= ODDS:
PODP . append(i)
def only_oddDigPrimes(n):
idx = bisect(PODP, n)
return [idx, PODP[idx - 1], PODP[idx + (PODP[idx] == n)]]
|
Pure odd digits primes
|
55e0a2af50adf50699000126
|
[
"Fundamentals",
"Algorithms",
"Mathematics",
"Data Structures"
] |
https://www.codewars.com/kata/55e0a2af50adf50699000126
|
6 kyu
|
# Task
A range-collapse representation of an array of integers looks like this: `"1,3-6,8"`, where `3-6` denotes the range from `3-6`, i.e. `[3,4,5,6]`.
Hence `"1,3-6,8"` = `[1,3,4,5,6,8]`. Some other range-collapse representations of `[1,3,4,5,6,8]` include `"1,3-5,6,8", "1,3,4,5,6,8", etc`.
Each range is written in the following format `"a-b"`, where `a < b`, and the whole range must belong to the array in an increasing order.
You are given an array `arr`. Your task is to find the number of different range-collapse representations of the given array.
# Example
For `arr = [1,3,4,5,6,8]`, the result should be `8`.
```
"1,3-4,5,6,8"
"1,3-4,5-6,8"
"1,3-5,6,8"
"1,3-6,8"
"1,3,4-5,6,8"
"1,3,4-6,8"
"1,3,4,5-6,8"
"1,3,4,5,6,8"```
# Input/OutPut
- `[input]` integer array `arr`
sorted array of different positive integers.
- `[output]` an integer
the number of different range-collapse representations of the given array.
|
games
|
def descriptions(arr):
return 2 * * sum(a + 1 == b for a, b in zip(arr, arr[1:]))
|
Simple Fun #120: Range Collapse Representation
|
589d6bc33b368ea992000035
|
[
"Puzzles"
] |
https://www.codewars.com/kata/589d6bc33b368ea992000035
|
6 kyu
|
# Task
Fred Mapper is considering purchasing some land in Louisiana to build his house on. In the process of investigating the land, he learned that the state of Louisiana is actually shrinking by 50 square miles each year, due to erosion caused by the Mississippi River. Since Fred is hoping to live in this house the rest of his life, he needs to know if his land is going to be lost to erosion.
After doing more research, Fred has learned that the land that is being lost forms a semicircle. This semicircle is part of a circle centered at (0,0), with the line that bisects the circle being the `x` axis. Locations below the `x` axis are in the water. The semicircle has an area of 0 at the beginning of year 1. (Semicircle illustrated in the Figure.)

Given two coordinates `x` and `y`, your task is to calculate that Fred Mapper's house will begin eroding in how many years.
Note:
1. No property will appear exactly on the semicircle boundary: it will either be inside or outside.
2. All locations are given in miles.
3. (0,0) will not be given.
# Example
For `x = 1, y = 1`, the result should be `1`.
After 1 year, Fred Mapper's house will begin eroding.
For `x = 25, y = 0`, the result should be `20`.
After 20 year, Fred Mapper's house will begin eroding.
# Input/Output
- `[input]` integer `x`
The X coordinates of the land Fred is considering. It will be an integer point numbers measured in miles.
`-100 <= x <= 100`
- `[input]` integer `y`
The Y coordinates of the land Fred is considering. It will be an integer point numbers measured in miles.
`0 <= y <= 100`
- `[output]` an integer
The first year (start from 1) this point will be within the semicircle AT THE END OF YEAR.
|
algorithms
|
from math import ceil, pi
def does_fred_need_houseboat(x, y):
return ceil(pi * (x * * 2 + y * * 2) / 100)
|
Simple Fun #187: Does Fred Need A Houseboat?
|
58bf72b02d1c7c18d9000127
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58bf72b02d1c7c18d9000127
|
7 kyu
|
## Task
`zipWith` ( or `zip_with` ) takes a function and two arrays and zips the arrays together, applying the function to every pair of values.
The function value is one new array.
If the arrays are of unequal length, the output will only be as long as the shorter one.
(Values of the longer array are simply not used.)
Inputs should not be modified.
## Examples
```c
zip_with(pow,4,{10,10,10,10},4,{0,1,2,3},*z,*a) =>
a = {1,10,100,1000}
z = 4
zip_with(max,3,{2,7,5},5,{8,7,4,1,3},*z,*a) =>
a = {8,7,5}
z = 3
```
```javascript
zipWith( Math.pow, [10,10,10,10], [0,1,2,3] ) => [1,10,100,1000]
zipWith( Math.max, [1,4,7,1,4,7], [4,7,1,4,7,1] ) => [4,7,7,4,7,7]
zipWith( function(a,b) { return a+b; }, [0,1,2,3], [0,1,2,3] ) => [0,2,4,6] // Both forms are valid
zipWith( (a,b) => a+b, [0,1,2,3], [0,1,2,3] ) => [0,2,4,6] // Both are functions
```
```python
zip_with( pow, [10,10,10,10], [0,1,2,3] ) => [1,10,100,1000]
zip_with( max, [1,4,7,1,4,7], [4,7,1,4,7,1]) => [4,7,7,4,7,7]
def add(a,b): return a+b; # or from operator import add
zip_with( add, [0,1,2,3], [0,1,2,3] ) => [0,2,4,6] # Both forms are valid
zip_with( lambda a,b: a+b, [0,1,2,3], [0,1,2,3] ) => [0,2,4,6] # Both are functions
```
```rust
zip_with(i32::pow, &[10,10,10,10], [0,1,2,3]) => [1,10,100,1000]
zip_with(i32::max, &[1,4,7,1,4,7], [4,7,1,4,7,1]) => [4,7,7,4,7,7]
fn add(a: i32, b: i32) -> i32 { a + b } // or i32::add
zip_with(add, &[0,1,2,3], &[0,1,2,3]) => [0,2,4,6] // Both forms are valid
zip_with(|a,b| a + b, &[0,1,2,3], &[0,1,2,3]) => [0,2,4,6] // Both are functions
```
```ocaml
zip_with ( * ) [10; 10; 10; 10] [0; 1; 2; 3] (* = [0; 10; 20; 30] *)
zip_with max [1; 4; 7; 1; 4; 7] [4; 7; 1; 4; 7; 1] (* = [4; 7; 7; 4; 7; 7] *)
zip_with (+) [0; 1; 2; 3] [0; 1; 2; 3] (* = [0; 2; 4; 6] *)
zip_with (fun a b -> a + b) [0; 1; 2; 3] [0; 1; 2; 3] (* = [0; 2; 4; 6] *)
```
## Input validation
Assume all input is valid.
|
algorithms
|
def zip_with(fn, a1, a2):
return list(map(fn, a1, a2))
|
zipWith
|
5825792ada030e9601000782
|
[
"Lists",
"Arrays",
"Functional Programming",
"Algorithms"
] |
https://www.codewars.com/kata/5825792ada030e9601000782
|
6 kyu
|
# Introduction
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">
The wave (known as the Mexican wave in the English-speaking world outside North America) is an example of metachronal rhythm achieved in a packed stadium when successive groups of spectators briefly stand, yell, and raise their arms. Immediately upon stretching to full height, the spectator returns to the usual seated position.
The result is a wave of standing spectators that travels through the crowd, even though individual spectators never move away from their seats. In many large arenas the crowd is seated in a contiguous circuit all the way around the sport field, and so the wave is able to travel continuously around the arena; in discontiguous seating arrangements, the wave can instead reflect back and forth through the crowd. When the gap in seating is narrow, the wave can sometimes pass through it. Usually only one wave crest will be present at any given time in an arena, although simultaneous, counter-rotating waves have been produced. (Source <a href="https://en.wikipedia.org/wiki/Wave_(audience)">Wikipedia</a>)
</pre>
# Task
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">
In this simple Kata your task is to create a function that turns a string into a Mexican Wave. You will be passed a string and you must return that string in an array where an uppercase letter is a person standing up.
</pre>
# Rules
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">
1. The input string will always be lower case but maybe empty.<br>
2. If the character in the string is whitespace then pass over it as if it was an empty seat
</pre>
# Example
```lua
wave("hello") => {"Hello", "hEllo", "heLlo", "helLo", "hellO"}
```
```go
wave("hello") => []string{"Hello", "hEllo", "heLlo", "helLo", "hellO"}
```
```racket
(wave "hello") ; returns '("Hello" "hEllo" "heLlo" "helLo" "hellO")
```
```javascript
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
```
```ruby
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
```
```python
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
```
```rust
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
```
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58663693b359c4a6560001d6" target="_blank">Maze Runner</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58693bbfd7da144164000d05" target="_blank">Scooby Doo Puzzle</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/7KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/586a1af1c66d18ad81000134" target="_blank">Driving License</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/586c0909c1923fdb89002031" target="_blank">Connect 4</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/586e6d4cb98de09e3800014f" target="_blank">Vending Machine</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/587136ba2eefcb92a9000027" target="_blank">Snakes and Ladders</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58a848258a6909dd35000003" target="_blank">Mastermind</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58b2c5de4cf8b90723000051" target="_blank">Guess Who?</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58ce88427e6c3f41c2000087" target="_blank">Am I safe to drive?</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58f5c63f1e26ecda7e000029" target="_blank">Mexican Wave</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/58fdcc51b4f81a0b1e00003e" target="_blank">Pigs in a Pen</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/590300eb378a9282ba000095" target="_blank">Hungry Hippos</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/5904be220881cb68be00007d" target="_blank">Plenty of Fish in the Pond</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/590adadea658017d90000039" target="_blank">Fruit Machine</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/591eab1d192fe0435e000014" target="_blank">Car Park Escape</a></span>
|
reference
|
def wave(str):
return [str[: i] + str[i]. upper() + str[i + 1:] for i in range(len(str)) if str[i]. isalpha()]
|
Mexican Wave
|
58f5c63f1e26ecda7e000029
|
[
"Arrays",
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/58f5c63f1e26ecda7e000029
|
6 kyu
|
Clients place orders to a stockbroker as strings. The order can be simple or multiple or empty.
Type of a simple order: Quote/white-space/Quantity/white-space/Price/white-space/Status
where Quote is formed of non-whitespace character,
Quantity is an int,
Price a double (with mandatory decimal point "." ),
Status is represented by the letter B (buy) or the letter S (sell).
#### Example:
`"GOOG 300 542.0 B"`
A multiple order is the concatenation of simple orders with a comma between each.
#### Example:
`"ZNGA 1300 2.66 B, CLH15.NYM 50 56.32 B, OWW 1000 11.623 B, OGG 20 580.1 B"`
or
`"ZNGA 1300 2.66 B,CLH15.NYM 50 56.32 B,OWW 1000 11.623 B,OGG 20 580.1 B"`
To ease the stockbroker your task is to produce a string of type
`"Buy: b Sell: s"`
where b and s are 'double'
formatted with no decimal, b representing the total price of bought stocks and s the total price of sold stocks.
#### Example:
`"Buy: 294990 Sell: 0"`
Unfortunately sometimes clients make mistakes. When you find mistakes in orders, you must pinpoint these badly formed orders
and produce a string of type:
`"Buy: b Sell: s; Badly formed nb: badly-formed 1st simple order ;badly-formed nth simple order ;"`
where nb is the number of badly formed simple orders, b representing the total price of bought stocks
with correct simple order and s the total price of sold stocks with correct simple order.
#### Examples:
`"Buy: 263 Sell: 11802; Badly formed 2: CLH16.NYM 50 56 S ;OWW 1000 11 S ;"`
`"Buy: 100 Sell: 56041; Badly formed 1: ZNGA 1300 2.66 ;"`
#### Notes:
- If the order is empty, Buy is 0 and Sell is 0 hence the return is: "Buy: 0 Sell: 0".
- Due to Codewars whitespace differences will not always show up in test results.
- With Golang (and maybe others) you can use a format with "%.0f" for "Buy" and "Sell".
|
reference
|
import re
def balance_statement(lst):
bad_formed, prices = [], {'B': 0, 'S': 0}
for order in filter(None, lst . split(', ')):
if not re . match('\S+ \d+ \d*\.\d+ (B|S)', order):
bad_formed . append(order + ' ;')
else:
_, quantity, price, status = order . split()
prices[status] += int(quantity) * float(price)
ret = "Buy: %.0f Sell: %.0f" % (prices['B'], prices['S'])
if bad_formed:
ret += "; Badly formed %d: %s" % (len(bad_formed), '' . join(bad_formed))
return ret
|
Ease the StockBroker
|
54de3257f565801d96001200
|
[
"Fundamentals",
"Strings"
] |
https://www.codewars.com/kata/54de3257f565801d96001200
|
6 kyu
|
Write a program that performs a search for solutions to a word game. The goal of the game is to find sets of five words that share a vowel alternation. E.g., one solution to the game might be the words:
['last', 'lest', 'list', 'lost', 'lust']
This list above is a valid solution instance since the vowels `'a'`, `'e'`, `'i'`, `'o'`, and `'u'` occur in the same positions between the consonant clusters `'l'` and `'st'`.
Your program should return a list of all solutions (like the list above) given a list of words to search through.
Note that **order matters**. If you prefer to use sets for book-keeping purposes, that is fine, but you will need to sort your list of solutions, and each solution set itself.
This is easy in Python:
solutions = [set(['last', 'lest', 'list', 'lost', 'lust']),
set(['bill', 'bull', 'bell', 'ball', 'boll'])]
sorted_soultions = sorted(sorted(solution) for solution in solutions)
sorted_solutions == [['ball', 'bell', 'bill', 'boll', 'bull'],
['last', 'lest', 'list', 'lost', 'lust']]
For the sake of simplificiation, you may assume that the words in the list you are searching over are unique.
|
games
|
def find_solutions(words):
vowels = set('aeiou')
seen = {}
for w in words:
for s in seen:
if len(w) == len(s) and sum((len(ltrs) > 1) * (1 if ltrs <= vowels else 2) for ltrs in map(set, zip(* seen[s], w))) == 1:
seen[s]. add(w)
break
else:
seen[w] = {w}
return sorted(sorted(v) for v in seen . values() if len(v) >= 5)
|
Vowel Alternations
|
54221c16dda52609b1000ffb
|
[
"Puzzles"
] |
https://www.codewars.com/kata/54221c16dda52609b1000ffb
|
5 kyu
|
In this kata, you have to implement two functions: `isCheck` and `isMate`.
Both of the functions are given two parameters: `player` signifies whose turn it is (0: white, 1: black) and `pieces` is an array of objects (***PHP:*** Array of associative arrays) describing a piece and its location in the following fashion:
```csharp
public enum FigureType { Pawn, King, Queen, Rook, Knight, Bishop}
//struct to make it convenient to work with cells
public struct Pos
{
public readonly sbyte X;
public readonly sbyte Y;
public Pos(sbyte y, sbyte x);
public Pos(int y, int x);
public override bool Equals(object obj);
public override int GetHashCode();
}
public class Figure
{
public FigureType Type { get; }
public byte Owner { get; }
public Pos Cell { get; set; }
public Pos? PrevCell { get; }
public Figure(FigureType type, byte owner, Pos cell, Pos? prevCell = null);
}
```
```javascript
{
piece: string, // pawn, rook, knight, bishop, queen or king
owner: int, // 0 for white or 1 for black
x: int, // 0-7 where 0 is the leftmost column (or "A")
y: int, // 0-7 where 0 is the top row (or "8" in the board below)
prevX: int, // 0-7, presents this piece's previous x, only given if this is the piece that was just moved
prevY: int // 0-7, presents this piece's previous y, only given if this is the piece that was just moved
}
```
```typescript
{
piece: 'king' | 'queen' | 'bishop' | 'knight' | 'rook' | 'pawn'
owner: 0 | 1, // 0 for white or 1 for black
x: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7, // 0 is the leftmost column (or "A")
y: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7, // 0 is the top row (or "8" in the board below)
prevX: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7, // presents this piece's previous x, only given if this is the piece that was just moved
prevY: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 // presents this piece's previous y, only given if this is the piece that was just moved
}
```
```coffeescript
{
piece: string, # pawn, rook, knight, bishop, queen or king
owner: int, # 0 for white or 1 for black
x: int, # 0-7 where 0 is the leftmost column (or "A")
y: int, # 0-7 where 0 is the top row (or "8" in the board below)
prevX: int, # 0-7, presents this piece's previous x, only given if this is the piece that was just moved
prevY: int # 0-7, presents this piece's previous y, only given if this is the piece that was just moved
}
```
```php
# Array of associative arrays
[
"piece" : string, # pawn, rook, knight, bishop, queen or king
"owner" : int, # 0 for white or 1 for black
"x" : int, # 0-7 where 0 is the leftmost column (or "A" in the board below)
"y" : int, # 0-7 where 0 is the top row (or "8" in the board below)
"prevX" : int # 0-7, presents this piece's previous x, only given if this is the piece that was just moved
"prevY" : int, # 0-7, presents this piece's previous y, only given if this is the piece that was just moved
]
# For example: $pieces[0]["piece"] might return "rook"
```
```python
{
'piece': string, # pawn, rook, knight, bishop, queen or king
'owner': int, # 0 for white or 1 for black
'x': int, # 0-7 where 0 is the leftmost column (or "A")
'y': int, # 0-7 where 0 is the top row (or "8" in the board below)
'prevX': int, # 0-7, presents this piece's previous x, only given if this is the piece that was just moved
'prevY': int # 0-7, presents this piece's previous y, only given if this is the piece that was just moved
}
```
```java
PieceConfig[] pieces, whose properties are:
{ 'piece': string, // pawn, rook, knight, bishop, queen or king
'owner': int, // 0 for white or 1 for black
'x': int, // 0-7 where 0 is the leftmost column (or "A")
'y': int, // 0-7 where 0 is the top row (or "8" in the board below)
'prevX': int, // 0-7, presents this piece's previous x, only given if this is the piece that was just moved
'prevY': int} // 0-7, presents this piece's previous y, only given if this is the piece that was just moved
All fields are private and final.
You may find below the usefull available methods/informations about the PieceConfig instances:
class PieceConfig {
public PieceConfig(final String piece, final int owner, final int x, final int y, final int prevX, final int prevY)
public PieceConfig(final String piece, final int owner, final int x, final int y)
public String getPiece()
public int getOwner()
public int getX()
public int getY()
public boolean hasPrevious()
public int getPrevX() // will throw a RuntimeException if invoked for an object that do not have informations about its previous move.
public int getPrevY() // will throw a RuntimeException if invoked for an object that do not have informations about its previous move.
@Override public int hashCode()
@Override public String toString() //return string formated as :"piece: king, owner: 0, x: 0, y: 4" (plus prevX and prevY if needed)
@Override public boolean equals(Object other)
```
Top (meaning y equals 0 or 1) is black's home and the bottom (y equals 6 or 7) is white's home, so the initial board looks like this (the numbers in the parentheses correspond to those used in the pieces objects fields):
<table style='width: 215px; background-color:black; font-size: 10px; border-collapse: collapse;'><tr><td style='line-height: 1; padding: 0; height:25px; width: 40px;'></td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(0)<br>A</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(1)<br>B</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(2)<br>C</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(3)<br>D</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(4)<br>E</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(5)<br>F</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(6)<br>G</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(7)<br>H</td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(0) 8</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♜</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♞</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♝</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♛</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♚</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♝</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♞</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♜</td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(1) 7</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♟</td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(2) 6</td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(3) 5</td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(4) 4</td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(5) 3</td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(6) 2</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♙</td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>(7) 1</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♖</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♘</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♗</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♕</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♔</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♗</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♘</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♖</td></tr></table><br><font size=2><i>Note: if you do not see correctly the pieces on the board, please install the "Deja Vu Sans" font.</i></font>
<br>
You can assume that the input is a valid chess position. The pieces are not in any particular order.
`isCheck` should return an array of the objects that threaten the king or `false` if not threatened (***Java:*** return a `Set<Piece>` object of the threatening pieces, or an empty set if none are found).
(***PHP:*** return an array of associative arrays, false if none are found.)
`isMate` should return `true` if the player can't make a move that takes his king out of check, and `false` if he can make such a move, or if the position is not a check.
To help with debugging, a function `outputBoard(pieces)` (***Java:*** static method `OutputBoard.print(pieces)`, ***PHP:*** `outputBoard($pieces)`, ***C#:*** static method void `Figures.OutputBoard(IList<Figure> figures)`) is provided and will log to console the whole board with all pieces on it. The piece with prevX and prevY properties will appear light gray on the board in the coordinates it used to occupy (Python currently does not support unicode chess symbols, so the standard piece abbreviations KPNBRQ are used. Same representation is used in Java and PHP).
A comprehensive list of how each piece moves can be found at http://en.wikipedia.org/wiki/Chess#Movement.
Note 1: these functions should work in a noninvasive fashion - don't change the contents of the array or values of the pieces contained within it.
Note 2: the tests might not imply explicitly why a certain position is or isn't a check or mate. If your code fails a test, you have to be able to analyze the situation and see which pieces are to blame. If all else fails, try asking for help at the discussion board.
|
algorithms
|
# Shortest and fastest solution, passing under 120ms
from copy import deepcopy
directions = {
'rook': [(1, 0), (- 1, 0), (0, 1), (0, - 1)],
'knight': [(- 2, 1), (- 2, - 1), (- 1, 2), (- 1, - 2), (1, 2), (1, - 2), (2, 1), (2, - 1)],
'bishop': [(- 1, - 1), (- 1, 1), (1, - 1), (1, 1)],
'queen': [(1, 0), (- 1, 0), (0, 1), (0, - 1), (- 1, - 1), (- 1, 1), (1, - 1), (1, 1)],
}
def is_empty(pieces, targets, x, y):
if any((piece['x'] == x and piece['y'] == y) for piece in pieces if not any(piece == target for target in targets)) or not (- 1 < x < 8 and - 1 < y < 8):
return False
return True
def possible_movements(pieces, piece, player, target=None, strat='attack'):
positions = []
x, y = piece['x'], piece['y']
direc = 1 if player == 0 else - 1
if piece['piece'] == 'pawn' and strat == 'attack':
positions . append((x - 1, y + direc))
positions . append((x + 1, y + direc))
elif piece['piece'] == 'pawn' and strat == 'defence':
positions . append((x, y + direc))
if y == max(0, - direc * 7) + direc:
positions . append((x, y + 2 * direc))
elif piece['piece'] == 'knight':
for k in directions['knight']:
nexX, nexY = x + k[0], y + k[1]
if is_empty(pieces, target, nexX, nexY):
positions . append((nexX, nexY))
elif piece['piece'] == 'king':
for k in directions['queen']:
nexX, nexY = x + k[0], y + k[1]
if is_empty(pieces, target, nexX, nexY):
positions . append((nexX, nexY))
else:
for k in directions[piece['piece']]:
nexX, nexY = x + k[0], y + k[1]
while is_empty(pieces, target, nexX, nexY):
positions . append((nexX, nexY))
nexX += k[0]
nexY += k[1]
return positions
def can_move(pieces, player, piece, pos, target, en_passant=0):
direc = (1 if player else - 1) if en_passant else 0
new_pieces = deepcopy(pieces)
i = new_pieces . index(piece)
new_pieces[i]['x'] = pos[0]
new_pieces[i]['y'] = pos[1] + direc
for p in target:
new_pieces . remove(p)
return False if isCheck(new_pieces, player) else True
def isCheck(pieces, player):
king = [p for p in pieces if p['owner']
== player and p['piece'] == 'king'][0]
enemy_pieces = [p for p in pieces if p['owner']
!= player and p['piece'] != 'king']
result = []
for piece in enemy_pieces:
if (king['x'], king['y']) in possible_movements(pieces, piece, player, target=[king]):
result . append(piece)
return result or False
def isMate(pieces, player):
attackers = isCheck(pieces, player)
if attackers == False:
return False
king = [p for p in pieces if p['owner']
== player and p['piece'] == 'king'][0]
friends = [p for p in pieces if p['owner']
== player and p['piece'] != 'king']
enemy_pieces = [p for p in pieces if p['owner']
!= player and p['piece'] != 'king']
# King can escape
for pos in possible_movements(pieces, king, player, target=enemy_pieces):
at = [p for p in enemy_pieces if p['x'] == pos[0] and p['y'] == pos[1]]
if can_move(pieces, player, king, pos, at):
return False
# if king can't escape he can only be saved if attacked by one and only one enemy piece, chess knowledge
if len(attackers) == 1:
att = attackers[0]
x1, y1, x2, y2 = king['x'], king['y'], att['x'], att['y']
direc = 1 if player == 1 else - 1
for piece in friends:
# King can be saved en passant
if att['piece'] == 'pawn' and piece['piece'] == 'pawn' and att['y'] == piece['y'] == max(0, - direc * 7) + direc * 4 and abs(att['x'] - piece['x']) == 1:
if can_move(pieces, player, piece, (x2, y2), attackers, en_passant=1):
return False
# Attacker can be eliminated by friend piece
if (x2, y2) in possible_movements(pieces, piece, 1 - player, target=attackers):
if can_move(pieces, player, piece, (x2, y2), attackers):
return False
# attack can be intercepted by friend piece
if not (att['piece'] == 'pawn' or att['piece'] == 'knight'):
for pos in possible_movements(pieces, piece, 1 - player, target=attackers, strat='defence'):
x3, y3 = pos[0], pos[1]
if (y2 - y1) * x3 + (x2 * y1 - x1 * y2) == y3 * (x2 - x1) and min(x1, x2) < x3 < max(x1, x2) and min(y1, y2) < y3 < max(y1, y2):
if can_move(pieces, player, piece, (x3, y3), []):
return False
return True
|
Check and Mate?
|
52fcc820f7214727bc0004b7
|
[
"Logic",
"Arrays",
"Data Structures",
"Games",
"Algorithms"
] |
https://www.codewars.com/kata/52fcc820f7214727bc0004b7
| null |
"The Shell Game" involves cups upturned on a playing surface, with a ball placed underneath one of them. The index of the cups are swapped around multiple times. After that the players will try to find which cup contains the ball.
Your task is as follows. Given the cup that the ball starts under, and list of swaps, return the location of the ball at the end. Cups are given like array/list indices.
For example, given the starting position `0` and the swaps `[(0, 1), (1, 2), (1, 0)]`:
* The first swap moves the ball from `0` to `1`
* The second swap moves the ball from `1` to `2`
* The final swap doesn't affect the position of the ball.
So
```haskell
findTheBall 0 [(0, 1), (2, 1), (0, 1)] == 2
```
```clojure
(= (find-the-ball 0 [[0 1] [2 1] [0 1]]) 2)
```
```ruby
swaps = [[0,1], [1,2], [1, 0]]
find_the_ball(0, swaps) == 2
```
```javascript
swaps = [[0,1], [1,2], [1, 0]]
find_the_ball(0, swaps) == 2
```
```python
find_the_ball(0, [(0, 1), (2, 1), (0, 1)]) == 2
```
There aren't necessarily only three cups in this game, but there will be at least two. You can assume all swaps are valid, and involve two distinct indices.
|
reference
|
def find_the_ball(start, swaps):
pos = start
for (a, b) in swaps:
if a == pos:
pos = b
elif b == pos:
pos = a
return pos
|
The Shell Game
|
546a3fea8a3502302a000cd2
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/546a3fea8a3502302a000cd2
|
6 kyu
|
DNA is a biomolecule that carries genetic information. It is composed of four different building blocks, called nucleotides: adenine (A), thymine (T), cytosine (C) and guanine (G). Two DNA strands join to form a double helix, whereby the nucleotides of one strand bond to the nucleotides of the other strand at the corresponding positions. The bonding is only possible if the nucleotides are complementary: A always pairs with T, and C always pairs with G.
Due to the asymmetry of the DNA, every DNA strand has a direction associated with it. The two strands of the double helix run in opposite directions to each other, which we refer to as the 'up-down' and the 'down-up' directions.
Write a function `checkDNA` that takes in two DNA sequences as strings, and checks if they are fit to form a fully complementary DNA double helix. The function should return a Boolean `true` if they are complementary, and `false` if there is a sequence mismatch (Example 1 below).
Note:
- All sequences will be of non-zero length, and consisting only of `A`, `T`, `C` and `G` characters.
- All sequences **will be given in the up-down direction**.
- The two sequences to be compared can be of different length. If this is the case and one strand is entirely bonded by the other, and there is no sequence mismatch between the two (Example 2 below), your function should still return `true`.
- If both strands are only partially bonded (Example 3 below), the function should return `false`.
Example 1:
```javascript
seq1 = 'GTCTTAGTGTAGCTATGCATGC'; // NB up-down
seq2 = 'GCATGCATAGCTACACTACGAC'; // NB up-down
checkDNA (seq1, seq2);
// --> false
// Because there is a sequence mismatch at position 4:
// (seq1) up-GTCTTAGTGTAGCTATGCATGC-down
// ||| ||||||||||||||||||
// (seq2) down-CAGCATCACATCGATACGTACG-up
```
Example 2:
```javascript
seq1 = 'GCGCTGCTAGCTGATCGA'; // NB up-down
seq2 = 'ACGTACGATCGATCAGCTAGCAGCGCTAC'; // NB up-down
checkDNA (seq1, seq2);
// --> true
// Because one strand is entirely bonded by the other:
// (seq1) up-GCGCTGCTAGCTGATCGA-down
// ||||||||||||||||||
// (seq2) down-CATCGCGACGATCGACTAGCTAGCATGCA-up
```
Example 3:
```javascript
seq1 = 'CGATACGAACCCATAATCG'; // NB up-down
seq2 = 'CTACACCGGCCGATTATGG'; // NB up-down
checkDNA (seq1, seq2);
// --> false
// Because both strands are only partially bonded:
// (seq1) up-CGATACGAACCCATAATCG-down
// |||||||||
// (seq2) down-GGTATTAGCCGGCCACATC-up
```
---
#### If you enjoyed this kata, check out also my other DNA kata: [**Longest Repeated DNA Motif**](http://www.codewars.com/kata/longest-repeated-dna-motif)
|
reference
|
table = str . maketrans("ACGT", "TGCA")
def check_DNA(seq1, seq2):
seq1, seq2 = sorted((seq1, seq2), key=len)
return seq1 in seq2[:: - 1]. translate(table)
|
DNA Sequence Tester
|
56fbb2b8fca8b97e4d000a31
|
[
"Fundamentals",
"Strings"
] |
https://www.codewars.com/kata/56fbb2b8fca8b97e4d000a31
|
6 kyu
|
See the following triangle:
```
____________________________________
1
2 4 2
3 6 9 6 3
4 8 12 16 12 8 4
5 10 15 20 25 20 15 10 5
___________________________________
```
The <b>total sum</b> of the numbers in the triangle, up to the 5th line included, is ```225```, part of it, ```144```, corresponds to the total <b>sum of the even terms</b> and ```81``` to the <b>total sum of the odd terms</b>.
Create a function that may output an array with three results for each value of n.
```groovy
Kata.triangMult(n) ----> [total_sum, total_even_sum, total_odd_sum]
```
```haskell
triangMult n ----> (total_sum, total_even_sum, total_odd_sum)
```
```python
triang_mult(n) ----> [total_sum, total_even_sum, total_odd_sum]
```
```javascript
triang_mult(n) ----> [total_sum, total_even_sum, total_odd_sum]
```
```ruby
triang_mult(n) ----> [total_sum, total_even_sum, total_odd_sum]
```
Our example will be:
```groovy
Kata.triangMult(5) ----> [225, 144, 81]
```
```haskell
triangMult 5 ----> (225, 144, 81)
```
```ruby
triang_mult(5) ----> [225, 144, 81]
```
```python
triang_mult(5) ----> [225, 144, 81]
```
```javascript
triang_mult(5) ----> [225, 144, 81]
```
Features of the random tests:
```
number of tests = 100
49 < n < 5000
```
Enjoy it!
This kata will be translated in another languages soon
|
reference
|
def mult_triangle(n):
total = (n * (n + 1) / 2) * * 2
odds = ((n + 1) / / 2) * * 4
return [total, total - odds, odds]
|
Triangle of Multiples (Easy One)
|
58ecc0a8342ee5e920000115
|
[
"Mathematics",
"Data Structures",
"Fundamentals"
] |
https://www.codewars.com/kata/58ecc0a8342ee5e920000115
|
6 kyu
|
Complete the function/method (depending on the language) to return `true`/`True` when its argument is an array that has the same nesting structures and same corresponding length of nested arrays as the first array.
For example:
```javascript
// should return true
[ 1, 1, 1 ].sameStructureAs( [ 2, 2, 2 ] );
[ 1, [ 1, 1 ] ].sameStructureAs( [ 2, [ 2, 2 ] ] );
// should return false
[ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2, 2 ], 2 ] );
[ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2 ], 2 ] );
// should return true
[ [ [ ], [ ] ] ].sameStructureAs( [ [ [ ], [ ] ] ] );
// should return false
[ [ [ ], [ ] ] ].sameStructureAs( [ [ 1, 1 ] ] );
```
```php
same_structure_as([1, 1, 1], [2, 2, 2]); // => true
same_structure_as([1, [1, 1]], [2, [2, 2]]); // => true
same_structure_as([1, [1, 1]], [[2, 2], 2]); // => false
same_structure_as([1, [1, 1]], [[2], 2]); // => false
same_structure_as([[[], []]], [[[], []]]); // => true
same_structure_as([[[], []]], [[1, 1]]); // => false
```
```ruby
# should return true
[ 1, 1, 1 ].same_structure_as( [ 2, 2, 2 ] )
[ 1, [ 1, 1 ] ].same_structure_as( [ 2, [ 2, 2 ] ] )
# should return false
[ 1, [ 1, 1 ] ].same_structure_as( [ [ 2, 2 ], 2 ] )
[ 1, [ 1, 1 ] ].same_structure_as( [ [ 2 ], 2 ] )
# should return true
[ [ [ ], [ ] ] ].same_structure_as( [ [ [ ], [ ] ] ] );
# should return false
[ [ [ ], [ ] ] ].same_structure_as( [ [ 1, 1 ] ] )
```
```python
# should return True
same_structure_as([ 1, 1, 1 ], [ 2, 2, 2 ] )
same_structure_as([ 1, [ 1, 1 ] ], [ 2, [ 2, 2 ] ] )
# should return False
same_structure_as([ 1, [ 1, 1 ] ], [ [ 2, 2 ], 2 ] )
same_structure_as([ 1, [ 1, 1 ] ], [ [ 2 ], 2 ] )
# should return True
same_structure_as([ [ [ ], [ ] ] ], [ [ [ ], [ ] ] ] )
# should return False
same_structure_as([ [ [ ], [ ] ] ], [ [ 1, 1 ] ] )
```
~~~if:javascript
For your convenience, there is already a function 'isArray(o)' declared and defined that returns true if its argument is an array, false otherwise.
~~~
~~~if:php
You may assume that all arrays passed in will be non-associative.
~~~
|
algorithms
|
def same_structure_as(original, other):
if isinstance(original, list) and isinstance(other, list) and len(original) == len(other):
for o1, o2 in zip(original, other):
if not same_structure_as(o1, o2):
return False
else:
return True
else:
return not isinstance(original, list) and not isinstance(other, list)
|
Nesting Structure Comparison
|
520446778469526ec0000001
|
[
"Arrays",
"Algorithms"
] |
https://www.codewars.com/kata/520446778469526ec0000001
|
4 kyu
|
# Task
Your task is to write a function for calculating the score of a 10 pin bowling game. The input for the function is a list of pins knocked down per roll for one player. Output is the player's total score.
# Rules
## General rules
Rules of bowling in a nutshell:
* A game consists of 10 frames. In each frame the player rolls 1 or 2 balls, except for the 10th frame, where the player rolls 2 or 3 balls.
* The total score is the sum of your scores for the 10 frames
* If you knock down fewer than 10 pins with 2 balls, your frame score is the number of pins knocked down
* If you knock down all 10 pins with 2 balls (spare), you score the amount of pins knocked down plus a bonus - amount of pins knocked down with the next ball
* If you knock down all 10 pins with 1 ball (strike), you score the amount of pins knocked down plus a bonus - amount of pins knocked down with the next 2 balls
## Rules for 10th frame
As the 10th frame is the last one, in case of spare or strike there will be no next balls for the bonus. To account for that:
* if the last frame is a spare, player rolls 1 bonus ball.
* if the last frame is a strike, player rolls 2 bonus balls.
These bonus balls on 10th frame are only counted as a bonus to the respective spare or strike.
# More information
http://en.wikipedia.org/wiki/Ten-pin_bowling#Scoring
# Input
You may assume that the input is always valid. This means:
* input list length is correct
* number of pins knocked out per roll is valid
|
algorithms
|
def bowling_score(rolls):
"Compute the total score for a player's game of bowling."
def is_spare(rolls):
return 10 == sum(rolls[: 2])
def is_strike(rolls):
return 10 == rolls[0]
def calc_score(rolls, frame):
return (sum(rolls) if frame == 10 else
sum(rolls[: 3]) + calc_score(rolls[1:], frame + 1) if is_strike(rolls) else
sum(rolls[: 3]) + calc_score(rolls[2:], frame + 1) if is_spare(rolls) else
sum(rolls[: 2]) + calc_score(rolls[2:], frame + 1))
return calc_score(rolls, 1)
|
Bowling score calculator
|
5427db696f30afd74b0006a3
|
[
"Games",
"Algorithms"
] |
https://www.codewars.com/kata/5427db696f30afd74b0006a3
|
5 kyu
|
## Mount the Bowling Pins!
### Task:
Did you ever play Bowling? Short: You have to throw a bowl into 10 Pins arranged like this:
```
I I I I # each Pin has a Number: 7 8 9 10
I I I 4 5 6
I I 2 3
I 1
```
You will get an array of integers between `1` and `10`, e.g. `[3, 5, 9]`, and have to remove them from the field like this:
```
I I I
I I
I
I
```
**Return a string with the current field.**
### Note that:
* The pins rows are separated by a newline (`\n`)
* Each Line must be `7` chars long
* Fill the missing pins with a space character (` `)
**Have fun!**
|
reference
|
pins = "{7} {8} {9} {10}\n" + \
" {4} {5} {6} \n" + \
" {2} {3} \n" + \
" {1} "
def bowling_pins(arr):
return pins . format(* (" " if i in arr else "I" for i in range(11)))
|
Bowling Pins
|
585cf93f6ad5e0d9bf000010
|
[
"Arrays",
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/585cf93f6ad5e0d9bf000010
|
6 kyu
|
Given the root node of a binary tree, write a function that will traverse the tree in a serpentine fashion. You could also think of this as a zig-zag.
We want to visit the first level from left to right, the second level from right to left, third level from left to right, and so on...
The function will return a list of the visited nodes in serpentine order.
The tree is not necessarily balanced.
It is very important that you start the first level from left to right!
A `Node` has 3 properties:
`data` (a number or string)
`left` (a reference to the left child)
`right` (a refencence to the right child)
The empty reference if there is no child is `undefined` (JS) / `None` (Python)
Example:
```
A
/\
B C
/\ /\
D E F G
```
Should result in `["A", "C", "B", "D", "E", "F", "G"]`
|
algorithms
|
def serpentine_traversal(tree) - > list:
def bfs(root):
depth = [root] if root else []
while depth:
yield [node . data for node in depth]
depth = [child for node in depth
for child in (node . left, node . right) if child]
return [node for i, line in enumerate(bfs(tree), 1) for node in line[:: i % 2 or - 1]]
|
Binary Tree Serpentine Traversal
|
5268988a1034287628000156
|
[
"Binary Trees",
"Trees",
"Recursion",
"Algorithms"
] |
https://www.codewars.com/kata/5268988a1034287628000156
|
5 kyu
|
Implement a class/function, which should parse time expressed as `HH:MM:SS`, or `null/nil/None` otherwise.
Any extra characters, or minutes/seconds higher than 59 make the input invalid, and so should return `null/nil/None`.
|
reference
|
import re
def to_seconds(time):
if bool(re . match('[0-9][0-9]:[0-5][0-9]:[0-5][0-9]\Z', time)):
return int(time[: 2]) * 3600 + int(time[3: 5]) * 60 + int(time[6: 8])
else:
return None
|
Regexp basics - parsing time
|
568338ea371e86728c000002
|
[
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/568338ea371e86728c000002
|
6 kyu
|
## Task
You are given n rectangular boxes, the ith box has the length length<sub>i</sub>, the width width<sub>i</sub> and the height height<sub>i</sub>.
Your task is to check if it is possible to pack all boxes into one so that inside each box there is no more than one another box (which, in turn, can contain at most one another box, and so on).
More formally, your task is to check whether there is such sequence of n different numbers pi (1 ≤ pi ≤ n) that for each 1 ≤ i < n the box number pi can be put into the box number pi+1.
A box can be put into another box if all sides of the first one are less than the respective ones of the second one. You can rotate each box as you wish, i.e. you can `swap` its length, width and height if necessary.
## Example
For `length = [1, 3, 2], width = [1, 3, 2] and height = [1, 3, 2]`, the output should be `true`;
For `length = [1, 1], width = [1, 1] and height = [1, 1],` the output should be `false`;
For `length = [3, 1, 2], width = [3, 1, 2] and height = [3, 2, 1]`, the output should be `false`.
# Input/Output
- `[input]` integer array `length`
Array of positive integers.
Constraints:
`1 ≤ length.length ≤ 100,`
`1 ≤ length[i] ≤ 2000.`
- `[input]` integer array `width`
Array of positive integers.
Constraints:
`width.length = length.length,`
`1 ≤ width[i] ≤ 2000.`
- `[input]` integer array `height`
Array of positive integers.
Constraints:
`height.length = length.length,`
`1 ≤ height[i] ≤ 2000.`
- `[output]` a boolean value
`true` if it is possible to put all boxes into one, `false` otherwise.
|
games
|
def boxes_packing(l, w, h):
boxes = sorted(sorted(t) for t in zip(l, w, h))
return all(s < l for b1, b2 in zip(boxes[: - 1], boxes[1:]) for s, l in zip(b1, b2))
|
Simple Fun #89: Boxes Packing
|
58957c5041c979cf9e00002f
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58957c5041c979cf9e00002f
|
5 kyu
|
### Task
Dudka has `n` details. He must keep exactly 3 of them.
To do this, he performs the following operations until he has only 3 details left:
```
He numbers them.
He keeps those with either odd or even numbers and throws the others away.
```
Dudka wants to know how many ways there are to get exactly 3 details. Your task is to help him calculate it.
### Example
For `n = 6`, the output should be `2`.
```
Dudka has 6 details, numbered 1 2 3 4 5 6.
He can keep either details with numbers 1, 3, 5,
or with numbers 2, 4, 6.
Both options leave him with 3 details,
so the answer is 2.
```
For `n = 7`, the output should be `1`.
```
Dudka has 7 details, numbered 1 2 3 4 5 6 7.
He can keep either details 1 3 5 7, or details 2 4 6.
If he keeps details 1 3 5 7 ,
he won't be able to get 3 details in the future,
because at the next step he will number them 1 2 3 4
and will have to keep either details 1 3, or 2 4,
only two details anyway.
That's why he must keep details 2 4 6 at the first step,
so the answer is 1.
```
### Input/Output
- `[input]` integer `n`
`3 ≤ n ≤ 10^9`
- `[output]` an integer
The number of ways to get exactly 3 details.
|
games
|
def three_details(n):
m = 1 << n . bit_length()
return min(n - (m >> 1), m - n)
|
Simple Fun #192: Three Details
|
58c212c6f130b7c4660000a5
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58c212c6f130b7c4660000a5
|
6 kyu
|
# Task
Vanya gets bored one day and decides to enumerate a large pile of rocks. He first counts the rocks and finds out that he has `n` rocks in the pile, then he goes to the store to buy labels for enumeration.
Each of the labels is a digit from 0 to 9 and each of the `n` rocks should be assigned a unique number from `1` to `n`.
If each label costs `$1`, how much money will Vanya spend on this project?
# Input/Output
- `[input]` integer `n`
The number of rocks in the pile.
`1 ≤ n ≤ 10^9`
- `[output]` an integer
the cost of the enumeration.
# Example
For `n = 13`, the result should be `17`.
```
the numbers from 1 to n are:
1 2 3 4 5 6 7 8 9 10 11 12 13
we need 17 single digit labels:
1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3
each label cost $1, so the output should be 17.
```
|
algorithms
|
from math import log10
def rocks(n):
return (n + 1) * int(log10(n) + 1) - (10 * * int(log10(n) + 1) - 1) / / 9
|
Simple Fun #151: Rocks
|
58acf6c20b3b251d6d00002d
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58acf6c20b3b251d6d00002d
|
6 kyu
|
# Task
A common way for prisoners to communicate secret messages with each other is to encrypt them. One such encryption algorithm goes as follows.
You take the message and place it inside an `nx6` matrix (adjust the number of rows depending on the message length) going from top left to bottom right (one row at a time) while replacing spaces with dots (.) and adding dots at the end of the last row (if necessary) to complete the matrix.
Once the message is in the matrix you read again from top left to bottom right but this time going one column at a time and treating each column as one word.
# Example
The following message `"Attack at noon or we are done for"` is placed in a `6 * 6` matrix :
```
Attack
.at.no
on.or.
we.are
.done.
for...```
Reading it one column at a time we get:
`A.ow.f tanedo tt..or a.oan. cnrre. ko.e..`
# Input/Output
- `[input]` string `msg`
a regular english sentance representing the original message
- `[output]` a string
encrypted message
|
games
|
def six_column_encryption(msg):
msg = msg . replace(' ', '.') + '.' * ((6 - len(msg) % 6) % 6)
return ' ' . join(msg[n:: 6] for n in range(6))
|
Simple Fun #133: Six Column Encryption
|
58a65945fd7051d5e1000041
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58a65945fd7051d5e1000041
|
6 kyu
|
# Task
A robot is standing at the `(0, 0)` point of the Cartesian plane and is oriented towards the vertical (y) axis in the direction of increasing y values (in other words, he's facing up, or north). The robot executes several commands each of which is a single positive integer. When the robot is given a positive integer K it moves K squares forward and then turns 90 degrees clockwise.
The commands are such that both of the robot's coordinates stay non-negative.
Your task is to determine if there is a square that the robot visits at least twice after executing all the commands.
# Example
For `a = [4, 4, 3, 2, 2, 3]`, the output should be `true`.
The path of the robot looks like this:

The point `(4, 3)` is visited twice, so the answer is `true`.
# Input/Output
- `[input]` integer array a
An array of positive integers, each number representing a command.
Constraints:
`3 ≤ a.length ≤ 100`
`1 ≤ a[i] ≤ 10000`
- `[output]` a boolean value
`true` if there is a square that the robot visits at least twice, `false` otherwise.
|
games
|
def robot_walk(a):
i = 3
while (i < len(a) and a[i] < a[i - 2]):
i += 1
return i < len(a)
|
Simple Fun #130: Robot Walk
|
58a64b48586e9828df000109
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58a64b48586e9828df000109
|
6 kyu
|
# Task
You're standing at the top left corner of an `n × m` grid and facing towards the `right`.
Then you start walking one square at a time in the direction you are facing.
If you reach the border of the grid or if the next square you are about to visit has already been visited, you turn right.
You stop when all the squares in the grid are visited. What direction will you be facing when you stop?
You can see the example of your long walk in the image below. The numbers denote the order in which you visit the cells.

Given two integers n and m, denoting the number of rows and columns respectively, find out the direction you will be facing at the end.
Output `"L"` for left, `"R"` for right, `"U"` for up, and `"D"` for down.
# Example:
For `n = 3, m = 3`, the output should be `"R"`.
This example refers to the picture given in the description. At the end of your walk you will be standing in the middle of the grid facing right.
# Input/Output
- `[input]` integer `n`
number of rows.
`1 <= n <= 1000`
- `[input]` integer `m`
number of columns.
`1 <= m <= 1000`
- `[output]` a string
The final direction.
|
games
|
def direction_in_grid(n, m):
return "LR" [n % 2] if m >= n else "UD" [m % 2]
|
Simple Fun #183: Direction In Grid
|
58bcd7f2f6d3b11fce000025
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58bcd7f2f6d3b11fce000025
|
6 kyu
|
## Task
* Complete the pattern, using the special characters ```■ □```
* In this kata, let's us draw a square, with a zoom effect.
## Rules
- parameter `n`: The side length of the square, always be a positive odd number.
- return a string square that `■` and `□` alternate expansion and each line is separated by `\n`.
## Example
```
zoom(1)
■
zoom(3)
□□□
□■□
□□□
zoom(5)
■■■■■
■□□□■
■□■□■
■□□□■
■■■■■
zoom(7)
□□□□□□□
□■■■■■□
□■□□□■□
□■□■□■□
□■□□□■□
□■■■■■□
□□□□□□□
zoom(9)
■■■■■■■■■
■□□□□□□□■
■□■■■■■□■
■□■□□□■□■
■□■□■□■□■
■□■□□□■□■
■□■■■■■□■
■□□□□□□□■
■■■■■■■■■
zoom(25)
■■■■■■■■■■■■■■■■■■■■■■■■■
■□□□□□□□□□□□□□□□□□□□□□□□■
■□■■■■■■■■■■■■■■■■■■■■■□■
■□■□□□□□□□□□□□□□□□□□□□■□■
■□■□■■■■■■■■■■■■■■■■■□■□■
■□■□■□□□□□□□□□□□□□□□■□■□■
■□■□■□■■■■■■■■■■■■■□■□■□■
■□■□■□■□□□□□□□□□□□■□■□■□■
■□■□■□■□■■■■■■■■■□■□■□■□■
■□■□■□■□■□□□□□□□■□■□■□■□■
■□■□■□■□■□■■■■■□■□■□■□■□■
■□■□■□■□■□■□□□■□■□■□■□■□■
■□■□■□■□■□■□■□■□■□■□■□■□■
■□■□■□■□■□■□□□■□■□■□■□■□■
■□■□■□■□■□■■■■■□■□■□■□■□■
■□■□■□■□■□□□□□□□■□■□■□■□■
■□■□■□■□■■■■■■■■■□■□■□■□■
■□■□■□■□□□□□□□□□□□■□■□■□■
■□■□■□■■■■■■■■■■■■■□■□■□■
■□■□■□□□□□□□□□□□□□□□■□■□■
■□■□■■■■■■■■■■■■■■■■■□■□■
■□■□□□□□□□□□□□□□□□□□□□■□■
■□■■■■■■■■■■■■■■■■■■■■■□■
■□□□□□□□□□□□□□□□□□□□□□□□■
■■■■■■■■■■■■■■■■■■■■■■■■■
```
|
games
|
def zoom(n):
pattern = ""
center = (n - 1) / 2
for y in range(n):
for x in range(n):
d = max(abs(x - center), abs(y - center))
pattern += "□" if d % 2 else "■"
pattern += "\n" if y < n - 1 else ""
return pattern
|
■□ Pattern □■ : Zoom
|
56e6705b715e72fef0000647
|
[
"ASCII Art",
"Puzzles"
] |
https://www.codewars.com/kata/56e6705b715e72fef0000647
|
5 kyu
|
# Task
Two integer numbers are added using the column addition method. When using this method, some additions of digits produce non-zero carries to the next positions. Your task is to calculate the number of non-zero carries that will occur while adding the given numbers.
The numbers are added in base 10.
# Example
For `a = 543 and b = 3456,` the output should be `0`
For `a = 1927 and b = 6426`, the output should be `2`
For `a = 9999 and b = 1`, the output should be `4`
# Input/Output
- `[input]` integer `a`
A positive integer.
Constraints: `1 ≤ a ≤ 10^7`
- `[input]` integer `b`
A positive integer.
Constraints: `1 ≤ b ≤ 10^7`
- `[output]` an integer
|
games
|
def number_of_carries(a, b):
ans, carrie = 0, 0
while a > 0 or b > 0:
carrie = (a % 10 + b % 10 + carrie) / / 10
ans += [0, 1][carrie > 0]
a / /= 10
b / /= 10
return ans
|
Simple Fun #132: Number Of Carries
|
58a6568827f9546931000027
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58a6568827f9546931000027
|
6 kyu
|
# Task
If string has more than one neighboring dashes(e.g. --) replace they with one dash(-).
Dashes are considered neighbors even if there is some whitespace **between** them.
# Example
For `str = "we-are- - - code----warriors.-"`
The result should be `"we-are- code-warriors.-"`
# Input/Output
- `[input]` string `str`
- `[output]` a string
|
algorithms
|
from re import sub
def replace_dashes_as_one(s):
return sub("-[\s-]*-", '-', s)
|
Simple Fun #161: Replace Dashes As One
|
58af9f7320a9ecedb30000f1
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58af9f7320a9ecedb30000f1
|
6 kyu
|
# Task
You are a magician. You're going to perform a trick.
You have `b` black marbles and `w` white marbles in your magic hat, and an infinite supply of black and white marbles that you can pull out of nowhere.
You ask your audience to repeatedly remove a pair of marbles from your hat and, for each pair removed, you add one marble to the hat according to the following rule, until there is only 1 marble left.
If the marbles of the pair that is removed are of the same color, you add a white marble to the hat. Otherwise, if one is black and one is white, you add a black marble.
Given the initial number of black and white marbles in your hat, your trick is to predict the color of the last marble.
Note: A magician may confuse your eyes, but not your mind ;-)
# Input/Output
- `[input]` integer `b`
Initial number of black marbles in the hat.
`1 <= b <= 10^9`
- `[input]` integer `w`
Initial number of white marbles in the hat.
`1 <= w <= 10^9`
- `[output]` a string
`"Black"` or `"White"` if you can safely predict the color of the last marble. If not, return `"Unsure"`.
~~~if:lambdacalc
# Encodings
* purity: `LetRec`
* numEncoding: `BinaryScott`
* output: `Unsure`, `Black` or `White` ( not strings! ); these values have been `Preloaded` for you
~~~
|
games
|
def not_so_random(b, w):
return ['White', 'Black'][b % 2]
|
Simple Fun #158: Not So Random
|
58ad2e9c0e3c08126000003f
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58ad2e9c0e3c08126000003f
|
6 kyu
|
## Decode the diagonal.
Given a grid of characters. Output a decoded message as a string.
Input
```
H Z R R Q
D I F C A E A !
G H T E L A E
L M N H P R F
X Z R P E
```
Output
`HITHERE!` (diagonally down right `↘` and diagonally up right `↗` if you can't go further).
The message ends when there is no space at the right up or down diagonal.
To make things even clearer: the same example, but in a simplified view
```
H _ _ _ _
_ I _ _ _ _ _ !
_ _ T _ _ _ E
_ _ _ H _ R _
_ _ _ _ E
```
|
algorithms
|
def get_diagonale_code(grid):
grid = [line . split() for line in grid . split("\n")]
i, j, d, word = 0, 0, 1, ""
while 0 <= i < len(grid) and j < len(grid[i]):
if 0 <= j < len(grid[i]):
word += grid[i][j]
i, j = i + d, j + 1
else:
i += d
if i == 0 or i == len(grid) - 1:
d = - d
return word
|
Decode Diagonal
|
55af0d33f9b829d0a800008d
|
[
"Algorithms"
] |
https://www.codewars.com/kata/55af0d33f9b829d0a800008d
|
6 kyu
|
_A mad sociopath scientist just came out with a brilliant invention! He extracted his own memories to forget all the people he hates! Now there's a lot of information in there, so he needs your talent as a developer to automatize that task for him._
> You are given the memories as a string containing people's surname and name (comma separated). The scientist marked one occurrence of each of the people he hates by putting a '!' right before their name.
**Your task is to destroy all the occurrences of the marked people.
One more thing ! Hate is contagious, so you also need to erase any memory of the person that comes after any marked name!**
---
Examples
---
---
Input:
```
"Albert Einstein, !Sarah Connor, Marilyn Monroe, Abraham Lincoln, Sarah Connor, Sean Connery, Marilyn Monroe, Bjarne Stroustrup, Manson Marilyn, Monroe Mary"
```
Output:
```
"Albert Einstein, Abraham Lincoln, Sean Connery, Bjarne Stroustrup, Manson Marilyn, Monroe Mary"
```
=> We must remove every memories of Sarah Connor because she's marked, but as a side-effect we must also remove all the memories about Marilyn Monroe that comes right after her! Note that we can't destroy the memories of Manson Marilyn or Monroe Mary, so be careful!
|
reference
|
def select(memory):
lst = memory . split(', ')
bad = {who . strip('!') for prev, who in zip(
[''] + lst, lst + ['']) if who . startswith('!') or prev . startswith('!')}
return ', ' . join(who for who in map(lambda s: s . strip('!'), lst) if who not in bad)
|
Selective memory
|
58bee820e9f98b215200007c
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/58bee820e9f98b215200007c
|
6 kyu
|
In the morning all the doors in the school are closed. The school is quite big: there are **N** doors. Then pupils start coming. It might be hard to believe, but all of them want to study! Also, there are exactly **N** children studying in this school, and they come one by one.
When these strange children pass by some doors they change their status (i.e. Open -> Closed, Closed -> Open). Each student has their number, and each i-th student alters the status of every i-th door. For example: when the first child comes to the schools, he changes every first door (he opens all of them). The second one changes the status of every second door (he closes some doors: the 2nd, the 4th and so on). Finally, when the last one – the n-th – comes to the school, he changes the status of each n-th door (there's only one such door, though).
You need to count how many doors are left opened after all the students have come.
Example:

*Here you can see red squares – closed doors, green – opened ones.*
Input:
> n – the number of doors and students, n ∈ N, n ∈ [1, 100000]
Output:
> o – the number of opened doors, o ∈ N
---
```
doors(5)
```
Should return
```
2
```
|
algorithms
|
def doors(n):
return int(n * * .5)
|
Doors in the school
|
57c15d314677bb2bd4000017
|
[
"Fundamentals",
"Algorithms"
] |
https://www.codewars.com/kata/57c15d314677bb2bd4000017
|
6 kyu
|
You are the Head of the Department and your responsibilities include creating monthly schedules for your employees.
Your employees work in shifts. Each shift is 24 hours. Employment policy prohibits employee from working more than 24 hours in a row, so one employee cannot have two consecutive shifts.
There must be `n` people at work each day. Arrange employees over the schedule so that their workload is equal or differs from others minimally (i. e. difference between any two employees must not exceed one shift).
If it is not possible to ensure one employee does not work two days in a row due to insufficient staff, return `None/null/nil`.
# Arguments
* Array of employee names as strings. Example: `['Smith", 'Jones', 'Gonzalez', 'White', 'Jackon', 'Taylor']`.
* Month and year in `'MMYYYY'` format.
* Number of employees per shift.
# Output
* Array of arrays, each representing a day in the given month. Each day array contains three employee names.
#Example
```
schedule(['Smith', 'Jones', 'Gonzalez', 'White', 'Jackon', 'Taylor'], '022015', 3)
```
may return
```
[['Smith', 'Jones', 'Gonzalez'],
['White', 'Jackson', 'Taylor'],
['Jones', 'Smith', 'Gonzalez'],
['Taylor', 'White', 'Jackson'],
['Smith', 'Jones', 'Gonzalez'],
['White', 'Jackson', 'Taylor'],
['Jones', 'Smith', 'Gonzalez'],
['Taylor', 'White', 'Jackson'],
['Smith', 'Jones', 'Gonzalez'],
['White', 'Jackson', 'Taylor'],
['Jones', 'Smith', 'Gonzalez'],
['Taylor', 'White', 'Jackson'],
['Smith', 'Jones', 'Gonzalez'],
['White', 'Jackson', 'Taylor'],
['Jones', 'Smith', 'Gonzalez'],
['Taylor', 'White', 'Jackson'],
['Smith', 'Jones', 'Gonzalez'],
['White', 'Jackson', 'Taylor'],
['Jones', 'Smith', 'Gonzalez'],
['Taylor', 'White', 'Jackson'],
['Smith', 'Jones', 'Gonzalez'],
['White', 'Jackson', 'Taylor'],
['Jones', 'Smith', 'Gonzalez'],
['Taylor', 'White', 'Jackson'],
['Smith', 'Jones', 'Gonzalez'],
['White', 'Jackson', 'Taylor'],
['Jones', 'Smith', 'Gonzalez'],
['Taylor', 'White', 'Jackson']]
```
Here each employee has 14 shifts and no one has two consecutive shifts.
**Note:** [rules for leap years](http://en.wikipedia.org/wiki/Leap_year#Algorithm) do apply, so keep that in mind ;)
|
algorithms
|
from calendar import monthrange
from itertools import cycle, islice
def schedule(staff, date, n):
if len(staff) < 2 * n:
return None
days = monthrange(int(date[2:]), int(date[: 2]))[1]
istaff = cycle(staff)
return [list(islice(istaff, n)) for _ in range(days)]
|
Department scheduler [simple]
|
5558bb17f7ba7532de0000aa
|
[
"Scheduling",
"Algorithms"
] |
https://www.codewars.com/kata/5558bb17f7ba7532de0000aa
|
5 kyu
|
# Task
Calculate a chess player's new Elo rating using their previous ratings (`experience`), their opponent's rating (`opponent`), the outcome of the new game (`score`), and the Factor k function (`k`).
## Arguments
* `experience` is an array/list containing the history of the player's ratings, with the last item in the array being the current rating. For example, if `experience` is `[995, 1025, 1050]`, then the player's 2 old ratings are 995 and 1025, and their current rating is 1050. If a player has no recorded experience (`experience = []`), use 1000 for their rating.
* `opponent` is a single number indicating the opponent's rating
* `score` is the outcome of the new game. `score` is `1` if the player won, `0` if the player lost, or `0.5` if it was a tie.
* `k` is a function that takes in the `experience` array/list as an argument. `k` is an optional argument - sometimes a `k` function will be passed for you to use and sometimes not. You must write a default `k` function to use in case no `k` function is passed (see below for details).
## Return
* The `elo` function must return the new rating of the player rounded to the nearest integer.
# Elo rating formula
The Elo rating system starts with an expectation formula:
```
expectation =
1 / (1+10^((opponent_rating - player_rating)/400))
```
This can then be used in the new rating formula as follows:
```
new_player_rating =
player_rating + k(experience) * (score - expectation)
```
Note that `k` is a function taking in `experience` as a parameter.
## Factor K function
You must write a default `k` function to use if no `k` function is passed to the `elo` function. The default `k` function should take in `experience` as an argument and return the following:
* If player is a newbie (less than 30 games of experience), return 25.
* If player is not a newbie, but player's rating has never reached 2400 before, return 15.
* If player is not a newbie and has at least one record of a rating >= 2400, return 10.
(These are pre-2011 FIDE rules.)
# Examples
* Example 1: `elo([], 1725, 1)`
Since player has no experience, we will use 1000 as their rating.
`opponent` rating is 1725.
`score` is 1.
Then we have:
```
expectation
= 1 / (1+10^((opponent_rating - player_rating)/400))
= 1 / (1+10^((1725 - 1000)/400))
= 0.01516572425000013
```
Since no `k` function was passed, we will use our default `k` function. Since player is a newbie (less than 30 games of experience), `k(experience)` will return 25.
Then in our new_player_rating formula:
```
new_player_rating
= player_rating + k(experience) * (score - expectation)
= 1000 + 25 * (1 - 0.01516572425000013)
= 1024.62085689375
```
When we round this to the nearest integer our final answer is 1025.
* Example 2:
```
def k_algo(exp):
return 800//len(exp)
elo([1025, 1025, 1050, 1075, 1100, 1125, 1150,
1175, 1200, 1225, 1250, 1275, 1300, 1325, 1350,
1375, 1400, 1425, 1450, 1475, 1500, 1525, 1550,
1575, 1600, 1625, 1650, 1675, 1700, 1725],
1000,
0,
k_algo)
```
The player's current rating is the last item in experience, 1725.
`opponent` rating is 1000.
`score` is 0.
A function called `k_algo` is passed which we will use instead of our default `k` function.
Then we have:
```
expectation
= 1 / (1+10^((opponent_rating - player_rating)/400))
= 1 / (1+10^((1000 - 1725)/400))
= 0.9848342757499998
```
When we pass `experience` to the `k_algo` function, we will get out `800//len(experience) = 26`.
Then in our new_player_rating formula:
```
new_player_rating
= player_rating + k(experience) * (score - expectation)
= 1725 + 26 * (0 - 0.9848342757499998)
= 1699.3943088305
```
When we round this to the nearest integer our final answer is 1699.
|
algorithms
|
def k_fide2010(experience):
if len(experience) < 30:
return 25
elif experience and max(experience) < 2400:
return 15
return 10
def elo(experience, opponent, game_result, k=k_fide2010):
try:
last = experience[- 1]
except IndexError:
last = 1000
expected = 1.0 / (1 + 10 * * ((opponent - last) / 400.0))
return last + int(round(k(experience) * (game_result - expected)))
|
Elo rating - one game, one pair
|
55633765da97b266e3000067
|
[
"Games",
"Algorithms"
] |
https://www.codewars.com/kata/55633765da97b266e3000067
|
5 kyu
|
#Split all even numbers to odd ones in different ways
Your task is to split all even numbers from an array to odd ones. So your method has to return a new array with only odd numbers.
For "splitting" the numbers there are four ways.
```
0 -> Split into two odd numbers, that are closest to each other.
(e.g.: 8 -> 3,5)
1 -> Split into two odd numbers, that are most far from each other.
(e.g.: 8 -> 1,7)
2 -> All new odd numbers from the splitting should be equal and the maximum possible number.
(e.g.: 8 -> 1, 1, 1, 1, 1, 1, 1, 1)
3 -> Split into 1s.
(e.g.: 8 -> 1, 1, 1, 1, 1, 1, 1, 1)
The new numbers (from the splitting) have always to be in ascending order.
So in the array every even number is replaced by the new odd numbers from the splitting.
```
Your method will get as parameters the input-array and the number of the way for splitting the even numbers.
Some Examples
```
[1,10,1,3],0 -> [1,5,5,1,3]
[1,10,1,3],1 -> [1,1,9,1,3]
[1,10,1,3],2 -> [1,5,5,1,3]
[1,10,1,3],3 -> [1,1,1,1,1,1,1,1,1,1,1,1,3]
[1,1,3,8],0 -> [1,1,3,3,5]
[1,1,3,8],1 -> [1,1,3,1,7]
[1,1,3,8],2 -> [1,1,3,1,1,1,1,1,1,1,1]
[1,1,3,8],3 -> [1,1,3,1,1,1,1,1,1,1,1]
```
The array will never be null and will always contain only integer numbers > 0. Also your result-array must contain only integer numbers > 0.
The way-parameter will always be between inclusive 0 and inclusive 3 (0,1,2,3).
You must not change the input-array!
<br><br><br>
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have also created other katas. Take a look if you enjoyed this kata!
|
algorithms
|
from itertools import chain
def split_all_even_numbers(lst, way):
def convert(n):
s = 1 - (n / / 2) % 2 # Shift for closest odd numbers
return ([n] if n % 2 else # Is already odd
[n / / 2 - s, n / / 2 + s] if way == 0 else # Two closest odd sum
[1, n - 1] if way == 1 else # Two farthest odd sum
[1] * n if way == 3 else # Split in ones
split_all_even_numbers([n / / 2] * 2, 2)) # Split in highest possible odds
return list(chain(* map(convert, lst)))
|
Split all even numbers to odd ones in different ways
|
5883b79101b769456e000003
|
[
"Arrays",
"Logic",
"Algorithms"
] |
https://www.codewars.com/kata/5883b79101b769456e000003
|
6 kyu
|
We are given two arrays of integers A and B and we have to output a sorted array with the integers that fulfill the following constraints:
- they are present in both ones
- they occur more than once in A and more than once in B
- their values are within a given range
- thay are odd or even according as it is requested
```
arrA = [1, -2, 7, 2, 1, 3, 7, 1, 0, 2, 3]
arrB = [2, -1, 1, 1, 1, 1, 2, 3, 3, 7, 7, 0]
rng = [-4, 4] # is the range of the integers from -4 to 4 (inclusive)
wanted = 'odd'
```
Process to obtain the result:
```
0, 1, 2, 3, 7, are the numbers present in arrA and arrB
1, 2, 3, 7, occur twice or more in arrA and arrB
1, 2, 3, are in the range [-4, 4]
1, 3, are odd
output: [1, 3]
```
For the case:
```
arrA = [1, -2, 7, 2, 1, 3, 4, 7, 1, 0, 2, 3, 0, 4]
arrB = [0, 4, 2, -1, 1, 1, 1, 1, 2, 3, 3, 7, 7, 0, 4]
rng = [-4, 4]
wanted = 'even'
output[0, 2, 4]
```
If there are no elements to fulfill the constraints given above the result will be the empty array.
The name of the function with the corresponding order of its arguments and the data structure for the output is as it follows below:
``` python
find_arr(arrA, arrB, rng, wanted) ----> []
```
(For Javascript the function will be ```findArr()```)
Features of the tests:
```
Number of Random Tests = 300
Length of the arrays A and B between 1000 and 10000
```
You may assume that you will always receive valid entries for all the tests.
Enjoy it!!
Very Important: For javascript run the tests only in Node v6.6.0 and Node v6.6.0/Babel.
|
reference
|
from collections import Counter
def find_arr(arrA, arrB, rng, wanted):
ca, cb = Counter(arrA), Counter(arrB)
m, n = rng
m += (m % 2 == 1) == (wanted == 'even')
r = range(m, n + 1, 2)
return [v for v in r if ca[v] > 1 and cb[v] > 1]
|
Find a Bunch of Common Elements of Two Lists in a Certain Range
|
58161c5ac7e37d17fc00002f
|
[
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic",
"Strings"
] |
https://www.codewars.com/kata/58161c5ac7e37d17fc00002f
|
6 kyu
|
Given two strings s1 and s2, we want to visualize how different the two strings are.
We will only take into account the *lowercase* letters (a to z).
First let us count the frequency of each *lowercase* letters in s1 and s2.
`s1 = "A aaaa bb c"`
`s2 = "& aaa bbb c d"`
`s1 has 4 'a', 2 'b', 1 'c'`
`s2 has 3 'a', 3 'b', 1 'c', 1 'd'`
So the maximum for 'a' in s1 and s2 is 4 from s1; the maximum for 'b' is 3 from s2.
In the following we will not consider letters when the maximum of their occurrences
is less than or equal to 1.
We can resume the differences between s1 and s2 in the following string:
`"1:aaaa/2:bbb"`
where `1` in `1:aaaa` stands for string s1 and `aaaa` because the maximum for `a` is 4.
In the same manner `2:bbb` stands for string s2 and `bbb` because the maximum for `b` is 3.
The task is to produce a string in which each *lowercase* letters of s1 or s2 appears as many times as
its maximum if this maximum is *strictly greater than 1*; these letters will be prefixed by the
number of the string where they appear with their maximum value and `:`.
If the maximum is in s1 as well as in s2 the prefix is `=:`.
In the result, substrings (a substring is for example 2:nnnnn or 1:hhh; it contains the prefix) will be in decreasing order of their length and when they have the same length sorted in ascending lexicographic order (letters and digits - more precisely sorted by codepoint); the different groups will be separated by '/'. See examples and "Example Tests".
Hopefully other examples can make this clearer.
```
s1 = "my&friend&Paul has heavy hats! &"
s2 = "my friend John has many many friends &"
mix(s1, s2) --> "2:nnnnn/1:aaaa/1:hhh/2:mmm/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss"
s1 = "mmmmm m nnnnn y&friend&Paul has heavy hats! &"
s2 = "my frie n d Joh n has ma n y ma n y frie n ds n&"
mix(s1, s2) --> "1:mmmmmm/=:nnnnnn/1:aaaa/1:hhh/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss"
s1="Are the kids at home? aaaaa fffff"
s2="Yes they are here! aaaaa fffff"
mix(s1, s2) --> "=:aaaaaa/2:eeeee/=:fffff/1:tt/2:rr/=:hh"
```
#### Note for Swift, R, PowerShell
The prefix `=:` is replaced by `E:`
```
s1 = "mmmmm m nnnnn y&friend&Paul has heavy hats! &"
s2 = "my frie n d Joh n has ma n y ma n y frie n ds n&"
mix(s1, s2) --> "1:mmmmmm/E:nnnnnn/1:aaaa/1:hhh/2:yyy/2:dd/2:ff/2:ii/2:rr/E:ee/E:ss"
```
|
reference
|
def mix(s1, s2):
hist = {}
for ch in "abcdefghijklmnopqrstuvwxyz":
val1, val2 = s1 . count(ch), s2 . count(ch)
if max(val1, val2) > 1:
which = "1" if val1 > val2 else "2" if val2 > val1 else "="
hist[ch] = (- max(val1, val2), which + ":" + ch * max(val1, val2))
return "/" . join(hist[ch][1] for ch in sorted(hist, key=lambda x: hist[x]))
|
Strings Mix
|
5629db57620258aa9d000014
|
[
"Fundamentals",
"Strings"
] |
https://www.codewars.com/kata/5629db57620258aa9d000014
|
4 kyu
|
Check that the two provided arrays both contain the same number of different unique items, regardless of order. For example in the following:
```
[a,a,a,a,b,b] and [c,c,c,d,c,d]
```
Both arrays have four of one item and two of another, so balance should return ```true```.
#Have fun!
|
reference
|
from collections import Counter
def balance(arr1, arr2):
return sorted(Counter(arr1). values()) == sorted(Counter(arr2). values())
|
Balance the arrays
|
58429d526312ce1d940000ee
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/58429d526312ce1d940000ee
|
6 kyu
|
# Task:
This kata asks you to make a custom esolang interpreter for the language [MiniBitMove](https://esolangs.org/wiki/MiniBitMove). MiniBitMove has only two commands and operates on a array of bits. It works like this:
- `1`: Flip the bit at the current cell
- `0`: Move selector by 1
It takes two inputs, the program and the bits in needs to operate on. The program returns the modified bits. The program stops when selector reaches the end of the array. Otherwise the program repeats itself. **Note: This means that if a program does not have any zeros it is an infinite loop**
Example of a program that flips all bits in an array:
```
Code: 10
Bits: 11001001001010
Result: 00110110110101
```
After you're done, feel free to make translations and discuss this kata.
|
reference
|
from itertools import cycle
def interpreter(tape, array):
idx, result = 0, list(map(int, array))
for cmd in cycle(map(int, tape)):
if idx == len(array):
break
if cmd:
result[idx] = 1 - result[idx]
else:
idx += 1
return '' . join(map(str, result))
|
Esolang: MiniBitMove
|
587c0138110b20624e000253
|
[
"Interpreters",
"Strings",
"Arrays",
"Bits",
"Esoteric Languages",
"Fundamentals"
] |
https://www.codewars.com/kata/587c0138110b20624e000253
|
6 kyu
|
Karan's company makes software that provides different features based on the version of operating system of the user.
To compare versions, Karan currently parses both version numbers as floats.
While this worked for OS versions 10.6, 10.7, 10.8 and 10.9, the operating system company just released OS version 10.10. This causes his method to fail, as 10.9 is greater than 10.10 when interpreting both as numbers, despite being a lesser version.
Help Karan by writing him a function which compares two versions, and returns whether or not the first one is greater than or equal to the second.
Specification notes:
- Versions are provided as strings of one or more integers separated by `.`.
- The version strings will never be empty.
- The two versions are not guaranteed to have an equal amount of sub-versions, when this happens assume that all missing sub-versions are zero.
- Two versions which differ only by trailing zero sub-versions will never be given.
|
reference
|
def compare_versions(ver1, ver2):
return [int(i) for i in ver1 . split(".")] >= [int(i) for i in ver2 . split(".")]
|
Compare Versions
|
53b138b3b987275b46000115
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/53b138b3b987275b46000115
|
6 kyu
|
Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht the frist and lsat ltteer be at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a wlohe.
Interesting <a href="http://www.mrc-cbu.cam.ac.uk/people/matt-davis/cmabridge/">article</a> about this.
<h3>Task:</h3>
Write a function which mix inner characters in each word,first and last character stays untouched.Notice that punctuation mark is not a part of a word!By word we define only alphanumeric characters.
<h4>Requirements:</h4>
-at least 10% of all changeable words must differ from original.
If you solve this kata,check how many percent of changeable words you have changed.If you reach 100% you will get a reward!
|
reference
|
def jumble(strng):
return __import__("re"). sub(r'(\w{3,})', lambda m: m . group(0)[0] + m . group(0)[1: - 1][:: - 1] + m . group(0)[- 1], strng)
|
Jumble words
|
589b30ddcf7d024850000089
|
[
"Strings",
"Algorithms",
"Fundamentals"
] |
https://www.codewars.com/kata/589b30ddcf7d024850000089
|
6 kyu
|
Write a function that returns only the decimal part of the given number.
You only have to handle valid numbers, not `Infinity`, `NaN`, or similar. Always return a positive decimal part.
### Examples
``` javascript
getDecimal(2.4) === 0.4
getDecimal(-0.2) === 0.2
```
``` python
get_decimal(2.4) # 0.4
get_decimal(-0.2) # 0.2
```
|
reference
|
def get_decimal(n):
return abs(n) % 1
|
Get decimal part of the given number
|
586e4c61aa0428f04e000069
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/586e4c61aa0428f04e000069
|
7 kyu
|
Write a function that will check whether ANY permutation of the characters of the input string is a palindrome. Bonus points for a solution that is efficient and/or that uses _only_ built-in language functions. Deem yourself **brilliant** if you can come up with a version that does not use _any_ function whatsoever.
For this kata assume that all characters are **lowercase**.
# Example
`madam` -> True
`adamm` -> True
`junk` -> False
## Hint
The brute force approach would be to generate _all_ the permutations of the string and check each one of them whether it is a palindrome. However, an optimized approach will not require this at all.
|
reference
|
def permute_a_palindrome(input):
return sum(input . count(c) % 2 for c in set(input)) < 2
|
Permute a Palindrome
|
58ae6ae22c3aaafc58000079
|
[
"Algorithms",
"Fundamentals"
] |
https://www.codewars.com/kata/58ae6ae22c3aaafc58000079
|
6 kyu
|
An array is **circularly sorted** if the elements are sorted in ascending order, but displaced, or rotated, by any number of steps.
Complete the function/method that determines if the given array of integers is circularly sorted.
## Examples
These arrays are circularly sorted (`true`):
```
[2, 3, 4, 5, 0, 1] --> [0, 1] + [2, 3, 4, 5]
[4, 5, 6, 9, 1] --> [1] + [4, 5, 6, 9]
[10, 11, 6, 7, 9] --> [6, 7, 9] + [10, 11]
[1, 2, 3, 4, 5] --> [1, 2, 3, 4, 5]
[5, 7, 43, 987, -9, 0] --> [-9, 0] + [5, 7, 43, 987]
[1, 2, 3, 4, 1] --> [1] + [1, 2, 3, 4]
```
While these are not (`false`):
```
[4, 1, 2, 5]
[8, 7, 6, 5, 4, 3]
[6, 7, 4, 8]
[7, 6, 5, 4, 3, 2, 1]
```
|
algorithms
|
def circularly_sorted(arr):
return sum(x > y for x, y in zip(arr, arr[1:] + [arr[0]])) < 2
|
Circularly Sorted Array
|
544975fc18f47481ba00107b
|
[
"Algorithms",
"Sorting"
] |
https://www.codewars.com/kata/544975fc18f47481ba00107b
|
6 kyu
|
Your task is to write a regular expression (regex) that will match a string only if it contains at least one valid date, in the format `[mm-dd]` (that is, a two-digit month, followed by a dash, followed by a two-digit date, surrounded by square brackets).
You should assume the year in question is _not_ a leap year. Therefore, the number of days each month should have are as follows:
- 1\. January - 31 days
- 2\. February - 28 days (leap years are ignored)
- 3\. March - 31 days
- 4\. April - 30 days
- 5\. May - 31 days
- 6\. June - 30 days
- 7\. July - 31 days
- 8\. August - 31 days
- 9\. September - 30 days
- 10\. October - 31 days
- 11\. November - 30 days
- 12\. December - 31 days
All text outside a valid date can be ignored, including other _invalid_ dates.
For example:
```javascript
"[01-23]" // January 23rd is a valid date
"[02-31]" // February 31st is an invalid date
"[02-16]" // valid
"[ 6-03]" // invalid format
"ignored [08-11] ignored" // valid
"[3] [12-04] [09-tenth]" // December 4th is a valid date
```
|
reference
|
import re
months_30 = '(04|06|09|11)'
months_31 = '(01|03|05|07|08|10|12)'
months_28 = '02'
days_30 = '(0[1-9]|[1-2][0-9]|30)'
days_31 = '(0[1-9]|[12][0-9]|3[01])'
days_28 = '(0[1-9]|1[0-9]|2[0-8])'
valid_date = re . compile('\[(%s-%s|%s-%s|%s-%s)\]' %
(months_30, days_30, months_31, days_31, months_28, days_28))
|
validDate Regex
|
548db0bd1df5bbf29b0000b7
|
[
"Date Time",
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/548db0bd1df5bbf29b0000b7
|
5 kyu
|
In this kata you are given an array to sort but you're expected to start sorting from a specific position of the array (in ascending order) and optionally you're given the number of items to sort.
#### Examples:
```php
sect_sort([1, 2, 5, 7, 4, 6, 3, 9, 8], 2) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
sect_sort([9, 7, 4, 2, 5, 3, 1, 8, 6], 2, 5) //=> [9, 7, 1, 2, 3, 4, 5, 8, 6]
```
```crystal
sect_sort([1, 2, 5, 7, 4, 6, 3, 9, 8], 2) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
sect_sort([9, 7, 4, 2, 5, 3, 1, 8, 6], 2, 5) //=> [9, 7, 1, 2, 3, 4, 5, 8, 6]
```
```ruby
sect_sort([1, 2, 5, 7, 4, 6, 3, 9, 8], 2) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
sect_sort([9, 7, 4, 2, 5, 3, 1, 8, 6], 2, 5) //=> [9, 7, 1, 2, 3, 4, 5, 8, 6]
```
```python
sect_sort([1, 2, 5, 7, 4, 6, 3, 9, 8], 2) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
sect_sort([9, 7, 4, 2, 5, 3, 1, 8, 6], 2, 5) //=> [9, 7, 1, 2, 3, 4, 5, 8, 6]
```
```javascript
sectSort([1, 2, 5, 7, 4, 6, 3, 9, 8], 2) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
sectSort([9, 7, 4, 2, 5, 3, 1, 8, 6], 2, 5) //=> [9, 7, 1, 2, 3, 4, 5, 8, 6]
```
```java
SectionalArray.sort([1, 2, 5, 7, 4, 6, 3, 9, 8], 2) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
SectionalArray.sort([9, 7, 4, 2, 5, 3, 1, 8, 6], 2, 5) // => [9, 7, 1, 2, 3, 4, 5, 8, 6]
```
#### Documentation:
```php
sect_sort($array, $start, $length);
```
```crystal
sect_sort($array, $start, $length);
```
```ruby
sect_sort($array, $start, $length);
```
```python
sect_sort(array, start, length);
```
```javascript
sectSort(array, start, length);
```
```java
SectionalArray.sort(array, start, length);
```
- array - array to sort
- start - position to begin sorting
- length - number of items to sort (optional)
if the **length** argument is not passed or is zero, you sort all items to the right of the start position in the array
|
algorithms
|
def sect_sort(lst, start, length=0):
end = start + length if length else len(lst)
return lst[: start] + sorted(lst[start: end]) + lst[end:]
|
Sectional Array Sort
|
58ef87dc4db9b24c6c000092
|
[
"Arrays",
"Sorting",
"Data Structures",
"Algorithms"
] |
https://www.codewars.com/kata/58ef87dc4db9b24c6c000092
|
7 kyu
|
You are standing on top of an amazing Himalayan mountain. The view is absolutely breathtaking! you want to take a picture on your phone, but... your memory is full again! ok, time to sort through your shuffled photos and make some space...
Given a gallery of photos, write a function to sort through your pictures.
You get a random hard disk drive full of pics, you must return an array with the 5 most recent ones PLUS the next one (same year and number following the one of the last).
You will always get at least a photo and all pics will be in the format `YYYY.imgN`
Examples:
```javascript
sortPhotos["2016.img1","2016.img2","2015.img3","2016.img4","2013.img5"]) ==["2013.img5","2015.img3","2016.img1","2016.img2","2016.img4","2016.img5"]
sortPhotos["2016.img1"]) ==["2016.img1","2016.img2"]
```
```ruby
sort_photos["2016.img1","2016.img2","2015.img3","2016.img4","2013.img5"]) ==["2013.img5","2015.img3","2016.img1","2016.img2","2016.img4","2016.img5"]
sort_photos["2016.img1"]) ==["2016.img1","2016.img2"]
```
```python
sort_photos["2016.img1","2016.img2","2015.img3","2016.img4","2013.img5"] ==["2013.img5","2015.img3","2016.img1","2016.img2","2016.img4","2016.img5"]
sort_photos["2016.img1"] ==["2016.img1","2016.img2"]
```
|
reference
|
import re
_PAT = re . compile(r'(\d{4})\.img(\d+)')
def _KEY(pic): return map(int, _PAT . match(pic). groups())
def sort_photos(pics):
pics = sorted(pics, key=_KEY)[- 5:]
year, idx = _KEY(pics[- 1])
return pics + ['{}.img{}' . format(year, idx + 1)]
|
Take a picture !
|
56c9f47b0844d85f81000fc2
|
[
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/56c9f47b0844d85f81000fc2
|
6 kyu
|
Your granny, who lives in town X0, has friends.
These friends are given in an array, for example:
array of friends is `["A1", "A2", "A3", "A4", "A5"]`.
**The order of friends in this array must *not be changed* since this order gives the order in which they will be visited.**
Friends inhabit towns and you get an array
with friends and their towns (or an associative array), for example:
`[["A1", "X1"], ["A2", "X2"], ["A3", "X3"], ["A4", "X4"]]`
which means A1 is in town X1, A2 in town X2...
It can happen that we do not know the town of one of the friends hence it will not be visited.
Your granny wants to visit her friends and to know approximately how many miles
she will have to travel. You will make the circuit that permits her to visit her friends.
For example here the circuit will be:`X0, X1, X2, X3, X4, X0`
and you will compute approximately the total distance `X0X1 + X1X2 + .. + X4X0`.
For the distances you are given an array or a dictionary that gives each distance X0X1, X0X2 and so on. For example (it depends on the language):
```
[ ["X1", 100.0], ["X2", 200.0], ["X3", 250.0], ["X4", 300.0] ]
or
("X1" -> 100.0, "X2" -> 200.0, "X3" -> 250.0, "X4" -> 300.0)
```
which means that X1 is at 100.0 miles from X0, X2 at 200.0 miles from X0, etc...
It's not real life, it's a story... :
the towns X0, X1, .., X0 are placed in the following manner (see drawing below):
X0X1X2 is a right triangle with the right angle in X1, X0X2X3 is a right triangle with the right angle in X2, ...
In a travel X0, X1, .., Xi-1, Xi, Xi+1.., X0 you will suppose - to make it easier - that there is a right angle in Xi (i > 0).
So if a town Xi is not visited you will consider that the triangle <code> X<sub>0</sub>X<sub>i-1</sub>X<sub>i+1</sub></code>
is still a right triangle in <code>X<sub>i-1</sub></code> and you can use the "Pythagorean_theorem".
#### Task
Can you help your granny and give her approximately the distance to travel?
#### Notes
If you have some difficulty to see the tour I made a maybe useful drawing:

#### All languages:
- See the type of data in the sample tests.
- Friends and towns can have other names than in the examples.
- Function "tour" returns an int which is the floor of the total distance.
|
reference
|
def tour(friends, friend_towns, home_to_town_distances):
res = 0
s = 0
for i in friend_towns:
if i[0] in friends:
res = res + (home_to_town_distances[i[1]] * * 2 - s * * 2) * * (0.5)
s = home_to_town_distances[i[1]]
res = res + s
return int(res)
|
Help your granny!
|
5536a85b6ed4ee5a78000035
|
[
"Fundamentals",
"Mathematics"
] |
https://www.codewars.com/kata/5536a85b6ed4ee5a78000035
|
5 kyu
|
We search non-negative integer numbers, with at **most** 3 digits, such as the sum of the cubes of their digits is the number itself; we will call them "cubic" numbers.
```
153 is such a "cubic" number : 1^3 + 5^3 + 3^3 = 153
```
These "cubic" numbers of at most 3 digits are easy to find, even by hand, so they are "hidden" with other numbers and characters in a string.
The task is to find, or not, the "cubic" numbers in the string and then to make the *sum* of these "cubic" numbers found in the string, if any, and to return a string such as:
```
"number1 number2 (and so on if necessary) sumOfCubicNumbers Lucky"
```
if "cubic" numbers number1, number2, ... were found.
The numbers in the output are to be in the order in which they are encountered in the input string.
If no cubic numbers are found return the string: `"Unlucky"``.
#### Examples:
```
- s = "aqdf&0#1xyz!22[153(777.777"
the groups of at most 3 digits are 0 and 1 (one digit), 22 (two digits), 153, 777, 777 (3 digits)
Only 0, 1, 153 are cubic and their sum is 154
Return: "0 1 153 154 Lucky"
- s = "QK29a45[&erui9026315"
the groups are 29, 45, 902, 631, 5. None is cubic.
Return: "Unlucky"
```
#### Notes
- In the string "001234" where 3 digits or more follow each other the first group to examine is "001" and the following is "234". If a packet of at most three digits has been taken, whether or not "cubic", it's over for that packet.
- When a continuous string of digits exceeds 3, the string is split into groups of 3 from the left. The last grouping could have 3, 2 or 1 digits.
e.g "24172410" becomes 3 strings comprising "241", "724" and "10"
e.g "0785" becomes 2 strings comprising "078" and "5".
|
reference
|
import re
PATTERN = re . compile(r'(\d{1,3})')
def is_sum_of_cubes(s):
found = list(filter(lambda nStr: int(nStr) == sum(int(d) * * 3 for d in nStr), PATTERN . findall(s)))
return "Unlucky" if not found else "{} {} {}" . format(' ' . join(found), sum(map(int, found)), 'Lucky')
|
Hidden "Cubic" numbers
|
55031bba8cba40ada90011c4
|
[
"Algorithms",
"Strings"
] |
https://www.codewars.com/kata/55031bba8cba40ada90011c4
|
6 kyu
|
Your task is to write a function that receives as its single argument a string that contains numbers delimited by single spaces. Each number has a single alphabet letter somewhere within it.
```
Example : "24z6 1x23 y369 89a 900b"
```
As shown above, this alphabet letter can appear anywhere within the number. You have to extract the letters and sort the numbers according to their corresponding letters.
```
Example : "24z6 1x23 y369 89a 900b" will become 89 900 123 369 246 (ordered according to the alphabet letter)
```
Here comes the difficult part, now you have to do a series of computations on the numbers you have extracted.
* The sequence of computations are `+ - * /`. Basic math rules do **NOT** apply, you have to do each computation in exactly this order.
* This has to work for any size of numbers sent in (after division, go back to addition, etc).
* In the case of duplicate alphabet letters, you have to arrange them according to the number that appeared first in the input string.
* Remember to also round the final answer to the nearest integer.
```
Examples :
"24z6 1x23 y369 89a 900b" = 89 + 900 - 123 * 369 / 246 = 1299
"24z6 1z23 y369 89z 900b" = 900 + 369 - 246 * 123 / 89 = 1414
"10a 90x 14b 78u 45a 7b 34y" = 10 + 45 - 14 * 7 / 78 + 90 - 34 = 60
```
Good luck and may the CODE be with you!
|
reference
|
from functools import reduce
from itertools import cycle
from operator import add, truediv, mul, sub
def do_math(s):
xs = sorted(s . split(), key=lambda x: next(c for c in x if c . isalpha()))
xs = [int('' . join(filter(str . isdigit, x))) for x in xs]
ops = cycle([add, sub, mul, truediv])
return round(reduce(lambda a, b: next(ops)(a, b), xs))
|
Number , number ... wait LETTER !
|
5782dd86202c0e43410001f6
|
[
"Strings",
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/5782dd86202c0e43410001f6
|
6 kyu
|
You will have a list of rationals in the form
```
lst = [ [numer_1, denom_1] , ... , [numer_n, denom_n] ]
```
or
```
lst = [ (numer_1, denom_1) , ... , (numer_n, denom_n) ]
```
where all numbers are positive integers. You have to produce their sum `N / D` in an irreducible form: this means that `N` and `D` have only `1` as a common divisor.
Return the result in the form:
- `[N, D]` in Ruby, Crystal, Python, Clojure, JS, CS, PHP, Julia, Pascal
- `Just "N D"` in Haskell, PureScript
- `"[N, D]"` in Java, CSharp, TS, Scala, PowerShell, Kotlin
- `"N/D"` in Go, Nim
- `{N, D}` in C, C++, Elixir, Lua
- `Some((N, D))` in Rust
- `Some "N D"` in F#, Ocaml
- `c(N, D)` in R
- `(N, D)` in Swift
- `'(N D)` in Racket
If the result is an integer (`D` evenly divides `N`) return:
- an integer in Ruby, Crystal, Elixir, Clojure, Python, JS, CS, PHP, R, Julia
- `Just "n"` (Haskell, PureScript)
- `"n"` Java, CSharp, TS, Scala, PowerShell, Go, Nim, Kotlin
- `{n, 1}` in C, C++, Lua
- `Some((n, 1))` in Rust
- `Some "n"` in F#, Ocaml,
- `(n, 1)` in Swift
- `n` in Racket
- `(n, 1)` in Swift, Pascal, Perl
If the input list is empty, return
- `nil/None/null/Nothing`
- `{0, 1}` in C, C++, Lua
- `"0"` in Scala, PowerShell, Go, Nim
- `O` in Racket
- `""` in Kotlin
- `[0, 1]` in C++, `"[0, 1]"` in Pascal
- `[0, 1]` in Perl
#### Example:
```
[ [1, 2], [1, 3], [1, 4] ] --> [13, 12]
1/2 + 1/3 + 1/4 = 13/12
```
#### Note
* See sample tests for more examples and form of results.
|
reference
|
from fractions import Fraction
def sum_fracts(lst):
if lst:
ret = sum(Fraction(a, b) for (a, b) in lst)
return ret . numerator if ret . denominator == 1 else [ret . numerator, ret . denominator]
|
Irreducible Sum of Rationals
|
5517fcb0236c8826940003c9
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5517fcb0236c8826940003c9
|
6 kyu
|
To participate in a prize draw each one gives his/her firstname.
Each letter of a firstname
has a value which is its rank in the English alphabet. `A` and `a` have rank `1`, `B` and `b` rank `2` and so on.
The *length* of the firstname is added to the *sum* of these ranks hence a number `som`.
An array of random weights is linked to the firstnames and each `som` is multiplied by its corresponding weight to get what they call a `winning number`.
#### Example:
```
names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH"
weights: [1, 4, 4, 5, 2, 1]
PauL -> som = length of firstname + 16 + 1 + 21 + 12 = 4 + 50 -> 54
The *weight* associated with PauL is 2 so PauL's *winning number* is 54 * 2 = 108.
```
Now one can sort the firstnames in *decreasing* order of the `winning numbers`. When two people have the same `winning number` sort them *alphabetically* by their firstnames.
#### Task:
- parameters: `st` a string of firstnames, `we` an array of weights, `n` a rank
- return: the firstname of the participant whose rank is `n`
(ranks are numbered from 1)
#### Example:
```
names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH"
weights: [1, 4, 4, 5, 2, 1]
n: 4
The function should return: "PauL"
```
#### Notes:
- The weight array is at least as long as the number of names, it may be longer.
- If `st` is empty return "No participants".
- If n is greater than the number of participants then return "Not enough participants".
- See Examples Test Cases for more examples.
|
reference
|
def rank(st, we, n):
if not st:
return "No participants"
if n > len(we):
return "Not enough participants"
def name_score(name, w): return w * (len(name) +
sum([ord(c . lower()) - 96 for c in name]))
scores = [name_score(s, we[i]) for i, s in enumerate(st . split(','))]
scores = list(zip(st . split(','), scores))
scores . sort(key=lambda x: (- x[1], x[0]))
return scores[n - 1][0]
|
Prize Draw
|
5616868c81a0f281e500005c
|
[
"Fundamentals",
"Strings",
"Sorting"
] |
https://www.codewars.com/kata/5616868c81a0f281e500005c
|
6 kyu
|
Implement a function that receives a string, and lets you extend it with repeated calls. When no argument is passed you should return a string consisting of space-separated words you've received earlier.
**Note**: There will always be at least 1 string; all inputs will be non-empty.
For example:
```javascript
createMessage("Hello")("World!")("how")("are")("you?")() === "Hello World! how are you?"
```
```python
create_message("Hello")("World!")("how")("are")("you?")() == "Hello World! how are you?"
```
Tip (helpful, but not necessary): Try using classes!
Good luck and happy coding!
|
reference
|
class create_message (str):
def __call__(self, s=''):
return create_message(f' { self } { s } ' . strip())
|
"Stringing"+"Me"+"Along"
|
55f4a44eb72a0fa91600001e
|
[
"Functional Programming",
"Fundamentals"
] |
https://www.codewars.com/kata/55f4a44eb72a0fa91600001e
|
6 kyu
|
`data`and `data1` are two strings with rainfall records of a few cities for months from January to December.
The records of towns are separated by `\n`. The name of each town is followed by `:`.
`data` and `towns` can be seen in "Your Test Cases:".
#### Task:
- function: `mean(town, strng)` should return the average of rainfall for the city `town` and the `strng` `data` or `data1` (In R and Julia this function is called `avg`).
- function: `variance(town, strng)` should return the variance of rainfall for the city `town` and the `strng` `data` or `data1`.
#### Examples:
```
mean("London", data), 51.19(9999999999996)
variance("London", data), 57.42(833333333374)
```
#### Notes:
- if functions `mean` or `variance` have as parameter `town` a city which has no records return `-1` or `-1.0` (depending on the language)
- Don't truncate or round: the tests will pass if `abs(your_result - test_result) <= 1e-2`
or `abs((your_result - test_result) / test_result) <= 1e-6` depending on the language.
- Shell
1) Shell tests only variance.
2) In "function "variance" $1 is "data", $2 is "town".
- A ref: <http://www.mathsisfun.com/data/standard-deviation.html>
- `data` and `data1` (can be named `d0` and `d1` depending on the language; see "Sample Tests:") are adapted from: <http://www.worldclimate.com>
|
reference
|
def get_towndata(town, strng):
for line in strng . split('\n'):
s_town, s_data = line . split(':')
if s_town == town:
return [s . split(' ') for s in s_data . split(',')]
return None
def mean(town, strng):
data = get_towndata(town, strng)
if data is not None:
return sum([float(x) for m, x in data]) / len(data)
else:
return - 1.
def variance(town, strng):
data = get_towndata(town, strng)
if data is not None:
mean = sum([float(x) for m, x in data]) / len(data)
return sum([(float(x) - mean) * * 2 for m, x in data]) / len(data)
else:
return - 1.
|
Rainfall
|
56a32dd6e4f4748cc3000006
|
[
"Fundamentals",
"Strings"
] |
https://www.codewars.com/kata/56a32dd6e4f4748cc3000006
|
6 kyu
|
[Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) is a two-dimensional Turing machine invented in the late 1980s. The ant starts out on a grid of black and white cells and follows a simple set of rules that has complex emergent behavior.
## Task
Complete the function and return the `n`th iteration of Langton's ant with the given input.
### Parameters:
* `grid` - a two dimensional array of `1`s and `0`s (representing white and black cells respectively)
* `column` - horizontal position of ant
* `row` - ant's vertical position
* `n` - number of iterations
* `dir` - ant's current direction (0 - north, 1 - east, 2 - south, 3 - west), **should default to 0**
**Note:** parameters `column` and `row` will always be inside the `grid`, and number of generations `n` will never be negative.
## Output
The state of the `grid` after `n` iterations.
## Rules
The ant can travel in any of the four cardinal directions at each step it takes. The ant moves according to the rules below:
* At a white square (represented with `1`), turn 90° right, flip the color of the square, and move forward one unit.
* At a black square (`0`), turn 90° left, flip the color of the square, and move forward one unit.
The grid has no limits and therefore if the ant moves outside the borders, the grid should be expanded with `0`s, respectively maintaining the rectangle shape.
## Example
```python
ant([[1]], 0, 0, 1, 0) # should return: [[0, 0]]
```
```julia
ant([1; 1], 1, 1, 1, 0) # should return: [0 0; 1 0]
```
Initially facing north (`0`), at the first iteration the ant turns right (because it stands on a white square, `1`), flips the square and moves forward.
|
algorithms
|
def ant(grid, col, row, n, dir=0):
for _ in range(n):
# turn
color = grid[row][col]
if color == 1:
dir = (dir + 1) % 4
elif color == 0:
dir = (dir - 1) % 4
# flip color
grid[row][col] ^= 1
# move forward
if dir == 0:
row -= 1
elif dir == 1:
col += 1
elif dir == 2:
row += 1
elif dir == 3:
col -= 1
# expand grid
if row < 0:
grid . insert(0, [0] * len(grid[0]))
row = 0
if row == len(grid):
grid . append([0] * len(grid[0]))
if col < 0:
for i in range(len(grid)):
grid[i]. insert(0, 0)
col = 0
if col == len(grid[0]):
for i in range(len(grid)):
grid[i]. append(0)
return grid
|
Langton's ant
|
58e6996019af2cff71000081
|
[
"Recursion",
"Algorithms"
] |
https://www.codewars.com/kata/58e6996019af2cff71000081
|
5 kyu
|
You know combinations: for example,
if you take `5` cards from a `52` cards deck you have `2,598,960` different combinations.
In mathematics the number of `x` combinations you can take from a set of `n` elements
is called the *binomial coefficient of n and x*, or more often `n choose x`.
The formula to compute `n choose x` is:
`n! / (x! * (n - x)!)`
where `!` is the factorial operator.
You are a renowned poster designer and painter. You are asked to provide `6` posters
all having the same design each in `2` colors. Posters must all have a different color combination and you have the choice of `4` colors: `red, blue, yellow, green`.
How many colors can you choose for each poster?
The answer is **two** since `4 choose 2 = 6`. The combinations will be:
`{red, blue}, {red, yellow}, {red, green}, {blue, yellow}, {blue, green}, {yellow, green}`.
Now same question but you have `35` posters to provide and `7` colors available. How many colors for each poster?
If you take combinations `7 choose 2` you will get `21` with the above formula.
But `21` schemes aren't enough for `35` posters. If you take `7 choose 5` combinations you will get `21` too.
Fortunately if you take `7 choose 3` or `7 choose 4` combinations you get `35` and so each poster will have a different combination of
`3` colors or `4` colors. You will take `3` colors because it's less expensive.
#### Hence the problem:
Knowing `m` (number of posters to design) and `n` (total number of available colors),
let us search `x`, the number of colors for each poster so that each poster has a unique combination of colors and the number of combinations is exactly the same as the number of posters `m`.
In other words, you must find `x` such that:
`n choose x = m`
for a given `m >= 0` and a given `n > 0`.
If there are several solutions, return the smallest. If there are no solutions, return `-1`.
#### Examples:
```
(m = 6, n = 4) --> 2
(m = 4, n = 4) --> 1
(m = 4, n = 2) --> -1
(m = 35, n = 7) --> 3
(m = 36, n = 7) --> -1
a = 47129212243960
(m = a, n = 50) --> 20
(m = a + 1, n = 50) --> -1
```
|
reference
|
def checkchoose(m, n):
c = 1
for x in range(n / / 2 + 1):
if c == m:
return x
c = c * (n - x) / / (x + 1)
else:
return - 1
|
Color Choice
|
55be10de92aad5ef28000023
|
[
"Combinatorics",
"Mathematics"
] |
https://www.codewars.com/kata/55be10de92aad5ef28000023
|
6 kyu
|
The numbers 6, 12, 18, 24, 36, 48 have a common property. They have the same two prime factors that are 2 and 3.
If we see their prime factorization we will see it more clearly:
```python
6 = 2 * 3
12 = 2^2 * 3
18 = 2 * 3^2
24 = 2^3 * 3
36 = 2^2 * 3^2
48 = 2^4 * 3
```
48 is the maximum of them bellow the value 50
We may see another cases, for numbers that have another two prime factors like: 5, 11, but bellow (or equal) a maximum value 1000
```python
55 = 5 * 11
275 = 5^2 * 11
605 = 5 * 11^2
```
In this case 605 is the highest possible number bellow 1000.
Make the function highest_biPrimefac(), that receives two primes as arguments and a maximum limit , nMax(found numbers should be less or equal to nMax). Output should be a list or array of highest number found and the corresponding exponents of primes in order given.
Representing the features for this function:
```python
highest_biPrimefac(p1, p2, nMax) -------> [max.number, k1, k2]
max.number = p1^k1 * p2^k2 <= nMax
p1 < p2 and k1 >= 1, k2 >= 1
```
Let's see the cases we have above:
```python
highest_biPrimefac(2, 3, 50) ------> [48, 4, 1]
highest_biPrime(5, 11, 1000) ------> [605, 1, 2]
```
Enjoy it and happy coding!
|
reference
|
def highest_biPrimefac(p1, p2, n): # p1, p2 primes and p1 < p2
factors = {}
k1, k2 = 1, 1
while p1 * * k1 * p2 * * k2 <= n:
while p1 * * k1 * p2 * * (k2 + 1) <= n:
k2 += 1
factors[p1 * * k1 * p2 * * k2] = (k1, k2)
k1, k2 = k1 + 1, 1
m = max(factors)
return [m, factors[m][0], factors[m][1]]
|
Highest number with two prime factors
|
55f347cfb44b879e1e00000d
|
[
"Fundamentals",
"Mathematics"
] |
https://www.codewars.com/kata/55f347cfb44b879e1e00000d
|
6 kyu
|
<h5 style='color:#ffff00'>Task:</h5>
This kata requires you to write an object that receives a file path
and does operations on it.
<b style='color:#ff0000'>NOTE FOR PYTHON USERS</b>: You cannot use modules os.path, glob, and re
<h5 style='color:#00ff00'>The purpose of this kata is to use string parsing, so you're not supposed to import external libraries. I could only enforce this in python.</h5>
<h5 style='color:#ffff00'>Testing:</h5>
Python:
```python
>>> master = FileMaster('/Users/person1/Pictures/house.png')
>>> master.extension()
'png'
>>> master.filename()
'house'
>>> master.dirpath()
'/Users/person1/Pictures/'
```
Ruby:
```ruby
master = FileMaster.new('/Users/person1/Pictures/house.png')
master.extension
#--> png
master.filename
#--> house
master.dirpath
#--> /Users/person1/Pictures/
```
C#:
```csharp
FileMaster FM = new FileMaster("/Users/person1/Pictures/house.png");
FM.extension(); // output: "png"
FM.filename(); // output: "house"
FM.dirpath(); // output: "/Users/person1/Pictures/"
```
JavaScript:
```javascript
const fm = new FileMaster('/Users/person1/Pictures/house.png');
fm.extension(); // output: 'png'
fm.filename(); // output: 'house'
fm.dirpath(); // output: '/Users/person1/Pictures/'
```
TypeScript:
```typescript
const fm = new FileMaster('/Users/person1/Pictures/house.png');
fm.extension(); // output: 'png'
fm.filename(); // output: 'house'
fm.dirpath(); // output: '/Users/person1/Pictures/'
```
PHP:
```php
$fm = new FileMaster('/Users/person1/Pictures/house.png');
$fm.extension(); // 'png'
$fm.filename(); // 'house'
$fm.dirpath(); // '/Users/person1/Pictures'
```
<h5 style='color:#ffff00'>Notes:</h5>
<ul style='text-align:left;'>
<li>I have other kata that need to be tested. You may find them <a href='https://www.codewars.com/kata/5866a58b9cbc02c4f8000cac'>here</a> and <a href='https://www.codewars.com/kata/58644e8ddf95f81a38001d8d'>here</a></li>
<li>Please post any questions or suggestion in the discourse section. Thank you!</li>
<li>Thank to all users who contributed to this kata! I appreciate your input!</li>
</ul>
|
reference
|
class FileMaster ():
def __init__(self, filepath):
lk = filepath . rfind('.')
ls = filepath . rfind('/')
self . ext = filepath[lk + 1:]
self . file = filepath[ls + 1: lk]
self . path = filepath[: ls + 1]
def extension(self):
return self . ext
def filename(self):
return self . file
def dirpath(self):
return self . path
|
File Path Operations
|
5844e0890d3bedc5c5000e54
|
[
"Fundamentals",
"Strings",
"Restricted"
] |
https://www.codewars.com/kata/5844e0890d3bedc5c5000e54
|
6 kyu
|
Implement a function, so it will produce a sentence out of the given parts.
Array of parts could contain:<br>
- words;<br>
- commas in the middle;<br>
- multiple periods at the end.<br>
Sentence making rules:<br>
- there must always be a space between words;<br>
- there must not be a space between a comma and word on the left;<br>
- there must always be one and only one period at the end of a sentence.<br>
**Example:**
```javascript
makeSentence(['hello', ',', 'my', 'dear']) // returns 'hello, my dear.'
```
```coffeescript
makeSentence ['hello', ',', 'my', 'dear'] # returns 'hello, my dear.'
```
```ruby
make_sentence ['hello', ',', 'my', 'dear'] # returns 'hello, my dear.'
```
|
reference
|
def make_sentences(parts):
return ' ' . join(parts). replace(' ,', ','). strip(' .') + '.'
|
Simple Sentences
|
5297bf69649be865e6000922
|
[
"Strings",
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/5297bf69649be865e6000922
|
6 kyu
|
~~~if-not:java
You have to code a function **getAllPrimeFactors**, which takes an integer as parameter and returns an array containing its prime decomposition by ascending factors. If a factor appears multiple times in the decomposition, it should appear as many times in the array.
exemple: `getAllPrimeFactors(100)` returns `[2,2,5,5]` in this order.
This decomposition may not be the most practical.
You should also write **getUniquePrimeFactorsWithCount**, a function which will return an array containing two arrays: one with prime numbers appearing in the decomposition and the other containing their respective power.
exemple: `getUniquePrimeFactorsWithCount(100)` returns `[[2,5],[2,2]]`
You should also write **getUniquePrimeFactorsWithProducts**, which returns an array containing the prime factors to their respective powers.
exemple: `getUniquePrimeFactorsWithProducts(100)` returns `[4,25]`
~~~
~~~if:java
You have to code a function **getAllPrimeFactors**, which take an integer as parameter and returns an array containing its prime decomposition by ascending factors. If a factor appears multiple times in the decomposition, it should appear as many times in the array.
exemple: `getAllPrimeFactors(100)` returns `[2,2,5,5]` in this order.
This decomposition may not be the most practical.
You should also write **getUniquePrimeFactorsWithCount**, a function which will return an array containing two arrays: one with prime numbers appearing in the decomposition and the other containing their respective power.
exemple: `getUniquePrimeFactorsWithCount(100)` returns `[[2,5],[2,2]]`
You should also write **getPrimeFactorPotencies**, which returns an array containing the prime factors to their respective powers.
exemple: `getPrimeFactorPotencies(100)` returns `[4,25]`
~~~
Errors, if:
* `n` is not a number
* `n` not an integer
* `n` is negative or 0
The three functions should respectively return `[]`, `[[],[]]` and `[]`.
Edge cases:
* if `n=0`, the function should respectively return `[]`, `[[],[]]` and `[]`.
* if `n=1`, the function should respectively return `[1]`, `[[1],[1]]`, `[1]`.
* if `n=2`, the function should respectively return `[2]`, `[[2],[1]]`, `[2]`.
The result for `n=2` is normal. The result for `n=1` is arbitrary and has been chosen to return a usefull result. The result for `n=0` is also arbitrary
but can not be chosen to be both usefull and intuitive. (`[[0],[0]]` would be meaningfull but wont work for general use of decomposition, `[[0],[1]]` would work but is not intuitive.)
|
reference
|
import math
import collections
def getAllPrimeFactors(n):
numberToDecompose = n
if (not isinstance(numberToDecompose, (int, long)) or numberToDecompose <= 0):
return []
answer = ([1] if (numberToDecompose == 1) else [])
for possibleFactor in range(2, numberToDecompose + 1):
while (numberToDecompose % possibleFactor == 0):
answer . extend([possibleFactor])
numberToDecompose = numberToDecompose / possibleFactor
answer = sorted(answer)
return answer
def getUniquePrimeFactorsWithProducts(n):
ch = getUniquePrimeFactorsWithCount(n)
x = [a * * b for (a, b) in zip(ch[0], ch[1])]
return x
def getUniquePrimeFactorsWithCount(n):
c = collections . Counter(getAllPrimeFactors(n))
d = [a for (a, _) in c . items()]
e = [b for (_, b) in c . items()]
return [d, e]
|
Prime number decompositions
|
53c93982689f84e321000d62
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/53c93982689f84e321000d62
|
5 kyu
|
Complete the method which returns the number which is most frequent in the given input array. If there is a tie for most frequent number, return the largest number among them.
Note: no empty arrays will be given.
## Examples
```
[12, 10, 8, 12, 7, 6, 4, 10, 12] --> 12
[12, 10, 8, 12, 7, 6, 4, 10, 12, 10] --> 12
[12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10] --> 3
```
|
reference
|
from collections import Counter
def highest_rank(arr):
if arr:
c = Counter(arr)
m = max(c . values())
return max(k for k, v in c . items() if v == m)
|
Highest Rank Number in an Array
|
5420fc9bb5b2c7fd57000004
|
[
"Arrays",
"Fundamentals"
] |
https://www.codewars.com/kata/5420fc9bb5b2c7fd57000004
|
6 kyu
|
Write a function ```convert_temp(temp, from_scale, to_scale)``` converting temperature from one scale to another.
Return converted temp value.
Round converted temp value to an integer(!).
Reading: http://en.wikipedia.org/wiki/Conversion_of_units_of_temperature
```
possible scale inputs:
"C" for Celsius
"F" for Fahrenheit
"K" for Kelvin
"R" for Rankine
"De" for Delisle
"N" for Newton
"Re" for Réaumur
"Ro" for Rømer
```
```temp``` is a number, ```from_scale``` and ```to_scale``` are strings.
```python
convert_temp( 100, "C", "F") # => 212
convert_temp( 40, "Re", "C") # => 50
convert_temp( 60, "De", "F") # => 140
convert_temp(373.15, "K", "N") # => 33
convert_temp( 666, "K", "K") # => 666
```
```ruby
convert_temp( 100, "C", "F") # => 212
convert_temp( 40, "Re", "C") # => 50
convert_temp( 60, "De", "F") # => 140
convert_temp(373.15, "K", "N") # => 33
convert_temp( 666, "K", "K") # => 666
```
|
reference
|
TO_KELVIN = {
'C': (1, 273.15),
'F': (5.0 / 9, 459.67 * 5.0 / 9),
'R': (5.0 / 9, 0),
'De': (- 2.0 / 3, 373.15),
'N': (100.0 / 33, 273.15),
'Re': (5.0 / 4, 273.15),
'Ro': (40.0 / 21, - 7.5 * 40 / 21 + 273.15),
}
def convert_temp(temp, from_scale, to_scale):
if from_scale == to_scale:
return temp
if from_scale != 'K':
(a, b) = TO_KELVIN[from_scale]
temp = a * temp + b
if to_scale == 'K':
return int(round(temp))
(a, b) = TO_KELVIN[to_scale]
return int(round((temp - b) / a))
|
Temperature converter
|
54ce9497975ca65e1a0008c6
|
[
"Functional Programming",
"Data Structures",
"Strings",
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/54ce9497975ca65e1a0008c6
|
6 kyu
|
You will be given a string (`x`) featuring a cat `'C'`, a dog `'D'` and a mouse `'m'`. The rest of the string will be made up of `'.'`.
You need to find out if the cat can catch the mouse from its current position. The cat can jump at most (`j`) characters, and cannot jump over the dog.
So:
* if `j` = `5`:
`..C.....m...D` returns `'Caught!'` <-- not more than `j` characters between the cat and the mouse
`.....C............m......D` returns `'Escaped!'` <-- as there are more than `j` characters between the two, the cat cannot jump far enough
* if `j` = `10`:
`...m.........C...D` returns `'Caught!'` <-- Cat can jump far enough and jump is not over dog
`...m....D....C.......` returns `'Protected!'` <-- Cat can jump far enough, but dog is in the way, protecting the mouse
* Finally, if not all three animals are present, return `'boring without all three'`
|
reference
|
def cat_mouse(x, j):
d, c, m = x . find('D'), x . find('C'), x . find('m')
if - 1 in [d, c, m]:
return 'boring without all three'
if abs(c - m) <= j:
return 'Protected!' if c < d < m or m < d < c else 'Caught!'
return 'Escaped!'
|
Cat and Mouse - Harder Version
|
57ee2a1b7b45efcf700001bf
|
[
"Fundamentals",
"Strings",
"Arrays"
] |
https://www.codewars.com/kata/57ee2a1b7b45efcf700001bf
|
6 kyu
|
<h2>The Rhinestone Cowboy - Count the dollars in his boots!</h2>
```
,|___|,
| |
| |
| |
| == |
|[(1)]|
/ &|
.-'` , )****
| | **
`~~~~~~~~~~ ^
^
|
One Dollar Bill
,|___|,
| |
| |
|[(1)]|
| == |
|[(1)]|
/ &|
.-'` , )****
| | **
`~~~~~~~~~~ ^
^
|
Two Dollar Bills
,|___|,
|[{1}]| <---- not a bill
| |
|[(1)]|
| == |
|[(1)]|
/ &| <---- top is above the "&"
.-'` , )****
| | **
`~~~~~~~~~~ ^
^
|
Two Dollar Bills
```
<h2>Task</h2>
You will receive an array of two strings with the Cowboys boots. Count the number of dollars in each boot and return a string such as:
"This Rhinestone Cowboy has 2 dollar bills in his right boot and 1 in the left"
```
boots[0] = left boot
boots[1] = right boot
```
The bill must be of form ```[(1)]``` to be counted and only count ones no other denominations. Only count bills in the top half of the boot(boot leg) so the cowboy can pull money out without removing the boots, see diagram above.
The test boots will be well-formed and always the same size.
You will always be given two boots since a Cowboy cannot walk around barefoot!
Dedicated to one of the coolest dudes ever....
Glen Campbell
=> https://www.youtube.com/watch?v=8kAU3B9Pi_U
|
reference
|
def cowboys_dollars(boots):
return "This Rhinestone Cowboy has %d dollar bills in his right boot and %d in the left" \
% tuple([boots[i]. split("&")[0]. count("[(1)]") for i in (1, 0)])
|
The Rhinestone Cowboy ~ Count the dollars in his boots!
|
58a2a561f749ed763c00000b
|
[
"Algorithms",
"ASCII Art"
] |
https://www.codewars.com/kata/58a2a561f749ed763c00000b
|
6 kyu
|
Have you heard about the myth that [if you fold a paper enough times, you can reach the moon with it](http://scienceblogs.com/startswithabang/2009/08/31/paper-folding-to-the-moon/)? Sure you have, but exactly how many? Maybe it's time to write a program to figure it out.
You know that a piece of paper has a thickness of `0.0001m`. Given `distance` in units of meters, calculate how many times you have to fold the paper to make the paper reach this distance.
(If you're not familiar with the concept of folding a paper: Each fold doubles its total thickness.)
Note: Of course you can't do half a fold. You should know what this means ;P
Also, if somebody is giving you a negative distance, it's clearly bogus and you should yell at them by returning `null` (or whatever equivalent in your language). In Shell please return `None`. In C and COBOL please return `-1`.
|
reference
|
def fold_to(distance, thickness=0.0001, folds=0):
if distance < 0:
return
while thickness < distance:
thickness *= 2
folds += 1
return folds
|
Folding your way to the moon
|
58f0ba42e89aa6158400000e
|
[
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/58f0ba42e89aa6158400000e
|
7 kyu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.