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 |
|---|---|---|---|---|---|---|---|
 You have a string. The string consists of words. Before words can be an exclamation mark `!`. Also some words are marked as one set with square brackets `[]`. You task is to split the string into separate words and sets.<br>
 The set can't be contained in another set.
Input:<br>
 String with words (separated by spaces), `!` and `[]`.
Output:<br>
 Array with separated words and sets.
Examples:
```
('Buy a !car [!red green !white] [cheap or !new]') => ['Buy', 'a', '!car', '[!red green !white]', '[cheap or !new]']
('!Learning !javascript is [a joy]') => ['!Learning', '!javascript', 'is', '[a joy]']
('[Cats and dogs] are !beautiful and [cute]') => ['[Cats and dogs]', 'are', '!beautiful', 'and', '[cute]']
```
|
reference
|
import re
def clever_split(s):
return re . findall(r'\[.*?\]|\S+', s)
|
Clever split
|
5992e11d6ca73b38d50000f0
|
[
"Strings",
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/5992e11d6ca73b38d50000f0
|
6 kyu
|
# Background
The famous Collatz Sequence is generated with the following rules:
* Start with a positive integer `a[0] = n`.
* If `a[i]` is even, `a[i+1] = a[i] / 2`.
* Otherwise, `a[i+1] = a[i] * 3 + 1`.
However, for the purpose of this Kata, I give a **slightly modified definition**:
* If `a[i]` is even, `a[i+1] = a[i] / 2`. This step is a step-down, or `D`.
* Otherwise, `a[i+1] = (a[i] * 3 + 1) / 2`. This step is a step-up, or `U`.
Also, for any starting number, the sequence is generated indefinitely, not ending at 1.
# Problem Description
For any given starting number, we can record the types of steps(`D` or `U`) from it.
For example, if we start with the number 11, the Collatz steps look like this:
```
a[0] = 11
a[1] = (11 * 3 + 1) / 2 = 17 -> U
a[2] = (17 * 3 + 1) / 2 = 26 -> U
a[3] = 26 / 2 = 13 -> D
a[4] = (13 * 3 + 1) / 2 = 20 -> U
a[5] = 20 / 2 = 10 -> D
a[6] = 10 / 2 = 5 -> D
a[7] = (5 * 3 + 1) / 2 = 8 -> U
a[8] = 8 / 2 = 4 -> D
a[9] = 4 / 2 = 2 -> D
a[10] = 2 / 2 = 1 -> D
a[11] = (1 * 3 + 1) / 2 = 2 -> U
a[12] = 2 / 2 = 1 -> D
...
```
```
11 -> 17 -> 26 -> 13 -> 20 -> 10 -> 5 -> 8 -> 4 -> 2 -> 1 -> 2 -> 1 -> ...
U U D U D D U D D D U D
```
Based on the steps shown above, the first four Collatz steps of 11 is `UUDU`.
Also, 107 is the smallest number over 100 whose Collatz steps start with `UUDU`, and
1003 is the smallest number over 1000 with the property.
A special example is the number 1, which can generate any number of `UD`.
Find the smallest integer exceeding or equal to `n` whose Collatz steps start with the given string `steps`.
# Constraints
`1 <= n <= 10 ** 9`
`n` is always a valid integer.
`1 <= length(steps) <= 25`
The string `steps` will entirely consist of `U`s and `D`s.
# Examples
```python
collatz_steps(1, 'UUDU') == 11
collatz_steps(100, 'UUDU') == 107
collatz_steps(1000, 'UUDU') == 1003
collatz_steps(1, 'UD') == 1
collatz_steps(1, 'UDUD') == 1
collatz_steps(1, 'UDUDUD') == 1
```
```javascript
collatzSteps(1, 'UUDU') == 11
collatzSteps(100, 'UUDU') == 107
collatzSteps(1000, 'UUDU') == 1003
collatzSteps(1, 'UD') == 1
collatzSteps(1, 'UDUD') == 1
collatzSteps(1, 'UDUDUD') == 1
```
# Hint
If you are completely lost, start by answering the following question:
* After applying the given steps (e.g. `UUDU`) to an initial number `x`,
what fraction do you get?
After that, you might want to study about [modular inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse).
# Acknowledgement
This problem was inspired by [Project Euler #277: A Modified Collatz sequence](https://projecteuler.net/problem=277).
If you enjoyed this Kata, please also have a look at [my other Katas](https://www.codewars.com/users/Bubbler/authored)!
|
games
|
def collatz_steps(n, steps):
def check(x, prefix):
for c in prefix:
if x % 2 == 0:
if c != 'D':
return False
x / /= 2
else:
if c != 'U':
return False
x = (x * 3 + 1) / / 2
return True
k = 1
for i in range(1, len(steps) + 1):
prefix = steps[: i]
while not check(n, prefix):
n += k
k *= 2
return n
|
Numbers with Collatz Starting Patterns
|
5992e103b1429877bb00006b
|
[
"Algorithms",
"Puzzles",
"Mathematics"
] |
https://www.codewars.com/kata/5992e103b1429877bb00006b
|
4 kyu
|
Write a function that takes a string and returns an array containing binary numbers equivalent to the ASCII codes of the characters of the string. The binary strings should be eight digits long.
Example: `'man'` should return `[ '01101101', '01100001', '01101110' ]`
|
reference
|
def word_to_bin(word):
return ['{:08b}' . format(ord(c)) for c in word]
|
Word to binary
|
59859f435f5d18ede7000050
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59859f435f5d18ede7000050
|
7 kyu
|
# Problem Description
You have a row of `n` square tiles, which are colored black and the side length is 1.
You also have infinite supplies of three kinds of rectangular tiles:
* Red tiles of Length `r`
* Green tiles of Length `g`
* Blue tiles of Length `b`
All tiles have integer lengths and share the same height of 1.
Now, you want to replace some black square tiles with your colored tiles.
However, you are quite picky, and you want to use *exactly two types of colored tiles* (RGB).
You can leave black gaps as much as you want.
In how many ways can you replace black tiles with your colored tiles?
Since your answer will be very large, please give your answer **modulo 12345787**.
# Example
For `n = 6` and `(r, g, b) = (2, 3, 4)`, these are the eight possible arrangements
using exactly two colors
(R, G, B denote red, green, blue tiles respectively, and a dot is a black tile):
```
RRGGG.
RR.GGG
.RRGGG
GGGRR.
GGG.RR
.GGGRR
RRBBBB
BBBBRR
```
# Constraints
`5 <= n <= 100`
`2 <= r, g, b <= 5`
Some of the values of `r`, `g`, or `b` may be the same.
The inputs will be always valid integers.
# More Examples
```python
# One Red (length 2) and one Green (length 3): two arrangements
tri_bicolor_tiling(5, 2, 3, 4) == 2
# One Red (length 2) and one Green (length 3): 6 arrangements
# One Red (length 2) and one Blue (length 4): 2 arrangements
tri_bicolor_tiling(6, 2, 3, 4) == 8
tri_bicolor_tiling(10, 2, 3, 4) == 248
# For these cases, think about tiling with dominos first
# and then coloring them with two colors.
tri_bicolor_tiling(5, 2, 2, 2) == 18
tri_bicolor_tiling(6, 2, 2, 2) == 54
```
```javascript
// One Red (length 2) and one Green (length 3): two arrangements
triBicolorTiling(5, 2, 3, 4) == 2
// One Red (length 2) and one Green (length 3): 6 arrangements
// One Red (length 2) and one Blue (length 4): 2 arrangements
triBicolorTiling(6, 2, 3, 4) == 8
triBicolorTiling(10, 2, 3, 4) == 248
// For these cases, think about tiling with dominos first
// and then coloring them with two colors.
triBicolorTiling(5, 2, 2, 2) == 18
triBicolorTiling(6, 2, 2, 2) == 54
```
```java
// One Red (length 2) and one Green (length 3): two arrangements
triBicolorTiling(5, 2, 3, 4) == 2
// One Red (length 2) and one Green (length 3): 6 arrangements
// One Red (length 2) and one Blue (length 4): 2 arrangements
triBicolorTiling(6, 2, 3, 4) == 8
triBicolorTiling(10, 2, 3, 4) == 248
// For these cases, think about tiling with dominos first
// and then coloring them with two colors.
triBicolorTiling(5, 2, 2, 2) == 18
triBicolorTiling(6, 2, 2, 2) == 54
```
```cpp
// One Red (length 2) and one Green (length 3): two arrangements
tri_bicolor_tiling(5, 2, 3, 4) == 2
// One Red (length 2) and one Green (length 3): 6 arrangements
// One Red (length 2) and one Blue (length 4): 2 arrangements
tri_bicolor_tiling(6, 2, 3, 4) == 8
tri_bicolor_tiling(10, 2, 3, 4) == 248
// For these cases, think about tiling with dominos first
// and then coloring them with two colors.
tri_bicolor_tiling(5, 2, 2, 2) == 18
tri_bicolor_tiling(6, 2, 2, 2) == 54
```
~~~if:cpp
**Please avoid the use of** `#define` **macros.**
~~~
# Acknowledgement
This problem was inspired by [Project Euler #116: Red, Green, or Blue Tiles](https://projecteuler.net/problem=116) and [Project Euler #117: Red, Green, and Blue Tiles](https://projecteuler.net/problem=117).
If you enjoyed this Kata, please also have a look at [my other Katas](https://www.codewars.com/users/Bubbler/authored)!
|
algorithms
|
from math import factorial as fact
def tri_bicolor_tiling(n, r, g, b):
colors, count = ((r, g), (r, b), (b, g)), 0
for c1, c2 in colors:
if c1 + c2 <= n:
m1 = (n - c2) / / c1
for n1 in range(1, m1 + 1):
for n2 in range(1, (n - n1 * c1) / / c2 + 1):
nd = n - n1 * c1 - n2 * c2
count += fact(nd + n1 + n2) / / (fact(nd) * fact(n1) * fact(n2))
return count % 12345787
|
Tri-Bicolor Tiling
|
599266b417bc9785f2000001
|
[
"Fundamentals",
"Algorithms",
"Mathematics"
] |
https://www.codewars.com/kata/599266b417bc9785f2000001
|
5 kyu
|
Your task is to ___Reverse and Combine Words___. It's not too difficult, but there are some things you have to consider...
### So what to do?
Input: String containing different "words" separated by spaces
```
1. More than one word? Reverse each word and combine first with second, third with fourth and so on...
(odd number of words => last one stays alone, but has to be reversed too)
2. Start it again until there's only one word without spaces
3. Return your result...
```
### Some easy examples:
```
Input: "abc def"
Output: "cbafed"
Input: "abc def ghi 123"
Output: "defabc123ghi"
Input: "abc def gh34 434ff 55_eri 123 343"
Output: "43hgff434cbafed343ire_55321"
```
I think it's clear?! First there are some static tests, later on random tests too...
### Hope you have fun! :-)
|
reference
|
from itertools import zip_longest
def reverse_and_combine_text(text):
words = text . split(' ')
while len(words) > 1:
it = map(lambda w: w[:: - 1], words)
words = [a + b for a, b in zip_longest(it, it, fillvalue='')]
return words[0]
|
Basics 06: Reversing and Combining Text
|
56b861671d36bb0aa8000819
|
[
"Strings",
"Arrays",
"Fundamentals"
] |
https://www.codewars.com/kata/56b861671d36bb0aa8000819
|
6 kyu
|
A [Finite State Machine](https://en.wikipedia.org/wiki/Finite-state_machine) (FSM) is an abstract machine that can be in exactly one of a finite number of states at any given time. Simple examples are:
* vending machines, which dispense products when the proper combination of coins is deposited;
* elevators, whose sequence of stops is determined by the floors requested by riders;
* traffic lights, which change sequence when cars are waiting;
* combination locks, which require the input of combination numbers in the proper order.
In this Kata we are going to design our very own basic FSM ```class``` that takes in a ```string``` of ```instructions```
```instructions``` is a string input with the following format:
```
first; next_if_input_0, next_if_input_1; output\n
second; next_if_input_0, next_if_input_1; output\n
third; next_if_input_0, next_if_input_1; output
```
A basic example would be:
```python
instructions = \
'''S1; S1, S2; 9
S2; S1, S3; 10
S3; S4, S3; 8
S4; S4, S1; 0'''
```
```c
char instructions[] = "S1; S1, S2; 9\n"
"S2; S1, S3; 10\n"
"S3; S4, S3; 8\n"
"S4; S4, S1; 0";
```
```javascript
const instructions = (
'S1; S1, S2; 9\n' +
'S2; S1, S3; 10\n'+
'S3; S4, S3; 8\n' +
'S4; S4, S1; 0' )
```
```julia
instructions = """
S1; S1, S2; 9
S2; S1, S3; 10
S3; S4, S3; 8
S4; S4, S1; 0"""
```
```java
String instructions = "S1; S1, S2; 9\n" +
"S2; S1, S3; 10\n" +
"S3; S4, S3; 8\n" +
"S4; S4, S1; 0\n";
```
Where each line in the string describes a state in the FSM.
Given in the example, if the current state was ```S1```, if the ```input is 0``` it would loop back to itself: ```S1``` and if the ```input is 1``` it would go to ```S2```
~~~if:python
The instructions are compiled into the `FSM` class, then the `run_fsm()` method will be called to simulate the compiled FSM.
~~~
~~~if:c
The FSM will be compiled by `fsm = compile(instructions)`, then it will be run `run_fsm(fsm, ...)`.
~~~
~~~if:javascript
The instructions are compiled into the `FSM` class, then the `runFSM()` function will be called to simulate the compiled FSM.
~~~
~~~if:julia
The FSM will be compiled into the `FSM` struct, then the `run_fsm()` function will be called to simulate the compiled FSM.
~~~
~~~if:java
The instructions are compiled into the `FSM` class, then the `runFSM()` method will be called to simulate the compiled FSM.
~~~
Example:
```python
# run_fsm takes in two arguments:
start = 'S1'
# where start is the name of the state that it starts from
sequence = [0, 1, 1, 0, 1]
# where sequence is a list of inputs
# inputs are only 1 or 0 (1 input variable)
# to keep it simple with this Kata
final_state, final_state_value, path = run_fsm(start, sequence)
# run_fsm should return a tuple as:
final_state => name of final state
final_state_value => integer value of state output
path => list of states the FSM sequence went through
```
```c
Fsm *fsm = compile(instructions);
const char *final_state;
const char *path[6];
int final_state_value = run_fsm(
fsm,
"S1", // name of the initial state
(_Bool[]){0, 1, 1, 0, 1}, // input
5, // input length
&final_state, // returned final state
&path // returned path
); // returns the output from the final state
```
```javascript
// runFSM takes two arguments:
start = 'S1'
// where start is the name of the state that it starts from
sequence = [0, 1, 1, 0, 1]
// where sequence is a list of inputs
// inputs are only 1 or 0 (1 input variable)
// to keep it simple with this Kata
// Input / Output
runFSM(start, sequence) --returns--> [final_state, final_state_value, path]
// runFSM should return an array as:
final_state //= name of final state
final_state_value //= integer value of state output
path //= array of states the FSM sequence went through
```
```julia
# run_fsm takes in three arguments:
# fsm is your compiled FSM
fsm = FSM(instructions)
# start is the name of the state that it starts from
start = "S1"
# sequence is a list of inputs
sequence = [0, 1, 1, 0, 1]
# inputs are only 1 or 0 (1 input variable)
# to keep it simple with this Kata
# run_fsm should return a tuple as:
final_state, final_state_value, path = run_fsm(fsm, start, sequence)
#=
final_state => name of final state
final_state_value => integer value of state output
path => list of states the FSM sequence went through
=#
```
```java
// runFSM takes in two arguments:
// fsm is your compiled FSM
FSM fsm = new FSM(instructions);
// start is the name of the state that it starts from
String start = "S1";
// sequence is a list of inputs
int[] sequence = new int[]{0, 1, 1, 0, 1};
// inputs are only 1 or 0 (1 input variable)
// to keep it simple with this Kata
// runFSM should return a Result as:
Result result = fsm.runFSM(start, sequence);
// result.finalState => name of final state
// result.output => integer value of state output
// result.path => array of states the FSM sequence went through
```
From the given example, when ```run_fsm``` is executed the following should proceed below
```
instructions:
S1; S1, S2; 9
S2; S1, S3; 10
S3; S4, S3; 8
S4; S4, S1; 0
start: S1
sequence: 0, 1, 1, 0, 1
input 0: S1->S1
input 1: S1->S2
input 1: S2->S3
input 0: S3->S4
input 1: S4->S1
final state: S1
output: 9
```
In this Kata are many FSM examples in real life described in:
https://en.wikipedia.org/wiki/Finite-state_machine
Good Luck!
~~~if:java
## Preloaded
```java
public class Result {
public final String finalState;
public final int output;
public final String[] path;
public Result(String finalState, int output, String... path) {
this.finalState = finalState;
this.output = output;
this.path = path;
}
}
```
~~~
|
reference
|
import re
class FSM (object):
def __init__(self, instructions):
self . config = {state: [if0, if1, int(out)] for state, if0, if1, out in re . findall(
r'(\w+); (\w+), (\w+); (\w+)', instructions)}
def run_fsm(self, state, sequence):
path = [state]
for i in sequence:
state = self . config[state][i]
path . append(state)
return state, self . config[state][2], path
|
Simple Finite State Machine Compiler
|
59923f1301726f5430000059
|
[
"Interpreters",
"Compilers"
] |
https://www.codewars.com/kata/59923f1301726f5430000059
|
5 kyu
|
Write a function that returns the count of characters that have to be removed in order to get a string with no consecutive repeats.
*Note:* This includes any characters
## Examples
```python
'abbbbc' => 'abc' # answer: 3
'abbcca' => 'abca' # answer: 2
'ab cca' => 'ab ca' # answer: 1
```
|
reference
|
from itertools import groupby
def count_repeats(s):
return len(s) - len(list(groupby(s)))
|
Count Repeats
|
598ee7b6ec6cb90dd6000061
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/598ee7b6ec6cb90dd6000061
|
6 kyu
|
Dee is lazy but she's kind and she likes to eat out at all the nice restaurants and gastropubs in town. To make paying quick and easy she uses a simple mental algorithm she's called The Fair %20 Rule. She's gotten so good she can do this in a few seconds and it always impresses her dates but she's perplexingly still single. Like you probably.
This is how she does it:
- She rounds the price `P` at the tens place e.g:
- 25 becomes 30
- 24 becomes 20
- 5 becomes 10
- 4 becomes 0
- She figures out the base tip `T` by dropping the singles place digit e.g:
- when `P = 24` she rounds to 20 drops 0 `T = 2`
- `P = 115` rounds to 120 drops 0 `T = 12`
- `P = 25` rounds to 30 drops 0 `T = 3`
- `P = 5` rounds to 10 drops 0 `T = 1`
- `P = 4` rounds to 0 `T = 0`
- She then applies a 3 point satisfaction rating `R` to `T` i.e:
- When she's satisfied: `R = 1` and she'll add 1 to `T`
- Unsatisfied: `R = 0` and she'll subtract 1 from `T`
- Appalled: `R = -1` she'll divide `T` by 2, **rounds down** and subtracts 1
## Your Task
Implement a method `calc_tip` that takes two integer arguments for price `p`
where `1 <= p <= 1000` and a rating `r` which is one of `-1, 0, 1`.
The return value `T` should be a non negative integer.
*Note: each step should be done in the order listed.*
Dee always politely smiles and says "Thank you" on her way out. Dee is nice. Be like Dee.
|
algorithms
|
def calc_tip(p, r):
t = (p + 5) / / 10
# t = round((p + 5) / 10)
return max(0, (t / 2 - 1) if r == - 1 else t + (- 1) * * (r + 1))
|
Dee, The Generous Tipper
|
568c3498e48a0231d200001f
|
[
"Mathematics",
"Algorithms"
] |
https://www.codewars.com/kata/568c3498e48a0231d200001f
|
7 kyu
|
Implement `String#six_bit_number?`, which should return true if given object is a number representable by 6 bit unsigned integer (0-63), `false` otherwise.
It should only accept numbers in canonical representation, so no leading `+`, extra `0`s, spaces etc.
|
reference
|
import re
def six_bit_number(s):
return bool(re . match(r'([1-5]?\d|6[0-3])\Z', s))
|
Regexp Basics - is it a six bit unsigned number?
|
567e8dbb9b6f4da558000030
|
[
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/567e8dbb9b6f4da558000030
|
7 kyu
|
# Grains
Write a program that calculates the number of grains of wheat on a specific square of chessboard given that the number on each square is double the previous one.
There are 64 squares on a chessboard.
#Example:
square(1) = 1
square(2) = 2
square(3) = 4
square(4) = 8
etc...
Write a program that shows how many grains were on each square.
|
algorithms
|
def square(number):
return 2 * * (number - 1)
|
Grains
|
55f7eb009e6614447b000099
|
[
"Algorithms"
] |
https://www.codewars.com/kata/55f7eb009e6614447b000099
|
7 kyu
|
Find the 2nd largest integer in array
If the array has no 2nd largest integer then return nil.
Reject all non integers elements and then find the 2nd largest integer in array
find_2nd_largest([1,2,3]) => 2
find_2nd_largest([1,1,1,1,1]) => nil
because all elements are same. Largest no. is 1. and there is no 2nd largest no.
find_2nd_largest([1,'a','2',3,3,4,5,'b']) => 4
as after rejecting non integers array will be [1,3,3,4,5]
Largest no. is 5. and 2nd largest is 4.
Return nil if there is no 2nd largest integer.
Take care of big numbers as well
|
reference
|
def find_2nd_largest(arr):
arr = sorted(i for i in set(arr) if type(i) == int)
return arr[- 2] if len(arr) > 1 else None
|
Find the 2nd largest integer in array
|
55a58505cb237a076100004a
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/55a58505cb237a076100004a
|
7 kyu
|
Given a string of integers, count how many times that integer repeats itself, then return a string showing the count and the integer.
Example: `countMe('1123')` (`count_me` in Ruby)
- Here 1 comes twice so `<count><integer>` will be `"21"`
- then 2 comes once so `<count><integer>` will be `"12"`
- then 3 comes once so `<count><integer>` will be `"13"`
hence output string will be `"211213"`.
Similarly `countMe('211213')` will return `'1221121113'`
(1 time 2, 2 times 1, 1 time 2, 1 time 1, 1 time 3)
Return `""` for empty, nil or non numeric strings
|
reference
|
def count_me(data):
if not data . isdigit():
return ''
result = []
count = 1
last = data[0]
for char in data[1:]:
if char == last:
count += 1
else:
result . append(str(count) + last)
last = char
count = 1
result . append(str(count) + last)
return '' . join(result)
|
Print count and numbers
|
559af787b4b8eac78b000022
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/559af787b4b8eac78b000022
|
7 kyu
|
There are some candies that need to be distributed to some children as fairly as possible (i.e. the variance of result needs to be as small as possible), but I don't know how to distribute them, so I need your help. Your assignment is to write a function with signature `distribute(m, n)` in which `m` represents how many candies there are, while `n` represents how many children there are. The function should return a container which includes the number of candies each child gains.
# Notice
1. *The candy can't be divided into pieces.*
2. The list's order doesn't matter.
# Requirements
1. The case `m < 0` is equivalent to `m == 0`.
2. If `n <= 0` the function should return an empty container.
3. If there isn't enough candy to distribute, you should fill the corresponding number with `0`.
# Examples
```ruby
distribute(-5, 0) # should be []
distribute( 0, 0) # should be []
distribute( 5, 0) # should be []
distribute(10, 0) # should be []
distribute(15, 0) # should be []
distribute(-5, -5) # should be []
distribute( 0, -5) # should be []
distribute( 5, -5) # should be []
distribute(10, -5) # should be []
distribute(15, -5) # should be []
distribute(-5, 10) # should be [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
distribute( 0, 10) # should be [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
distribute( 5, 10) # should be [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
distribute(10, 10) # should be [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
distribute(15, 10) # should be [2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
```
```python
distribute(-5, 0) # should be []
distribute( 0, 0) # should be []
distribute( 5, 0) # should be []
distribute(10, 0) # should be []
distribute(15, 0) # should be []
distribute(-5, -5) # should be []
distribute( 0, -5) # should be []
distribute( 5, -5) # should be []
distribute(10, -5) # should be []
distribute(15, -5) # should be []
distribute(-5, 10) # should be [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
distribute( 0, 10) # should be [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
distribute( 5, 10) # should be [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
distribute(10, 10) # should be [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
distribute(15, 10) # should be [2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
```
```javascript
distribute(-5, 0) // should be []
distribute( 0, 0) // should be []
distribute( 5, 0) // should be []
distribute(10, 0) // should be []
distribute(15, 0) // should be []
distribute(-5, -5) // should be []
distribute( 0, -5) // should be []
distribute( 5, -5) // should be []
distribute(10, -5) // should be []
distribute(15, -5) // should be []
distribute(-5, 10) // should be [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
distribute( 0, 10) // should be [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
distribute( 5, 10) // should be [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
distribute(10, 10) // should be [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
distribute(15, 10) // should be [2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
```
```cpp
distribute(-5, 0) // should be {}
distribute( 0, 0) // should be {}
distribute( 5, 0) // should be {}
distribute(10, 0) // should be {}
distribute(15, 0) // should be {}
distribute(-5, -5) // should be {}
distribute( 0, -5) // should be {}
distribute( 5, -5) // should be {}
distribute(10, -5) // should be {}
distribute(15, -5) // should be {}
distribute(-5, 10) // should be {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
distribute( 0, 10) // should be {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
distribute( 5, 10) // should be {1, 1, 1, 1, 1, 0, 0, 0, 0, 0}
distribute(10, 10) // should be {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
distribute(15, 10) // should be {2, 2, 2, 2, 2, 1, 1, 1, 1, 1}
```
# Input
1. m: Integer (m <= 100000)
2. n: Integer (n <= 1000)
# Output
1. [Integer]
|
algorithms
|
def distribute(m, n):
if n <= 0:
return []
q, r = divmod(max(m, 0), n)
return [q + (i < r) for i in range(n)]
|
Distributing Candies Fairly
|
59901cd68fc658ab6c000025
|
[
"Fundamentals",
"Algorithms"
] |
https://www.codewars.com/kata/59901cd68fc658ab6c000025
|
7 kyu
|
Find the sum of the digits of all the numbers from `1` to `N` (both ends included).
## Examples
```
# N = 4
1 + 2 + 3 + 4 = 10
# N = 10
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + (1 + 0) = 46
# N = 12
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + (1 + 0) + (1 + 1) + (1 + 2) = 51
```
|
algorithms
|
def compute_sum(n):
return sum(int(c) for i in range(1, n + 1) for c in str(i))
|
Twisted Sum
|
527e4141bb2ea5ea4f00072f
|
[
"Mathematics",
"Algorithms"
] |
https://www.codewars.com/kata/527e4141bb2ea5ea4f00072f
|
6 kyu
|
Implement `String#eight_bit_number?`, which should return true if given object is a number representable by 8 bit unsigned integer (0-255), `false` otherwise.
It should only accept numbers in canonical representation, so no leading `+`, extra `0`s, spaces etc.
|
reference
|
import re
def eight_bit_number(n):
return bool(re . fullmatch(r"([1-9]?|1\d|2[0-4])\d|25[0-5]", n))
|
Regexp Basics - is it a eight bit unsigned number?
|
567e8f7b4096f2b4b1000005
|
[
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/567e8f7b4096f2b4b1000005
|
7 kyu
|
In this kata, you will do addition and subtraction on a given string. The return value must be also a string.
**Note:** the input will not be empty.
## Examples
```
"1plus2plus3plus4" --> "10"
"1plus2plus3minus4" --> "2"
```
|
reference
|
def calculate(s):
return str(sum(int(n) for n in s . replace("minus", "plus-"). split("plus")))
# I heard here and there that using eval is a very bad practice…
# return str(eval(s.replace("plus", "+").replace("minus", "-")))
|
Basic Math (Add or Subtract)
|
5809b62808ad92e31b000031
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/5809b62808ad92e31b000031
|
7 kyu
|
For a given string `s` find the character `c` (or `C`) with longest consecutive repetition and return:
```c
c
(assign l to pointer)
```
```cpp
std::pair<char, unsigned int>(c, l)
```
```lua
{ character = c, length = l }
```
```go
type Result struct {
C rune // character
L int // count
}
```
```python
(c, l)
```
```haskell
Just (Char, Int)
```
```csharp
Tuple<char?, int>(c, l)
```
```shell
# in Shell a String of comma-separated values
c,l
```
```javascript
[c, l]
```
```php
[$c, $l]
```
```ruby
[c, l]
```
```groovy
[c, l]
```
```coffeescript
[c, l]
```
```java
Object[]{c, l};
```
```typescript
[c, l]: [string, number]
```
```scala
Some(c, l)
```
```ocaml
Some (c, l)
```
```nim
(c, l)
```
```kotlin
Pair(c, l)
```
```vb
Tuple(Of Char?, Integer>(c, l)
```
```elixir
{c, l}
```
```rust
Some((c, l))
```
```perl
[c, l]
```
where `l` (or `L`) is the length of the repetition. If there are two or more characters with the same `l` return the first in order of appearance.
For empty string return:
```c
'\0'
(assign 0 to pointer)
```
```cpp
std::nullopt
```
```lua
{character = "", length = 0 }
```
```go
Result{}
```
```python
('', 0)
```
```haskell
Nothing
```
```csharp
Tuple<char?, int>(null, 0)
```
```shell
,0
```
```javascript
["", 0]
```
```php
["", 0]
```
```groovy
["", 0]
```
```ruby
["", 0]
```
```coffeescript
["", 0]
```
```java
Object[]{"", 0}
```
```typescript
["", 0]
```
```scala
None
```
```ocaml
None
```
```nim
('\0', 0)
```
```kotlin
Pair(null, 0)
```
```vb
Tuple(Of Char?, Integer)(Nothing, 0)
```
```elixir
{"", 0}
```
```rust
None
```
```swift
["": 0]
```
```perl
["", 0]
```
Happy coding! :)
|
algorithms
|
def longest_repetition(chars):
max_char, max_count = '', 0
char, count = '', 0
for c in chars:
if c != char:
count, char = 0, c
count += 1
if count > max_count:
max_char, max_count = char, count
return max_char, max_count
|
Character with longest consecutive repetition
|
586d6cefbcc21eed7a001155
|
[
"Strings",
"Fundamentals",
"Algorithms"
] |
https://www.codewars.com/kata/586d6cefbcc21eed7a001155
|
6 kyu
|
This method, which is supposed to return the result of dividing its first argument by its second, isn't always returning correct values. Fix it.
|
bug_fixes
|
def divide_numbers(x, y):
return x / y
|
Incorrect division method
|
54d1c59aba326343c80000e7
|
[
"Debugging"
] |
https://www.codewars.com/kata/54d1c59aba326343c80000e7
|
8 kyu
|
This kata is part of the collection [Mary's Puzzle Books](https://www.codewars.com/collections/marys-puzzle-books).
Mary brought home a "spot the differences" book. The book is full of a bunch of problems, and each problem consists of two strings that are similar. However, in each string there are a few characters that are different. An example puzzle from her book is:
```
String 1: "abcdefg"
String 2: "abcqetg"
```
Notice how the "d" from String 1 has become a "q" in String 2, and "f" from String 1 has become a "t" in String 2.
It's your job to help Mary solve the puzzles. Write a program `spot_diff`/`Spot` that will compare the two strings and return a list with the positions where the two strings differ. In the example above, your program should return `[3, 5]` because String 1 is different from String 2 at positions 3 and 5.
NOTES:
```if-not:csharp
• If both strings are the same, return `[]`
```
```if:csharp
• If both strings are the same, return `new List<int>()`
```
• Both strings will always be the same length
• Capitalization and punctuation matter
|
reference
|
def spot_diff(s1, s2):
return [i for i in range(len(s1)) if s1[i] != s2[i]]
|
Spot the Differences
|
5881460c780e0dd207000084
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/5881460c780e0dd207000084
|
7 kyu
|
You work for a company that analyzes traffic count at a particular intersection during the peak hours of 4:00 PM to 8:00 PM. Each day, you are given a list that contains the number of vehicles that pass through the intersection every 10 minutes from 4:00 to 8:00 PM.
You are expected to return a list of tuples that each contain the hour and the maximum amount of traffic for each hour.
For example:
```python
a1 = [23,24,34,45,43,23,57,34,65,12,19,45, 54,65,54,43,89,48,42,55,22,69,23,93]
traffic_count(a1) ==> [('4:00pm', 45), ('5:00pm', 65), ('6:00pm', 89), ('7:00pm', 93)]
```
All values in the given list are integers.
|
reference
|
def traffic_count(array):
return [('4:00pm', max(array[: 6])), ('5:00pm', max(array[6: 12])), ('6:00pm', max(array[12: 18])), ('7:00pm', max(array[18:]))]
|
Traffic Count During Peak Hours
|
586ed2dbaa0428f791000885
|
[
"Fundamentals",
"Lists"
] |
https://www.codewars.com/kata/586ed2dbaa0428f791000885
|
7 kyu
|
Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string <code>"The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog"</code>, the sum of the integers is <code>3635</code>.
*Note: only positive integers will be tested.*
|
reference
|
import re
def sum_of_integers_in_string(s):
return sum(int(x) for x in re . findall(r"(\d+)", s))
|
Sum of integers in string
|
598f76a44f613e0e0b000026
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/598f76a44f613e0e0b000026
|
7 kyu
|
Your goal is to create a function to format a number given a template; if the number is not present, use the digits `1234567890` to fill in the spaces.
A few rules:
* the template might consist of other numbers, special characters or the like: you need to replace only alphabetical characters (both lower- and uppercase);
* if the given or default string representing the number is shorter than the template, just repeat it to fill all the spaces.
A few examples:
```javascript
numericFormatter("xxx xxxxx xx","5465253289") === "546 52532 89"
numericFormatter("xxx xxxxx xx") === "123 45678 90"
numericFormatter("+555 aaaa bbbb", "18031978") === "+555 1803 1978"
numericFormatter("+555 aaaa bbbb") === "+555 1234 5678"
numericFormatter("xxxx yyyy zzzz") === "1234 5678 9012"
```
```python
numeric_formatter("xxx xxxxx xx","5465253289") == "546 52532 89"
numeric_formatter("xxx xxxxx xx") == "123 45678 90"
numeric_formatter("+555 aaaa bbbb", "18031978") == "+555 1803 1978"
numeric_formatter("+555 aaaa bbbb") == "+555 1234 5678"
numeric_formatter("xxxx yyyy zzzz") == "1234 5678 9012"
```
```ruby
numeric_formatter("xxx xxxxx xx","5465253289") == "546 52532 89"
numeric_formatter("xxx xxxxx xx") == "123 45678 90"
numeric_formatter("+555 aaaa bbbb", "18031978") == "+555 1803 1978"
numeric_formatter("+555 aaaa bbbb") == "+555 1234 5678"
numeric_formatter("xxxx yyyy zzzz") == "1234 5678 9012"
```
```crystal
numeric_formatter("xxx xxxxx xx","5465253289") == "546 52532 89"
numeric_formatter("xxx xxxxx xx", nil) == "123 45678 90"
numeric_formatter("+555 aaaa bbbb", "18031978") == "+555 1803 1978"
numeric_formatter("+555 aaaa bbbb", nil) == "+555 1234 5678"
numeric_formatter("xxxx yyyy zzzz", nil) == "1234 5678 9012"
```
```haskell
numericFormatter "xxx xxxxx xx" "5465253289" == "546 52532 89"
numericFormatter "xxx xxxxx xx" "" == "123 45678 90"
numericFormatter "+555 aaaa bbbb" "18031978" == "+555 1803 1978"
numericFormatter "+555 aaaa bbbb" "" == "+555 1234 5678"
numericFormatter "xxxx yyyy zzzz" "" == "1234 5678 9012"
```
```swift
numericFormatter("xxx xxxxx xx","5465253289") == "546 52532 89"
numericFormatter("xxx xxxxx xx") == "123 45678 90"
numericFormatter("+555 aaaa bbbb", "18031978") == "+555 1803 1978"
numericFormatter("+555 aaaa bbbb") == "+555 1234 5678"
numericFormatter("xxxx yyyy zzzz") == "1234 5678 9012"
```
```c
numeric_formatter("xxx xxxxx xx", "5465253289") == "546 52532 89"
numeric_formatter("xxx xxxxx xx", "") == "123 45678 90"
numeric_formatter("+555 aaaa bbbb", "18031978") == "+555 1803 1978"
numeric_formatter("+555 aaaa bbbb", "") == "+555 1234 5678"
numeric_formatter("xxxx yyyy zzzz", "") == "1234 5678 9012"
Note that numeric_formatter should return a dynamically allocated string.
The tests will automatically free this string.
```
|
algorithms
|
from itertools import cycle
def numeric_formatter(template, data='1234567890'):
data = cycle(data)
return '' . join(next(data) if c . isalpha() else c for c in template)
|
Generic numeric template formatter
|
59901fb5917839fe41000029
|
[
"Regular Expressions",
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/59901fb5917839fe41000029
|
6 kyu
|
#Bubbleing around
Since everybody hates chaos and loves sorted lists we should implement some more sorting algorithms. Your task is to implement a Bubble sort (for some help look at https://en.wikipedia.org/wiki/Bubble_sort) and return a list of snapshots after **each change** of the initial list.
e.g.
If the initial list would be l=[1,2,4,3] my algorithm rotates l[2] and l[3] and after that it adds [1,2,3,4] to the result, which is a list of snapshots.
```
[1,2,4,3] should return [ [1,2,3,4] ]
[2,1,4,3] should return [ [1,2,4,3], [1,2,3,4] ]
[1,2,3,4] should return []
```
|
algorithms
|
def bubble(l):
ret = []
for i in range(len(l) - 1, 0, - 1):
for j in range(i):
if l[j] > l[j + 1]:
l[j], l[j + 1] = l[j + 1], l[j]
ret . append(l[:])
return ret
|
Bubble Sort
|
57403b5ad67e87b5e7000d1d
|
[
"Sorting",
"Arrays",
"Fundamentals",
"Algorithms"
] |
https://www.codewars.com/kata/57403b5ad67e87b5e7000d1d
|
7 kyu
|
## Task
Tranform of input array of zeros and ones to array in which counts number of continuous ones. If there is none, return an empty array
## Example
```
[1, 1, 1, 0, 1] -> [3,1]
[1, 1, 1, 1, 1] -> [5]
[0, 0, 0, 0, 0] -> []
```
|
reference
|
from itertools import groupby
def ones_counter(nums):
return [sum(g) for k, g in groupby(nums) if k]
|
Counter of neighbor ones
|
56ec1e8492446a415e000b63
|
[
"Algorithms",
"Fundamentals"
] |
https://www.codewars.com/kata/56ec1e8492446a415e000b63
|
7 kyu
|
You seem to have the worst luck at rock, paper, scissors! Everyday you play against your friends, but never win. You want a taste of victory!
In this kata you need to define `r_p_s_cheat()` that takes an argument, either `'rock'`, `'paper'`, or `'scissors'` and returns your counter to win!
But there's a catch! Your friends know how terrible you are at rock, paper, scissors, and if you win all of the time, then they'll see through your deception!
You need `r_p_s_cheat` to __win__ 88-92% of the time and __lose__ 8-12% of the time!
In other words, you should __never__ tie!
Note: The testing ___will___ check to see that this condition is fulfilled!
If you believe your solution will work, but doesn't on the first try, submit again!
|
reference
|
import random
def r_p_s_cheat(choice):
options = {"rock": "paper", "paper": "scissors", "scissors": "rock"}
return options[choice] if random . randint(1, 10) <= 9 else options[options[choice]]
|
Cheat at rock paper scissors!
|
57e141ad8a8b8d4d150004f6
|
[
"Fundamentals",
"Probability"
] |
https://www.codewars.com/kata/57e141ad8a8b8d4d150004f6
|
7 kyu
|
Your task here is to generate a list of prime numbers, starting from 2.
One way of doing this is using python's `generators`.
In case you choose to use `generators`, notice that the generator object should contain all the generated prime numbers, from 2 to an upper limit (included) provided as the argument to the function. If the input limit is less than 2 (including negatives), it should return an empty list.
Each iteration of the generator will yield one prime number. See [this link](https://wiki.python.org/moin/Generators) for reference.
The generator object will be converted to a list outside the code, within the test cases.
There will be no check if you are using `generators` or `lists`, so use the one you feel more confortable with.
### Examples
Some expected results:
```python
list(generate_primes(10)) = [2, 3, 5, 7]
list(generate_primes(23)) = [2, 3, 5, 7, 11, 13, 17, 19, 23]
list(generate_primes(28)) = [2, 3, 5, 7, 11, 13, 17, 19, 23]
list(generate_primes(-1)) = []
```
Good luck!
|
algorithms
|
from gmpy2 import is_prime
def generate_primes(x):
return [n for n in range(2, x + 1) if is_prime(n)]
|
Simple Prime Number Generator
|
58fa5e33a6d84c1324000207
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58fa5e33a6d84c1324000207
|
7 kyu
|
In this kata, your task is to create a function that takes a single list as an argument and returns a flattened list. The input list will have a maximum of one level of nesting (list(s) inside of a list).
```python
# no nesting
[1, 2, 3]
# one level of nesting
[1, [2, 3]]
```
---
# Examples
```python
>>> flatten_me(['!', '?'])
['!', '?']
>>> flatten_me([1, [2, 3], 4])
[1, 2, 3, 4]
>>> flatten_me([['a', 'b'], 'c', ['d']])
['a', 'b', 'c', 'd']
>>> flatten_me([[True, False], ['!'], ['?'], [71, '@']])
[True, False, '!', '?', 71, '@']
```
Good luck!
|
reference
|
def flatten_me(lst):
res = []
for l in lst:
if isinstance(l, list):
res . extend(l)
else:
res . append(l)
return res
|
Flatten Me
|
55a5bef147d6be698b0000cd
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/55a5bef147d6be698b0000cd
|
7 kyu
|
This series of katas will introduce you to basics of doing geometry with computers.
`Vector` objects (`struct` in C) have `x`, `y`, and `z` attributes.
Write a function calculating cross product of `Vector a` and `Vector b`.
[You can read more about cross product on Wikipedia](https://en.wikipedia.org/wiki/Cross_product).
Tests round answers to 6 decimal places.
|
reference
|
def cross_product(a, b):
return Vector(
a . y * b . z - a . z * b . y,
a . z * b . x - a . x * b . z,
a . x * b . y - a . y * b . x
)
|
Geometry Basics: Cross Product in 3D
|
58e440d8acfd3edfb2000aee
|
[
"Geometry",
"Fundamentals"
] |
https://www.codewars.com/kata/58e440d8acfd3edfb2000aee
|
7 kyu
|
This series of katas will introduce you to basics of doing geometry with computers.
`Vector` objects have `x`, `y`, and `z` attributes.
```if:prolog
*Note for **prolog** users: a [record](https://www.swi-prolog.org/pldoc/man?section=record) named **vector** is used.*
```
Write a function calculating dot product of `Vector a` and `Vector b`.
[You can read more about dot product on Wikipedia](https://en.wikipedia.org/wiki/Dot_product).
Tests round answers to 6 decimal places.
|
reference
|
def dot_product(a, b):
return a . x * b . x + a . y * b . y + a . z * b . z
|
Geometry Basics: Dot Product in 3D
|
58e3ea29a33b52c1dc0000c0
|
[
"Geometry",
"Fundamentals"
] |
https://www.codewars.com/kata/58e3ea29a33b52c1dc0000c0
|
7 kyu
|
There is a sentence which has a mistake in its ordering.
The part with a capital letter should be the first word.
Please build a function for re-ordering
---
# Examples
```python
>>> re_ordering('ming Yao')
'Yao ming'
>>> re_ordering('Mano donowana')
'Mano donowana'
>>> re_ordering('wario LoBan hello')
'LoBan wario hello'
>>> re_ordering('bull color pig Patrick')
'Patrick bull color pig'
```
|
reference
|
def re_ordering(name):
return ' ' . join(sorted(name . split(), key=str . islower))
|
ReOrdering
|
5785cd91a1b8d5c06e000007
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5785cd91a1b8d5c06e000007
|
7 kyu
|
Impliment the reverse function, which takes in input n and reverses it. For instance, `reverse(123)` should return `321`. You should do this without converting the inputted number into a string.
```python
# Please do not use anything from the following list:
['encode','decode','join','zfill','codecs','chr','bytes','ascii', 'substitute','template','bin', 'os','sys','re', '"', "'", 'str','repr', '%s', 'format', 'type', '__', '.keys','eval','exec','subprocess']
```
```javascript
// Please do not use
const forbidden = "
'
`
string
fixed
precision
.keys
```
|
reference
|
def reverse(n):
m = 0
while n > 0:
n, m = n / / 10, m * 10 + n % 10
return m
|
Reverser
|
58069e4cf3c13ef3a6000168
|
[
"Recursion",
"Fundamentals"
] |
https://www.codewars.com/kata/58069e4cf3c13ef3a6000168
|
7 kyu
|
You just took a contract with the Jedi council. They need you to write a function, `greet_jedi()`, which takes two arguments (a first name and a last name), works out the corresponding *Jedi name*, and returns a string greeting the Jedi.
A person's *Jedi name* is the first three letters of their last name followed by the first two letters of their first name. For example:
```python
>>> greet_jedi('Beyonce', 'Knowles')
'Greetings, master KnoBe'
```
Note the capitalization: the first letter of each name is capitalized. Your input may or may not be capitalized. Your function should handle it and return the Jedi name in the correct case no matter what case the input is in:
```python
>>> greet_jedi('grae', 'drake')
'Greetings, master DraGr'
```
You can trust that your input names will always be at least three characters long.
If you're stuck, check out the [python.org tutorial](https://docs.python.org/3/tutorial/introduction.html#strings) section on strings and search "slice".
|
reference
|
def greet_jedi(first, last):
return "Greetings, master {}{}" . format(last[: 3]. capitalize(), first[: 2]. capitalize())
|
Thinkful - String Drills: Jedi name
|
585a29183d357b31f700023f
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/585a29183d357b31f700023f
|
7 kyu
|
Professor Oak has just begun learning Python and he wants to program his new Pokedex prototype with it.
For a starting point, he wants to instantiate each scanned Pokemon as an object that is stored at Pokedex's memory. He needs your help!
Your task is to:
1) Create a ```PokeScan``` class that takes in 3 arguments: ```name```, ```level``` and ```pkmntype```.
2) Create a ```info``` method for this class that returns some comments about the Pokemon, specifying it's name, an observation about the ```pkmntype``` and other about the ```level```.
3) Keep in mind that he has in his possession just three Pokemons for you to test the scanning function: ```Squirtle```, ```Charmander``` and ```Bulbasaur```, of ```pkmntypes``` ```water```, ```fire``` and ```grass```, respectively.
4) The ```info``` method shall return a string like this:
```Charmander, a fiery and strong Pokemon.```
5) If the Pokemon level is less than or equal to 20, it's a ```weak``` Pokemon. If greater than 20 and less than or equal to 50, it's a ```fair``` one. If greater than 50, it's a ```strong``` Pokemon.
6) For the ```pkmntypes```, the observations are ```wet```, ```fiery``` and ```grassy``` Pokemon, according to each Pokemon type.
IMPORTANT: The correct spelling of "Pokémon" is "Pokémon", with the ```"é"```, but to maximize the compatibility of the code I've had to write it as ```"Pokemon"```, without the ```"é"```. So, in your code, don't use the ```"é"```.
|
reference
|
class PokeScan:
def __init__(self, name, level, pkmntype):
self . name = name
self . level = level
self . pkmntype = pkmntype
def info(self):
level_info = "weak" if self . level <= 20 else "fair" if self . level <= 50 else "strong"
pkmntypes_info = {"water": "wet", "fire": "fiery", "grass": "grassy", }
return "{}, a {} and {} Pokemon." . format(self . name, pkmntypes_info[self . pkmntype], level_info)
|
Professor Oak's Trouble - New Pokedex prototype
|
57520361f2dac757360018ce
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/57520361f2dac757360018ce
|
7 kyu
|
You are given two positive integer lists with a random number of elements (1 <= n <= 100). Create a [GCD](https://en.wikipedia.org/wiki/Greatest_common_divisor) matrix and calculate the average of all values.
Return a float value rounded to 3 decimal places.
## Example
```
a = [1, 2, 3]
b = [4, 5, 6]
# a = 1 2 3 b =
gcd(a, b) = [ [1, 2, 1], # 4
[1, 1, 1], # 5
[1, 2, 3] ] # 6
average(gcd(a, b)) = 1.444
```
|
reference
|
from fractions import gcd
from itertools import product, starmap
from statistics import mean
def gcd_matrix(a, b):
return round(mean(starmap(gcd, product(a, b))), 3)
|
GCD Matrix
|
58a30be22d5b6ca8d9000012
|
[
"Matrix",
"Fundamentals"
] |
https://www.codewars.com/kata/58a30be22d5b6ca8d9000012
|
7 kyu
|
Write a program that prints a chessboard with N rows and M columns with the following rules:
The top left cell must be an asterisk (*)
Any cell touching (left, right, up or down) a cell with an asterisk must be a dot (.)
Any cell touching (left, right, up or down) a cell with a dot must be an asterisk.
A chessboard of 8 rows and 8 columns printed using these rules would be:
```
*.*.*.*.
.*.*.*.*
*.*.*.*.
.*.*.*.*
*.*.*.*.
.*.*.*.*
*.*.*.*.
.*.*.*.*
```
Input
A single line with two integers N and M separated by space. The number N will represent the number of rows and M the number of columns.
Output
Return N lines each containing M characters with the chessboard pattern.
Empty string if N, M or both are 0.
From: 2016 AIPO National Finals
http://aipo.computing.dcu.ie/2016-aipo-national-finals-problems
|
games
|
def chessboard(s):
N, M = map(int, s . split())
row = ".*" * M
return "\n" . join([row[: M] if i & 1 else row[1: M + 1] for i in range(N)])
|
Chessboard
|
5749b82229d16cbc320015fe
|
[
"Puzzles",
"Fundamentals",
"Games",
"Strings",
"Data Types"
] |
https://www.codewars.com/kata/5749b82229d16cbc320015fe
|
7 kyu
|
What is the answer to life the universe and everything
Create a function that will make anything true
```python
anything({}) != [], 'True'
anything('Hello') < 'World', 'True'
anything(80) > 81, 'True'
anything(re) >= re, 'True'
anything(re) <= math, 'True'
anything(5) == ord, 'True'
```
Source: [CheckIO](https://checkio.org/mission/solution-for-anything/)
|
reference
|
class anything (object):
def __init__(self, foo): pass
def __eq__(self, other): return True
__ne__ = __lt__ = __le__ = __gt__ = __ge__ = __eq__
|
Anything
|
557d9e4d155e2dbf050000aa
|
[
"Object-oriented Programming",
"Fundamentals"
] |
https://www.codewars.com/kata/557d9e4d155e2dbf050000aa
|
7 kyu
|
Here you have a connected to a socket, and the data looks very strange. It seems to be separated by a random special character! Oh No! We need your help to find the special character, parse the data, and return it translated! There isn't much time, hurry we need your help!
|
algorithms
|
import re
def word_splitter(string1):
return re . split('[^\w\.-]', string1)
|
Strange Strings Parser!
|
584d88622609c8bda30000cf
|
[
"Parsing",
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/584d88622609c8bda30000cf
|
7 kyu
|
Make a program that takes a value (x) and returns "Bang" if the number is divisible by 3, "Boom" if it is divisible by 5, "BangBoom" if it divisible by 3 and 5, and "Miss" if it isn't divisible by any of them.
Note: Your program should only return one value
Ex: Input: 105 --> Output: "BangBoom"
Ex: Input: 9 --> Output: "Bang"
Ex:Input: 25 --> Output: "Boom"
|
reference
|
def multiple(x):
if x % 15 == 0:
return "BangBoom"
if x % 5 == 0:
return "Boom"
if x % 3 == 0:
return "Bang"
return "Miss"
|
Multiples!
|
55a8a36703fe4c45ed00005b
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/55a8a36703fe4c45ed00005b
|
7 kyu
|
Write a function that takes a list comprised of other lists of integers and returns the sum of all numbers that appear in two or more lists in the input list. Now that might have sounded confusing, it isn't:
```python
repeat_sum([[1, 2, 3],[2, 8, 9],[7, 123, 8]])
>>> sum of [2, 8]
return 10
repeat_sum([[1], [2], [3, 4, 4, 4], [123456789]])
>>> sum of []
return 0
repeat_sum([[1, 8, 8], [8, 8, 8], [8, 8, 8, 1]])
sum of [1,8]
return 9
```
|
algorithms
|
from collections import defaultdict
def repeat_sum(l):
count = defaultdict(int)
for l1 in l:
for val in set(l1):
count[val] += 1
return sum(k for k, v in count . items() if v > 1)
|
Sum the Repeats
|
56b4bae128644b5613000037
|
[
"Lists",
"Algorithms"
] |
https://www.codewars.com/kata/56b4bae128644b5613000037
|
7 kyu
|
In this kata you will create a function to check a non-negative input to see if it is a prime number.
~~~if-not:factor
The function will take in a number and will return True if it is a prime number and False if it is not.
~~~
~~~if:factor
The function will take in a number and will return `t` if it is a prime number and `f` if it is not.
~~~
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
### Examples(input --> output)
```
0 --> false
1 --> false
2 --> true
11 --> true
12 --> false
```
|
algorithms
|
def is_prime(n):
'Return True if n is a prime number otherwise return False'
# 0 and 1 are not primes
if n < 2:
return False
# 2 is only even prime so reject all others
if n == 2:
return True
if not n & 1:
return False
# test other possiblities
for i in range(3, n):
if (n % i) == 0 and n != i:
return False
return True
|
Check for prime numbers
|
53daa9e5af55c184db00025f
|
[
"Algorithms",
"Mathematics"
] |
https://www.codewars.com/kata/53daa9e5af55c184db00025f
|
7 kyu
|
Your users' passwords were all stolen in the Yahoo! hack, and it turns out they have been lax in creating secure passwords. Create a function that checks their new password (passed as a string) to make sure it meets the following requirements:
* Between 8 - 20 characters
* Contains **only** the following characters (and at least one character from each category):
* uppercase letters,
* lowercase letters,
* digits,
* special characters from `!@#$%^&*?`
Return `"valid"` if passed or `"not valid"` otherwise.
|
reference
|
import re
def check_password(s):
if re . search('^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)(?=.*?[!@#$%^&*?])[a-zA-Z\d!@#$%^&*?]{8,20}$', s):
return 'valid'
else:
return 'not valid'
|
Strong password?
|
57e35f1bc763b8ccce000038
|
[
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/57e35f1bc763b8ccce000038
|
7 kyu
|
There's not much explaining for this kata.
Make it so if I call `solve()` it gives an output of True.
`But you are not allowed to use the return keyword!`
If you do disregard the challenge, `at least` look at others solutions for learning value.
Good luck!
|
reference
|
def solve(): return True
|
Challenge: True without return
|
57e524847fbcc9300300004c
|
[
"Puzzles",
"Restricted",
"Fundamentals"
] |
https://www.codewars.com/kata/57e524847fbcc9300300004c
|
7 kyu
|
## The game
In this game, there are 21 sticks lying in a pile. Players take turns taking 1, 2, or 3 sticks. The last person to take a stick wins. For example:
```
21 sticks in the pile
Bob takes 2 --> 19 sticks left
Jim takes 3 --> 16 sticks
Bob takes 3 --> 13 sticks
Jim takes 1 --> 12 sticks
Bob takes 2 --> 10 sticks
Jim takes 2 --> 8 sticks
Bob takes 3 --> 5 sticks
Jim takes 3 --> 2 sticks
Bob takes 2 --> Bob wins!
```
## Your task
Create a robot that will always win the game. Your robot will always go first. The function should take an integer and returns `1`, `2`, or `3`.
**Note:** The input will always be valid (a positive integer)
---
*Hint: https://youtu.be/9KABcmczPdg*
|
algorithms
|
def make_move(sticks):
return sticks % 4
|
21 Sticks
|
5866a58b9cbc02c4f8000cac
|
[
"Games",
"Algorithms",
"Mathematics",
"Game Solvers"
] |
https://www.codewars.com/kata/5866a58b9cbc02c4f8000cac
|
7 kyu
|
[Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) (RLE) is a very simple form of lossless data compression in which runs of data are stored as a single data value and count.
A simple form of RLE would encode the string `"AAABBBCCCD"` as `"3A3B3C1D"` meaning, first there are `3 A`, then `3 B`, then `3 C` and last there is `1 D`.
Your task is to write a RLE encoder and decoder using this technique. The texts to encode will always consist of only uppercase characters, no numbers.
|
algorithms
|
from re import sub
def encode(string):
return sub(r'(.)\1*', lambda m: str(len(m . group(0))) + m . group(1), string)
def decode(string):
return sub(r'(\d+)(\D)', lambda m: m . group(2) * int(m . group(1)), string)
|
Data compression using run-length encoding
|
578bf2d8daa01a4ee8000046
|
[
"Algorithms"
] |
https://www.codewars.com/kata/578bf2d8daa01a4ee8000046
|
6 kyu
|
Triangular numbers count the number of objects that can form an equilateral triangle. The nth triangular number forms an equilateral triangle with n dots on each side (including the vertices).
Here is a graphic example for the triangular numbers of 1 to 5:
```
n=1: triangular number: 1
*
n=2: triangular number: 3
*
* *
n=3: triangular number: 6
*
* *
* * *
n=4: triangular number: 10
*
* *
* * *
* * * *
n=5: triangular number: 15
*
* *
* * *
* * * *
* * * * *
```
Your task is to implement a function ```triangular_range(start, stop)``` that <b>returns a dictionary of all numbers as keys and the belonging triangular numbers as values, where the triangular number is in the range start, stop (including start and stop)</b>.
For example, ```triangular_range(1, 3)``` should return ```{1: 1, 2: 3}``` and ```triangular_range(5, 16)``` should return ```{3: 6, 4: 10, 5: 15}```.
|
reference
|
def triangular_range(start, stop):
return {i: i * (i + 1) / 2 for i in range(stop) if start <= i * (i + 1) / 2 <= stop}
|
Triangular range
|
5620dc848370b4ad750000a1
|
[
"Algorithms",
"Mathematics",
"Data Structures",
"Fundamentals"
] |
https://www.codewars.com/kata/5620dc848370b4ad750000a1
|
7 kyu
|
Your Goal is to create a function that takes two strings, a guess and a phone number.
Based on the guess, the function should display a portion of the phone number:
guess_my_number('052', '123-451-2345')
would return the string: '#2#-#5#-2##5'
or
guess_my_number('142', '123-451-2345')
would return the string: '12#-4#1-2#4#'
Order of the guess string should not matter, and should not have duplicates of the ten digitis 0-9. Guess will never be an empty string or contains any other charachters. The phone number will always bea ten digit number in the format ###-###-####.
The default number of 123-451-2345 should be included, but can be overwriten by a different number if supplied at the time of execution.
|
reference
|
def guess_my_number(guess, number='123-451-2345'):
return "" . join(c if c in guess + "-" else "#" for c in number)
|
Guess My Number
|
5654d2428be803670a000030
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5654d2428be803670a000030
|
7 kyu
|
Create a `Vector` class with `x` and a `y` attributes that represent component magnitudes in the x and y directions.
Your vectors should handle vector additon with an `.add()` method that takes a second vector as an argument and returns a new vector equal to the sum of the vector you call `.add()` on and the vector you pass in.
For example:
```python
>>> a = Vector(3, 4)
>>> a.x
3
>>> a.y
4
>>> b = Vector(1, 2)
>>> c = a.add(b)
>>> c.x
4
>>> c.y
6
```
Adding vectors when you have their components is easy: just add the two x components together and the two y components together to get the x and y components for the vector sum.
|
reference
|
class Vector (object):
def __init__(self, x, y):
self . x = x
self . y = y
def add(self, vector):
return Vector(self . x + vector . x, self . y + vector . y)
|
Thinkful - Object Drills: Vectors
|
587f1e1f39d444cee6000ad4
|
[
"Fundamentals",
"Object-oriented Programming"
] |
https://www.codewars.com/kata/587f1e1f39d444cee6000ad4
|
7 kyu
|
Factorials are often used in probability and are used as an introductory problem for looping constructs. In this kata you will be summing together multiple factorials.
Here are a few examples of factorials:
```
4 Factorial = 4! = 4 * 3 * 2 * 1 = 24
6 Factorial = 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720
```
In this kata you will be given a list of values that you must first find the factorial, and then return their sum.
For example if you are passed the list `[4, 6]` the equivalent mathematical expression would be `4! + 6!` which would equal `744`.
Good Luck!
Note: Assume that all values in the list are positive integer values > 0 and each value in the list is unique.
~~~if:python
Also, you must write your own implementation of factorial, as you cannot use the built-in `math.factorial()` method.
~~~
|
algorithms
|
def sum_factorial(lst):
return sum(map(fac, lst)) if lst else None
def fac(n):
return n * fac(n - 1) if n != 0 else 1
|
Sum Factorial
|
56b0f6243196b9d42d000034
|
[
"Algorithms"
] |
https://www.codewars.com/kata/56b0f6243196b9d42d000034
|
7 kyu
|
Find the most frequent element or elements in the list.
Example:
```python
find_most_frequent([1, 1, 2, 3]) == set([1])
find_most_frequent([1, 1, 2, 2, 3]) == set([1, 2])
find_most_frequent([1, 1, '2', '2', 3]) == set([1, '2'])
```
|
reference
|
def find_most_frequent(l):
return set(x for x in set(l) if l . count(x) == max([l . count(y) for y in l]))
|
Most Frequent Elements
|
53f103c3ef9ad4014f00013b
|
[
"Algorithms",
"Fundamentals"
] |
https://www.codewars.com/kata/53f103c3ef9ad4014f00013b
|
7 kyu
|
Given an integer, if the length of it's digits is a perfect square, return a square block of sqroot(length) * sqroot(length). If not, simply return "Not a perfect square!".
Examples:
`1212` returns:
```ruby
"12
12"
```
Note: 4 digits so 2 squared (2x2 perfect square). 2 digits on each line.
`123123123` returns:
```ruby
"123
123
123"
```
Note: 9 digits so 3 squared (3x3 perfect square). 3 digits on each line.
|
reference
|
def square_it(digits):
s = str(digits)
n = len(s) * * 0.5
if n != int(n):
return "Not a perfect square!"
n = int(n)
return "\n" . join(s[i * n: i * n + n] for i in range(int(n)))
|
Perfect squares, perfect fun
|
5705ca6a41e5be67720012c0
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5705ca6a41e5be67720012c0
|
7 kyu
|
Remember the movie with David Bowie: 'The Labyrinth'?
You can remember your childhood here: https://www.youtube.com/watch?v=2dgmgub8mHw
In this scene the girl is faced with two 'Knights" and two doors. One door leads the castle where the Goblin King and her kid brother is, the other leads to certain death. She can ask the 'Knights' a question to find out which door is the right one to go in. But...
One of them always tells the truth, and the other one always lies.
In this Kata one of the 'Knights' is on a coffee break, leaving the other one to watch the doors. You have to determine if the one there is the Knight(Truth teller) or Knave(Liar) based off of what he ```says```
Create a function:
```
def knight_or_knave(says):
# returns if knight or knave
```
Your function should determine if the input '''says''' is True or False and then return:
```'Knight!'``` if True or ```'Knave! Do not trust.'``` if False
Input will be either boolean values, or strings.
The strings will be simple statements that will be either true or false, or evaluate to True or False.
See example test cases for, well... examples
You will porbably need to ```eval(says)```
But note: Eval is evil, and is only here for this Kata as a game.
And remember the number one rule of The Labyrinth, even if it is easy, Don't ever say 'that was easy.'
|
games
|
def knight_or_knave(said):
return "Knight!" if eval(str(said)) else "Knave! Do not trust."
|
Knight or Knave (From the Motion Picture: The Labyrinth)
|
574881a216ac9be096001ade
|
[
"Puzzles"
] |
https://www.codewars.com/kata/574881a216ac9be096001ade
|
7 kyu
|
# Background:
You have a starting string of the lowercase alphabet, space-separated:
```python
"a b c d e f g h i j k l m n o p q r s t u v w x y z"
```
Then you are given random **sets** of letters to throw against this string. For example:
```python
{'e', 'B', 'F', 'i'}
```
Whenever there is a match (case sensitive), the letter in the original string is knocked out and replaced by an underscore. Using the random set above as an example would result in:
```python
"a b c d _ f g h _ j k l m n o p q r s t u v w x y z"
```
# Implementation
Write a function ```destroyer(input_sets)``` that takes input as a tuple of one or more of these random character sets and returns the alphabet formatted as shown, with underscores showing where matches knocked out a letter.
For example:
```python
>>> input_sets = ({'A', 'b'}, {'d', 'C', 'b'})
>>> destroyer(input_sets)
>>> "a _ c _ e f g h i j k l m n o p q r s t u v w x y z"
```
~~~if:rust
In Rust:
```rust
let mut input_set: Vec<HashSet<char>> = Vec::new();
input_set.push(['A', 'b'].iter().cloned().collect());
input_set.push(['C', 'd'].iter().cloned().collect());
destroy(input_set) -> "a _ c _ e f g h i j k l m n o p q r s t u v w x y z"
```
~~~
## Extra credit question:
If the average random set thrown at the lowercase alphabet is ten (10) characters long (same rules as above, uppercase and lowercase letters only), then how many random sets - on average - do you have to throw at the alphabet in order to be left with only underscores?
|
reference
|
def destroyer(input_sets):
from string import ascii_lowercase as alphabet
return " " . join(c if c not in set . union(* input_sets) else "_" for c in alphabet)
|
String destroyer (plus extra credit)
|
5872637c2eefcb1216000081
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5872637c2eefcb1216000081
|
7 kyu
|
<h1>How much will you spend?</h1>
Given a dictionary of items and their costs and an array specifying the items bought, calculate the total cost of the items plus a given tax.
If item doesn't exist in the given cost values, the item is ignored.
Output should be rounded to two decimal places.
Python:
```python
costs = {'socks':5, 'shoes':60, 'sweater':30}
get_total(costs, ['socks', 'shoes'], 0.09)
#-> 5+60 = 65
#-> 65 + 0.09 of 65 = 70.85
#-> Output: 70.85
```
|
algorithms
|
def getTotal(costs, items, tax):
return round(sum(costs . get(e, 0) for e in items) * (1 + tax), 2)
|
How much will you spend?
|
585d7b4685151614190001fd
|
[
"Mathematics",
"Algorithms"
] |
https://www.codewars.com/kata/585d7b4685151614190001fd
|
7 kyu
|
Write a function `index_finder`/`index-finder` that returns the index of the first occurrence of an item (`x`) in the list (`lst`), but ignoring the first item in the list. The item will always occur at least once after the first item in the list. For example:
`lst = ['a','b','c']`, `x = 'b'` >>> returns `1` ('b' occurs first at position 1)
`lst = ['b','b','b']`, `x = 'b'` >>> returns `1` ('b' occurs first at position 1 if you ignore index 0)
`lst = ['b','c','b','a']`, `x = 'b'` >>> returns `2` ('b' occurs first at position 2 if you ignore index 0)
`lst = [0,2,'a','5',0,1,0]`, `x = 0` >>> returns `4` (0 occurs first at position 4 if you ignore index 0)
|
reference
|
def index_finder(l, x):
return l . index(x, 1)
|
Find the index of the first occurrence of an item in a list (with a twist)
|
585ba66ce08bae791b00011b
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/585ba66ce08bae791b00011b
|
7 kyu
|
Write a program to determine if the two given numbers are coprime. A pair of numbers are coprime if their greatest shared factor is `1`.
The inputs will always be two positive integers between `2` and `99`.
## Examples
`20` and `27`:
* Factors of `20`: `1, 2, 4, 5, 10, 20`
* Factors of `27`: `1, 3, 9, 27`
* Greatest shared factor: `1`
* Result: `20` and `27` are coprime
`12` and `39`:
* Factors of `12`: `1, 2, 3, 4, 6, 12`
* Factors of `39`: `1, 3, 13, 39`
* Greatest shared factor: `3`
* Result: `12` and `39` are **not** coprimes
~~~if:lambdacalc
## Encodings
purity: `LetRec`
numEncoding: `Church`
~~~
|
algorithms
|
from fractions import gcd
def are_coprime(n, m):
return gcd(n, m) == 1
|
Coprime Validator
|
585c50e75d0930e6a7000336
|
[
"Algorithms",
"Mathematics"
] |
https://www.codewars.com/kata/585c50e75d0930e6a7000336
|
7 kyu
|
A byte is a sequence of 8 bits. One could imagine implementing a small set data structure using a single byte. The set would hold at most the elements 0 through 7. The value of each bit in the byte would indicate whether the index of that bit was included in the set.
Consider the following byte, where the index of each bit is marked below.
Byte: 0 1 1 0 0 1 0 1
Index: 0 1 2 3 4 5 6 7
This byte would represent the set {1, 2, 5, 7}. Similarly,
10101010 ==> {0, 2, 4, 6}
11100000 ==> {0, 1, 2}
Your task is to write a function byte\_to\_set which takes a single byte (an integer 0-255), and returns the corresponding set.
```python
>> byte_to_set(0)
set()
>> byte_to_set(255)
{0,1,2,3,4,5,6,7}
>> byte_to_set(3)
{6,7}
```
|
algorithms
|
def byte_to_set(byte):
return {i for i in range(8) if (byte & (128 >> i))}
|
Creating a Bitset, Part 1
|
594c6ad5d909ca19e200002f
|
[
"Sets",
"Data Structures",
"Algorithms",
"Binary"
] |
https://www.codewars.com/kata/594c6ad5d909ca19e200002f
|
7 kyu
|
<h3>The Story:</h3>
Aliens from Kepler 27b have immigrated to Earth! They have learned English and go to our stores, eat our food, dress like us, ride Ubers, use Google, etc. However, they speak English a little differently. Can you write a program that converts our English to their Alien English?
<h3>Task:</h3>
Write a function converting their speech to ours. They tend to speak the letter `a` like `o` and `o` like a `u`.
```python
>>> convert('hello')
'hellu'
>>> convert('codewars')
'cudewors'
```
```ruby
convert('hello') # => 'hellu'
convert('codewars') # =>'cudewors'
```
|
reference
|
def convert(st):
return st . replace('o', 'u'). replace('a', 'o')
|
Alien Accent
|
5874657211d7d6176a00012f
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/5874657211d7d6176a00012f
|
7 kyu
|
Given some positive integers, I wish to print the integers such that all take up the same width by adding a minimum number of leading zeroes. No leading zeroes shall be added to the largest integer.
For example, given `1, 23, 2, 17, 102`, I wish to print out these numbers as follows:
```
001
023
002
017
102
```
Write a function that takes a variable number of integers and returns the string to be printed out.
|
reference
|
def print_nums(* arr):
if not arr:
return ''
ln = len(str(max(arr)))
return '\n' . join(str(c). zfill(ln) for c in arr)
|
Format to the 2nd
|
58311faba317216aad000168
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/58311faba317216aad000168
|
7 kyu
|
You're a statistics professor and the deadline for submitting your students' grades is tonight at midnight. Each student's grade is determined by their mean score across all of the tests they took this semester.
You've decided to automate grade calculation by writing a function `calculate_grade()` that takes a list of test scores as an argument and returns a one character string representing the student's grade calculated as follows:
* 90% <= mean score <= 100%: `"A"`,
* 80% <= mean score < 90%: `"B"`,
* 70% <= mean score < 80%: `"C"`,
* 60% <= mean score < 70%: `"D"`,
* mean score < 60%: `"F"`
For example, `calculate_grade([92, 94, 99])` would return `"A"` since the mean score is `95`, and `calculate_grade([50, 60, 70, 80, 90])` would return `"C"` since the mean score is `70`.
Your function should handle an input list of any length greater than zero.
|
reference
|
from bisect import bisect
from statistics import mean
def calculate_grade(scores):
return 'FDCBA' [bisect([60, 70, 80, 90], mean(scores))]
|
Thinkful - List and Loop Drills: Grade calculator
|
586e0dc9b98de0064b000247
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/586e0dc9b98de0064b000247
|
7 kyu
|
# Help Johnny!
### He can't make his code work!
##### Easy Code
Johnny is trying to make a function that encode 2 strings into their ASCII values and sum them together, but he can't find the error in his code! Help him!
|
bug_fixes
|
def add(s1, s2):
return sum(ord(x) for x in s1 + s2)
|
Noob Debug 1: Fix the string sum!
|
5848cd33c3689be0dc00175c
|
[
"Debugging",
"Strings",
"Mathematics"
] |
https://www.codewars.com/kata/5848cd33c3689be0dc00175c
|
7 kyu
|
<em>So</em> - shouted boss, heading to Tim's office - <em>we have new contract!</em>.
<br /><em>- What is it?</em> - ask Tim.
<br /><em>- Do not know, frankly, it's secret! It's from <strong>army</strong>!</em> - boss was obviously excited.
<br /><em>- So how are we supposed to write anything, if it is so big secret?</em>
<br /><em>- And that's the point! We won't know it, but we will write it. We have to prepare mechanism to create <strong>dynamic classes with properties and methods</strong> given as a parameters.</em> - explained boss.
<br /><em>- I don't think that's, umm... But would we at least know names of these properties and methods, right?</em>
<br /><em>- No. Remember that it's secret, so we'll not know anything!</em>
<br /><em>- Nah, it's impossible!</em> - cried Tim.
Then Tims went to find you - his almighty guru - and ask to help him. You reminded him: -<em> It's Python, here everything is possible! Ok, let's see...</em>.
So, in that Kata, your task is to finish function ```create_class``` that will get some class name and <em>secret</em> dictionary and make class of it. That dictionary will be delivered by function ```army_get_secret_from_file()``` which is already completed.
Tim also asked you to make sure that if class name is empty, it should be None as result, and to make possible to call function without second parameter. Returned object should be the new-style class, which has only to inherit the base methods of the class `object`.
Do not worry, these test properties and methods are dummy, so you won't know the army's mysteries, so you (probably) won't be executed.
<br/><br/>
<strong>Check also previous: <a href="http://www.codewars.com/kata/pythons-dynamic-classes-number-1"> Python's Dynamic Classes #1 Kata</a> and <a href="http://www.codewars.com/kata/pythons-dynamic-classes-number-2"> Python's Dynamic Classes #2 Kata</a></strong>.
|
reference
|
def create_class(class_name, secrets={}):
if class_name:
return type(class_name, (), secrets)
|
Python's Dynamic Classes #3
|
55dec8f72ead8624e5000028
|
[
"Fundamentals",
"Object-oriented Programming"
] |
https://www.codewars.com/kata/55dec8f72ead8624e5000028
|
5 kyu
|
<strong>Continuation to <a href="http://www.codewars.com/kata/pythons-dynamic-classes-number-1"> Python's Dynamic Classes #1 Kata</a></strong>.
<br/>
<br/>
<em>- That name changing function is awesome!</em> - Timmy heard from his boss - <em> but would it not be possible to hide somehow that function in classes itself?</em>
Timmy was thinking about it for while than decided to contact with his guru - you - and ask about it. You offered him to build class that could be <strong>inherited</strong>, and could provide some class method to modify name of already existing classes.
The new class should be named as
```python
ReNameAbleClass
```
and the special one method should be
```python
change_class_name
```
Like before, be sure that new solution will allow only names with alphanumeric chars (upper & lower letters plus digits), but starting only with upper case letter.
Moreover, for testing purposes, he want new class to have
```python
__str__
```
method which will be returning string like "Class name is: MyClass" for MyClass.
<br /><br />
<strong>Too easy? Check <a href="http://www.codewars.com/kata/pythons-dynamic-classes-number-3"> Python's Dynamic Classes #3 Kata</a> and make sure that solved <a href="http://www.codewars.com/kata/pythons-dynamic-classes-number-1"> Python's Dynamic Classes #1 Kata</a></strong>.
|
reference
|
class ReNameAbleClass (object):
@ classmethod
def change_class_name(cls, new_name):
if not (new_name and new_name[0]. isupper() and new_name . isalnum()):
raise ValueError('Bad class name')
cls . __name__ = new_name
@ classmethod
def __str__(cls):
return 'Class name is: {}' . format(cls . __name__)
|
Python's Dynamic Classes #2
|
55ddcef532f8678af1000006
|
[
"Fundamentals",
"Object-oriented Programming"
] |
https://www.codewars.com/kata/55ddcef532f8678af1000006
|
7 kyu
|
Timmy's quiet and calm work has been suddenly stopped by his project manager (let's call him boss) yelling:
<p><em>- Who named these classes?! Class <strong>MyClass</strong>? It's ridiculous! I want you to change it to <strong>UsefulClass</strong>!</em></p>
Tim sighed, he already knew it's gonna be a long day.
<br />
Few hours later, boss came again:
<p><em>
Much better - </em>he said<em> - but now I want to change that class name to <strong>SecondUsefulClass</strong>,
</em></p>
and went off. Although Timmy had no idea why changing name is so important for his boss, he realized, that it's not the end, so he turned to you, his guru, to help him and asked you to prepare some function, which could change name of given class.
<em>Note: Proposed function should allow only names with alphanumeric chars (upper & lower letters plus ciphers), but starting only with upper case letter. In other case it should raise an exception.
<br />
Disclaimer: there are obviously betters way to check class name than in example cases, but let's stick with that, that Timmy yet has to learn them.</em>
<br /><br />
<strong>To easy? Check <a href="http://www.codewars.com/kata/pythons-dynamic-classes-number-2"> Python's Dynamic Classes #2 Kata</a> and <a href="http://www.codewars.com/kata/pythons-dynamic-classes-number-3"> Python's Dynamic Classes #3 Kata</a></strong>.
|
reference
|
def class_name_changer(cls, new_name):
assert new_name[0]. isupper() and new_name . isalnum()
cls . __name__ = new_name
|
Python's Dynamic Classes #1
|
55ddb0ea5a133623b6000043
|
[
"Fundamentals",
"Object-oriented Programming"
] |
https://www.codewars.com/kata/55ddb0ea5a133623b6000043
|
7 kyu
|
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all!
You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark.
---
```python
>>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan'])
{'goat': 2, 'horse': 2, 'rabbit': 2}
# If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!!
>>> two_by_two([])
False
# If there are no pairs of animals, return an empty dictionary
>>> two_by_two(['goat'])
{}
```
|
reference
|
def two_by_two(animals):
return {x: 2 for x in animals if animals . count(x) > 1} if animals else False
|
The animals went in two by two
|
578de3801499359921000130
|
[
"Fundamentals",
"Arrays"
] |
https://www.codewars.com/kata/578de3801499359921000130
|
7 kyu
|
You were given a string of integer temperature values. Create a function `close_to_zero(t)` and return the closest value to 0 or `0` if the string is empty. If two numbers are equally close to zero, return the positive integer.
|
reference
|
def close2zero(t):
return min(map(int, t . split()), key=lambda t: (abs(t), - t), default=0)
|
Temperature analysis II
|
588e10c5f051b147ff00004b
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/588e10c5f051b147ff00004b
|
7 kyu
|
The "Russian Peasant Method" is an old algorithm used by Russian peasants (and before them ancient Egyptians) to perform multiplication. Consider that X and Y are two numbers. X can be any number but Y must be a positive integer. To multiply X and Y:
1. Let the product = 0
2. If Y is odd, then the product = product + X
3. X = X + X
4. Y = integer part of Y / 2
5. if Y is nonzero, repeat from step 2; otherwise the algorithm terminates and returns the product.
For example:
Let X = 10
Let Y = 5
X: 10 20 40 80
Y: 5 2 1 0
product = 10 + 40 = 50
Note: usage of multiplication is of course forbidden...
|
reference
|
def russian_peasant_multiplication(x, y):
product = 0
while y != 0:
if y % 2 == 1:
product += x
x += x
y / /= 2
return product
|
Russian Peasant Multiplication
|
5870ef72aa04283934000043
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5870ef72aa04283934000043
|
7 kyu
|
The module ```ast``` may give some advantages in Python when you want to evaluate functions for certain values of its variables but are in string format. This may be useful for math operands like ```+```, ```-```, ```*```, ```/``` and ```**```.
Suposse that I want to evaluate the polynomial, ```P(x) = 2x² + 3x```
we want to calculate ```P(4)```.
```python
>>> import ast
>>> x = 4
>>> pol_str = "2*x**2 + 3*x"
>>> node = ast.parse(pol_str, mode='eval')
>>> code_object = compile(node, filename='<string>', mode='eval')
>>> result = eval(code_object)
>>> print result
44
>>>
```
Make a function, ```calc_pol()``` that receives a polynomial like a string, ```pol_str``` and a value of the variable x, ```x```. The function will output the result in a string format. If the result P(x) is ```0```, the function will output that x is a root of the polynomial.
```python
calc_pol("2*x**2 + 3*x", 4) == "Result = 44"
calc_pol("2*x**2 + 3*x - 44", 4) == "Result = 0, so 4 is a root of 2*x**2 + 3*x - 44"
```
If the function receives only one variable, ```pol_str``` :
See the case:
```python
calc_pol(pol_str) == "There is no value for x"
```
Happy coding!!
|
reference
|
def calc_pol(pol_str, x=None):
return "There is no value for x" if x == None else "Result = " + str(eval(pol_str)) + ("" if eval(pol_str) != 0 else ", so {} is a root of {}" . format(x, pol_str))
|
Polynomials I: String Format
|
56917304360b39073f00003b
|
[
"Fundamentals",
"Mathematics",
"Strings"
] |
https://www.codewars.com/kata/56917304360b39073f00003b
|
7 kyu
|
Poor Cade has got his number conversions mixed up again!
Fix his ```convert_num()``` function so it correctly converts a base-10 ```int```eger,
to the selected of ```bin```ary or ```hex```adecimal.
```#The output should be a string at all times```
```python
convert_num(number, base):
if 'base' = hex:
return int(number, 16)
if 'base' = bin:
return int(number, 2)
return (Incorrect base input)
```
Please note, invalid ```number``` or ```base``` inputs will be tested.
In the event of an invalid ```number/base``` you should return:
```python
"Invalid number input"
or
"Invalid base input"
```
For each respectively.
Good luck coding! :D
|
bug_fixes
|
def convert_num(number, base):
try:
if base == 'hex':
return hex(number)
if base == 'bin':
return bin(number)
except:
return 'Invalid number input'
return 'Invalid base input'
|
Fix the base conversion function!
|
57cded7cf5f4ef768800003c
|
[
"Debugging"
] |
https://www.codewars.com/kata/57cded7cf5f4ef768800003c
|
7 kyu
|
When you want to get the square of a binomial of two variables x and y, you will have:
`$(x+y)^2 = x^2 + 2xy + y ^2$`
And the cube:
`$(x+y)^3 = x^3 + 3x^2y + 3xy^2 +y^3$`
It is known from many centuries ago that for an exponent n, the result of a binomial x + y raised to the n-th power is:
```math
\displaystyle (x+y)^n = {{n} \choose {0}} x^ny^0 + {{n} \choose {1}} x^{n-1}y^1 + {{n} \choose {2}} x^{n-2}y^2 +\cdots +{{n} \choose {n-1}} x^1y^{n-1} + {{n} \choose {n}} x^0y^n
```
Or using the sumation notation:
```math
\displaystyle (x+y)^n = \sum_{k=0}^n {{n} \choose {k}} x^{n-k} y^k=\sum_{k=0}^n {{n} \choose {k}} x^k y^{n-k}
```
Each coefficient of a term has the following value:
```math
\displaystyle {n \choose k} = \dfrac{n!}{(n-k)! \cdot k!} = \dfrac{(n-k+1)\cdots(n-2)(n-1)n}{k!}
```
Each coefficient value coincides with the amount of combinations without replacements of a set of n elements using only k different ones of that set.
Let's see the total sum of the coefficients of the different powers for the binomial:
`$(x+y)^0(1)$`
`$(x+y)^1 = x+y(2)$`
`$(x+y)^2 = x^2 + 2xy + y ^2(4)$`
`$(x+y)^3 = x^3 + 3x^2y + 3xy^2 +y^3(8)$`
# Task
Create a function that returns (an array) of the coefficients sums from 0 to n (inclusive), where the last element is the sum of all previous elements.
We add some examples below:
```
for n = 0, return 1, 1
for n = 1, return 1, 2, 3
for n = 2, return 1, 2, 4, 7
for n = 3, return 1, 2, 4, 8, 15
```
Features of the test
```
Low Performance Tests
Number of tests = 50
9 < n < 101
High Performance Tests
Number of Tests = 50
99 < n < 5001
N.B. In C, input is limited to 0 <= n <= 63
```
|
reference
|
def f(n):
return [2 * * i for i in range(n + 1)] + [(2 * * (n + 1)) - 1]
|
Total Sums of Coefficients of a Binomial Raised to the Nth-Power
|
584a6d9d7d22f8fa09000094
|
[
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic"
] |
https://www.codewars.com/kata/584a6d9d7d22f8fa09000094
|
7 kyu
|
Write a function `centroid(c)` to calculate the centroid of 3D coordinates.
Return the results as a list of floats. Round the values to two decimal places.
|
algorithms
|
import numpy as np
def centroid(c):
return np . mean(c, axis=0). round(2). tolist()
|
Centroid I
|
58811e9cfd05cb5aed0000a4
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58811e9cfd05cb5aed0000a4
|
7 kyu
|
If I give you a date, can you tell me what day that date is? For example, december 8th, 2015 is a tuesday.
Your job is to write the function ```day(d)```
which takes a string representation of a date as input, in the format YYYYMMDD. The example would be "20151208". The function needs to output the string representation of the day, so in this case ```"Tuesday"```.
Your function should be able to handle dates ranging from January first, 1582 (the year the Gregorian Calendar was introduced) to December 31st, 9999. You will not be given invalid dates. Remember to take leap years into account.
|
algorithms
|
import datetime
import calendar
def day(date):
return calendar . day_name[datetime . datetime . strptime(date, "%Y%m%d"). weekday()]
|
What day is it?
|
5666bd1011beb6f768000073
|
[
"Algorithms",
"Puzzles"
] |
https://www.codewars.com/kata/5666bd1011beb6f768000073
|
7 kyu
|
You are trying to make a checkerboard made up of X's and O's. You've implemented the function before in a different language but it just won't work. The function creates an n by n board of X's and O's.
For example (**Input --> Output**)
```
n = 4 -->
[['X', 'O', 'X', 'O'],
['O', 'X', 'O', 'X'],
['X', 'O', 'X', 'O'],
['O', 'X', 'O', 'X']]
```
|
bug_fixes
|
def make_checkered_board(n):
line = ['X' for x in range(n)]
board = [line[:] for y in range(n)]
for row in range(0, n):
for col in range(0, n):
if (row + col) % 2:
board[row][col] = "O"
return board
|
Python Checkerboard
|
57785441311a24465e000025
|
[
"Debugging"
] |
https://www.codewars.com/kata/57785441311a24465e000025
|
7 kyu
|
You have invented a time-machine which has taken you back to ancient Rome. Caeser is impressed with your programming skills and has appointed you to be the new information security officer.
Caeser has ordered you to write a Caeser cipher to prevent Asterix and Obelix from reading his emails.
A Caeser cipher shifts the letters in a message by the value dictated by the encryption key. Since Caeser's emails are very important, he wants all encryptions to have upper-case output, for example:
If key = 3
"hello" -> KHOOR
If key = 7
"hello" -> OLSSV
Input will consist of the message to be encrypted and the encryption key.
|
algorithms
|
from string import maketrans, lowercase, uppercase
def caeser(message, key):
return message . translate(maketrans(lowercase, uppercase[key:] + uppercase[: key]))
|
Caeser Encryption
|
56dc695b2a4504b95000004e
|
[
"Algorithms"
] |
https://www.codewars.com/kata/56dc695b2a4504b95000004e
|
7 kyu
|
A cyclops number is a number in binary that is made up of all 1's, with one 0 in the exact middle. That means all cyclops numbers must have an odd number of digits for there to be an exact middle.
A couple examples:
101
11111111011111111
You must take an input, n, that will be in decimal format (base 10), then return True if that number wil be a cyclops number when converted to binary, or False if it won't.
Assume n will be a positive integer.
A test cases with the process shown:
```python
cyclops (5)
"""5 in biinary"""
"0b101"
"""because 101 is made up of all "1"s with a "0" in the middle, 101 is a cyclops number"""
return True
cyclops(13)
"""13 in binary"""
"0b1101"
"""because 1101 has an even number of bits, it cannot be a cyclops"""
return False
cyclops(17)
"""17 in binary"""
"0b10001"
"""Because 10001 has more than 1 "0" it cannot be a cyclops number"""
return False
```
`n` will always be `> 0`.
|
algorithms
|
def cyclops(n):
n = bin(n)[2:]
return n . count("0") == 1 and n == n[:: - 1]
|
Cyclops numbers
|
56b0bc0826814364a800005a
|
[
"Algorithms"
] |
https://www.codewars.com/kata/56b0bc0826814364a800005a
|
7 kyu
|
The objective is to disambiguate two given names: the original with another
Let's start simple, and just work with plain ascii strings.
The function ```could_be``` is given the original name and another one to test
against.
```python
# should return True if the other name could be the same person
> could_be("Chuck Norris", "Chuck")
True
# should False otherwise (whatever you may personnaly think)
> could_be("Chuck Norris", "superman")
False
```
Let's say your name is *Carlos Ray Norris*, your objective is to return True if
the other given name matches any combinaison of the original fullname:
```python
could_be("Carlos Ray Norris", "Carlos Ray Norris") : True
could_be("Carlos Ray Norris", "Carlos Ray") : True
could_be("Carlos Ray Norris", "Norris") : True
could_be("Carlos Ray Norris", "Norris Carlos") : True
```
For the sake of simplicity:
* the function is case sensitive and accent sensitive for now
* it is also punctuation sensitive
* an empty other name should not match any original
* an empty orginal name should not be matchable
* the function is not symmetrical
The following matches should therefore fail:
```python
could_be("Carlos Ray Norris", " ") : False
could_be("Carlos Ray Norris", "carlos") : False
could_be("Carlos Ray Norris", "Norris!") : False
could_be("Carlos Ray Norris", "Carlos-Ray Norris") : False
could_be("Ray Norris", "Carlos Ray Norris") : False
could_be("Carlos", "Carlos Ray Norris") : False
```
Too easy ? Try the next steps:
* [Author Disambiguation: a name is a Name!](https://www.codewars.com/kata/author-disambiguation-a-name-is-a-name)
* or even harder: [Author Disambiguation: Signatures worth it](https://www.codewars.com/kata/author-disambiguation-signatures-worth-it)
|
reference
|
def could_be(original, another):
if not another . strip(): return False
return all ( name in original . split () for name in another . split ())
|
Author Disambiguation: to the point
|
580a429e1cb4028481000019
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/580a429e1cb4028481000019
|
7 kyu
|
The Caesar cipher is a notorious (and notoriously simple) algorithm for encrypting a message: each letter is shifted a certain constant number of places in the alphabet. For example, applying a shift of `5` to the string `"Hello, world!"` yields `"Mjqqt, btwqi!"`, which is jibberish.
In this kata, your task is to decrypt Caesar-encrypted messages using nothing but your wits, your computer, and a `set` of the 1000 (plus a few) most common words in English in **lowercase** (made available to you as a preloaded variable named `WORDS`, which you may use in your code as if you had defined it yourself).
### Given a message, your function must return the most likely shift value as an integer.
A few hints:
* Be wary of punctuation
* Shift values may not be higher than 25
|
reference
|
abc = 'abcdefghijklmnopqrstuvwxyz'
def caesar(s, shift):
# make a translation table with the current shift
transtable = str . maketrans(abc, abc[shift:] + abc[: shift])
return s . translate(transtable)
def break_caesar(message):
# sanitize the input
message = '' . join(c if c . isalpha() else ' ' for c in message). lower()
# keep track of hits
hits = []
# try all possible shifts
for shift in range(26):
# decode the message with the current shift
decoded = caesar(message, - shift)
cnt = 0
for word in decoded . split():
# count the number of common English words
if word in WORDS:
cnt += 1
# append the result
hits . append(cnt)
# find the most likely shift value
shift = hits . index(max(hits))
return shift
|
Break the Caesar!
|
598e045b8c13926d8c0000e8
|
[
"Ciphers",
"Cryptography",
"Fundamentals"
] |
https://www.codewars.com/kata/598e045b8c13926d8c0000e8
|
5 kyu
|
Given a string `"abc"` and assuming that each letter in the string has a value equal to its position in the alphabet, our string will have a value of `1 + 2 + 3 = 6`. This means that: `a = 1, b = 2, c = 3 ....z = 26`.
You will be given a list of strings and your task will be to return the values of the strings as explained above multiplied by the position of that string in the list. For our purpose, position begins with `1`.
`nameValue ["abc","abc abc"]` should return `[6,24]` because of `[ 6 * 1, 12 * 2 ]`. Note how spaces are ignored.
`"abc"` has a value of `6`, while `"abc abc"` has a value of `12`. Now, the value at position `1` is multiplied by `1` while the value at position `2` is multiplied by `2`.
Input will only contain lowercase characters and spaces.
Good luck!
If you like this Kata, please try:
[String matchup](https://www.codewars.com/kata/59ca8e8e1a68b7de740001f4)
[Consonant value](https://www.codewars.com/kata/59c633e7dcc4053512000073)
|
reference
|
def nameValue(myList):
return [i * sum(map(lambda c: [0, ord(c) - 96][c . isalpha()], w . lower())) for i, w in enumerate(myList, 1)]
|
Word values
|
598d91785d4ce3ec4f000018
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/598d91785d4ce3ec4f000018
|
7 kyu
|
Removed due to copyright infringement.
<!---
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited `N` his friends there.
If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from `1` to `N`. Petya remembered that a friend number `i` gave a gift to a friend number `j`. He also remembered that each of his friends received exactly one gift.
Now Petya wants to know for each friend `i` the number of a friend who has given him a gift.
### Input
Input contains array with `N` integers: the `i`-th number is the number of the friend who was given a present by friend number `i`. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.
### Output
Return array with `N` integers: the `i`-th number should equal the number of the friend who gave a gift to friend number `i`.
### Examples
```
[2, 3, 4, 1] => [4, 1, 2, 3]
[1, 3, 2] => [1, 3, 2]
[1, 2] => [1, 2]
```
First example step-by-step explanation (note: the explanation uses 1-based indexing to make the correspondence with friend-numbering clearer):
1. The friend `1` gave gift to the friend `2` (`a[1] == 2`) - this means that in the output array number `1` is at position `2` : `[_, 1, _, _]`.
1. The friend `2` gave gift to the friend `3` (`a[2] == 3`) - this means that in the output array number `2` is at position `3` : `[_, 1, 2, _]`.
1. The friend `3` gave gift to the friend `4` (`a[3] == 4`) - this means that in the output array number `3` is at position `4` : `[_, 1, 2, 3]`.
1. The friend `4` gave gift to the friend `1` (`a[4] == 1`) - this means that in the output array number `4` is at position `1` : `[4, 1, 2, 3]`.
(c)KADR
--->
|
reference
|
def presents(a):
res = [None] * len(a)
for i, j in enumerate(a, 1):
res[j - 1] = i
return res
|
Presents
|
598d6fd5b383eda05c000046
|
[
"Fundamentals",
"Arrays",
"Data Types"
] |
https://www.codewars.com/kata/598d6fd5b383eda05c000046
|
7 kyu
|
Convert text to [BF](https://esolangs.org/wiki/Brainfuck)
-------------------------
You are tasked with writing a function that converts a given string to [BF](https://esolangs.org/wiki/Brainfuck) that would print the given string.
For example, if we were to call the function with the string ```"Hello World!"``` it might give us a result that is something like:
```"-[------->+<]>-.-[->+++++<]>++.+++++++..+++.[--->+<]>-----.---[->+++<]>.-[--->+<]>---.+++.------.--------.-[--->+<]>."```.
If we execute that code, we would get ```"Hello World!"``` as the output.
|
algorithms
|
from itertools import pairwise
def to_brainfuck(s):
return '' . join('+-' [a > b] * abs(a - b) + '.' for a, b in pairwise(map(ord, "\0" + s)))
|
Brainfuck generator
|
579e646353ba33cce2000093
|
[
"Algorithms"
] |
https://www.codewars.com/kata/579e646353ba33cce2000093
|
6 kyu
|
Removed due to copyright infringement.
<!---
 Little Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the xor operation is performed on this computer (and whether there is anything like it).
 It turned out that the operation does exist (however, it is called tor) and it works like this. Suppose that we need to calculate the value of the expression A tor B. Both numbers A and B are written in the ternary notation one under the other one (B under A). If they have a different number of digits, then leading zeroes are added to the shorter number until the lengths are the same. Then the numbers are summed together digit by digit. The result of summing each two digits is calculated modulo 3. Note that there is no carry between digits (i. e. during this operation the digits aren't transferred). For example: 14<sub>10</sub> tor 50<sub>10</sub> == 0112<sub>3</sub> tor 1212<sub>3</sub> == 1021<sub>3</sub> == 34<sub>10</sub>.
 Petya wrote numbers A and C on a piece of paper. Help him find such number B, that A tor B = C. If there are several such numbers, print the smallest one.
Input:<br>
 Input contains two integers A and C. Both numbers are written in decimal notation.
Output:<br>
 Return the single integer B, such that A tor B = C. If there are several possible numbers B, print the smallest one. You should print the number in decimal notation.
Examples:
```
(14, 34) => 50
(50, 34) => 14
(387420489, 225159023) => 1000000001
(5, 5) => 0
```
<b>NOTE:</b><br>
You need to find B!<br>
`A tor ??? = C`
(c)KADR
--->
|
algorithms
|
def ternary(a, c):
res, p = 0, 1
while a or c:
a, x = divmod(a, 3)
c, y = divmod(c, 3)
res += (y - x) % 3 * p
p *= 3
return res
|
Ternary Logic
|
598d79f7b1954bc4cc000028
|
[
"Algorithms"
] |
https://www.codewars.com/kata/598d79f7b1954bc4cc000028
|
6 kyu
|
Removed due to copyright infringement.
<!---
**Introduction**<br>
 Little Petya very much likes sequences. However, recently he received a sequence as a gift from his mother.<br>
 Petya didn't like it at all! He decided to make a single replacement. After this replacement, Petya would like to the sequence in increasing order.<br>
 He asks himself: What is the lowest possible value I could have got after making the replacement and sorting the sequence?
**About the replacement**<br>
 Choose exactly one element from the sequence and replace it with another integer > 0. You are **not allowed** to replace a number with itself, or to change no number at all.
**Task**<br>
 Find the lowest possible sequence after performing a valid replacement, and sorting the sequence.
**Input:**<br>
 Input contains sequence with `N` integers. All elements of the sequence > 0. The sequence will never be empty.
**Output:**<br>
 Return sequence with `N` integers — which includes the lowest possible values of each sequence element, after the single replacement and sorting has been performed.
**Examples**:<br>
```
([1,2,3,4,5]) => [1,1,2,3,4]
([4,2,1,3,5]) => [1,1,2,3,4]
([2,3,4,5,6]) => [1,2,3,4,5]
([2,2,2]) => [1,2,2]
([42]) => [1]
```
--->
|
reference
|
def sort_number(a):
a = sorted(a)
return [1] + a if a . pop() != 1 else a + [2]
|
Replacement
|
598d89971928a085c000001a
|
[
"Fundamentals",
"Algorithms",
"Logic",
"Arrays",
"Data Types"
] |
https://www.codewars.com/kata/598d89971928a085c000001a
|
6 kyu
|
# Pattern Generator
create a function that accepts 1 (one) parameter and returns a string that has such a pattern:
> parameter: 1,
> generate pattern:
> ```
> x```
-
> parameter: 2,
> generate pattern:
```
x
x x
x
```
-
> parameter: 3,
> generate pattern:
```
x
x
x o x
x
x
```
-
> parameter: 4,
> generate pattern:
```
x
x
o x
x o o x
x o
x
x
```
-
> parameter: 5,
> generate pattern:
```
x
x
o x
o x
x o x o x
x o
x o
x
x
```
-
> parameter: 6,
> generate pattern:
```
x
x
o x
o x
x o x
x o x x o x
x o x
x o
x o
x
x
```
and so on...
-
# assume that:
- `N` is an integer within range [-100..200]
- the function should return empty string if given parameter lower than `1`
-
# additional info
the result is compared with smart algorithm, so you don't have to worry about additional space characters that's not visible.
##### for example, this string:
```
x \n x \n o x \n o x \nx o x o x\n x o \n x o \n x \n x \n
```
which is seen as:
```
x
x
o x
o x
x o x o x
x o
x o
x
x
```
##### is treated the same as:
```
x\n x\n o x\n o x\nx o x o x\n x o\n x o\n x\n x
```
which is seen as:
```
x
x
o x
o x
x o x o x
x o
x o
x
x
```
##### because both are visibly the same.
|
algorithms
|
def pattern_generator(n):
base, leftBlanks = '' . join(" " if i % 2 else "ox" [
not i % 4] for i in range(n)), " " * (n - 1)
upper = ('\n' . join(leftBlanks + base[: i + 1][:: - 1]
for i in range(n - 1)) + '\n') * (n > 1)
middle = base + base[: n - 1][:: - 1]
lower = ('\n' + '\n' . join(" " * i +
base[: n - i] for i in range(1, n))) * (n > 1)
return upper + middle + lower
|
Pattern Generator
|
598ab728062fc49a22000410
|
[
"Algorithms",
"ASCII Art"
] |
https://www.codewars.com/kata/598ab728062fc49a22000410
|
5 kyu
|
# The Basic Problem
Given a grid of `v` vertical roads and `h` horizontal roads, find the number of ways to go from the top-left intersection to the bottom-right, moving only right or down.
For example, a grid of `v = 4` and `h = 3` would look like this:
```
+-+-+-+
| | | |
+-+-+-+
| | | |
+-+-+-+
```
Then the answer is 10. Easy enough, right?
I suspect some of you are already typing in `factorial` stuff...
# The Twist
*But wait!* Due to some obscure reason, some of the intersections are blocked, so you can't pass through them. In other words, you cannot use all four road segments connected to such intersection.
Now, a grid with one blocked intersection might look like this:
```
+-+-+-+ +-+-+-+
| | | | | | |
+-X-+-+ + +-+
| | | | | | |
+-+-+-+ or +-+-+-+
```
Then the answer is 4.
# Task
The function `lattice_paths` should accept one input, which will be a two-dimensional list,
and return the number of ways to travel from top-left to bottom-right.
Each value in the input list will indicate whether the corresponding intersection is available or not. For example, the two grids discussed above will be passed as follows:
```python
# The following should return 10
lattice_paths([
[True, True, True, True],
[True, True, True, True],
[True, True, True, True]
])
# The following should return 4
lattice_paths([
[True, True, True, True],
[True, False, True, True],
[True, True, True, True]
])
```
The top-left and bottom-right intersection will always be available, i.e. `True`.
Also, it is guaranteed that `v >= 2` and `h >= 2`, the array shape is rectangular, and all elements are boolean values.
Also, *do not modify the input array!*
# Acknowledgement
This problem was inspired by [Project Euler #15: Lattice Paths](https://projecteuler.net/problem=15).
|
algorithms
|
def lattice_paths(grid):
sentinel = [0] * (1 + len(grid[0]))
sentinel[1] = 1 # always 1 in the top left corner
for i, g in enumerate(grid[0][1:], 2): # initiate the sentinel array
sentinel[i] = sentinel[i - 1] and g
for r in grid[1:]: # runs through the grid
for i, v in enumerate(r, 1):
# reset value of the sentinel if the node is blocked
sentinel[i] = sum(sentinel[i - 1: i + 1]) * v
return sentinel[- 1]
|
Lattice Paths, But...?
|
598c84db8ba6103bc40000ad
|
[
"Algorithms",
"Dynamic Programming"
] |
https://www.codewars.com/kata/598c84db8ba6103bc40000ad
|
5 kyu
|
Your task in order to complete this Kata is to write a function which calculates the area covered by a <a href='https://en.wikipedia.org/wiki/Union_(set_theory)'>union</a> of rectangles.<br>
Rectangles can have <b> non-empty intersection</b>, in this way simple solution:
S<sub>all</sub> = S<sub>1</sub> + S<sub>2</sub> + ... + S<sub>n-1</sub> + S<sub>n</sub> (where n - the quantity of rectangles) <b> will not work.</b>
### Preconditions
* each rectangle is represented as: [x<sub>0</sub>, y<sub>0</sub>, x<sub>1</sub>, y<sub>1</sub>]
* (x<sub>0</sub>, y<sub>0</sub>) - coordinates of the bottom left corner
* (x<sub>1</sub>, y<sub>1</sub>) - coordinates of the top right corner
* x<sub>i</sub>, y<sub>i</sub> - `positive integers or zeroes` (0, 1, 2, 3, 4..)
* sides of rectangles are `parallel to coordinate axes`
* your input data is array of rectangles
### Requirements
* Number of rectangles in one test (not including simple tests) range from `3000 to 15000.` There are `10 tests` with such range. So, your algorithm should be optimal.
* Sizes of the rectangles can reach values like 1e6.
### Example
<div>
<img src="https://s33.postimg.cc/nf3brdckv/111.png">
</div>
There are three rectangles:
* R1: [3,3,8,5], with area 10
* R2: [6,3,8,9], with area 12
* R3: [11,6,14,12], with area 18
* R1 and R2 are overlapping (2x2), the grayed area is removed from the total area
Hence the total area is `10 + 12 + 18 - 4 = 36`
---
Note: expected time complexity: something around O(N²), but with a good enough constant factor. If you think about using something better, try this kata instead: [Total area covered by more rectangles](https://www.codewars.com/kata/6425a1463b7dd0001c95fad4)
|
algorithms
|
def calculate(rectangles):
xs = sorted(set(x for (x0, y0, x1, y1) in rectangles for x in (x0, x1)))
inds = {x: i for i, x in enumerate(xs)}
bins = [[] for _ in range(len(xs) - 1)]
for x0, y0, x1, y1 in rectangles:
for j in range(inds[x0], inds[x1]):
bins[j]. append((y0, y1))
s = 0
for i, bin in enumerate(bins):
if not bin:
continue
bin . sort()
h, y = 0, bin[0][0]
for y0, y1 in bin:
h += max(y, y1) - max(y, y0)
y = max(y, y1)
s += h * (xs[i + 1] - xs[i])
return s
|
Total area covered by rectangles
|
55dcdd2c5a73bdddcb000044
|
[
"Algorithms",
"Geometry"
] |
https://www.codewars.com/kata/55dcdd2c5a73bdddcb000044
|
3 kyu
|
Here you have to do some mathematical operations on a "dirty string". This kata checks some basics, it's not too difficult.
__So what to do?__
<u>Input:</u> String which consists of two positive numbers (doubles) and exactly one operator like `+, -, * or /` always between these numbers. The string is dirty, which means that there are different characters inside too, not only numbers and the operator. You have to combine all digits left and right, perhaps with "." inside (doubles), and to calculate the result which has to be rounded to an integer and converted to a string at the end.
### Easy example:
```
Input: "gdfgdf234dg54gf*23oP42"
Output: "54929268" (because 23454*2342=54929268)
```
First there are some static tests, later on random tests too...
### Hope you have fun! :-)
|
reference
|
import re
def calculate_string(st):
st = re . sub(r'[^-+*/\d.]', '', st)
result = eval(st)
return str(int(round(result)))
|
Basics 03: Strings, Numbers and Calculation
|
56b5dc75d362eac53d000bc8
|
[
"Strings",
"Fundamentals",
"Mathematics",
"Arrays"
] |
https://www.codewars.com/kata/56b5dc75d362eac53d000bc8
|
6 kyu
|
Given a list of integers, return the n<sup>th</sup> smallest integer in the list. **Only distinct elements should be considered** when calculating the answer. `n` will always be positive (`n > 0`)
If the n<sup>th</sup> small integer doesn't exist, return `-1` (C++) / `None` (Python) / `nil` (Ruby) / `null` (JavaScript).
Notes:
* "indexing" starts from 1
* huge lists (of 1 million elements) will be tested
## Examples
```cpp
small({1, 3, 4, 5}, 7) -> -1 // n is more than the size of the list
small({4, 3, 4, 5}, 4) -> -1 // 4th smallest integer doesn't exist
small({45, -10, 4, 5, 4}, 4) -> 45 // 4th smallest integer is 45
```
```python
nth_smallest([1, 3, 4, 5], 7) ==> None # n is more than the size of the list
nth_smallest([4, 3, 4, 5], 4) ==> None # 4th smallest integer doesn't exist
nth_smallest([45, -10, 4, 5, 4], 4) ==> 45 # 4th smallest integer is 45
```
```ruby
nth_smallest([1, 3, 4, 5], 7) ==> nil # n is more than the size of the list
nth_smallest([4, 3, 4, 5], 4) ==> nil # 4th smallest integer doesn't exist
nth_smallest([45, -10, 4, 5, 4], 4) ==> 45 # 4th smallest integer is 45
```
```javascript
nthSmallest([1, 3, 4, 5], 7) ==> null // n is more than the size of the list
nthSmallest([4, 3, 4, 5], 4) ==> null // 4th smallest integer doesn't exist
nthSmallest([45, -10, 4, 5, 4], 4) ==> 45 // 4th smallest integer is 45
```
```crystal
nth_smallest([1, 3, 4, 5], 7) ==> nil # n is more than the size of the list
nth_smallest([4, 3, 4, 5], 4) ==> nil # 4th smallest integer doesn't exist
nth_smallest([45, -10, 4, 5, 4], 4) ==> 45 # 4th smallest integer is 45
```
If you get a timeout, just try to resubmit your solution. However, if you ***always*** get a timeout, review your code.
|
algorithms
|
def nth_smallest(arr, n):
s = set(arr)
return sorted(s)[n - 1] if n <= len(s) else None
|
The nth smallest integer
|
57a03b8872292dd851000069
|
[
"Fundamentals",
"Algorithms"
] |
https://www.codewars.com/kata/57a03b8872292dd851000069
|
6 kyu
|
*This question is a variation on the [Arithmetic Progression kata]( https://www.codewars.com/kata/find-the-missing-term-in-an-arithmetic-progression)*
---
The following was a question that I received during a technical interview for an entry level software developer position. I thought I'd post it here so that everyone could give it a go:
You are given an unsorted array containing all the integers from 0 to 100 inclusively. However, one number is missing. Write a function to find and return this number. What are the time and space complexities of your solution?
|
algorithms
|
def missing_no(lst):
return 5050 - sum(lst)
|
Find the Missing Number
|
57f5e7bd60d0a0cfd900032d
|
[
"Algorithms"
] |
https://www.codewars.com/kata/57f5e7bd60d0a0cfd900032d
|
7 kyu
|
In this kata you are expected to recover a scattered password in a (m x n) grid (you'll be given directions of all password pieces in the array)
The array will contain pieces of the password to be recovered, you'll get directions on how to get all the the pieces, your initial position in the array will be the character "x".
Heres what the array looks like
```javascript
[
["p", "x", "m"],
["a", "$", "$"],
["k", "i", "t"]
]
```
The given directions would consist of `[left, right, up, down]` and `[leftT, rightT, upT, downT]`, the former would be used to move around the grid while the latter would be used when you have a password to that direction of you.(
**E.g** if you are in a position and the move to make is `leftT` it means theres a password to the left of you, so take the value and move there)
So in the 2d array example above, you will be given the directions `["lefT", "downT", "rightT", "rightT"]`, making for the word `"pa$$"`.
Remember you initial position is the character "x".
So you write the function `getPassword(grid, directions)` that uses the directions to get a password in the grid.
Another example.
```javascript
grid = [
["a", "x", "c"],
["g", "l", "t"],
["o", "v", "e"]
];
directions = ["downT", "down", "leftT", "rightT", "rightT", "upT"]
getPassword(grid, directions) // => "lovet"
```
Once again, Your initial position is the character "x", so from the position of "x" you follow the directions given and get all pieces in the grid.
|
bug_fixes
|
MOVES = {"right": (0, 1), "down": (1, 0), "left": (0, - 1), "up": (- 1, 0)}
def get_password(grid, dirs):
x, y = next((x, y) for x, r in enumerate(grid)
for y, c in enumerate(r) if c == 'x')
pwd = []
for d in dirs:
dx, dy = MOVES[d . strip('T')]
x, y = x + dx, y + dy
if d . endswith('T'):
pwd . append(grid[x][y])
return '' . join(pwd)
|
Get Password from grid
|
58f6e7e455d7597dcc000045
|
[
"Logic",
"Arrays",
"Algorithms",
"Data Structures"
] |
https://www.codewars.com/kata/58f6e7e455d7597dcc000045
|
6 kyu
|
Removed due to copyright infringement.
<!---
In a small restaurant there are `A` tables for one person and `B` tables for two persons.
It it known that `N` groups of people come today, each consisting of one or two people.
If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person. If there are still none of them, the restaurant denies service to this group.
If a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.
You are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.
### Input:
Input contains two integers `A` and `B` - the number of one-seater and the number of two-seater tables respectively, and a list of integers - the number of people in each group of clients in chronological order of their arrival.
### Output:
Return the total number of people the restaurant denies service to.
### Examples:
```
(1, 2, [1, 2, 1, 1]) => 0
(1, 1, [1, 1, 2, 1]) => 2
```
In the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. The third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, all clients are served.
In the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, it occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. The fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.
(c)KAN
--->
|
algorithms
|
def restaurant(single_tables, double_tables, visitors):
kicked = 0
half = 0
for i in visitors:
if i == 1:
if single_tables > 0:
single_tables -= 1
elif double_tables > 0:
double_tables -= 1
half += 1
elif half > 0:
half -= 1
else:
kicked += 1
if i == 2:
if double_tables > 0:
double_tables -= 1
else:
kicked += 2
return kicked
|
Restaurant Tables
|
598c1bc6a04cd3b8dd000012
|
[
"Algorithms"
] |
https://www.codewars.com/kata/598c1bc6a04cd3b8dd000012
|
6 kyu
|
Simply find the closest value to zero from the list. Notice that there are negatives in the list.
List is always not empty and contains only integers. Return ```None``` if it is not possible to define only one of such values. And of course, we are expecting 0 as closest value to zero.
Examples:
```code
[2, 4, -1, -3] => -1
[5, 2, -2] => None
[5, 2, 2] => 2
[13, 0, -6] => 0
```
|
reference
|
def closest(lst):
m = min(lst, key=abs)
return m if m == 0 or - m not in lst else None
|
Closest to Zero
|
59887207635904314100007b
|
[
"Lists",
"Fundamentals"
] |
https://www.codewars.com/kata/59887207635904314100007b
|
7 kyu
|
# Story
It's a pretty relaxing life here at the nut farm.
Most of the time we just sit around looking at our nuts.
But once a year comes harvesting time...
Harvesting nuts is very easy. We just shake the trees and the nuts fall out!
---
As they fall down the nuts might hit branches:
* Sometimes they bounce left.
* Sometimes they bounce right.
* Sometimes they get stuck in the tree and don't fall out at all.
# Legend
* ```o``` = a nut
* ```\``` = branch. A nut hitting this branch bounces right
* ```/``` = branch. A nut hitting this branch bounces left
* ```_``` = branch. A nut hitting this branch gets stuck in the tree
* ```.``` = leaves, which have no effect on falling nuts
* ```|``` = tree trunk, which has no effect on falling nuts
* ``` ``` = empty space, which has no effect on falling nuts
# Kata Task
Shake the tree and count where the nuts land.
**Output** - An array (same width as the tree) which indicates how many nuts fell at each position ^
^ See the example tests
# Notes
* The nuts are always found at the top of the tree
* Nuts do not affect the falling patterns of other nuts
* There are always enough spaces for nuts to fall between branches
* There are no branches at the extreme left/right edges of the tree matrix so it is not possible for a nut to fall "out of bounds"
# Example
<pre style='font-size:20px;line-height:22px;'>
<span style='background:green'>.</span>o<span style='background:green'>.</span>oooooo<span style='background:green'>.</span>o<span style='background:green'>.</span>o<span style='background:green'>.</span>oooooo<span style='background:green'>.</span>
<span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>
<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>
<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>/<span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span>\<span style='background:green'>.</span>
<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>/<span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>
<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span>/<span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>
<span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>
<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>
<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>\<span style='background:green'>.</span>_<span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>_<span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>\<span style='background:green'>.</span>
<span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>
<span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span>
<span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span>
<span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span>
<span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span>
<span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span>
<span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span>
<span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span>
101005000020000000040
</pre>
|
algorithms
|
from collections import Counter
def shake_tree(tree):
nutsPos = [p for p, c in enumerate(tree[0]) if c == 'o']
for line in tree[1:]:
nutsPos = [p + 1 if line[p] == '\\' else p - 1 if line[p]
== '/' else p for p in nutsPos if line[p] != '_']
nuts = Counter(nutsPos)
return [nuts[p] for p in range(len(tree[0]))]
|
Nut Farm
|
59884371d1d8d3d9270000a5
|
[
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/59884371d1d8d3d9270000a5
|
6 kyu
|
The Stack Arithmetic Machine
---------------------------
This time we're going to be writing a stack arithmetic machine, and we're going to call it Sam. Essentially, Sam is a very small virtual machine, with a simple intruction set, four general registers, and a stack. We've already given a CPU class, which gives you read and write access to registers and the stack, through `readReg()` and `writeReg()`, and `popStack()` and `writeStack()` respectively. All instructions on Sam are 32-bit (Java int), and either interact with the stack, or one of the 4 registers; `a`, `b`, `c`, or `d`.
<hr>
The CPU API
-----------
The CPU instructions available through the CPU class, with a bit more detail:
```java
int readReg(String name): Returns the value of the named register.
void writeReg(String name, int value): Stores the value into the given register.
int popStack(): Pops the top element of the stack, returning the value.
void writeStack(int value): Pushes an element onto the stack.
```
```python
read_reg(self, name): Returns the value of the named register.
write_reg(self, name, value): Stores the value into the given register.
pop_stack(self): Pops the top element of the stack, returning the value.
write_stack(self, value): Pushes an element onto the stack.
```
```csharp
public int ReadReg(string name): Returns the value of the named register.
public void WriteReg(string name, int value): Stores the value into the given register.
public int PopStack(): Pops the top element of the stack, returning the value.
public void WriteStack(int value): Pushes an element onto the stack.
public void PrintStack(): Prints the contents of the stack to System.Console.
```
Note that the registers have a default value of `0` and that the sStack is printable (if needed).
<hr>
The Instruction Set
-------------------
Instructions for same are done in assembly style, and are passed one by one into the `Exec|exec|execute` function (depending on your language). Each instruction begins with the name of the operation, and is optionally followed by either one or two operands. The operands are marked in the table below by either `[reg]`, which accepts a register name, or `[reg|int]` which accepts either a register, or an immediate integer value.
### Stack Operations
```
push [reg|int]: Pushes a register [reg] or an immediate value [int] to the stack.
pop: Pops a value of the stack, discarding the value.
pop [reg]: Pops a value of the stack, into the given register [reg].
pushr: Pushes the general registers onto the stack, in order. (a, b, c, d)
pushrr: Pushes the general registers onto the stack, in reverse order. (d, c, b, a)
popr: Pops values off the stack, and loads them into the general registers, in order so that the two executions `pushr()` and `popr()` would leave the registers unchanged.
poprr: Pops values off the stack, and loads them into the general registers, in order so that the two executions `pushr()` and `poprr()` would invert the values of the registers from left to right.
```
### Misc Operations
```
mov [reg|int], [reg2]: Stores the value from [reg|int] into the register [reg2].
```
### Arithmetic Operations
```
add [reg|int]: Pops [reg|int] arguments off the stack, storing the sum in register a.
sub [reg|int]: Pops [reg|int] arguments off the stack, storing the difference in register a.
mul [reg|int]: Pops [reg|int] arguments off the stack, storing the product in register a.
div [reg|int]: Pops [reg|int] arguments off the stack, storing the quotient in register a.
and [reg|int]: Pops [reg|int] arguments off the stack, performing a bit-and operation, and storing the result in register a.
or [reg|int] : Pops [reg|int] arguments off the stack, performing a bit-or operation, and storing the result in register a.
xor [reg|int]: Pops [reg|int] arguments off the stack, performing a bit-xor operation, and storing the result in register a.
```
All arithmetic operations have 4 variants; they may be suffixed with the character `'a'` (`adda`, `xora`), and they may take an additional register parameter, which is the destination register. Thus, using add as an example:
```
add 5: Adds the top 5 values of the stack, storing the result in register a.
add 5, b: Adds the top 5 values of the stack, storing the result in register b instead.
adda 5: Pushes the value of register A onto the stack, then adds the top 5 values of the stack, and stores the result in register a.
adda 5, b: Pushes the value of register A onto the stack, adds the top 5 values of the stack, and stores the result in register b.
```
All arithmetic instructions may also take a register as their first argument, to perform a variable number of operation, as follows:
```
mov 3, a: Stores the number 3 in register a.
add a: Adds the top a values of the stack (in this case 3), storing the result in register a.
```
|
algorithms
|
from operator import add, sub, mul, floordiv as div, and_, or_, xor
OP = {'add': add, 'sub': sub, 'mul': mul,
'div': div, 'and': and_, 'or': or_, 'xor': xor}
class Machine (object):
def __init__(self, cpu):
self . cpu = cpu
def execute(self, instruction):
cmd, a, b = (instruction . replace(',', ' ') + ' 0 0'). split()[: 3]
v = self . cpu . read_reg(a) if a in 'abcd' else int(a)
if cmd == 'mov':
self . cpu . write_reg(b, v)
elif cmd == 'pop':
self . cpu . write_reg(a, self . cpu . pop_stack(
)) if a in 'abcd' else self . cpu . pop_stack()
elif cmd == 'push':
self . cpu . write_stack(v)
elif cmd in ['pushr', 'pushrr']:
for r in ('abcd' if cmd == 'pushr' else 'dcba'):
self . cpu . write_stack(self . cpu . read_reg(r))
elif cmd in ['popr', 'poprr']:
for r in ('abcd' if cmd == 'poprr' else 'dcba'):
self . cpu . write_reg(r, self . cpu . pop_stack())
else:
r = self . cpu . pop_stack(
) if cmd[- 1] != 'a' else self . cpu . read_reg('a')
for _ in range(v - 1):
r = OP[cmd if cmd[- 1] != 'a' else cmd[: - 1]](r, self . cpu . pop_stack())
self . cpu . write_reg(b if b in 'abcd' else 'a', r)
|
Stack Arithmetic Machine
|
54c1bf903f0696f04600068b
|
[
"Algorithms"
] |
https://www.codewars.com/kata/54c1bf903f0696f04600068b
|
4 kyu
|
In this Kata, you're going to transpile an expression from one langauge into another language.
The source language looks like Kotlin and the target language looks like Dart. And you **don't need to know neither of them** to complete this Kata.
We're going to transpile a `function call` expression.
If you successfully parsed the input, return `Right output`, otherwise give me `Left "Hugh?"`.
~~~if:java
For Java, return the empty string upon failure, else the transpiled string.
~~~
~~~if:csharp
For C#, return the empty string upon failure, else the transpiled string.
~~~
~~~if:c
For C, return the empty string upon failure, else the transpiled string.
~~~
~~~if:cpp
For C++, return the empty string upon failure, else the transpiled string.
~~~
~~~if:python
For Python, return the empty string upon failure, else the transpiled string.
~~~
~~~if:ruby
For Ruby, return the empty string upon failure, else the transpiled string.
~~~
~~~if:rust
For Rust, return `Ok(transpiled string)` on success, or `Err("Hugh?")` on failure.
~~~
We have three kinds of basic expressions:
+ names, like `abc`, `ABC`, `run`, `a1`, beginning with `_`/letters and followed by `_`/letters/numbers
+ numbers, like `123`, `02333`, `66666` (may have leading zeroes)
+ lambda expressions, like `{ a -> a }`, `{ a, b -> a b }`(source), `(a){a;}`, `(a,b){a;b;}`(target)
We have empty characters `blank space` and `\n`.
The definition of `names` is quite similiar to C/Java. Names like this are invalid:
+ `1a`
You don't have to worry about reserved words here.
Lambda expressions consist of two parts:
+ parameters, they're just names/numbers
+ statements, a list of names/numbers, seperated by whitespaces in source language, by `;` in target language.
Invoking a function is to pass some arguments to something callable(names and lambdas), like `plus(1, 2)`, or `repeat(10, { xxx })`.
There's a syntax sugar in Kotlin: if the last argument is a lambda, it can be out of the brackets. Like, `repeat(10, { xxx })` can be written in `repeat(10) { xxx }`. And if that lambda is the only argument, you can even ignore the brackets. Like: `run({ xxx })` is equaled to `run { xxx }`.
You can refer to the examples at the bottom.
## The source language looks like:
```
function ::= expression "(" [parameters] ")" [lambda]
| expression lambda
expression ::= nameOrNumber
| lambda
parameters ::= expression ["," parameters]
lambdaparam ::= nameOrNumber ["," lambdaparam]
lambdastmt ::= nameOrNumber [lambdastmt]
lambda ::= "{" [lambdaparam "->"] [lambdastmt] "}"
```
Notice: there can be whitespaces among everywhere, it's not a part of the language grammar.
## The target language looks like:
```
function ::= expression "(" [parameters] ")"
expression ::= nameOrNumber
| lambda
parameters ::= expression ["," parameters]
lambdaparam ::= nameOrNumber ["," lambdaparam]
lambdastmt ::= nameOrNumber ";" [lambdastmt]
lambda ::= "(" [lambdaparam] "){" [lambdastmt] "}"
```
You shouldn't produce any whitespaces in the target language.
Those examples covered all the language features shown above. Hope you enjoy it :D
`fun()` => `fun()`
`fun(a)` => `fun(a)`
`fun(a, b)` => `fun(a,b)`
`{}()` => `(){}()`
`fun {}` => `fun((){})`
`fun(a, {})` => `fun(a,(){})`
`fun(a) {}` => `fun(a,(){})`
`fun {a -> a}` => `fun((a){a;})`
`{a -> a}(1)` => `(a){a;}(1)`
`fun { a, b -> a b }` => `fun((a,b){a;b;})`
`{a, b -> a b} (1, 2)` => `(a,b){a;b;}(1,2)`
`f { a }` => `f((){a;})`
`f { a -> }` => `f((a){})`\
`{}{}` => `(){}((){})`
~~~if:javascript,haskell,python,ruby,java,rust,csharp
You have to write your own tokenizer (hint: whitespace is significant to separate some tokens, but can be ignored otherwise).
~~~
~~~if:c,cpp
A tokenizer is provided.
~~~
|
reference
|
import re
def name_or_number(expr):
return re . fullmatch(r'[a-zA-Z_][a-zA-Z0-9_]*', expr) != None or re . fullmatch(r'\d+', expr) != None
def transp_lambda(lmbd):
if '->' in lmbd:
ind = lmbd . index('->')
if ind > 0 and all(name_or_number(e) for e in lmbd[: ind: 2]) and all(c == ',' for c in lmbd[1: ind: 2]):
res = '(' + '' . join(lmbd[: ind]) + '){'
lmbd = lmbd[ind + 1:]
else:
raise ValueError
else:
res = '(){'
if all(name_or_number(e) for e in lmbd):
return res + ';' . join(lmbd + ['']) + '}'
else:
raise ValueError
def name_or_number_or_lambda(expr):
return name_or_number(expr) or (expr[- 1] == '}' and len(expr) > 1)
def transpile(expression):
tokens = re . findall(
r'[a-zA-Z_][a-zA-Z0-9_]*|[0-9]+(?![a-zA-Z])|[{}(),]|\-\>', expression)
try:
if not tokens or len('' . join(tokens)) != len(re . sub(r'\s+', '', expression)):
raise ValueError
cur = 0
while cur < len(tokens):
if tokens[cur] == '{':
f_cur = next((k for k, x in enumerate(
tokens[cur + 1:], cur + 1) if x == '}'), None)
if f_cur == None:
raise ValueError
lmbd = transp_lambda(tokens[cur + 1: f_cur])
tokens[cur: f_cur + 1] = [lmbd]
cur += 1
if not name_or_number_or_lambda(tokens[0]):
raise ValueError
if tokens[- 1]. endswith('}'):
if tokens[1: 3] == ['(', ')']:
tokens[- 2:] = [tokens[- 1], ')']
elif tokens[1] == '(':
tokens[- 2:] = [',', tokens[- 1], ')']
else:
tokens[- 1:] = ['(', tokens[- 1], ')']
if (tokens[1] == '(' and tokens[- 1] == ')' and
(len(tokens[2: - 1]) == 0 or len(tokens[2: - 1]) % 2) and
all(name_or_number_or_lambda(e)
for e in tokens[2: - 1: 2]) and all(c == ',' for c in tokens[3: - 1: 2])
):
return '' . join(tokens)
else:
raise ValueError
except:
return ''
|
Expression Transpiler
|
597ccf7613d879c4cb00000f
|
[
"Compilers"
] |
https://www.codewars.com/kata/597ccf7613d879c4cb00000f
|
2 kyu
|
From <a href='https://en.wikipedia.org/wiki/Matryoshka_doll'>Wikipedia</a> : A matryoshka doll (Russian: матрёшка), also known as a Russian nesting doll, or Russian doll, is a set of wooden dolls of decreasing size placed one inside another.
<img src = 'http://www.alkotagifts.com/sites/default/files/styles/gallery_image/public/a03b__61795.jpg?itok=Ax7YjtiI'>
Such dolls are often used for decoration. In this kata, you will be using them to develop your recursion skills.
Your function will receive an instance of class RussianNestingDoll. This russianNestingDoll instance may contain another russianNestingDoll. RussianNestingDolls are callable, such that if a nesting doll contains another nesting doll, calling it [like a function with no parameters, e.g. <code>russianNestingDoll()</code>] will return the smaller nesting doll inside. If it is empty (i.e., it does not contain another doll), it will return <code>None</code>. Your task is to return the size of the smallest doll (russianNestingDolls have a "size" attribute).
*Don't worry about Python's recursion limit.*
*Depending on what you value most in your code, you may prefer an iterative solution.*
Happy coding!
|
reference
|
def smallest_doll_size(doll):
return smallest_doll_size(doll()) if doll() else doll . size
|
Russian nesting dolls
|
598a1fc1676fdd837f000e56
|
[
"Recursion",
"Fundamentals"
] |
https://www.codewars.com/kata/598a1fc1676fdd837f000e56
|
7 kyu
|
Correct this code so that it takes one argument, `x`, and returns "`x` is more than zero" if `x` is positive (and nonzero), and otherwise, returns "`x` is equal to or less than zero." In both cases, replace `x` with the actual value of `x`.
|
bug_fixes
|
def corrections(x):
if x > 0:
return f' { x } is more than zero.'
else:
return f' { x } is equal to or less than zero.'
|
More than Zero?
|
55a710b462afc49a540000b9
|
[
"Debugging"
] |
https://www.codewars.com/kata/55a710b462afc49a540000b9
|
7 kyu
|
<h2>Which Gas Station should I pick?</h2>
<br>
You have to fill up your gas and there are multiple gas stations with different prices and different distance to you. Sometimes it is cheaper to drive to a more distant gas station, because the prices are cheaper!
<br>
<br>
<ul>
<li>Your tank can contain 60l at maximum.</li>
<li>You always fill your tank full</li>
<li>Calculate the current fuel in tank with the actual price of the gas stations</li>
</ul>
<h3> Your task: </h3>
Given an object with multiple gas stations, your currentFuel as integer between 0 and 60 and the fuel consumption of your car (l/100km, float) - <code>find the cheapest gas station and return the name of the gas station!</code>
<br>
<br>
Return <code>undefined (in JS) | None (in Python)</code> if there are no gas station or your fuel is not enough to reach one!
<br>
<br>
No need to test for invalid input! <br>
Remember: You also need fuel to drive to the gas station! The way back home should also be considered :)
<h4> Example </h4>
<pre>
<code>
var obj = {
"gas_station1": {"price": 1.5, "distance": 50},
"gas_station2": {"price": 2.0, "distance": 75}
};
var currentFuel = 35;
var fuelConsumption = 7.5;
costs gas_station1 = 48.75; <- is cheaper
costs gas_station2 = 72.5;
#distance: distance between you and the gasstation in km
#fuelConsumption: how much your car consumes in l/100km
#currentFuel: your current fuel in l
</code>
</pre>
|
reference
|
def gas_station(obj, cfuel, fcons):
obj = {k: v for k, v in obj . items(
) if v['distance'] <= cfuel * 100 / fcons}
return min(obj, key=lambda x: (60 - cfuel + 2 * obj[x]['distance'] * fcons / 100) * obj[x]['price']) if obj else None
|
Which Gas Station should I pick?
|
5877839c0594a6ead600012c
|
[
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/5877839c0594a6ead600012c
|
6 kyu
|
Given an object of likely nested objects, where the final element is an array containing positive integers, write a function that returns the name of the root property that a particular integer lives in.
### E.g
Heres what the object looks like:
```javascript
object = {
"one": {
"nest1": {
"val1": [9, 34, 92, 100]
}
},
"2f7": {
"n1": [10, 92, 53, 71],
"n2": [82, 34, 6, 19]
}
}
getRootProperty(object, 9); //=> "one"
```
`getRootProperty(object, 9)` returns "one" because `"one"` is the root property name where the value `9` is buried in (in an array), other root properties may also have `9` buried in it but you should always return the first
### Another Example
```javascript
object = {
"r1n": {
"mkg": {
"zma": [21, 45, 66, 111],
"mii": {
"ltf": [2, 5, 3, 9, 21]
},
"fv": [1, 3, 6, 9]
},
"rmk": {
"amr": [50, 50, 100, 150, 250]
}
},
"fik": {
"er": [592, 92, 32, 13]
"gp": [12, 34, 116, 29]
}
}
getRootProperty(object, 250); //=> "r1n"
getRootProperty(object, 116); //=> "fik"
getRootProperty(object, 111); //=> "r1n"
getRootProperty(object, 999); //=> null
```
return `null` if the value isn't found.
|
reference
|
def get_root_property(dict_, v):
for key in dict_:
if isinstance(dict_[key], list):
if v in dict_[key]:
return key
elif get_root_property(dict_[key], v):
return key
|
Get root property name
|
598638d7f3a2c489b2000030
|
[
"Data Structures",
"Fundamentals"
] |
https://www.codewars.com/kata/598638d7f3a2c489b2000030
|
6 kyu
|
You will be given a fruit which a farmer has harvested, your job is to see if you should buy or sell.
You will be given 3 pairs of fruit. Your task is to trade your harvested fruit back into your harvested fruit via the intermediate pair, you should return a string of 3 actions.
if you have harvested apples, you would buy this fruit pair: apple_orange, if you have harvested oranges, you would sell that fruit pair.
(In other words, to go from left to right (apples to oranges) you buy, and to go from right to left you sell (oranges to apple))
e.g.
apple_orange, orange_pear, apple_pear
1. if you have harvested apples, you would buy this fruit pair: apple_orange
2. Then you have oranges, so again you would buy this fruit pair: orange_pear
3. After you have pear, but now this time you would sell this fruit pair: apple_pear
4. Finally you are back with the apples
So your function would return a list: [“buy”,”buy”,”sell”]
If any invalid input is given, "ERROR" should be returned
|
algorithms
|
def buy_or_sell(pairs, harvested_fruit):
currentFruit = harvested_fruit
actions = list()
for pair in pairs:
if currentFruit not in pair:
return 'ERROR'
if currentFruit == pair[0]:
actions . append('buy')
currentFruit = pair[1]
else:
actions . append('sell')
currentFruit = pair[0]
return actions
|
Pointless Farmer
|
597ab747d1ba5b843f0000ca
|
[
"Algorithms"
] |
https://www.codewars.com/kata/597ab747d1ba5b843f0000ca
|
7 kyu
|
*Debug* function `getSumOfDigits` that takes positive integer to calculate sum of its digits. Assume that argument is an integer.
### Example
```
123 => 6
223 => 7
1337 => 14
```
|
bug_fixes
|
def get_sum_of_digits(num):
return sum(map(int, str(num)))
|
Debug Sum of Digits of a Number
|
563d59dd8e47a5ed220000ba
|
[
"Debugging",
"Fundamentals"
] |
https://www.codewars.com/kata/563d59dd8e47a5ed220000ba
|
7 kyu
|
Given a string, s, return a new string that orders the characters in order of frequency.
The returned string should have the same number of characters as the original string.
Make your transformation stable, meaning characters that compare equal should stay in their original order in the string s.
```python
most_common("Hello world") => "lllooHe wrd"
most_common("Hello He worldwrd") => "lllHeo He wordwrd"
```
```r
most_common("Hello world") => "lllooHe wrd"
most_common("Hello He worldwrd") => "lllHeo He wordwrd"
```
Explanation:
In the `hello world` example, there are 3 `'l'`characters, 2 `'o'`characters, and one each of `'H'`, `'e'`, `' '`, `'w'`, `'r'`, and `'d'`characters. Since `'He wrd'`are all tied, they occur in the same relative order that they do in the original string, `'Hello world'`.
Note that ties don't just happen in the case of characters occuring once in a string. See the second example, `most_common("Hello He worldwrd")`should return `'lllHeo He wordwrd'`, not `'lllHHeeoo wwrrdd'`. **This is a key behavior if this method were to be used to transform a string on multiple passes.**
|
reference
|
from collections import Counter
def most_common(s):
count = Counter(s)
return '' . join(sorted(s, key=lambda c: - count[c]))
|
Most common first
|
59824f384df1741e05000913
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59824f384df1741e05000913
|
7 kyu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.