id
stringlengths 12
12
| text
stringlengths 52
14k
| token_count
int64 10
5.52k
|
---|---|---|
ZR3TF7I2Q9QP
|
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number
and `n` a positive integer (n > 0).
When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit
`lim` depending on `z`.
Experiment with `S(n, z)` to guess the domain of convergence `D`of `S` and `lim` value when `z` is in `D`.
Then determine the smallest integer `n` such that `abs(S(n, z) - lim) < eps`
where `eps` is a given small real number and `abs(Z)` is the modulus or norm of the complex number Z.
Call `f` the function `f(z, eps)` which returns `n`.
If `z` is such that `S(n, z)` has no finite limit (when `z` is outside of `D`) `f` will return -1.
# Examples:
I is a complex number such as I * I = -1 (sometimes written `i` or `j`).
`f(0.3 + 0.5 * I, 1e-4) returns 17`
`f(30 + 5 * I, 1e-4) returns -1`
# Remark:
For languages that don't have complex numbers or "easy" complex numbers, a complex number `z` is represented by two real numbers `x` (real part) and `y` (imaginary part).
`f(0.3, 0.5, 1e-4) returns 17`
`f(30, 5, 1e-4) returns -1`
# Note:
You pass the tests if `abs(actual - exoected) <= 1`
[
| 420 |
WGDK5TJT0SCH
|
We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions.
Function should take width and height of an image and return a ratio string (ex."16:9").
If any of width or height entry is 0 function should throw an exception (or return `Nothing`).
[
| 81 |
D0TJLSFRU3SE
|
The built-in print function for Python class instances is not very entertaining.
In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "...look at my a, b and c").
Example:
For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class
```
class Vehicle:
def __init__(self, seats, wheels, engine):
self.seats = seats
self.wheels = wheels
self.engine = engine
```
the function call ```show_me(porsche)``` should return the string 'Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels.'
Hints:
For simplicity we assume that the parameter "instname" is always a class instance.
[
| 252 |
SO768N5ONP5D
|
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term.
If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence.
An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] )
Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence.
Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ]
There are some sequences that aren't arithmetic nor are they geometric.
Here is a link to feed your brain : Sequence !
You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set").
The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where:
- ``first`` is the first value in the 0 INDEX.
- ``n`` is the index of the value we want.
- ``c`` is the constant added between the terms.
Remember that `first` is in the index ``0`` .. just saying ...
[
| 336 |
TKRAV1OVZOOR
|
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another.
Example:
```python
unpack([None, [1, ({2, 3}, {'foo': 'bar'})]]) == [None, 1, 2, 3, 'foo', 'bar']
```
Note: you don't have to bother about the order of the elements, especially when unpacking a `dict` or a `set`. Just unpack all the elements.
[
| 141 |
LJ5B9PL8434Q
|
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
[
| 26 |
93JE3TP73Y1M
|
**See Also**
* [Traffic Lights - one car](.)
* [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5)
---
# Overview
A character string represents a city road.
Cars travel on the road obeying the traffic lights..
Legend:
* `.` = Road
* `C` = Car
* `G` = GREEN traffic light
* `O` = ORANGE traffic light
* `R` = RED traffic light
Something like this:
C...R............G......
# Rules
## Simulation
At each iteration:
1. the lights change, according to the traffic light rules... then
2. the car moves, obeying the car rules
## Traffic Light Rules
Traffic lights change colour as follows:
* GREEN for `5` time units... then
* ORANGE for `1` time unit... then
* RED for `5` time units....
* ... and repeat the cycle
## Car Rules
* Cars travel left to right on the road, moving 1 character position per time unit
* Cars can move freely until they come to a traffic light. Then:
* if the light is GREEN they can move forward (temporarily occupying the same cell as the light)
* if the light is ORANGE then they must stop (if they have already entered the intersection they can continue through)
* if the light is RED the car must stop until the light turns GREEN again
# Kata Task
Given the initial state of the road, return the states for all iterations of the simiulation.
## Input
* `road` = the road array
* `n` = how many time units to simulate (n >= 0)
## Output
* An array containing the road states at every iteration (including the initial state)
* Note: If a car occupies the same position as a traffic light then show only the car
## Notes
* There is only one car
* For the initial road state
* the car is always at the first character position
* traffic lights are either GREEN or RED, and are at the beginning of their countdown cycles
* There are no reaction delays - when the lights change the car drivers will react immediately!
* If the car goes off the end of the road it just disappears from view
* There will always be some road between adjacent traffic lights
# Example
Run simulation for 10 time units
**Input**
* `road = "C...R............G......"`
* `n = 10`
**Result**
---
Good luck!
DM
[
| 539 |
WJSI2CILLELN
|
# Task
When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover.
You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles as soon as you have enough leftovers?
# Example
For candlesNumber = 5 and makeNew = 2, the output should be `9`.
Here is what you can do to burn 9 candles:
```
burn 5 candles, obtain 5 leftovers;
create 2 more candles, using 4 leftovers (1 leftover remains);
burn 2 candles, end up with 3 leftovers;
create another candle using 2 leftovers (1 leftover remains);
burn the created candle, which gives another leftover (2 leftovers in total);
create a candle from the remaining leftovers;
burn the last candle.
Thus, you can burn 5 + 2 + 1 + 1 = 9 candles, which is the answer.
```
# Input/Output
- `[input]` integer `candlesNumber`
The number of candles you have in your possession.
Constraints: 1 ≤ candlesNumber ≤ 50.
- `[input]` integer `makeNew`
The number of leftovers that you can use up to create a new candle.
Constraints: 2 ≤ makeNew ≤ 5.
- `[output]` an integer
[
| 301 |
3R3MARXHRXLD
|
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length
`dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
# Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
# Notes:
- You will pass the tests if
`abs(actual - expected) <= 1`
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.

[
| 644 |
2KRK16J7SI9O
|
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it!
[
| 139 |
YT31KQ77HFMI
|
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion).
When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it!
Your task is to implement class ```Fraction``` that takes care of simple fraction arithmetics. Requirements:
* class must have two-parameter constructor `Fraction(numerator, denominator)`; passed values will be non-zero integers, and may be positive or negative.
* two conversion methods must be supported:
* `toDecimal()` returns decimal representation of fraction
* `toString()` returns string with fractional representation of stored value in format:
[ SIGN ] [ WHOLES ] [ NUMERATOR / DENOMINATOR ]
* **Note**: each part is returned only if it is available and non-zero, with the only possible space character going between WHOLES and fraction. Examples: '-1/2', '3', '-5 3/4'
* The fractional part must always be normalized (ie. the numerator and denominators must not have any common divisors).
* Four operations need to be implemented: `add`, `subtract`, `multiply` and `divide`. Each of them may take integers as well as another `Fraction` instance as an argument, and must return a new `Fraction` instance.
* Instances must be immutable, hence none of the operations may modify either of the objects it is called upon, nor the passed argument.
#### Python Notes
* If one integer is passed into the initialiser, then the fraction should be assumed to represent an integer not a fraction.
* You must implement the standard operator overrides `__add__`, `__sub__`, `__mul__`, `__div__`, in each case you should support `other` being an `int` or another instance of `Fraction`.
* Implement `__str__` and `to_decimal` in place of `toString` and `toDecimal` as described above.
[
| 422 |
5DU427MV5U5A
|
#Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always be greater than 0.
The shifting value is always a value from 0 up to the size of the arrays.
There are always arrays in the array, so you do not need to check for null or empty.
#1. Example:
```
[[1,2,3,4,5,6], [7,7,7,7,7,-7]], 0
1,2,3,4,5,6
7,7,7,7,7,-7
--> [8,9,10,11,12,-1]
```
#2. Example
```
[[1,2,3,4,5,6], [7,7,7,7,7,7]], 3
1,2,3,4,5,6
7,7,7,7,7,7
--> [1,2,3,11,12,13,7,7,7]
```
#3. Example
```
[[1,2,3,4,5,6], [7,7,7,-7,7,7], [1,1,1,1,1,1]], 3
1,2,3,4,5,6
7,7,7,-7,7,7
1,1,1,1,1,1
--> [1,2,3,11,12,13,-6,8,8,1,1,1]
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
[
| 432 |
47MI7HNSAB73
|
# Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output should be "</button>";
For startTag = "<i>", the output should be "</i>".
# Input/Output
- `[input]` string `startTag`/`start_tag`
- `[output]` a string
[
| 115 |
K3I5IM4SM8SW
|
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word identical to the prior word except for one letter. They just keep on going until their memories fail out.
# Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from a list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
# The Rules
* a valid response word must contain four different letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in their memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if 1st player fails 1st turn, 2nd can win with a valid word
* when both players fail the initial word, there is no winner
# Your Task
To determine the winner!
# Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more`
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
4) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
# Input
``` c
size_t n // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
``` python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (10 <= n <= 2000)
word # string of the initial challenge word
first # integer of whom begins: 0 for Alice, 1 for Bob
```
``` javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (10 <= n <= 2000)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
# Output
``` c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
``` python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
``` javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
# Enjoy!
If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cab471da732b30018968071) to consider solving.
[
| 1,085 |
Q4PTQ1E77LFW
|
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta`
[
| 50 |
FN4LU9UFUM9K
|
Help Suzuki rake his garden!
The monastery has a magnificent Zen garden made of white gravel and rocks and it is raked diligently everyday by the monks. Suzuki having a keen eye is always on the lookout for anything creeping into the garden that must be removed during the daily raking such as insects or moss.
You will be given a string representing the garden such as:
```
garden = 'gravel gravel gravel gravel gravel gravel gravel gravel gravel rock slug ant gravel gravel snail rock gravel gravel gravel gravel gravel gravel gravel slug gravel ant gravel gravel gravel gravel rock slug gravel gravel gravel gravel gravel snail gravel gravel rock gravel snail slug gravel gravel spider gravel gravel gravel gravel gravel gravel gravel gravel moss gravel gravel gravel snail gravel gravel gravel ant gravel gravel moss gravel gravel gravel gravel snail gravel gravel gravel gravel slug gravel rock gravel gravel rock gravel gravel gravel gravel snail gravel gravel rock gravel gravel gravel gravel gravel spider gravel rock gravel gravel'
```
Rake out any items that are not a rock or gravel and replace them with gravel such that:
```
garden = 'slug spider rock gravel gravel gravel gravel gravel gravel gravel'
```
Returns a string with all items except a rock or gravel replaced with gravel:
```
garden = 'gravel gravel rock gravel gravel gravel gravel gravel gravel gravel'
```
Please also try the other Kata in this series..
* [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b)
* [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c)
* [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255)
* [Suzuki needs help lining up his students!](https://www.codewars.com/kata/5701800886306a876a001031)
* [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
[
| 453 |
DERHID4ZNG8D
|
Write a function generator that will generate the first `n` primes grouped in tuples of size `m`. If there are not enough primes for the last tuple it will have the remaining values as `None`.
## Examples
```python
For n = 11 and m = 2:
(2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, None)
For n = 11 and m = 3:
(2, 3, 5), (7, 11, 13), (17, 19, 23), (29, 31, None)
For n = 11 and m = 5:
(2, 3, 5, 7, 11), (13, 17, 19, 23, 29), (31, None, None, None, None)]
For n = 3 and m = 1:
(2,), (3,), (5,)
```
Note: large numbers of `n` will be tested, up to 50000
[
| 231 |
JE99DW92VZOP
|
Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return `true` if the string is valid, and `false` if it's invalid.
This Kata is similar to the [Valid Parentheses](https://www.codewars.com/kata/valid-parentheses) Kata, but introduces new characters: brackets `[]`, and curly braces `{}`. Thanks to `@arnedag` for the idea!
All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: `()[]{}`.
### What is considered Valid?
A string of braces is considered valid if all braces are matched with the correct brace.
## Examples
```
"(){}[]" => True
"([{}])" => True
"(}" => False
"[(])" => False
"[({})](]" => False
```
[
| 197 |
WF9K4F4SFK9R
|
You have been tasked with converting a number from base i (sqrt of -1) to base 10.
Recall how bases are defined:
abcdef = a * 10^5 + b * 10^4 + c * 10^3 + d * 10^2 + e * 10^1 + f * 10^0
Base i follows then like this:
... i^4 + i^3 + i^2 + i^1 + i^0
The only numbers in any place will be 1 or 0
Examples:
101 in base i would be:
1 * i^2 + 0 * i^1 + 1*i^0 = -1 + 0 + 1 = 0
10010 in base i would be:
1*i^4 + 0 * i^3 + 0 * i^2 + 1 * i^1 + 0 * i^0 = 1 + -i = 1-i
You must take some number, n, in base i and convert it into a number in base 10, in the format of a 2x1 vector.
[a,b] = a+b*i
The number will always be some combination of 0 and 1
In Python you will be given an integer.
In Javascript and C++ you will be given a string
[
| 299 |
54DDGIJDIQV7
|
You are given an n by n ( square ) grid of characters, for example:
```python
[['m', 'y', 'e'],
['x', 'a', 'm'],
['p', 'l', 'e']]
```
You are also given a list of integers as input, for example:
```python
[1, 3, 5, 8]
```
You have to find the characters in these indexes of the grid if you think of the indexes as:
```python
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
```
Remember that the indexes start from one and not zero.
Then you output a string like this:
```python
"meal"
```
All inputs will be valid.
[
| 170 |
F55TCFMAMJQ1
|
Given a certain array of integers, create a function that may give the minimum number that may be divisible for all the numbers of the array.
```python
min_special_mult([2, 3 ,4 ,5, 6, 7]) == 420
```
The array may have integers that occurs more than once:
```python
min_special_mult([18, 22, 4, 3, 21, 6, 3]) == 2772
```
The array should have all its elements integer values. If the function finds an invalid entry (or invalid entries) like strings of the alphabet or symbols will not do the calculation and will compute and register them, outputting a message in singular or plural, depending on the number of invalid entries.
```python
min_special_mult([16, 15, 23, 'a', '&', '12']) == "There are 2 invalid entries: ['a', '&']"
min_special_mult([16, 15, 23, 'a', '&', '12', 'a']) == "There are 3 invalid entries: ['a', '&', 'a']"
min_special_mult([16, 15, 23, 'a', '12']) == "There is 1 invalid entry: a"
```
If the string is a valid number, the function will convert it as an integer.
```python
min_special_mult([16, 15, 23, '12']) == 5520
min_special_mult([16, 15, 23, '012']) == 5520
```
All the `None`/`nil` elements of the array will be ignored:
```python
min_special_mult([18, 22, 4, , None, 3, 21, 6, 3]) == 2772
```
If the array has a negative number, the function will convert to a positive one.
```python
min_special_mult([18, 22, 4, , None, 3, -21, 6, 3]) == 2772
min_special_mult([16, 15, 23, '-012']) == 5520
```
Enjoy it
[
| 462 |
0TUF1S5WF9Y2
|
In this kata, we're going to create the function `nato` that takes a `word` and returns a string that spells the word using the [NATO phonetic alphabet](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet).
There should be a space between each word in the returned string, and the first letter of each word should be capitalized.
For those of you that don't want your fingers to bleed, this kata already has a dictionary typed out for you.
``` python
nato("Banana") # == "Bravo Alpha November Alpha November Alpha"
```
``` ruby
nato("Banana") # == "Bravo Alpha November Alpha November Alpha"
```
[
| 144 |
2QF17K9GI7C6
|
Linked lists are data structures composed of nested or chained objects, each containing a single value and a reference to the next object.
Here's an example of a list:
```python
class LinkedList:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
LinkedList(1, LinkedList(2, LinkedList(3)))
```
Write a function listToArray (or list\_to\_array in Python) that converts a list to an array, like this:
```
[1, 2, 3]
```
Assume all inputs are valid lists with at least one value. For the purpose of simplicity, all values will be either numbers, strings, or Booleans.
[
| 152 |
H1Y0I7LDY3XV
|
You have two arguments: ```string``` - a string of random letters(only lowercase) and ```array``` - an array of strings(feelings). Your task is to return how many specific feelings are in the ```array```.
For example:
```
string -> 'yliausoenvjw'
array -> ['anger', 'awe', 'joy', 'love', 'grief']
output -> '3 feelings.' // 'awe', 'joy', 'love'
string -> 'griefgriefgrief'
array -> ['anger', 'awe', 'joy', 'love', 'grief']
output -> '1 feeling.' // 'grief'
string -> 'abcdkasdfvkadf'
array -> ['desire', 'joy', 'shame', 'longing', 'fear']
output -> '0 feelings.'
```
If the feeling can be formed once - plus one to the answer.
If the feeling can be formed several times from different letters - plus one to the answer.
Eeach letter in ```string``` participates in the formation of all feelings. 'angerw' -> 2 feelings: 'anger' and 'awe'.
[
| 239 |
0GZ03PABYEUQ
|
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 ```"é"```.
[
| 384 |
GNQ5I9WGT6FM
|
## Preface
A collatz sequence, starting with a positive integern, is found by repeatedly applying the following function to n until n == 1 :
`$f(n) =
\begin{cases}
n/2, \text{ if $n$ is even} \\
3n+1, \text{ if $n$ is odd}
\end{cases}$`
----
A more detailed description of the collatz conjecture may be found [on Wikipedia](http://en.wikipedia.org/wiki/Collatz_conjecture).
## The Problem
Create a function `collatz` that returns a collatz sequence string starting with the positive integer argument passed into the function, in the following form:
"X0->X1->...->XN"
Where Xi is each iteration of the sequence and N is the length of the sequence.
## Sample Input
```python
collatz(4) # should return "4->2->1"
collatz(3) # should return "3->10->5->16->8->4->2->1"
```
Don't worry about invalid input. Arguments passed into the function are guaranteed to be valid integers >= 1.
[
| 249 |
P3Y42M0B746E
|
Given any number of boolean flags function should return true if and only if one of them is true while others are false. If function is called without arguments it should return false.
```python
only_one() == False
only_one(True, False, False) == True
only_one(True, False, False, True) == False
only_one(False, False, False, False) == False
```
[
| 87 |
HSP8R4NK6B5H
|
Given an array `A` and an integer `x`, map each element in the array to `F(A[i],x)` then return the xor sum of the resulting array.
where F(n,x) is defined as follows:
F(n, x) = ^(x)Cx **+** ^(x+1)Cx **+** ^(x+2)Cx **+** ... **+** ^(n)Cx
and ^(n)Cx represents [Combination](https://en.m.wikipedia.org/wiki/Combination) in mathematics
### Example
```python
a = [7, 4, 11, 6, 5]
x = 3
# after mapping, `a` becomes [F(7,3), F(4,3), F(11,3), F(6,3), F(5,3)]
return F(7,3) ^ F(4,3) ^ F(11,3) ^ F(6,3) ^ F(5,3)
#=> 384
```
##### e.g
F(7, 3) = ^(3)C3 + ^(4)C3 + ^(5)C3 + ^(6)C3 + ^(7)C3
## Constraints
**1 <= x <= 10**
**x <= A[i] <= 10^(4)**
**5 <= |A| <= 10^(3)**
[
| 299 |
5XDN37KDC9NT
|
A startup office has an ongoing problem with its bin. Due to low budgets, they don't hire cleaners. As a result, the staff are left to voluntarily empty the bin. It has emerged that a voluntary system is not working and the bin is often overflowing. One staff member has suggested creating a rota system based upon the staff seating plan.
Create a function `binRota` that accepts a 2D array of names. The function will return a single array containing staff names in the order that they should empty the bin.
Adding to the problem, the office has some temporary staff. This means that the seating plan changes every month. Both staff members' names and the number of rows of seats may change. Ensure that the function `binRota` works when tested with these changes.
**Notes:**
- All the rows will always be the same length as each other.
- There will be no empty spaces in the seating plan.
- There will be no empty arrays.
- Each row will be at least one seat long.
An example seating plan is as follows:

Or as an array:
```
[ ["Stefan", "Raj", "Marie"],
["Alexa", "Amy", "Edward"],
["Liz", "Claire", "Juan"],
["Dee", "Luke", "Katie"] ]
```
The rota should start with Stefan and end with Dee, taking the left-right zigzag path as illustrated by the red line:
As an output you would expect in this case:
```
["Stefan", "Raj", "Marie", "Edward", "Amy", "Alexa", "Liz", "Claire", "Juan", "Katie", "Luke", "Dee"])
```
[
| 386 |
NARRDIOVWMWO
|
## Decode the diagonal.
Given a grid of characters. Output a decoded message as a string.
Input
```
H Z R R Q
D I F C A E A !
G H T E L A E
L M N H P R F
X Z R P E
```
Output
`HITHERE!` (diagonally down right `↘` and diagonally up right `↗` if you can't go further).
The message ends when there is no space at the right up or down diagonal.
To make things even clearer: the same example, but in a simplified view
```
H _ _ _ _
_ I _ _ _ _ _ !
_ _ T _ _ _ E
_ _ _ H _ R _
_ _ _ _ E
```
[
| 177 |
60D6I8K0T9U2
|
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once.
Find all the combinations of n elements of the array that their sum are 0.
```python
arr = [1, -1, 2, 3, -2]
n = 3
find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0
```
The function should ouput every combination or group in increasing order.
We may have more than one group:
```python
arr = [1, -1, 2, 3, -2, 4, 5, -3 ]
n = 3
find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]]
```
In the case above the function should output a sorted 2D array.
The function will not give a group twice, or more, only once.
```python
arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ]
n = 3
find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]]
```
If there are no combinations with sum equals to 0, the function will output an alerting message.
```python
arr = [1, 1, 2, 3]
n = 2
find_zero_sum_groups(arr, n) == "No combinations"
```
If the function receives an empty array will output an specific alert:
```python
arr = []
n = 2
find_zero_sum_groups(arr, n) == "No elements to combine"
```
As you have seen the solutions may have a value occurring only once.
Enjoy it!
[
| 463 |
C61DCRLTWU1H
|
# Task
Given a rectangular matrix containing only digits, calculate the number of different `2 × 2` squares in it.
# Example
For
```
matrix = [[1, 2, 1],
[2, 2, 2],
[2, 2, 2],
[1, 2, 3],
[2, 2, 1]]
```
the output should be `6`.
Here are all 6 different 2 × 2 squares:
```
1 2
2 2
2 1
2 2
2 2
2 2
2 2
1 2
2 2
2 3
2 3
2 1
```
# Input/Output
- `[input]` 2D integer array `matrix`
Constraints:
`1 ≤ matrix.length ≤ 100,`
`1 ≤ matrix[i].length ≤ 100,`
`0 ≤ matrix[i][j] ≤ 9.`
- `[output]` an integer
The number of different `2 × 2` squares in matrix.
[
| 256 |
XMMHYAUKQR0N
|
# Toggling Grid
You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid.
Solved:
```
[ [1, 1, 1],
[1, 1, 1],
[1, 1, 1] ]
```
"0" (first row) toggle:
```
[ [0, 0, 0],
[1, 1, 1],
[1, 1, 1] ]
```
then "3" (first column) toggle:
```
[ [1, 0, 0],
[0, 1, 1],
[0, 1, 1] ]
```
The numbers in quotes are codes for the row/column, and will be explained.
## Your task: findSolution()
Your task is to write a function, `findSolution()` (or `find_solution()`), which takes as input a 2d array, and returns an array of "steps" that represent a sequence of toggles to solve the puzzle.
For example:
```python
solution = find_solution(puzzle)
print(solution);
> [0, 3]
```
Note that, in the above example, `[1, 2, 4, 5]` is also a valid solution! Any solution will pass the tests.
The solution is tested like this, for each number in the solution:
```python
if n < puzzle.size:
toggleRow(n)
else:
toggleCol(n - puzzle.size)
```
To elaborate, possible n's for a 3x3 puzzle:
- Row numbers = (0 --> size - 1)
- Cols numbers = (size --> size * 2 - 1)
### Example of "2" toggle:
### Example of "4" toggle:
## More examples:
```python
puzzle = [
[ 0, 1, 0 ],
[ 1, 0, 1 ],
[ 1, 0, 1 ]
];
solution = find_solution(puzzle)
print(solution);
> [0, 4]
```
let's try some bigger puzzles:
```python
puzzle = [
[ 1, 0, 1, 0, 0 ],
[ 0, 1, 0, 1, 1 ],
[ 0, 1, 0, 1, 1 ],
[ 0, 1, 0, 1, 1 ],
[ 1, 0, 1, 0, 0 ]
];
solution = find_solution(puzzle)
print(solution);
> [ 0, 5, 4, 7 ]
```
```python
puzzle = [
[ 1, 1, 1, 0, 1, 1, 1 ],
[ 1, 1, 1, 0, 1, 1, 1 ],
[ 1, 1, 1, 0, 1, 1, 1 ],
[ 0, 0, 0, 1, 0, 0, 0 ],
[ 1, 1, 1, 0, 1, 1, 1 ],
[ 1, 1, 1, 0, 1, 1, 1 ],
[ 1, 1, 1, 0, 1, 1, 1 ]
];
solution = find_solution(puzzle)
print(solution);
> [ 3, 10 ]
```
There are randomized tests with puzzles of up to 100x100 in size. Have fun!
[
| 807 |
D024NWAG5UHQ
|
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python).
A few examples:
```
randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt"
randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs"
```
Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
[
| 143 |
7X7G1Q7Y3EEZ
|
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order.
Example Input:
`['b', 'ba', 'ab', 'bb', 'c']`
Expected Output:
`['ab', 'b', 'ba', 'bb', 'c']`
* The argument for your function will be a generator that will return a new word for each call of next()
* Your function will return its own generator of the same words, except your generator will return the words in lexographic order
* All words in the list are unique
* All words will be comprised of lower case letters only (a-z)
* All words will be between 1 and 8 characters long
* There will be hundreds of thousands of words to sort
* You may not use Python's sorted built-in function
* You may not use Python's list.sort method
* An empty list of words should result in an empty list.
* `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
[
| 216 |
I3G9C0IOFU45
|
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️
🗺️ You would be given a map of the world in a type of string:
string s = "01000000X000X011X0X"
'0' : uninfected
'1' : infected
'X' : ocean
⚫ The virus can't spread in the other side of the ocean.
⚫ If one person is infected every person in this continent gets infected too.
⚫ Your task is to find the percentage of human population that got infected in the end.
☑️ Return the percentage % of the total population that got infected.
❗❗ The first and the last continent are not connected!
💡 Example:
start: map1 = "01000000X000X011X0X"
end: map1 = "11111111X000X111X0X"
total = 15
infected = 11
percentage = 100*11/15 = 73.33333333333333
➕ For maps without oceans "X" the whole world is connected.
➕ For maps without "0" and "1" return 0 as there is no population.
[
| 290 |
SF62NOMRPDDS
|
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure)
(the dedicated builtin(s) functionalities are deactivated)
[
| 35 |
88VFZE4UPIH0
|
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is.
You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds.
*The Martingale strategy*
You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet.
## Example
```
martingale(1000, [1, 1, 0, 0, 1]) === 1300
```
Explanation:
* you win your 1st round: gain $100, balance = 1100
* you win the 2nd round: gain $100, balance = 1200
* you lose the 3rd round: lose $100 dollars, balance = 1100
* double stake for 4th round and lose: staked $200, lose $200, balance = 900
* double stake for 5th round and win: staked $400, won $400, balance = 1300
**Note: Your balance is allowed to go below 0.**
[
| 321 |
7ADC55K4PZY7
|
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive.
For example:
```python
count_char("fizzbuzz","z") => 4
count_char("Fancy fifth fly aloof","f") => 5
```
The character can be any alphanumeric character.
Good luck.
[
| 93 |
TQDA4ZORHBP0
|
# Background
I drink too much coffee. Eventually it will probably kill me.
*Or will it..?*
Anyway, there's no way to know.
*Or is there...?*
# The Discovery of the Formula
I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers!
For
* ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD)
* ```CAFE``` is a cup of *regular* coffee
* ```DECAF``` is a cup of *decaffeinated* coffee
To determine the life-time coffee limits:
* Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD`
* If the test subject can survive drinking five thousand cups wihout being ```DEAD``` then coffee has no ill effect on them
# Kata Task
Given the test subject's date of birth, return an array describing their life-time coffee limits
```[ regular limit , decaffeinated limit ]```
## Notes
* The limits are ```0``` if the subject is unaffected as described above
* At least 1 cup must be consumed (Just thinking about coffee cannot kill you!)
# Examples
* John was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well.
* Susan (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan.
* Elizabeth (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk?
* Peter (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!!
Hint: https://en.wikipedia.org/wiki/Hexadecimal
*Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.*
[
| 499 |
88E3XPOC6YR2
|
# Story
Old MacDingle had a farm...
...and on that farm he had
* horses
* chickens
* rabbits
* some apple trees
* a vegetable patch
Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open**
Depending which gate was left open then...
* horses might run away
* horses might eat the apples
* horses might eat the vegetables
* chickens might run away
* rabbits might run away
* rabbits might eat the vegetables
# Kata Task
Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to.
# Legend
* ```H``` horse
* ```C``` chicken
* ```R``` rabbit
* ```A``` apple tree
* ```V``` vegetables
* ```|``` gate (closed),
* ```\``` or ```/``` gate (open)
* ```.``` everything else
# Example
Before
```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC```
After
```|..HH....\....\CC..|AAA/.../RRRR|...```
Because:
The horses ate whatever apples they could get to
The rabbits ate the vegetables
The chickens ran away
# Notes
* If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry!
* An animal cannot "go around" a closed gate...
* ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
[
| 356 |
F3UR8ST3RNH3
|
Suzuki needs help lining up his students!
Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn.
You will be given a string of student names. Sort them and return a list of names in descending order.
Here is an example input:
```python
string = 'Tadashi Takahiro Takao Takashi Takayuki Takehiko Takeo Takeshi Takeshi'
```
Here is an example return from your function:
```python
lst = ['Takehiko',
'Takayuki',
'Takahiro',
'Takeshi',
'Takeshi',
'Takashi',
'Tadashi',
'Takeo',
'Takao']
```
Names of equal length will be returned in reverse alphabetical order (Z->A) such that:
```python
string = "xxa xxb xxc xxd xa xb xc xd"
```
Returns
```python
['xxd', 'xxc', 'xxb', 'xxa', 'xd', 'xc', 'xb', 'xa']
```
Please also try the other Kata in this series..
* [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b)
* [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c)
* [Help Suzuki pack his coal basket!](https://www.codewars.com/kata/57f09d0bcedb892791000255)
* [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d)
* [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
[
| 447 |
FJCIJ115N7O9
|
You are given a list of directions in the form of a list:
goal = ["N", "S", "E", "W"]
Pretend that each direction counts for 1 step in that particular direction.
Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W.
If you get back to beginning, return an empty array.
[
| 97 |
2UCSIYUUNQ31
|
Your task is to return how many times a string contains a given character.
The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count.
For example, if you get an input string "Hello world" and the character to find is "o", return 2.
[
| 73 |
PXZCZ40AXWQT
|
Create a class Vector that has simple (3D) vector operators.
In your class, you should support the following operations, given Vector ```a``` and Vector ```b```:
```python
a + b # returns a new Vector that is the resultant of adding them
a - b # same, but with subtraction
a == b # returns true if they have the same magnitude and direction
a.cross(b) # returns a new Vector that is the cross product of a and b
a.dot(b) # returns a number that is the dot product of a and b
a.to_tuple() # returns a tuple representation of the vector.
str(a) # returns a string representation of the vector in the form ""
a.magnitude # returns a number that is the magnitude (geometric length) of vector a.
a.x # gets x component
a.y # gets y component
a.z # gets z component
Vector([a,b,c]) # creates a new Vector from the supplied 3D array.
Vector(a,b,c) # same as above
```
The test cases will not mutate the produced Vector objects, so don't worry about that.
[
| 235 |
DLA8IGERRLJW
|
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'])
{}
```
[
| 234 |
V2718G8R53QG
|
# Task
A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the numbers don't appear to him in any particular order.
At some point during the walk the boy encounters a house with number `0` written on it, which surprises him so much that he stops adding numbers to his total right after seeing that house.
For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there will always be at least one 0 house on the path.
# Example
For `inputArray = [5, 1, 2, 3, 0, 1, 5, 0, 2]`, the output should be `11`.
The answer was obtained as `5 + 1 + 2 + 3 = 11`.
# Input/Output
- `[input]` integer array `inputArray`
Constraints: `5 ≤ inputArray.length ≤ 50, 0 ≤ inputArray[i] ≤ 10.`
- `[output]` an integer
[
| 266 |
9OM8MOT6YUXA
|
Create a function ```sel_number()```, that will select numbers that fulfill the following constraints:
1) The numbers should have 2 digits at least.
2) They should have their respective digits in increasing order from left to right.
Examples: 789, 479, 12678, have these feature. But 617, 89927 are not of this type.
In general, if ```d1, d2, d3....``` are the digits of a certain number ```i```
Example:
```( i = d1d2d3d4d5) so, d1 < d2 < d3 < d4 < d5```
3) They cannot have digits that occurs twice or more. Example: 8991 should be discarded.
4) The difference between neighbouring pairs of digits cannot exceed certain value.
Example: If the difference between contiguous digits cannot excced 2, so 1345, 23568 and 234578 pass this test. Other numbers like 1456, 389, 157 don't belong to that group because in the first number(1456), the difference between second and first digit 4 - 1 > 2; in the next one(389), we have 8 - 3 > 2; and see by yourself why 157 should be discarded.
In general, taking the example above of ```i = d1d2d3d4d5```:
```
d2 - d1 <= d;
d3 - d2 <= d;
d4 - d3 <= d;
d5 - d4 <= d;
```
The function should accept two arguments n and d; n is the upper limit of the range to work with(all the numbers should be less or equal than n), and d is maximum difference between every pair of its contiguous digits. It's clear that 1 <= d <= 8.
Here we have some cases:
```
sel_number(0,1) = 0 # n = 0, empty range
sel_number(3, 1) = 0 # n = 3, numbers should be higher or equal than 12
sel_number(13, 1) = 1 # only 12 fulfill the requirements
sel_number(20, 2) = 2 # 12 and 13 are the numbers
sel_number(30, 2) = 4 # 12, 13, 23 and 24 are the selected ones
sel_number(44, 2) = 6 # 12, 13, 23, 24, 34 and 35 are valid ones
sel_number(50, 3) = 12 # 12, 13, 14, 23, 24, 25, 34, 35, 36, 45, 46 and 47 are valid
```
Compare the last example with this one:
```
sel_number(47, 3) = 12 # 12, 13, 14, 23, 24, 25, 34, 35, 36, 45, 46 and 47 are valid
```
(because the instructions says the value of may be included if it fulfills the above constraints of course)
Happy coding!!
[
| 688 |
1O7AHZPKAJ3V
|
Write the function `resistor_parallel` that receive an undefined number of resistances parallel resistors and return the total resistance.
You can assume that there will be no 0 as parameter.
Also there will be at least 2 arguments.
Formula:
`total = 1 / (1/r1 + 1/r2 + .. + 1/rn)`
Examples:
`resistor_parallel(20, 20)` will return `10.0`
`resistor_parallel(20, 20, 40)` will return `8.0`
[
| 118 |
9Q2ACAGA8REP
|
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.
We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...
Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?
The function `crusoe` has parameters;
- n : numbers of steps in the process
- d : initial chosen distance
- ang : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult : constant multiplier of the previous angle
`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.
### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->
The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)
The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)
and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
### A drawing:

Successive points:
- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`
### Note
Please could you ask before translating: some translations are already written and published when/if the kata is approved.
[
| 555 |
G7MWV9NKIGRR
|
### Task
Your main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.
### Euclid's GCD
```CSharp
BigInteger FindGCD(BigInteger a, BigInteger b) {
// Swaping `a` and `b`
if (a < b) {
a += b;
b = a - b;
a = a - b;
}
while (b > 0) {
// Iteration of calculation
BigInteger c = a % b;
a = b;
b = c;
}
// `a` - is greates common divisor now
return a;
}
```
### Restrictions
Your program should work with numbers
`0 < divisor < 1000`
`0 <= iterations <= 50'000`
[
| 194 |
QHHBTNRUMGSI
|
Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32
bit number: 2149583361.
Write a function ip_to_int32(ip) ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns
a 32 bit number.
```python
ip_to_int32("128.32.10.1") => 2149583361
```
[
| 226 |
XF6F66R61ISN
|
**The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, you should be able to access its value on the returned object by using a key `idNum` or even simply `id`. `Num` and `Number` shouldn't work because we are only looking for matches at the beginning of a key.
Be aware that you _could_ simply add all these partial keys one by one to the object. However, for the sake of avoiding clutter, we don't want to have a JSON with a bunch of nonsensical keys. Thus, in the random tests there will be a test to check that you did not add or remove any keys from the object passed in or the object returned.
Also, if a key is tested that appears as the beginning of more than one key in the original object (e.g. if the original object had a key `idNumber` and `idString` and we wanted to test the key `id`) then return the value corresponding with whichever key comes first **alphabetically**. (In this case it would be `idNumber`s value because it comes first alphabetically.)
**Example**
```python
o = partial_keys({"abcd": 1})
o['abcd'] == 1 # true
o['abc'] == 1 # true
o['ab'] == 1 # true
o['a'] == 1 # true
o['b'] == 1 # false!
o['b'] == None # true
list(o.keys()) # ['abcd']
```
[
| 365 |
39SKJWCUPECI
|
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended but either player still hits the ball
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
[
| 407 |
82WF1R8R29DZ
|
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only lowercase letters.
## Examples
```python
add_word("bad")
add_word("dad")
add_word("mad")
search("pad") == False
search("bad") == True
search(".ad") == True
search("b..") == True
```
**Note:** the data structure will be initialized multiple times during the tests!
[
| 141 |
A8KAF8QZCARI
|
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be `21 * 19 * 1 * 3 * 15` = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
Write a program which reads in the name of the comet and the name of the group and figures out whether according to the above scheme the names are a match, printing "GO" if they match and "STAY" if not. The names of the groups and the comets will be a string of capital letters with no spaces or punctuation, up to 6 characters long.
Example:
Converting the letters to numbers:
```
C O M E T Q
3 15 13 5 20 17
H V N G A T
8 22 14 7 1 20
```
then calculate the product mod 47:
```
3 * 15 * 13 * 5 * 20 * 17 = 994500 mod 47 = 27
8 * 22 * 14 * 7 * 1 * 20 = 344960 mod 47 = 27
```
Because both products evaluate to 27 (when modded by 47), the mission is 'GO'.
[
| 535 |
WOIGZV9599FE
|
Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. Each letter, or base, gets transcribed.
```T -> A
A -> U
G -> C
C -> G```
Also, you will split it into groups of three, or _codons_.
The above example would become:
`"AUG UCG AGC GAU ACU UAG"`
---
**Step 2: Translation**
After you have the mRNA strand, you will turn it into an amino acid chain.
Each codon corresponds to an amino acid:
```
Ala GCU, GCC, GCA, GCG
Leu UUA, UUG, CUU, CUC, CUA, CUG
Arg CGU, CGC, CGA, CGG, AGA, AGG
Lys AAA, AAG
Asn AAU, AAC
Met AUG
Asp GAU, GAC
Phe UUU, UUC
Cys UGU, UGC
Pro CCU, CCC, CCA, CCG
Gln CAA, CAG
Ser UCU, UCC, UCA, UCG, AGU, AGC
Glu GAA, GAG
Thr ACU, ACC, ACA, ACG
Gly GGU, GGC, GGA, GGG
Trp UGG
His CAU, CAC
Tyr UAU, UAC
Ile AUU, AUC, AUA
Val GUU, GUC, GUA, GUG
Stop UAG, UGA, UAA```
Phew, that's a long list!
The above example would become:
`"Met Ser Ser Thr Asp Stop"`
Any additional sets of bases that aren't in a group of three aren't included. For example:
`"AUG C"`
would become
`"Met"`
---
Anyway, your final output will be the mRNA sequence and the polypeptide.
Here are some examples:
*In:*
`"TACAGCTCGCTATGAATC"`
*Out:*
`["AUG UCG AGC GAU ACU UAG","Met Ser Ser Asp Thr Stop"]`
---
*In:*
`"ACGTG"`
*Out:*
`["UGC AC","Cys"]`
[
| 571 |
GSVYSSSERSD8
|
Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark.
[
| 70 |
MGMZC3DBBPV5
|
Complete the solution so that it returns a formatted string. The return value should equal "Value is VALUE" where value is a 5 digit padded number.
Example:
```python
solution(5) # should return "Value is 00005"
```
[
| 55 |
OHAN9WG1WZT2
|
There are a **n** balls numbered from 0 to **n-1** (0,1,2,3,etc). Most of them have the same weight, but one is heavier. Your task is to find it.
Your function will receive two arguments - a `scales` object, and a ball count. The `scales` object has only one method:
```python
get_weight(left, right)
```
where `left` and `right` are arrays of numbers of balls to put on left and right pan respectively.
If the method returns `-1` - left pan is heavier
If the method returns `1` - right pan is heavier
If the method returns `0` - both pans weigh the same
So what makes this the "ubermaster" version of this kata? First, it's not restricted to 8 balls as in the previous versions - your solution has to work for 8-500 balls.
Second, you can't use the scale any more than mathematically necessary. Here's a chart:
ball count | uses
-----------------
0-9 | 2
10-27 | 3
28-81 | 4
82-243 | 5
244-500 | 6
Too hard? Try lower levels by [tiriana](http://www.codewars.com/users/tiriana):
* [novice](http://www.codewars.com/kata/544047f0cf362503e000036e)
* [conqueror](http://www.codewars.com/kata/54404a06cf36258b08000364)
* [master](http://www.codewars.com/kata/find-heavy-ball-level-master)
[
| 376 |
XPKK39FA6B6P
|
[Harshad numbers](http://en.wikipedia.org/wiki/Harshad_number) (also called Niven numbers) are positive numbers that can be divided (without remainder) by the sum of their digits.
For example, the following numbers are Harshad numbers:
* 10, because 1 + 0 = 1 and 10 is divisible by 1
* 27, because 2 + 7 = 9 and 27 is divisible by 9
* 588, because 5 + 8 + 8 = 21 and 588 is divisible by 21
While these numbers are not:
* 19, because 1 + 9 = 10 and 19 is not divisible by 10
* 589, because 5 + 8 + 9 = 22 and 589 is not divisible by 22
* 1001, because 1 + 1 = 2 and 1001 is not divisible by 2
Harshad numbers can be found in any number base, but we are going to focus on base 10 exclusively.
## Your task
Your task is to complete the skeleton Harshad object ("static class") which has 3 functions:
* ```isValid()``` that checks if `n` is a Harshad number or not
* ```getNext()``` that returns the next Harshad number > `n`
* ```getSerie()``` that returns a series of `n` Harshad numbers, optional `start` value not included
You do not need to care about the passed parameters in the test cases, they will always be valid integers (except for the start argument in `getSerie()` which is optional and should default to `0`).
**Note:** only the first 2000 Harshad numbers will be checked in the tests.
## Examples
```python
Harshad.is_valid(1) ==> True
Harshad.get_next(0) ==> 1
Harshad.get_series(3) ==> [ 1, 2, 3 ]
Harshad.get_series(3, 1000) ==> [ 1002, 1008, 1010 ]
```
[
| 466 |
1K4NRV7UYUNQ
|
Everyday we go to different places to get our things done. Those places can be represented by specific location points `[ [, ], ... ]` on a map. I will be giving you an array of arrays that contain coordinates of the different places I had been on a particular day. Your task will be to find `peripheries (outermost edges)` of the bounding box that contains all the points. The response should only contain `Northwest and Southeast` points as follows: `{ "nw": [, ], "se": [ , ] }`. You are adviced to draw the points on a 2D plan to visualize:
```
N
^
p(nw) ______________|________________
| | |
| | all other |
| | points |
| | |
----------------------------------------> E
| | |
| all other | |
| points | |
|______________|________________|
| p(se)
```
[
| 218 |
C9G0GXKI5CBX
|
Polly is 8 years old. She is eagerly awaiting Christmas as she has a bone to pick with Santa Claus. Last year she asked for a horse, and he brought her a dolls house. Understandably she is livid.
The days seem to drag and drag so Polly asks her friend to help her keep count of how long it is until Christmas, in days. She will start counting from the first of December.
Your function should take 1 argument (a Date object) which will be the day of the year it is currently. The function should then work out how many days it is until Christmas.
Watch out for leap years!
[
| 130 |
LE3ETEHRKVD2
|
Given a number return the closest number to it that is divisible by 10.
Example input:
```
22
25
37
```
Expected output:
```
20
30
40
```
[
| 42 |
5HBHRQS7Y1O3
|
# Is the string uppercase?
## Task
```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby
Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example:
```
```if:haskell,reason,typescript
Create a method `isUpperCase` to see whether the string is ALL CAPS. For example:
```
```if:csharp
Create an extension method `IsUpperCase` to see whether the string is ALL CAPS. For example:
```
```if:julia
Create a function `isupper` to see whether the string is ALL CAPS. For example:
```
```if:cpp
Create a function `is_uppercase()` to see whether the string is ALL CAPS. For example:
```
```if:javascript,coffeescript
Add the `isUpperCase` method to `String` to see whether the string is ALL CAPS. For example:
```
```if:elixir
Create a method `upper_case?` to see whether the string is ALL CAPS. For example:
```
```if:forth,factor
Create a word `uppercase?` to check whether a string is ALL CAPS. For example:
```
```if:go
Create a method `IsUpperCase` to see whether the string is ALL CAPS. For example:
```
```if:racket
Create a method `upcase?` to see whether the string is ALL CAPS. For example:
```
```if:ruby
Create a method `is_upcase?` to see whether the string is ALL CAPS. For example:
```
```python
is_uppercase("c") == False
is_uppercase("C") == True
is_uppercase("hello I AM DONALD") == False
is_uppercase("HELLO I AM DONALD") == True
is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False
is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True
```
In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS.
[
| 496 |
C2ADSL4FLJTE
|
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 "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635.
*Note: only positive integers will be tested.*
[
| 75 |
ZAGWBB4VUS4V
|
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death.
Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tacitcs they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic.
Your job is to decide who wins.
Example:
```python
robot_1 = {
"name": "Rocky",
"health": 100,
"speed": 20,
"tactics": ["punch", "punch", "laser", "missile"]
}
robot_2 = {
"name": "Missile Bob",
"health": 100,
"speed": 21,
"tactics": ["missile", "missile", "missile", "missile"]
}
tactics = {
"punch": 20,
"laser": 30,
"missile": 35
}
fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight."
```
robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on.
**Rules**
- A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first.
- Robots alternate turns attacking. Tactics are used in order.
- A fight is over when a robot has 0 or less health or both robots have run out of tactics.
- A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics.
- If both robots run out of tactics, whoever has the most health wins. Return the message "{Name} has won the fight."
- If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw."
**To Java warriors**
`Robot` class is immutable.
Check out my other 80's Kids Katas:
80's Kids #1: How Many Licks Does It Take
80's Kids #2: Help Alf Find His Spaceship
80's Kids #3: Punky Brewster's Socks
80's Kids #4: Legends of the Hidden Temple
80's Kids #5: You Can't Do That on Television
80's Kids #6: Rock 'Em, Sock 'Em Robots
80's Kids #7: She's a Small Wonder
80's Kids #8: The Secret World of Alex Mack
80's Kids #9: Down in Fraggle Rock
80's Kids #10: Captain Planet
[
| 623 |
YI53YQM6RGGF
|
Imagine the following situations:
- A truck loading cargo
- A shopper on a budget
- A thief stealing from a house using a large bag
- A child eating candy very quickly
All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you.
The Problem
===
Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection.
However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2)
The Simplification
===
Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio.
For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items
- a 6-Liter item worth $9 (1.5 $/L)
- a 5-Liter item worth $5 (1.0 $/L)
the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math.
Now, go be bad at math!
The Kata
===
Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities.
`capacity` will be a positive number
`items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...]
`knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
[
| 469 |
JEJRRVJ703Z6
|
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1.
`13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations:
```python
13: 13
16: 2 * 2 * 2 * 2
9: 3 * 3
5: 5
119: 17 * 7
```
Complete the function that takes 2 arguments: a number (`n`), and a list of numbers (`arr`). The function should return a list of all the numbers in `arr` that are relatively prime to `n`. All numbers in will be positive integers.
## Examples
```python
relatively_prime(8, [1, 2, 3, 4, 5, 6, 7])
>> [1, 3, 5, 7]
relatively_prime(15, [72, 27, 32, 61, 77, 11, 40])
>> [32, 61, 77, 11]
relatively_prime(210, [15, 100, 2222222, 6, 4, 12369, 99])
>> []
```
[
| 303 |
A7BFXNVGLVVS
|
Build Tower Advanced
---
Build Tower by the following given arguments:
__number of floors__ (integer and always greater than 0)
__block size__ (width, height) (integer pair and always greater than (0, 0))
Tower block unit is represented as `*`
* Python: return a `list`;
* JavaScript: returns an `Array`;
Have fun!
***
for example, a tower of 3 floors with block size = (2, 3) looks like below
```
[
' ** ',
' ** ',
' ** ',
' ****** ',
' ****** ',
' ****** ',
'**********',
'**********',
'**********'
]
```
and a tower of 6 floors with block size = (2, 1) looks like below
```
[
' ** ',
' ****** ',
' ********** ',
' ************** ',
' ****************** ',
'**********************'
]
```
***
Go take a look at [Build Tower](https://www.codewars.com/kata/576757b1df89ecf5bd00073b) which is a more basic version :)
[
| 274 |
0827NNUFE0LH
|
----
Vampire Numbers
----
Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows:
```python
6 * 21 = 126
# 6 and 21 would be valid 'fangs' for a vampire number as the
# digits 6, 1, and 2 are present in both the product and multiplicands
10 * 11 = 110
# 110 is not a vampire number since there are three 1's in the
# multiplicands, but only two 1's in the product
```
Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
[
| 151 |
MJDHUNJCCU8C
|
Linked Lists - Sorted Insert
Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list.
The push() and buildOneTwoThree() functions do not need to be redefined.
[
| 84 |
9EO2Q2XY17D8
|
Linked Lists - Length & Count
Implement Length() to count the number of nodes in a linked list.
Implement Count() to count the occurrences of an integer in a linked list.
I've decided to bundle these two functions within the same Kata since they are both very similar.
The `push()`/`Push()` and `buildOneTwoThree()`/`BuildOneTwoThree()` functions do not need to be redefined.
[
| 87 |
Q7ON67MP5QT8
|
Given an array of integers (x), and a target (t), you must find out if any two consecutive numbers in the array sum to t. If so, remove the second number.
Example:
x = [1, 2, 3, 4, 5]
t = 3
1+2 = t, so remove 2. No other pairs = t, so rest of array remains:
[1, 3, 4, 5]
Work through the array from left to right.
Return the resulting array.
[
| 112 |
J6SL4906O97H
|
You're putting together contact information for all the users of your website to ship them a small gift. You queried your database and got back a list of users, where each user is another list with up to two items: a string representing the user's name and their shipping zip code. Example data might look like:
```python
[["Grae Drake", 98110], ["Bethany Kok"], ["Alex Nussbacher", 94101], ["Darrell Silver", 11201]]
```
Notice that one of the users above has a name but _doesn't_ have a zip code.
Write a function `user_contacts()` that takes a two-dimensional list like the one above and returns a dictionary with an item for each user where the key is the user's name and the value is the user's zip code. If your data doesn't include a zip code then the value should be `None`.
For example, using the input above, `user_contacts()` would return this dictionary:
```python
{
"Grae Drake": 98110,
"Bethany Kok": None,
"Alex Nussbacher": 94101,
"Darrell Silver": 11201,
}
```
You don't have to worry about leading zeros in zip codes.
[
| 266 |
JRZHU3W7U0BM
|
Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.
Example:
```python
solution(1000) # should return 'M'
```
Help:
```
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
```
Remember that there can't be more than 3 identical symbols in a row.
More about roman numerals - http://en.wikipedia.org/wiki/Roman_numerals
[
| 219 |
1EV92Y9DCUVW
|
The function must return the sequence of titles that match the string passed as an argument.
```if:javascript
TITLES is a preloaded sequence of strings.
```
```python
titles = ['Rocky 1', 'Rocky 2', 'My Little Poney']
search(titles, 'ock') --> ['Rocky 1', 'Rocky 2']
```
But the function return some weird result and skip some of the matching results.
Does the function have special movie taste?
Let's figure out !
[
| 112 |
BLPYQ249JSI8
|
# Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
```
[
| 90 |
36GLT76WYJE4
|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two arguments — a positive integer n and a string value.
The decode method will receive one argument — a string value.
Output
Each method will return a string value.
How It Works
Encoding and decoding are done by performing a series of character and substring rotations on a string input.
Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
Step 1: remove all spaces in the string (but remember their positions)
Step 2: shift the order of characters in the new string to the right by n characters
Step 3: put the spaces back in their original positions
Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
Repeat this process until it has been completed n times in total.
The value n is then prepended to the resulting string with a space.
Decoding: Decoding simply reverses the encoding process.
Test Example
```python
quote = 'If you wish to make an apple pie from scratch, you must first invent the universe.'
solution = '10 hu fmo a,ys vi utie mr snehn rni tvte .ysushou teI fwea pmapi apfrok rei tnocsclet'
IterativeRotationCipher['encode'](10,quote) == solution; //True
'''Step-by-step breakdown:
Step 1 — remove all spaces:
'Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventtheuniverse.'
Step 2 — shift the order of string characters to the right by 10:
'euniverse.Ifyouwishtomakeanapplepiefromscratch,youmustfirstinventth'
Step 3 — place the spaces back in their original positions:
'eu niv erse .I fyou wi shtom ake anap plepiefr oms crat ch,yo umustf irs tinventth'
Step 4 — shift the order of characters for each space-separated substring to the right by 10:
'eu vni seer .I oufy wi shtom eak apan frplepie som atcr ch,yo ustfum sir htinventt'
Repeat the steps 9 more times before returning the string with '10 ' prepended.
'''
```
Technical Details
- Input will always be valid.
- The characters used in the strings include any combination of alphanumeric characters, the space character, the newline character, and any of the following: `_!@#$%^&()[]{}+-*/="'<>,.?:;`.
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
[
| 651 |
ZY52URUU316I
|
# Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The Town Square is a rectangle of square paving stones (the Square has 1-15 pavers per side)
* The Pied Piper is always present
## Output Notes
* Deaf rats are those that are moving to paving stone **further away** from the Piper than where they are now
* Use Euclidian distance for your calculations
## Legend
* `P` = The Pied Piper
* `←` `↑` `→` `↓` `↖` `↗` `↘` `↙` = Rats going in different directions
* space = Everything else
# Examples
ex1 - has 1 deaf rat
↗ P
↘ ↖
↑
↗
---
ex2 - has 7 deaf rats
↗
P ↓ ↖ ↑
← ↓
↖ ↙ ↙
↓ ↓ ↓
[
| 265 |
0QMCITOISG8E
|
#Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (only visualization):
|myjinxin2015|raulbc777|smile67|Dentzil|SteffenVogel_79|
|17945 |10091 |10088 |3907 |10132 |
|2 |12 |13 |48 |11 |
The csv-file:
myjinxin2015;raulbc777;smile67;Dentzil;SteffenVogel_79\n
17945;10091;10088;3907;10132\n
2;12;13;48;11
----------------------------------
After sorting:
As table (only visualization):
|Dentzil|myjinxin2015|raulbc777|smile67|SteffenVogel_79|
|3907 |17945 |10091 |10088 |10132 |
|48 |2 |12 |13 |11 |
The csv-file:
Dentzil;myjinxin2015;raulbc777;smile67;SteffenVogel_79\n
3907;17945;10091;10088;10132\n
48;2;12;13;11
```
There is no need for prechecks. You will always get a correct string with more than 1 line und more than 1 row. All columns will have different names.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
[
| 417 |
JDK8KVLAT9XQ
|
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result.
#### Task:
Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below:
```python
{
"": "",
"": "",
...
}
For your convenience, a function named round1 has been defined for you. You can
use it to round to the nearest tenth correctly (due to the inaccuracy of round
and floats in general).
```
_The input should not be modified._
#### Calculation for projections:
```
[(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...)
```
#### An example:
```python
candidates = ['A', 'B', 'C']
poll1res = [20, 30, 50]
poll1wt = 1
poll1 = [poll1res, poll1wt]
poll2res = [40, 40, 20]
poll2wt = 0.5
poll2 = [poll2res, poll2wt]
poll3res = [50, 40, 10]
poll3wt = 2
poll3 = [poll3res, poll3wt]
polls = [poll1, poll2, poll3]
predict(candidates, polls)
#=> {
'A': 40,
'B': 37.1,
'C': 22.9
}
# because...
candidate 'A' weighted average
= ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2)
= (20 + 20 + 100) / 3.5
= 140 / 3.5
= 40
candidate 'B' weighted average
= ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2)
= (30 + 20 + 80) / 3.5
= 130 / 3.5
= 37.142857...
≈ 37.1 (round to nearest tenth)
candidate 'C' weighted average
= ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2)
= (50 + 10 + 20) / 3.5
= 80 / 3.5
= 22.857142...
≈ 22.9 (round to nearest tenth)
```
Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
[
| 985 |
QZSYMSC6CS6Q
|
# Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of dots, two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. The player who completes the fourth side of a 1×1 box earns one point and takes another turn only if another box can be made. (A point is typically recorded by placing a mark that identifies the player in the box, such as an initial). The game ends when no more lines can be placed. The winner is the player with the most points. The board may be of any size. When short on time, a 2×2 board (a square of 9 dots) is good for beginners. A 5×5 is good for experts. (Source Wikipedia)
# Task
Your task is to complete the class called Game. You will be given the board size as an integer board that will be between 1 and 26, therefore the game size will be board x board. You will be given an array of lines that have already been taken, so you must complete all possible squares.
# Rules
1. The integer board will be passed when the class is initialised.
2. board will be between 1 and 26.
3. The lines array maybe empty or contain a list of line integers.
4. You can only complete a square if 3 out of the 4 sides are already complete.
5. The lines array that is passed into the play() function may not be sorted numerically!
# Returns
Return an array of all the lines filled in including the original lines.
Return array must be sorted numerically.
Return array must not contain duplicate integers.
# Example 1
## Initialise
Initialise a board of 2 squares by 2 squares where ```board = 2```
## Line Numbering
## Line Input
So for the line input of `[1, 3, 4]` the below lines would be complete
to complete the square line `6` is needed
## Game Play
```python
board = 2
lines = [1, 3, 4]
game = Game(board)
game.play(lines) => [1, 3, 4, 6]
```
# Example 2
## Initialise
```python
board = 2
lines = [1, 2, 3, 4, 5, 8, 10, 11, 12]
game = Game.new(board)
game.play(lines) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
```
## Solution
Good luck and enjoy!
# Kata Series
If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you.
Maze Runner
Scooby Doo Puzzle
Driving License
Connect 4
Vending Machine
Snakes and Ladders
Mastermind
Guess Who?
Am I safe to drive?
Mexican Wave
Pigs in a Pen
Hungry Hippos
Plenty of Fish in the Pond
Fruit Machine
Car Park Escape
[
| 749 |
CP9B868J4T66
|
Your task is to implement a function that takes one or more dictionaries and combines them in one result dictionary.
The keys in the given dictionaries can overlap. In that case you should combine all source values in an array. Duplicate values should be preserved.
Here is an example:
```cs
var source1 = new Dictionary{{"A", 1}, {"B", 2}};
var source2 = new Dictionary{{"A", 3}};
Dictionary result = DictionaryMerger.Merge(source1, source2);
// result should have this content: {{"A", [1, 3]}, {"B", [2]}}
```
```python
source1 = {"A": 1, "B": 2}
source2 = {"A": 3}
result = merge(source1, source2);
// result should have this content: {"A": [1, 3]}, "B": [2]}
```
You can assume that only valid dictionaries are passed to your function.
The number of given dictionaries might be large. So take care about performance.
[
| 222 |
1R547770PIU3
|
John has invited some friends. His list is:
```
s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
```
Could you make a program that
- makes this string uppercase
- gives it sorted in alphabetical order by last name.
When the last names are the same, sort them by first name.
Last name and first name of a guest come in the result between parentheses separated by a comma.
So the result of function `meeting(s)` will be:
```
"(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"
```
It can happen that in two distinct families with the same family name two people have the same first name too.
# Notes
- You can see another examples in the "Sample tests".
[
| 225 |
C3PXMQ6455KI
|
*You are a composer who just wrote an awesome piece of music. Now it's time to present it to a band that will perform your piece, but there's a problem! The singers vocal range doesn't stretch as your piece requires, and you have to transpose the whole piece.*
# Your task
Given a list of notes (represented as strings) and an interval, output a list of transposed notes in *sharp* notation.
**Input notes may be represented both in flat and sharp notations (more on that below).**
**For this kata, assume that input is always valid and the song is *at least* 1 note long.**
**Assume that interval is an integer between -12 and 12.**
# Short intro to musical notation
Transposing a single note means shifting its value by a certain interval.
The notes are as following:
A, A#, B, C, C#, D, D#, E, F, F#, G, G#.
This is using *sharp* notation, where '#' after a note means that it is one step higher than the note. So A# is one step higher than A.
An alternative to sharp notation is the *flat* notation:
A, Bb, B, C, Db, D, Eb, E, F, Gb, G, Ab.
The 'b' after a note means that it is one step lower than the note.
# Examples
['G'] -> 5 steps -> ['C']
['Db'] -> -4 steps -> ['A#']
['E', 'F'] -> 1 step -> ['F', 'F#']
[
| 341 |
TXU65IXQFORX
|
# Write this function

`for i from 1 to n`, do `i % m` and return the `sum`
f(n=10, m=5) // returns 20 (1+2+3+4+0 + 1+2+3+4+0)
*You'll need to get a little clever with performance, since n can be a very large number*
[
| 98 |
AI6ZAISQXYWU
|
Write a function that receives two strings as parameter. This strings are in the following format of date: `YYYY/MM/DD`.
Your job is: Take the `years` and calculate the difference between them.
Examples:
```
'1997/10/10' and '2015/10/10' -> 2015 - 1997 = returns 18
'2015/10/10' and '1997/10/10' -> 2015 - 1997 = returns 18
```
At this level, you don't need validate months and days to calculate the difference.
[
| 125 |
2JFN7TQXIFWP
|
Now you have to write a function that takes an argument and returns the square of it.
[
| 19 |
J9S0JG5IEEE2
|
Create a function hollow_triangle(height) that returns a hollow triangle of the correct height. The height is passed through to the function and the function should return a list containing each line of the hollow triangle.
```
hollow_triangle(6) should return : ['_____#_____', '____#_#____', '___#___#___', '__#_____#__', '_#_______#_', '###########']
hollow_triangle(9) should return : ['________#________', '_______#_#_______', '______#___#______', '_____#_____#_____', '____#_______#____', '___#_________#___', '__#___________#__', '_#_____________#_', '#################']
```
The final idea is for the hollow triangle is to look like this if you decide to print each element of the list:
```
hollow_triangle(6) will result in:
_____#_____ 1
____#_#____ 2
___#___#___ 3
__#_____#__ 4
_#_______#_ 5
########### 6 ---- Final Height
hollow_triangle(9) will result in:
________#________ 1
_______#_#_______ 2
______#___#______ 3
_____#_____#_____ 4
____#_______#____ 5
___#_________#___ 6
__#___________#__ 7
_#_____________#_ 8
################# 9 ---- Final Height
```
Pad spaces with underscores i.e _ so each line is the same length.Goodluck and have fun coding !
[
| 368 |
HRLQHVZJTBWI
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
[
| 58 |
1S0LK2Z36BDD
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
[
| 26 |
QYO4JMR9UK9D
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
[
| 590 |
KO2BT5V010NS
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
[
| 945 |
6FT6UE9T987P
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
[
| 485 |
Z8BDDSOAOC2H
|
Another rewarding day in the fast-paced world of WebDev. Man, you love your job! But as with any job, somtimes things can get a little tedious. Part of the website you're working on has a very repetitive structure, and writing all the HTML by hand is a bore. Time to automate! You want to write some functions that will generate the HTML for you.
To organize your code, make of all your functions methods of a class called HTMLGen. Tag functions should be named after the tag of the element they create. Each function will take one argument, a string, which is the inner HTML of the element to be created. The functions will return the string for the appropriate HTML element.
For example,
In JavaScript:
In Python:
```python
g = HTMLGen();
paragraph = g.p('Hello, World!')
block = g.div(paragraph)
# The following are now true
paragraph == 'Hello, World!'
block == 'Hello, World!'
```
Your HTMLGen class should have methods to create the following elements:
* a
* b
* p
* body
* div
* span
* title
* comment
Note: The comment method should wrap its argument with an HTML comment. It is the only method whose name does not match an HTML tag. So, ```g.comment('i am a comment')``` must produce ``````.
[
| 293 |
CBPQU75EFCW3
|
## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.
For the sake of this kata, you can assume all input will be a positive integer.
## **Use Cases**
Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.
## **Examples**
Input:
```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~
Input:
```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~
Input:
```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~
##Good Luck!##
[
| 284 |
Z3T14ONDAOF7
|
The function sigma 1, σ1 in mathematics, is known as the one that gives the sum of the divisors of an integer number.
For example for the number 10,
```python
σ1(10) = 18 # because the divisors of 10 are: 1, 2, 5, 10
σ1(10) = 1 + 2 + 5 + 10 = 18
```
You can see the graph of this important function up to 250:
The number 528 and its reversed, 825 have equal value for the function σ1.
```python
σ1(528) = σ1(825)
divisors of 528 are: 1, 2, 3, 4, 6, 8, 11, 12, 16, 22, 24, 33, 44, 48, 66, 88, 132, 176, 264 and 528
the sum of the divisors of 528 is 1488
divisors of 825 are: 1, 3, 5, 11, 15, 25, 33, 55, 75, 165, 275 and 825
the sum of the divisors of 825 is 1488
```
In fact 528 is the smallest non palindromic integer that has this property.
We need a function, ```equal_sigma1()```, that may collect all the positive integers that fulfill the property described above.
The function receives an upper limit, ```nMax```, will output the total sum of these numbers and its reversed while are less or equal nMax.
Let's see some cases:
```python
equal_sigma1(100) = 0 # There are no numbers.
equal_sigma1(1000) = 1353 # 528 and its revesed 825 were found, 528 + 825 = 1353
equal_sigma1(2000) = 4565 # There are four numbers_: 528 + 825 + 1561 + 1651 = 4565
equal_sigma1(1600) = 2914 # Now we have three numbers: 528 + 825 + 1561 = 2914
equal_sigma1(1561) = 2914
```
The palindromic numbers (like 88, 808, 929), numbers that are equal to its reversed should be discarded.
Happy coding!!
(For more information about the general sigma function see at: https://en.wikipedia.org/wiki/Divisor_function)
[
| 550 |
2P1FCK4E3K76
|
The principal of a school likes to put challenges to the students related with finding words of certain features.
One day she said: "Dear students, the challenge for today is to find a word that has only one vowel and seven consonants but cannot have the letters "y" and "m". I'll give a special award for the first student that finds it." One of the students used his dictionary and spent all the night without sleeping, trying in vain to find the word. The next day, the word had not been found yet.
This student observed that the principal has a pattern in the features for the wanted words:
- The word should have **n** vowels, may be repeated, for example: in "engineering", n = 5.
- The word should have **m** consonants, may be repeated also: in "engineering", m = 6.
- The word should not have some forbidden letters (in an array), forbid_letters
You will be provided with a list of words, WORD_LIST(python/crystal), wordList(javascript), wordList (haskell), $word_list(ruby), and you have to create the function, ```wanted_words()```, that receives the three arguments in the order given above, ```wanted_words(n, m, forbid_list)```and output an array with the word or an array, having the words in the order given in the pre-loaded list, in the case of two or more words were found.
Let's see some cases:
```python
wanted_words(1, 7, ["m", "y"]) == ["strength"]
wanted_words(3, 7, ["m", "y"]) == ['afterwards', 'background', 'photograph', 'successful', 'understand']
```
For cases where no words are found the function will output an empty array.
```python
wanted_words(3, 7, ["a", "s" , "m", "y"]) == []
```
Help our student to win this and the next challenges of the school. He needs to sure about a suspect that he has. That many times there are no solutions for what the principal is asking for.
All words have its letters in lowercase format.
Enjoy it!
[
| 458 |
G5RRDTAOOUIY
|
Complete the method that takes a sequence of objects with two keys each: country or state, and capital. Keys may be symbols or strings.
The method should return an array of sentences declaring the state or country and its capital.
## Examples
```python
[{'state': 'Maine', 'capital': 'Augusta'}] --> ["The capital of Maine is Augusta"]
[{'country' : 'Spain', 'capital' : 'Madrid'}] --> ["The capital of Spain is Madrid"]
[{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}] --> ["The capital of Maine is Augusta", "The capital of Spain is Madrid"]
```
[
| 152 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.