description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
sequencelengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
Bob needs a fast way to calculate the volume of a cuboid with three values: the `length`, `width` and `height` of the cuboid. Write a function to help Bob with this calculation. ```if:shell In bash the script is ran with the following 3 arguments: `length` `width` `height` ```
reference
def get_volume_of_cuboid(length, width, height): return length * width * height # PEP8: kata function name should use snake_case not mixedCase getVolumeOfCubiod = get_volume_of_cuboid
Volume of a Cuboid
58261acb22be6e2ed800003a
[ "Geometry", "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/58261acb22be6e2ed800003a
8 kyu
A child is playing with a ball on the nth floor of a tall building. The height of this floor above ground level, *h*, is known. He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66). His mother looks out of a window 1.5 meters from the ground. How many times will the mother see the ball pass in front of her window (including when it's falling _and_ bouncing)? #### Three conditions must be met for a valid experiment: * Float parameter "h" in meters must be greater than 0 * Float parameter "bounce" must be greater than 0 and less than 1 * Float parameter "window" must be less than h. **If all three conditions above are fulfilled, return a positive integer, otherwise return -1.** #### Note: The ball can only be seen if the height of the rebounding ball is strictly *greater* than the window parameter. #### Examples: ``` - h = 3, bounce = 0.66, window = 1.5, result is 3 - h = 3, bounce = 1, window = 1.5, result is -1 (Condition 2) not fulfilled). ```
reference
def bouncingBall(h, bounce, window): if not 0 < bounce < 1: return - 1 count = 0 while h > window: count += 1 h *= bounce if h > window: count += 1 return count or - 1
Bouncing Balls
5544c7a5cb454edb3c000047
[ "Puzzles", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5544c7a5cb454edb3c000047
6 kyu
Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example: ``` 12 ==> 21 513 ==> 531 2017 ==> 2071 ``` If the digits can't be rearranged to form a bigger number, return `-1` (or `nil` in Swift, `None` in Rust): ``` 9 ==> -1 111 ==> -1 531 ==> -1 ```
refactoring
import itertools def next_bigger(n): s = list(str(n)) for i in range(len(s) - 2, - 1, - 1): if s[i] < s[i + 1]: t = s[i:] m = min(filter(lambda x: x > t[0], t)) t . remove(m) t . sort() s[i:] = [m] + t return int("" . join(s)) return - 1
Next bigger number with the same digits
55983863da40caa2c900004e
[ "Strings", "Refactoring" ]
https://www.codewars.com/kata/55983863da40caa2c900004e
4 kyu
The year is 1214. One night, Pope Innocent III awakens to find the the archangel Gabriel floating before him. Gabriel thunders to the pope: > Gather all of the learned men in Pisa, especially Leonardo Fibonacci. In order for the crusades in the holy lands to be successful, these men must calculate the *millionth* number in Fibonacci's recurrence. Fail to do this, and your armies will never reclaim the holy land. It is His will. The angel then vanishes in an explosion of white light. Pope Innocent III sits in his bed in awe. *How much is a million?* he thinks to himself. He never was very good at math. He tries writing the number down, but because everyone in Europe is still using Roman numerals at this moment in history, he cannot represent this number. If he only knew about the invention of zero, it might make this sort of thing easier. He decides to go back to bed. He consoles himself, *The Lord would never challenge me thus; this must have been some deceit by the devil. A pretty horrendous nightmare, to be sure.* Pope Innocent III's armies would go on to conquer Constantinople (now Istanbul), but they would never reclaim the holy land as he desired. --------------------------- In this kata you will have to calculate `fib(n)` where: fib(0) := 0 fib(1) := 1 fib(n + 2) := fib(n + 1) + fib(n) Write an algorithm that can handle `n` up to `2000000`. Your algorithm must output the exact integer answer, to full precision. Also, it must correctly handle negative numbers as input. **HINT I**: Can you rearrange the equation `fib(n + 2) = fib(n + 1) + fib(n)` to find `fib(n)` if you already know `fib(n + 1)` and `fib(n + 2)`? Use this to reason what value `fib` has to have for negative values. **HINT II**: See https://web.archive.org/web/20220614001843/https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2.4
algorithms
def fib(n): if n < 0: return (- 1) * * (n % 2 + 1) * fib(- n) a = b = x = 1 c = y = 0 while n: if n % 2 == 0: (a, b, c) = (a * a + b * b, a * b + b * c, b * b + c * c) n /= 2 else: (x, y) = (a * x + b * y, b * x + c * y) n -= 1 return y
The Millionth Fibonacci Kata
53d40c1e2f13e331fc000c26
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/53d40c1e2f13e331fc000c26
3 kyu
### Task You've just moved into a perfectly straight street with exactly ```n``` identical houses on either side of the road. Naturally, you would like to find out the house number of the people on the other side of the street. The street looks something like this: -------------------- ### Street ``` 1| |6 3| |4 5| |2 you ``` Evens increase on the right; odds decrease on the left. House numbers start at ```1``` and increase without gaps. When ```n = 3```, ```1``` is opposite ```6```, ```3``` opposite ```4```, and ```5``` opposite ```2```. ----------------- ### Example (address, n --> output) Given your house number ```address``` and length of street ```n```, give the house number on the opposite side of the street. ~~~if-not:shell ``` 1, 3 --> 6 3, 3 --> 4 2, 3 --> 5 3, 5 --> 8 ``` ~~~ ~~~if:shell ``` over_the_road args: [ address, street ] over_the_road: [ 1, 3 ] = 6 over_the_road: [ 3, 3 ] = 4 over_the_road: [ 2, 3 ] = 5 over_the_road: [ 3, 5 ] = 8 ``` ~~~ ## Note about errors If you are timing out, running out of memory, or get any kind of "error", read on. Both n and address could get upto 500 billion with over 200 random tests. If you try to store the addresses of 500 billion houses in a list then you will run out of memory and the tests will crash. This is not a kata problem so please don't post an issue. Similarly if the tests don't complete within 12 seconds then you also fail. To solve this, you need to think of a way to do the kata without making massive lists or huge for loops. Read the discourse for some inspiration :)
reference
def over_the_road(address, n): ''' Input: address (int, your house number), n (int, length of road in houses) Returns: int, number of the house across from your house. ''' # this is as much a math problem as a coding one # if your house is [even/odd], the opposite house will be [odd/even] # highest number on street is 2n # Left side houses are [1, 3, ... 2n-3, 2n-1] # Right side houses are [2n, 2n-2, ... 4, 2] # Sum of opposite house numbers will always be 2n+1 return (2 * n + 1 - address)
Over The Road
5f0ed36164f2bc00283aed07
[ "Fundamentals", "Mathematics", "Performance" ]
https://www.codewars.com/kata/5f0ed36164f2bc00283aed07
7 kyu
There is an array with some numbers. All numbers are equal except for one. Try to find it! ```javascript findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2 findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55 ``` ```swift findUniq([ 1, 1, 1, 2, 1, 1 ]) == 2 findUniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 ``` ```ruby find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 ``` ```python find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 ``` ```java Kata.findUniq(new double[]{ 1, 1, 1, 2, 1, 1 }); // => 2 Kata.findUniq(new double[]{ 0, 0, 0.55, 0, 0 }); // => 0.55 ``` ```haskell getUnique [1, 1, 1, 2, 1, 1] -- Result is 2 getUnique [0, 0, 0.55, 0, 0] -- Result is 0.55 ``` ```fsharp findUniq([ 1; 1; 1; 2; 1; 1 ]) = 2 findUniq([ 0; 0; 0.55; 0; 0 ]) = 0.55 ``` ```c finduniq((const float[]){1, 1, 1, 2, 1, 1}, 5); /* --> 2 */ finduniq((const float[]){0, 0, 0.55, 0, 0}, 5); /* --> 0.55 */ ``` ```nasm nums: dd 1., 1., 1., 2., 1., 1. mov rdi, nums mov rsi, 6 call finduniq ; XMM0 <- 2 nums: dd 0., 0., 0.55, 0., 0. mov rdi, nums mov rsi, 6 call finduniq ; XMM0 <- 0.55 ``` ```cpp find_uniq(std::vector<float>{1, 1, 1, 2, 1, 1}); // --> 2 find_uniq(std::vector<float>{0, 0, 0.55, 0, 0}); // --> 0.55 ``` It’s guaranteed that array contains at least 3 numbers. The tests contain some very huge arrays, so think about performance. This is the first kata in series: 1. Find the unique number (this kata) 2. [Find the unique string](https://www.codewars.com/kata/585d8c8a28bc7403ea0000c3) 3. [Find The Unique](https://www.codewars.com/kata/5862e0db4f7ab47bed0000e5)
reference
def find_uniq(arr): a, b = set(arr) return a if arr . count(a) == 1 else b
Find the unique number
585d7d5adb20cf33cb000235
[ "Fundamentals", "Algorithms", "Arrays" ]
https://www.codewars.com/kata/585d7d5adb20cf33cb000235
6 kyu
Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of `$ n^3 $`, the cube above will have volume of `$ (n-1)^3 $` and so on until the top which will have a volume of `$ 1^3 $`. You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build? The parameter of the function findNb `(find_nb, find-nb, findNb, ...)` will be an integer m and you have to return the integer n such as `$ n^3 + (n-1)^3 + (n-2)^3 + ... + 1^3 = m $` if such a n exists or -1 if there is no such n. #### Examples: ```if-not:nasm findNb(1071225) --> 45 findNb(91716553919377) --> -1 ``` ~~~if:nasm ``` mov rdi, 1071225 call find_nb ; rax <-- 45 mov rdi, 91716553919377 call find_nb ; rax <-- -1 ```
reference
def find_nb(m): n = 1 volume = 0 while volume < m: volume += n * * 3 if volume == m: return n n += 1 return - 1
Build a pile of Cubes
5592e3bd57b64d00f3000047
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5592e3bd57b64d00f3000047
6 kyu
Write a function, `persistence`, that takes in a positive parameter `num` and returns its multiplicative persistence, which is the number of times you must multiply the digits in `num` until you reach a single digit. For example **(Input --> Output)**: ``` 39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit) 999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2) 4 --> 0 (because 4 is already a one-digit number) ```
reference
def persistence(n): n = str(n) count = 0 while len(n) > 1: p = 1 for i in n: p *= int(i) n = str(p) count += 1 return count # your code
Persistent Bugger.
55bf01e5a717a0d57e0000ec
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec
6 kyu
The cockroach is one of the fastest insects. Write a function which takes its speed in km per hour and returns it in cm per second, rounded down to the integer (= floored). For example: ``` 1.08 --> 30 ``` Note! The input is a Real number (actual type is language dependent) and is >= 0. The result should be an Integer.
reference
def cockroach_speed(s): return s / / 0.036
Beginner Series #4 Cockroach
55fab1ffda3e2e44f00000c6
[ "Fundamentals" ]
https://www.codewars.com/kata/55fab1ffda3e2e44f00000c6
8 kyu
# Don't give me five! In this kata you get the start number and the end number of a region and should return the count of all numbers except numbers with a 5 in it. The start and the end number are both inclusive! **Examples:** ``` 1,9 -> 1,2,3,4,6,7,8,9 -> Result 8 4,17 -> 4,6,7,8,9,10,11,12,13,14,16,17 -> Result 12 ``` The result may contain fives. ;-)<br> The start number will always be smaller than the end number. Both numbers can be also negative! I'm very curious for your solutions and the way you solve it. Maybe someone of you will find an easy pure mathematics solution. Have fun coding it and please don't forget to vote and rank this kata! :-) I have also created other katas. Take a look if you enjoyed this kata!
algorithms
def dont_give_me_five(start, end): return sum('5' not in str(i) for i in range(start, end + 1))
Don't give me five!
5813d19765d81c592200001a
[ "Mathematics", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5813d19765d81c592200001a
7 kyu
Create a function `close_compare` that accepts 3 parameters: `a`, `b`, and an optional `margin`. The function should return whether `a` is lower than, close to, or higher than `b`. Please note the following: - When `a` is close to `b`, return `0`. - For this challenge, `a` is considered "close to" `b` if `margin` is greater than or equal to the absolute distance between `a` and `b`. Otherwise... - When `a` is less than `b`, return `-1`. - When `a` is greater than `b`, return `1`. If `margin` is not given, treat it as if it were zero. Assume: `margin >= 0` Tip: Some languages have a way to make parameters optional. ------ ### Example 1 If `a = 3`, `b = 5`, and `margin = 3`, then `close_compare(a, b, margin)` should return `0`. This is because `a` and `b` are no more than 3 numbers apart. ### Example 2 If `a = 3`, `b = 5`, and `margin = 0`, then `close_compare(a, b, margin)` should return `-1`. This is because the distance between `a` and `b` is greater than 0, and `a` is less than `b`.
reference
def close_compare(a, b, margin=0): return 0 if abs(a - b) <= margin else - 1 if b > a else 1
Compare within margin
56453a12fcee9a6c4700009c
[ "Fundamentals", "Logic" ]
https://www.codewars.com/kata/56453a12fcee9a6c4700009c
8 kyu
```if-not:swift Create a function that accepts a list/array and a number **n**, and returns a list/array of the first **n** elements from the list/array. If you need help, here's a reference: ``` ```if:swift Create a function *take* that takes an `Array<Int>` and an `Int`, *n*, and returns an `Array<Int>` containing the first up to *n* elements from the array. If you need help, here's a reference: ``` ~~~if:javascript,coffeescript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice ~~~ ~~~if:ruby http://www.rubycuts.com/enum-take ~~~ ~~~if:python https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range ~~~ ~~~if:java https://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#copyOfRange(int[],%20int,%20int) ~~~ ~~~if:swift https://developer.apple.com/documentation/swift/array ~~~ ~~~if:csharp https://docs.microsoft.com/en-us/dotnet/api/system.array?view=netcore-3.1 ~~~ ~~~if:cobol https://www.ibm.com/docs/en/cobol-zos/4.2?topic=program-handling-tables ~~~ ~~~if:scala https://scala-lang.org/api/3.x/scala/collection/Seq.html ~~~
reference
def take(arr, n): return arr[: n]
Enumerable Magic #25 - Take the First N Elements
545afd0761aa4c3055001386
[ "Fundamentals" ]
https://www.codewars.com/kata/545afd0761aa4c3055001386
8 kyu
Removed due to copyright infringement. <!--- &ensp;Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting of uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * replaces all uppercase consonants with corresponding lowercase ones. &ensp;Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string. Input:<br> &ensp;The first argument represents input string of Petya's program. This string only consists of uppercase and lowercase Latin letters. Output:<br> &ensp;Return the resulting string. Examples: ``` ('tour') => '.t.r' ('Codewars') => '.c.d.w.r.s' ('aBAcAba') => '.b.c.b' ``` (c)Alexander --->
reference
def string_task(s): return '' . join(f'. { a } ' for a in s . lower() if a not in 'aoyeui')
String Task
598ab63c7367483c890000f4
[ "Fundamentals", "Strings", "Data Types", "Regular Expressions", "Declarative Programming", "Advanced Language Features", "Programming Paradigms" ]
https://www.codewars.com/kata/598ab63c7367483c890000f4
7 kyu
You will be given an array `a` and a value `x`. All you need to do is check whether the provided array contains the value. ~~~if:swift The type of `a` and `x` can be `String` or `Int`. ~~~ ~~~if-not:swift Array can contain numbers or strings. X can be either. ~~~ ~~~if:racket In racket, you'll be given a list instead of an array. If the value is in the list, return #t instead of another value that is also considered true. ```racket (contains '(1 2 3) 3) ; returns #t (contains '(1 2 3) 5) ; returns #f ``` ~~~ Return `true` if the array contains the value, `false` if not.
reference
def check(seq, elem): return elem in seq
You only need one - Beginner
57cc975ed542d3148f00015b
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57cc975ed542d3148f00015b
8 kyu
I love Fibonacci numbers in general, but I must admit I love some more than others. I would like for you to write me a function that, when given a number `n` (`n >= 1` ), returns the n<sup>th</sup> number in the Fibonacci Sequence. For example: ```javascript nthFibo(4) == 2 ``` ```coffeescript nthFibo(4) == 2 ``` ```ruby nth_fibonacci(4) == 2 ``` ```haskell fib 4 == 2 ``` ```lambdacalc nth-fibo 4 == 2 ``` ```python nth_fib(4) == 2 ``` ```csharp NthFib(4) == 2 ``` ```c nth_fib(4) == 2 ``` ```julia nthfibo(4) == 2 ``` ```lua nth_fib(4) == 2 ``` ```nasm mov edi, 4 call nth_fib cmp rax, 2 ; should be equal ``` Because 2 is the 4th number in the Fibonacci Sequence. For reference, the first two numbers in the Fibonacci sequence are `0` and `1`, and each subsequent number is the sum of the previous two. ~~~if: lua Note: Since the 94th term of the sequence would cause an overflow in Lua, n will be between 0 and 93 (inclusive). ~~~ ~~~if:lambdacalc #### Encodings `numEncoding: BinaryScott` ~~~
algorithms
def nth_fib(n): a, b = 0, 1 for i in range(n - 1): a, b = b, a + b return a
N-th Fibonacci
522551eee9abb932420004a0
[ "Algorithms" ]
https://www.codewars.com/kata/522551eee9abb932420004a0
6 kyu
Jenny has written a function that returns a greeting for a user. However, she's in love with Johnny, and would like to greet him slightly different. She added a special case to her function, but she made a mistake. Can you help her?
bug_fixes
def greet(name): if name == "Johnny": return "Hello, my love!" return "Hello, {name}!" . format(name=name)
Jenny's secret message
55225023e1be1ec8bc000390
[ "Debugging" ]
https://www.codewars.com/kata/55225023e1be1ec8bc000390
8 kyu
Your task is to make two functions ( `max` and `min`, or `maximum` and `minimum`, etc., depending on the language ) that receive a list of integers as input, and return the largest and lowest number in that list, respectively. ### Examples (Input -> Output) ``` * [4,6,2,1,9,63,-134,566] -> max = 566, min = -134 * [-52, 56, 30, 29, -54, 0, -110] -> min = -110, max = 56 * [42, 54, 65, 87, 0] -> min = 0, max = 87 * [5] -> min = 5, max = 5 ``` ### Notes - You may consider that there will not be any empty arrays/vectors.
reference
def minimum(arr): return min(arr) def maximum(arr): return max(arr)
Find Maximum and Minimum Values of a List
577a98a6ae28071780000989
[ "Fundamentals" ]
https://www.codewars.com/kata/577a98a6ae28071780000989
8 kyu
I would like to be able to pass an array with two elements to my swapValues function to swap the values. However it appears that the values aren't changing. Can you figure out what's wrong here?
bug_fixes
def swap_values(args): args[0], args[1] = args[1], args[0] return args
Swap Values
5388f0e00b24c5635e000fc6
[ "Debugging", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5388f0e00b24c5635e000fc6
8 kyu
A natural number is called **k-prime** if it has exactly `k` prime factors, counted with multiplicity. For example: ``` k = 2 --> 4, 6, 9, 10, 14, 15, 21, 22, ... k = 3 --> 8, 12, 18, 20, 27, 28, 30, ... k = 5 --> 32, 48, 72, 80, 108, 112, ... ``` A natural number is thus prime if and only if it is 1-prime. #### Task: Complete the function `count_Kprimes` (or `countKprimes`, `count-K-primes`, `kPrimes`) which is given parameters `k, start, end` (or `nd`) and returns an **array** (or a list or a string depending on the language - see "Solution" and "Sample Tests") of the `k-primes` between `start (inclusive)` and `end (inclusive)`. #### Example: ``` countKprimes(5, 500, 600) --> [500, 520, 552, 567, 588, 592, 594] ``` Notes: - The first function would have been better named: `findKprimes` or `kPrimes` :-) - In C some helper functions are given (see declarations in 'Solution'). - For Go: nil slice is expected when there are no k-primes between `start` and `end`. ----- #### Second Task: puzzle (*not for Shell*) Given a positive integer s, find the total number of solutions of the equation `a + b + c = s`, where a is 1-prime, b is 3-prime, and c is 7-prime. Call this function `puzzle(s)`. #### Examples: ``` puzzle(138) --> 1 because [2 + 8 + 128] is the only solution puzzle(143) --> 2 because [3 + 12 + 128] and [7 + 8 + 128] are the solutions ```
reference
def count_Kprimes(k, start, end): return [n for n in range(start, end + 1) if find_k(n) == k] def puzzle(s): a = count_Kprimes(1, 0, s) b = count_Kprimes(3, 0, s) c = count_Kprimes(7, 0, s) return sum(1 for x in a for y in b for z in c if x + y + z == s) def find_k(n): res = 0 i = 2 while i * i <= n: while n % i == 0: n / /= i res += 1 i += 1 if n > 1: res += 1 return res
k-Primes
5726f813c8dcebf5ed000a6b
[ "Number Theory", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5726f813c8dcebf5ed000a6b
5 kyu
~~~if:sql Write a select statement that takes `name` from `person` table and return `"Hello, <name> how are you doing today?"` results in a column named `greeting` ~~~ ~~~if-not:sql Make a function that will return a greeting statement that uses an input; your program should return, `"Hello, <name> how are you doing today?"`. ~~~ *[Make sure you type the exact thing I wrote or the program may not execute properly]*
reference
def greet(name): return f'Hello, { name } how are you doing today?'
Returning Strings
55a70521798b14d4750000a4
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/55a70521798b14d4750000a4
8 kyu
## Your Job Find the sum of all multiples of `n` below `m` ## Keep in Mind * `n` and `m` are natural numbers (positive integers) * `m` is **excluded** from the multiples ## Examples ```javascript sumMul(2, 9) ==> 2 + 4 + 6 + 8 = 20 sumMul(3, 13) ==> 3 + 6 + 9 + 12 = 30 sumMul(4, 123) ==> 4 + 8 + 12 + ... = 1860 sumMul(4, -7) ==> "INVALID" ``` ```csharp Kata.SumMul(2, 9) => 2 + 4 + 6 + 8 = 20 Kata.SumMul(3, 13) => 3 + 6 + 9 + 12 = 30 Kata.SumMul(4, 123) => 4 + 8 + 12 + ... = 1860 Kata.SumMul(4, 1) // throws ArgumentException Kata.SumMul(0, 20) // throws ArgumentException ``` ```r sum_mul(2, 9) ==> 2 + 4 + 6 + 8 = 20 sum_mul(3, 13) ==> 3 + 6 + 9 + 12 = 30 sum_mul(4, 123) ==> 4 + 8 + 12 + ... = 1860 sum_mul(4, -7) ==> "INVALID" ``` ```java Kata.sumMul(2, 9) ==> 2 + 4 + 6 + 8 = 20 Kata.sumMul(3, 13) ==> 3 + 6 + 9 + 12 = 30 Kata.sumMul(4, 123) ==> 4 + 8 + 12 + ... = 1860 Kata.sumMul(4, -7) // throws IllegalArgumentException ``` ```scala sumMul(2, 9) // => 2 + 4 + 6 + 8 = Some(20) sumMul(3, 13) // => 3 + 6 + 9 + 12 = Some(30) sumMul(4, 123) // => 4 + 8 + 12 + ... = Some(1860) sumMul(4, -7) // => None (m must be greater than 0) sumMul(-4, 7) // => None (n must be greater than 0) sumMul(0, 2) // => None sumMul(2, 0) // => None ``` ```cobol SumMul(2, 9) => 2 + 4 + 6 + 8 = 20 SumMul(3, 13) => 3 + 6 + 9 + 12 = 30 SumMul(4, 123) => 4 + 8 + 12 + ... = 1860 SumMul(4, 1) => -1 SumMul(0, 20) => -1 ```
reference
def sum_mul(n, m): if m > 0 and n > 0: return sum(range(n, m, n)) else: return 'INVALID'
Sum of Multiples
57241e0f440cd279b5000829
[ "Fundamentals" ]
https://www.codewars.com/kata/57241e0f440cd279b5000829
8 kyu
## Objective Given a number `n` we will define it's sXORe to be `0 XOR 1 XOR 2 ... XOR n` where `XOR` is the [bitwise XOR operator](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Write a function that takes `n` and returns it's sXORe. ## Examples | n | sXORe n |---------|-------- | 0 | 0 | 1 | 1 | 50 | 51 | 1000000 | 1000000 ---
algorithms
def sxore(n): return [n, 1, n + 1, 0][n % 4]
Binary sXORe
56d3e702fc231fdf72001779
[ "Binary", "Algorithms" ]
https://www.codewars.com/kata/56d3e702fc231fdf72001779
7 kyu
Given an array of integers, find the one that appears an odd number of times. There will always be only one integer that appears an odd number of times. ### Examples `[7]` should return `7`, because it occurs 1 time (which is odd). `[0]` should return `0`, because it occurs 1 time (which is odd). `[1,1,2]` should return `2`, because it occurs 1 time (which is odd). `[0,1,0,1,0]` should return `0`, because it occurs 3 times (which is odd). `[1,2,2,3,3,3,4,3,3,3,2,2,1]` should return `4`, because it appears 1 time (which is odd).
reference
def find_it(seq): for i in seq: if seq . count(i) % 2 != 0: return i
Find the odd int
54da5a58ea159efa38000836
[ "Fundamentals" ]
https://www.codewars.com/kata/54da5a58ea159efa38000836
6 kyu
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 unsigned 32 bit number: `2149583361` Complete the function that takes an unsigned 32 bit number and returns a string representation of its IPv4 address. ## Examples ``` 2149583361 ==> "128.32.10.1" 32 ==> "0.0.0.32" 0 ==> "0.0.0.0" ```
algorithms
from ipaddress import IPv4Address def int32_to_ip(int32): return str(IPv4Address(int32))
int32 to IPv4
52e88b39ffb6ac53a400022e
[ "Networks", "Bits", "Algorithms" ]
https://www.codewars.com/kata/52e88b39ffb6ac53a400022e
5 kyu
Determine the total number of digits in the integer (`n>=0`) given as input to the function. For example, 9 is a single digit, 66 has 2 digits and 128685 has 6 digits. Be careful to avoid overflows/underflows. All inputs will be valid.
reference
def digits(n): return len(str(n))
Number of Decimal Digits
58fa273ca6d84c158e000052
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/58fa273ca6d84c158e000052
7 kyu
Your job is to create a calculator which evaluates expressions in [Reverse Polish notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). For example expression `5 1 2 + 4 * + 3 -` (which is equivalent to `5 + ((1 + 2) * 4) - 3` in normal notation) should evaluate to `14`. For your convenience, the input is formatted such that a space is provided between every token. Empty expression should evaluate to `0`. Valid operations are `+`, `-`, `*`, `/`. You may assume that there won't be exceptional situations (like stack underflow or division by zero).
algorithms
import operator def calc(expr): OPERATORS = {'+': operator . add, '-': operator . sub, '*': operator . mul, '/': operator . truediv} stack = [0] for token in expr . split(" "): if token in OPERATORS: op2, op1 = stack . pop(), stack . pop() stack . append(OPERATORS[token](op1, op2)) elif token: stack . append(float(token)) return stack . pop()
Reverse polish notation calculator
52f78966747862fc9a0009ae
[ "Algorithms", "Mathematics", "Interpreters", "Parsing", "Strings" ]
https://www.codewars.com/kata/52f78966747862fc9a0009ae
6 kyu
You were camping with your friends far away from home, but when it's time to go back, you realize that your fuel is running out and the nearest pump is `50` miles away! You know that on average, your car runs on about `25` miles per gallon. There are `2` gallons left. Considering these factors, write a function that tells you if it is possible to get to the pump or not. ```if-not:prolog,nasm,cobol Function should return `true` if it is possible and `false` if not. ``` ```if:prolog,nasm,cobol Function should return `1` if it is possible and `0` if not. ```
reference
def zeroFuel(distance_to_pump, mpg, fuel_left): return distance_to_pump <= mpg * fuel_left
Will you make it?
5861d28f124b35723e00005e
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5861d28f124b35723e00005e
8 kyu
You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return `-1`. ### For example: Let's say you are given the array `{1,2,3,4,3,2,1}`: Your function will return the index `3`, because at the 3rd position of the array, the sum of left side of the index (`{1,2,3}`) and the sum of the right side of the index (`{3,2,1}`) both equal `6`. Let's look at another one. You are given the array `{1,100,50,-51,1,1}`: Your function will return the index `1`, because at the 1st position of the array, the sum of left side of the index (`{1}`) and the sum of the right side of the index (`{50,-51,1,1}`) both equal `1`. Last one: You are given the array `{20,10,-80,10,10,15,35}` At index 0 the left side is `{}` The right side is `{10,-80,10,10,15,35}` They both are equal to `0` when added. (Empty arrays are equal to 0 in this problem) Index 0 is the place where the left side and right side are equal. Note: Please remember that in most languages the index of an array starts at 0. ### Input An integer array of length `0 < arr < 1000`. The numbers in the array can be any integer positive or negative. ### Output The lowest index `N` where the side to the left of `N` is equal to the side to the right of `N`. If you do not find an index that fits these rules, then you will return `-1`. ### Note If you are given an array with multiple answers, return the lowest correct index. ~~~if:lambdacalc ### Encodings purity: `LetRec` numEncoding: custom `NegaBinaryScott` Export constructors `nil, cons` for your `List` encoding. `NegaBinaryScott` is just like `BinaryScott`, but uses base `-2` instead of `2`. ~~~
reference
def find_even_index(arr): for i in range(len(arr)): if sum(arr[: i]) == sum(arr[i + 1:]): return i return - 1
Equal Sides Of An Array
5679aa472b8f57fb8c000047
[ "Algorithms", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5679aa472b8f57fb8c000047
6 kyu
Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers. Return your answer as a number.
reference
def sum_mix(arr): return sum(map(int, arr))
Sum Mixed Array
57eaeb9578748ff92a000009
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57eaeb9578748ff92a000009
8 kyu
Given a number, write a function to output its reverse digits. (e.g. given 123 the answer is 321) Numbers should preserve their sign; i.e. a negative number should still be negative when reversed. ### Examples ``` 123 -> 321 -456 -> -654 1000 -> 1 ```
games
def reverseNumber(n): if n < 0: return - reverseNumber(- n) return int(str(n)[:: - 1])
Reverse a Number
555bfd6f9f9f52680f0000c5
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/555bfd6f9f9f52680f0000c5
7 kyu
Return the Nth Even Number Example(**Input** --> **Output**) ``` 1 --> 0 (the first even number is 0) 3 --> 4 (the 3rd even number is 4 (0, 2, 4)) 100 --> 198 1298734 --> 2597466 ``` The input will not be 0.
games
def nth_even(n): return 2 * (n - 1)
Get Nth Even Number
5933a1f8552bc2750a0000ed
[ "Mathematics", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5933a1f8552bc2750a0000ed
8 kyu
Create function fib that returns n'th element of Fibonacci sequence (classic programming task). ~~~if:lambdacalc #### Encodings `numEncoding: Scott` ~~~
reference
def fibonacci(n: int) - > int: """Given a positive argument n, returns the nth term of the Fibonacci Sequence. """ x, y = 0, 1 for i in range(n): x, y = y, y + x return x
Fibonacci
57a1d5ef7cb1f3db590002af
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/57a1d5ef7cb1f3db590002af
7 kyu
A stream of data is received and needs to be reversed. Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example: ``` 11111111 00000000 00001111 10101010 (byte1) (byte2) (byte3) (byte4) ``` should become: ``` 10101010 00001111 00000000 11111111 (byte4) (byte3) (byte2) (byte1) ``` The total number of bits will always be a multiple of 8. The data is given in an array as such: ``` [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0] ``` Note: In the C and NASM languages you are given the third parameter which is the number of segment blocks.
reference
def data_reverse(data): res = [] for i in range(len(data) - 8, - 1, - 8): res . extend(data[i: i + 8]) return res
Data Reverse
569d488d61b812a0f7000015
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/569d488d61b812a0f7000015
6 kyu
## Task You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions. ### Examples ``` [7, 1] => [1, 7] [5, 8, 6, 3, 4] => [3, 8, 6, 5, 4] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0] ``` ~~~if:lambdacalc ### Encodings purity: `LetRec` numEncoding: `BinaryScott` export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding ~~~
reference
def sort_array(arr): odds = sorted((x for x in arr if x % 2 != 0), reverse=True) return [x if x % 2 == 0 else odds . pop() for x in arr]
Sort the odd
578aa45ee9fd15ff4600090d
[ "Fundamentals", "Arrays", "Sorting" ]
https://www.codewars.com/kata/578aa45ee9fd15ff4600090d
6 kyu
My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest. I am the one who establishes the list so I told him: "Don't worry any more, I will modify the order of the list". It was decided to attribute a "weight" to numbers. The weight of a number will be from now on the sum of its digits. For example `99` will have "weight" `18`, `100` will have "weight" `1` so in the list `100` will come before `99`. Given a string with the weights of FFC members in normal order can you give this string ordered by "weights" of these numbers? #### Example: ``` "56 65 74 100 99 68 86 180 90" ordered by numbers weights becomes: "100 180 90 56 65 74 68 86 99" ``` When two numbers have the same "weight", let us class them as if they were strings (alphabetical ordering) and not numbers: `180` is before `90` since, having the same "weight" (9), it comes before as a *string*. All numbers in the list are positive numbers and the list can be empty. #### Notes - it may happen that the input string have leading, trailing whitespaces and more than a unique whitespace between two consecutive numbers - For C: The result is freed.
algorithms
def order_weight(_str): return ' ' . join(sorted(sorted(_str . split(' ')), key=lambda x: sum(int(c) for c in x)))
Weight for weight
55c6126177c9441a570000cc
[ "Algorithms" ]
https://www.codewars.com/kata/55c6126177c9441a570000cc
5 kyu
Take 2 strings `s1` and `s2` including only letters from `a` to `z`. Return a new **sorted** string, the longest possible, containing distinct letters - each taken only once - coming from s1 or s2. #### Examples: ``` a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy" a = "abcdefghijklmnopqrstuvwxyz" longest(a, a) -> "abcdefghijklmnopqrstuvwxyz" ```
reference
def longest(a1, a2): return "" . join(sorted(set(a1 + a2)))
Two to One
5656b6906de340bd1b0000ac
[ "Fundamentals" ]
https://www.codewars.com/kata/5656b6906de340bd1b0000ac
7 kyu
### Lyrics... Pyramids are amazing! Both in architectural and mathematical sense. If you have a computer, you can mess with pyramids even if you are not in Egypt at the time. For example, let's consider the following problem. Imagine that you have a pyramid built of numbers, like this one here: ``` /3/ \7\ 4 2 \4\ 6 8 5 \9\ 3 ``` ### Here comes the task... Let's say that the *'slide down'* is the maximum sum of consecutive numbers from the top to the bottom of the pyramid. As you can see, the longest *'slide down'* is `3 + 7 + 4 + 9 = 23` Your task is to write a function that takes a pyramid representation as an argument and returns its __largest__ *'slide down'*. For example: ``` * With the input `[[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]` * Your function should return `23`. ``` ### By the way... My tests include some extraordinarily high pyramids so as you can guess, brute-force method is a bad idea unless you have a few centuries to waste. You must come up with something more clever than that. ~~~if:lambdacalc ### Encodings... purity: `LetRec` numEncoding: `BinaryScott` export constructors `nil, cons` for your `List` encoding ~~~ (c) This task is a lyrical version of __Problem 18__ and/or __Problem 67__ on [ProjectEuler](https://projecteuler.net).
algorithms
def longest_slide_down(p): res = p . pop() while p: tmp = p . pop() res = [tmp[i] + max(res[i], res[i + 1]) for i in range(len(tmp))] return res . pop()
Pyramid Slide Down
551f23362ff852e2ab000037
[ "Algorithms", "Dynamic Programming" ]
https://www.codewars.com/kata/551f23362ff852e2ab000037
4 kyu
A `Nice array` is defined to be an array where for every value `n` in the array, there is also an element `n - 1` or `n + 1` in the array. examples: ``` [2, 10, 9, 3] is a nice array because 2 = 3 - 1 10 = 9 + 1 3 = 2 + 1 9 = 10 - 1 [4, 2, 3] is a nice array because 4 = 3 + 1 2 = 3 - 1 3 = 2 + 1 (or 3 = 4 - 1) [4, 2, 1] is a not a nice array because for n = 4, there is neither n - 1 = 3 nor n + 1 = 5 ``` Write a function named `isNice`/`IsNice` that returns `true` if its array argument is a Nice array, else `false`. An empty array is not considered nice.
reference
def is_nice(arr): s = set(arr) return bool(arr) and all(n + 1 in s or n - 1 in s for n in s)
Nice Array
59b844528bcb7735560000a0
[ "Arrays", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/59b844528bcb7735560000a0
7 kyu
This time no story, no theory. The examples below show you how to write function `accum`: #### Examples: ``` accum("abcd") -> "A-Bb-Ccc-Dddd" accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" accum("cwAt") -> "C-Ww-Aaa-Tttt" ``` The parameter of accum is a string which includes only letters from `a..z` and `A..Z`.
reference
def accum(s): return '-' . join(c . upper() + c . lower() * i for i, c in enumerate(s))
Mumbling
5667e8f4e3f572a8f2000039
[ "Fundamentals", "Strings", "Puzzles" ]
https://www.codewars.com/kata/5667e8f4e3f572a8f2000039
7 kyu
As you probably know, Fibonacci sequence are the numbers in the following integer sequence: 1, 1, 2, 3, 5, 8, 13... Write a method that takes the index as an argument and returns last digit from fibonacci number. Example: getLastDigit(15) - 610. Your method must return 0 because the last digit of 610 is 0. Fibonacci sequence grows very fast and value can take very big numbers (bigger than integer type can contain), so, please, be careful with overflow. [Hardcore version of this kata](http://www.codewars.com/kata/find-last-fibonacci-digit-hardcore-version), no bruteforce will work here ;)
algorithms
def get_last_digit(index): a, b = 0, 1 for _ in range(index): a, b = b, (a + b) % 10 return a
Find Fibonacci last digit
56b7251b81290caf76000978
[ "Algorithms" ]
https://www.codewars.com/kata/56b7251b81290caf76000978
7 kyu
Given two arrays of strings `a1` and `a2` return a sorted array `r` in lexicographical order of the strings of `a1` which are substrings of strings of `a2`. #### Example 1: `a1 = ["arp", "live", "strong"]` `a2 = ["lively", "alive", "harp", "sharp", "armstrong"]` returns `["arp", "live", "strong"]` #### Example 2: `a1 = ["tarp", "mice", "bull"]` `a2 = ["lively", "alive", "harp", "sharp", "armstrong"]` returns `[]` #### Notes: - Arrays are written in "general" notation. See "Your Test Cases" for examples in your language. - In Shell bash `a1` and `a2` are strings. The return is a string where words are separated by commas. - Beware: In some languages `r` must be without duplicates.
refactoring
def in_array(array1, array2): # your code res = [] for a1 in array1: for a2 in array2: if a1 in a2 and not a1 in res: res . append(a1) res . sort() return res
Which are in?
550554fd08b86f84fe000a58
[ "Arrays", "Lists", "Strings", "Refactoring" ]
https://www.codewars.com/kata/550554fd08b86f84fe000a58
6 kyu
Given two integers `a` and `b`, which can be positive or negative, find the sum of all the integers between and including them and return it. If the two numbers are equal return `a` or `b`. **Note:** `a` and `b` are not ordered! ## Examples (a, b) --> output (explanation) ``` (1, 0) --> 1 (1 + 0 = 1) (1, 2) --> 3 (1 + 2 = 3) (0, 1) --> 1 (0 + 1 = 1) (1, 1) --> 1 (1 since both are same) (-1, 0) --> -1 (-1 + 0 = -1) (-1, 2) --> 2 (-1 + 0 + 1 + 2 = 2) ``` Your function should only return a number, not the explanation about how you get that number.
reference
def get_sum(a, b): return sum(range(min(a, b), max(a, b) + 1))
Beginner Series #3 Sum of Numbers
55f2b110f61eb01779000053
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/55f2b110f61eb01779000053
7 kyu
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. ```php moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0] ``` ```javascript moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0] ``` ```python move_zeros([1, 0, 1, 2, 0, 1, 3]) # returns [1, 1, 2, 1, 3, 0, 0] ``` ```cpp move_zeros({1, 0, 1, 2, 0, 1, 3}) // returns {1, 1, 2, 1, 3, 0, 0} ``` ```coffeescript moveZeros [false,1,0,1,2,0,1,3,"a"] # returns[false,1,1,2,1,3,"a",0,0] ``` ```csharp Kata.MoveZeroes(new int[] {1, 2, 0, 1, 0, 1, 0, 3, 0, 1}) => new int[] {1, 2, 1, 1, 3, 1, 0, 0, 0, 0} ``` ```go MoveZeros([]int{1, 2, 0, 1, 0, 1, 0, 3, 0, 1}) // returns []int{ 1, 2, 1, 1, 3, 1, 0, 0, 0, 0 } ``` ```haskell moveZeros [1,2,0,1,0,1,0,3,0,1] -> [1,2,1,1,3,1,0,0,0,0] ``` ```factor { 1 2 0 1 0 1 0 3 0 1 } move-zeros -> { 1 2 1 1 3 1 0 0 0 0 } ``` ```ruby moveZeros [1,2,0,1,0,1,0,3,0,1] #-> [1,2,1,1,3,1,0,0,0,0] ``` ```c move_zeros(10, int [] {1, 2, 0, 1, 0, 1, 0, 3, 0, 1}); // -> int [] {1, 2, 1, 1, 3, 1, 0, 0, 0, 0} ``` ```scala moveZeroes(List(1, 0, 1, 2, 0, 1, 3)) // -> List(1, 1, 2, 1, 3, 0, 0) ``` ```bf "1012013\0" --> "1121300" ```
algorithms
def move_zeros(array): for i in array: if i == 0: array . remove(i) # Remove the element from the array array . append(i) # Append the element to the end return array
Moving Zeros To The End
52597aa56021e91c93000cb0
[ "Arrays", "Sorting", "Algorithms" ]
https://www.codewars.com/kata/52597aa56021e91c93000cb0
5 kyu
Your goal is to return multiplication table for ```number``` that is always an integer from 1 to 10. For example, a multiplication table (string) for ```number == 5``` looks like below: ``` 1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 6 * 5 = 30 7 * 5 = 35 8 * 5 = 40 9 * 5 = 45 10 * 5 = 50 ``` ```if-not:powershell P. S. You can use ```\n``` in string to jump to the next line. ``` ```if:powershell P. S. You can use ``` `n ``` in string to jump to the next line. ``` Note: newlines should be added between rows, but there should be no trailing newline at the end. If you're unsure about the format, look at the sample tests.
reference
def multi_table(number): return '\n' . join(f' { i } * { number } = { i * number } ' for i in range(1, 11))
Multiplication table for number
5a2fd38b55519ed98f0000ce
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5a2fd38b55519ed98f0000ce
8 kyu
Give the summation of all even numbers in a Fibonacci sequence up to, but not including, the number passed to your function. Or, in other words, sum all the even Fibonacci numbers that are lower than the given number n (n is not the nth element of Fibonacci sequence) without including n. The Fibonacci sequence is a series of numbers where the next value is the addition of the previous two values. The series starts with 0 and 1: 0 1 1 2 3 5 8 13 21... For example: ```csharp Kata.Fibonacci(0) // returns 0 Kata.Fibonacci(33) // returns 10 Kata.Fibonacci(25997544) // returns 19544084 ``` ```javascript fibonacci(0)==0 fibonacci(33)==10 fibonacci(25997544)==19544084 ``` ```python eve_fib(0)==0 eve_fib(33)==10 eve_fib(25997544)==19544084 ``` ```ruby eve_fib(0)==0 eve_fib(33)==10 eve_fib(25997544)==19544084 ``` ```haskell fibSum 0 -> 0 fibSum 33 -> 10 fibSum 25997544 -> 19544084 ``` ```cobol fibSum 0 = 0 fibSum 33 = 10 fibSum 25997544 = 19544084 ``` ```julia fibsum(0) == 0 fibsum(33) == 10 fibsum(25997544) == 19544084 ``` ```c even_fib(0)==0 even_fib(33)==10 even_fib(25997544)==19544084 ``` ```java fibonacci(0)==0 fibonacci(33)==10 fibonacci(25997544)==19544084 ``` ```cpp fibonacci(0)==0 fibonacci(33)==10 fibonacci(25997544)==19544084 ```
algorithms
def even_fib(m): x, y = 0, 1 counter = 0 while y < m: if y % 2 == 0: counter += y x, y = y, x + y return counter
Even Fibonacci Sum
55688b4e725f41d1e9000065
[ "Algorithms" ]
https://www.codewars.com/kata/55688b4e725f41d1e9000065
6 kyu
Character recognition software is widely used to digitise printed texts. Thus the texts can be edited, searched and stored on a computer. When documents (especially pretty old ones written with a typewriter), are digitised character recognition softwares often make mistakes. Your task is correct the errors in the digitised text. You only have to handle the following mistakes: * `S` is misinterpreted as `5` * `O` is misinterpreted as `0` * `I` is misinterpreted as `1` The test cases contain numbers only by mistake.
reference
def correct(string): return string . translate(str . maketrans("501", "SOI"))
Correct the mistakes of the character recognition software
577bd026df78c19bca0002c0
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/577bd026df78c19bca0002c0
8 kyu
## Task Sum all the numbers of a given array ( cq. list ), except the highest and the lowest element ( by value, not by index! ). The highest or lowest element respectively is a single element at each edge, even if there are more than one with the same value. Mind the input validation. ## Example { 6, 2, 1, 8, 10 } => 16 { 1, 1, 11, 2, 3 } => 6 ## Input validation If an empty value ( `null`, `None`, `Nothing` etc. ) is given instead of an array, or the given array is an empty list or a list with only `1` element, return `0`.
reference
def sum_array(arr): if arr == None or len(arr) < 3: return 0 return sum(arr) - max(arr) - min(arr)
Sum without highest and lowest number
576b93db1129fcf2200001e6
[ "Fundamentals" ]
https://www.codewars.com/kata/576b93db1129fcf2200001e6
8 kyu
# 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 ```
reference
def goals(* a): return sum(a)
Grasshopper - Messi goals function
55f73be6e12baaa5900000d4
[ "Fundamentals" ]
https://www.codewars.com/kata/55f73be6e12baaa5900000d4
8 kyu
Write a function which takes a number and returns the corresponding ASCII char for that value. Example: ``` 65 --> 'A' 97 --> 'a' 48 --> '0 ``` For ASCII table, you can refer to http://www.asciitable.com/
reference
def get_char(c): return chr(c)
get character from ASCII Value
55ad04714f0b468e8200001c
[ "Fundamentals" ]
https://www.codewars.com/kata/55ad04714f0b468e8200001c
8 kyu
Numbers ending with zeros are boring. They might be fun in your world, but not here. Get rid of them. Only the ending ones. 1450 -> 145 960000 -> 96 1050 -> 105 -1050 -> -105 Zero alone is fine, don't worry about it. Poor guy anyway
reference
def no_boring_zeros(n): try: return int(str(n). rstrip('0')) except ValueError: return 0
No zeros for heros
570a6a46455d08ff8d001002
[ "Fundamentals" ]
https://www.codewars.com/kata/570a6a46455d08ff8d001002
8 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" /> <!-- Featured 30/6/2021 --> # Kata Task I have a cat and a dog. I got them at the same time as kitten/puppy. That was `humanYears` years ago. Return their respective ages now as [`humanYears`,`catYears`,`dogYears`] NOTES: * `humanYears` >= 1 * `humanYears` are whole numbers only ## Cat Years * `15` cat years for first year * `+9` cat years for second year * `+4` cat years for each year after that ## Dog Years * `15` dog years for first year * `+9` dog years for second year * `+5` dog years for each year after that <hr> **References** * http://www.catster.com/cats-101/calculate-cat-age-in-cat-years * http://www.slate.com/articles/news_and_politics/explainer/2009/05/a_dogs_life.html <hr> If you liked this Kata there is another <a href="https://www.codewars.com/kata/cat-years-dog-years-2">related one here</a>
reference
def human_years_cat_years_dog_years(human_years): catYears = 0 dogYears = 0 if human_years == 1: catYears += 15 dogYears += 15 return [human_years, catYears, dogYears] elif human_years == 2: catYears += 24 dogYears += 24 return [human_years, catYears, dogYears] elif human_years > 2: catYears += 24 dogYears += 24 years = human_years - 2 catYears += years * 4 dogYears += years * 5 return [human_years, catYears, dogYears] return [0, 0, 0]
Cat years, Dog years
5a6663e9fd56cb5ab800008b
[ "Fundamentals" ]
https://www.codewars.com/kata/5a6663e9fd56cb5ab800008b
8 kyu
HELP! Jason can't find his textbook! It is two days before the test date, and Jason's textbooks are all out of order! Help him sort a list (ArrayList in java) full of textbooks by subject, so he can study before the test. The sorting should **NOT** be case sensitive
reference
def sorter(textbooks): return sorted(textbooks, key=str . lower)
Sort My Textbooks
5a07e5b7ffe75fd049000051
[ "Lists", "Sorting", "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a07e5b7ffe75fd049000051
8 kyu
Write a function that rotates a two-dimensional array (a matrix) either clockwise or anti-clockwise by 90 degrees, and returns the rotated array. The function accepts two parameters: a matrix, and a string specifying the direction or rotation. The direction will be either `"clockwise"` or `"counter-clockwise"`. ## Examples For matrix: ``` [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] ``` Clockwise rotation: ``` [ [7, 4, 1], [8, 5, 2], [9, 6, 3] ] ``` Counter-clockwise rotation: ``` [ [3, 6, 9], [2, 5, 8], [1, 4, 7] ] ```
algorithms
import numpy as np d = {"clockwise": 3, "counter-clockwise": 1} def rotate(matrix, direction): return np . rot90(matrix, d[direction]). tolist()
Rotate an array matrix
525a566985a9a47bc8000670
[ "Matrix", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/525a566985a9a47bc8000670
5 kyu
For every good kata idea there seem to be quite a few bad ones! In this kata you need to check the provided array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is often the case, return 'Fail!'. ~~~if:c For C: do not dynamically allocate memory, instead return a string literal ~~~
refactoring
def well(x): c = x . count('good') return 'I smell a series!' if c > 2 else 'Publish!' if c else 'Fail!'
Well of Ideas - Easy Version
57f222ce69e09c3630000212
[ "Fundamentals", "Arrays", "Strings", "Refactoring" ]
https://www.codewars.com/kata/57f222ce69e09c3630000212
8 kyu
Welcome. In this kata, you are asked to square every digit of a number and concatenate them. For example, if we run 9119 through the function, 811181 will come out, because 9<sup>2</sup> is 81 and 1<sup>2</sup> is 1. (81-1-1-81) Example #2: An input of 765 will/should return 493625 because 7<sup>2</sup> is 49, 6<sup>2</sup> is 36, and 5<sup>2</sup> is 25. (49-36-25) **Note:** The function accepts an integer and returns an integer. Happy Coding!
reference
def square_digits(num): ret = "" for x in str(num): ret += str(int(x) * * 2) return int(ret)
Square Every Digit
546e2562b03326a88e000020
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/546e2562b03326a88e000020
7 kyu
Write a function that merges two sorted arrays into a single one. The arrays only contain integers. Also, the final outcome must be sorted and not have any duplicate.
reference
def merge_arrays(a, b): return sorted(set(a + b))
Merging sorted integer arrays (without duplicates)
573f5c61e7752709df0005d2
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/573f5c61e7752709df0005d2
8 kyu
The code provided is supposed replace all the dots `.` in the specified String `str` with dashes `-` But it's not working properly. # Task Fix the bug so we can all go home early. # Notes String `str` will never be null.
bug_fixes
def replace_dots(string): return string . replace('.', '-')
FIXME: Replace all dots
596c6eb85b0f515834000049
[ "Debugging" ]
https://www.codewars.com/kata/596c6eb85b0f515834000049
8 kyu
This function should test if the `factor` is a factor of `base`. Return `true` if it is a factor or `false` if it is not. ## About factors Factors are numbers you can multiply together to get another number. 2 and 3 are factors of 6 because: `2 * 3 = 6` - You can find a factor by dividing numbers. If the remainder is 0 then the number is a factor. - You can use the mod operator (`%`) in most languages to check for a remainder For example 2 is not a factor of 7 because: `7 % 2 = 1` Note: `base` is a non-negative number, `factor` is a positive number.
reference
def check_for_factor(base, factor): return base % factor == 0
Grasshopper - Check for factor
55cbc3586671f6aa070000fb
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/55cbc3586671f6aa070000fb
8 kyu
This kata is about multiplying a given number by eight if it is an even number and by nine otherwise.
reference
def simple_multiplication(number): return number * 9 if number % 2 else number * 8
Simple multiplication
583710ccaa6717322c000105
[ "Fundamentals" ]
https://www.codewars.com/kata/583710ccaa6717322c000105
8 kyu
# Convert number to reversed array of digits Given a random non-negative number, you have to return the digits of this number within an array in reverse order. ## Example(Input => Output): ``` 35231 => [1,3,2,5,3] 0 => [0] ```
reference
def digitize(n): return [int(x) for x in str(n)[:: - 1]]
Convert number to reversed array of digits
5583090cbe83f4fd8c000051
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5583090cbe83f4fd8c000051
8 kyu
## Longest Common Subsequence (Performance version) from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem): The longest common subsequence (LCS) problem is the problem of finding the longest subsequence common to all sequences in a set of sequences. It differs from problems of finding common substrings: unlike substrings, subsequences are not required to occupy consecutive positions within the original sequences. ## Task Write a function `lcs` that accepts two `string`s and returns their longest common subsequence as a `string`. Performance matters. #### Examples ```javascript lcs( "abcdef", "abc" ) => "abc" lcs( "abcdef", "acf" ) => "acf" lcs( "132535365", "123456789" ) => "12356" lcs( "abcdefghijklmnopq", "apcdefghijklmnobq" ) => "acdefghijklmnoq" ``` ```haskell lcs "abcdef" "abc" -> "abc" lcs "abcdef" "acf" -> "acf" lcs "132535365" "123456789" -> "12356" lcs "abcdefghijklmnopq" "apcdefghijklmnobq" -> "acdefghijklmnoq" ``` ```clojure (lcs "abcdef" "abc") ; "abc" (lcs "abcdef" "acf") ; "acf" (lcs "132535365" "123456789") ; "12356" (lcs "abcdefghijklmnopq" "apcdefghijklmnobq") ; "acdefghijklmnoq" ``` #### Testing This is a performance version of [xDranik](http://www.codewars.com/users/xDranik)'s [kata of the same name](http://www.codewars.com/kata/longest-common-subsequence/). This kata, however, has much more full and heavy testing. Intermediate random tests have string arguments of 20 characters; hard random tests 40 characters; extreme 60 characters (characters are chosen out of 36 different ones). ```if:javascript The reference algorithm solves all (12 fixed, 72 intermediate, 24 hard, 12 extreme) tests within ~150ms. The example algorithm without memoisation would take ~15000ms. ``` ```if:haskell The naive (Wikipedia) solution will run out of time, but the reference algorithm, stolen from the other kata from user geekyfox, showcasing memoisation, and the example algorithm, optimising the recursion, do not have any runtime problems (at all). ``` #### Notes The subsequences of `"abc"` are `"", "a", "b", "c", "ab", "ac", "bc", "abc"`. `""` is a valid subsequence in this kata, and a possible return value. All inputs will be valid. Two strings may have more than one longest common subsequence. When this occurs, return any of them. ```javascript lcs( string0, string1 ) === lcs( string1, string0 ) ``` ```haskell lcs xs ys == lcs ys xs ``` ```clojure (= (lcs xs ys) (lcs ys xs)) ``` Wikipedia has an [article](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem) that may be helpful.
algorithms
from functools import lru_cache @ lru_cache(None) def lcs(x, y): if not (x and y): return '' if x[0] == y[0]: return x[0] + lcs(x[1:], y[1:]) return max(lcs(x, y[1:]), lcs(x[1:], y), key=len)
Longest Common Subsequence (Performance version)
593ff8b39e1cc4bae9000070
[ "Performance", "Strings", "Dynamic Programming", "Memoization", "Algorithms" ]
https://www.codewars.com/kata/593ff8b39e1cc4bae9000070
4 kyu
The code gives an error! ```clojure (def a (123 toString)) ``` ```haskell a = 123 . toString ``` ```ruby a = some_number.toString ``` ```crystal a = A.toString ``` ```python a = 123.toString() ``` ```java public static final String a = 123.toString(); ``` ```javascript a = 123.toString ``` ```coffeescript a = 123.toString ``` ```csharp Kata.A = 123.ToSTring(); ``` Fix it!
bug_fixes
a = str(123)
Number toString
53934feec44762736c00044b
[ "Bugs", "Strings", "Data Types" ]
https://www.codewars.com/kata/53934feec44762736c00044b
8 kyu
A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant). Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation. ```if:prolog **Note for prolog users**: your task is to write a predicate **is_pangram/1** instead. ``` ```if:lambdacalc **For Lambda Calculus**: the string is a list of [BinaryScott-encoded numbers](https://github.com/codewars/lambda-calculus/wiki/encodings-guide#scott-binary-encoded-numerals) representing [Unicode code points](https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin).* `succ :: Number -> Number` and `add :: Number -> Number -> Number` are provided for free, if you need them. Church boolean and Scott list encodings are also provided for free, but you can optionally use your own encodings by replacing the exported functions `if-then-else`, `nil`, and `cons`, which are used by the tests. - purity: `LetRec` - numEncoding: `BinaryScott` **For example, the letter 'B' is represented by the decimal code point 66, which in big-endian binary is `1000010`, and therefore in little-endian BinaryScott would be `Bit0 (Bit1 (Bit0 (Bit0 (Bit0 (Bit0 (Bit1 End))))))`.* ```
reference
import string def is_pangram(s): s = s . lower() for char in 'abcdefghijklmnopqrstuvwxyz': if char not in s: return False return True
Detect Pangram
545cedaa9943f7fe7b000048
[ "Strings", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/545cedaa9943f7fe7b000048
6 kyu
Our football team has finished the championship. Our team's match results are recorded in a collection of strings. Each match is represented by a string in the format `"x:y"`, where `x` is our team's score and `y` is our opponents score. For example: ```["3:1", "2:2", "0:1", ...]``` Points are awarded for each match as follows: - if x > y: 3 points (win) - if x < y: 0 points (loss) - if x = y: 1 point (tie) We need to write a function that takes this collection and returns the number of points our team (`x`) got in the championship by the rules given above. Notes: - our team always plays 10 matches in the championship - 0 <= x <= 4 - 0 <= y <= 4
reference
def points(games): count = 0 for score in games: res = score . split(':') if res[0] > res[1]: count += 3 elif res[0] == res[1]: count += 1 return count
Total amount of points
5bb904724c47249b10000131
[ "Fundamentals", "Arrays", "Strings" ]
https://www.codewars.com/kata/5bb904724c47249b10000131
8 kyu
# Ten-Pin Bowling In the game of ten-pin bowling, a player rolls a bowling ball down a lane to knock over pins. There are ten pins set at the end of the bowling lane. Each player has 10 frames to roll a bowling ball down a lane and knock over as many pins as possible. The first nine frames are ended after two rolls or when the player knocks down all the pins. The last frame a player will receive an extra roll every time they knock down all ten pins; up to a maximum of three total rolls. ## The Challenge In this challenge you will be given a string representing a player's ten frames. It will look something like this: `'X X 9/ 80 X X 90 8/ 7/ 44'` (in Java: `"X X 9/ 80 X X 90 8/ 7/ 44"`), where each frame is space-delimited, `'X'` represents strikes, and `'/'` represents spares. Your goal is take in this string of frames into a function called `bowlingScore` and return the players total score. ## Scoring The scoring for ten-pin bowling can be difficult to understand, and if you're like most people, easily forgotten if you don't play often. Here is a quick breakdown: ### Frames In Ten-Pin Bowling there are ten frames per game. Frames are the players turn to bowl, which can be multiple rolls. The first 9 frames you get 2 rolls maximum to try to get all 10 pins down. **On the 10th or last frame a player will receive an extra roll each time they get all ten pins down to a maximum of three total rolls. Also on the last frame bonuses are not awarded for strikes and spares moving forward.** In this challenge, three frames might be represented like this: `54 72 44`. In this case, the player has had three frames. On their first frame they scored 9 points (5 + 4), on their second frame they scored 9 points (7 + 2) and on their third frame they scored 8 points (4 + 4). This is a very simple example of bowling scoring. It gets more complicated when we introduce strikes and spares. ### Strikes Represented in this challenge as `'X'` A strike is scored when a player knocks all ten pins down in one roll. In the first 9 frames this will conclude the players turn and it will be scored as 10 points plus the points received from the next two rolls. So if a player were to have two frames `X 54`, the total score of those two frames would be 28. The first frame would be worth 19 (10 + 5 + 4) and the second frame would be worth 9 (5 + 4). A perfect game in bowling is 12 strikes in a row and would be represented like this `'X X X X X X X X X XXX'` (in Java: `"X X X X X X X X X XXX"`). This adds up to a total score of 300. ### Spares Represented in this challenge as `'/'` A spare is scored when a player knocks down all ten pins in two rolls. In the first 9 frames this will be scored as 10 points plus the next roll. So if a player were to have two frames `9/ 54`, the total score of the two frames would be 24. The first frame would be worth 15 (10 + 5) and the second frame would be worth 9 (5 + 4). For a more detailed explanation see Wikipedia: http://en.wikipedia.org/wiki/Ten-pin_bowling#Scoring
algorithms
def bowling_score(frames): rolls = list(frames . replace(' ', '')) for i, hit in enumerate(rolls): if hit == 'X': rolls[i] = 10 elif hit == '/': rolls[i] = 10 - rolls[i - 1] else: rolls[i] = int(hit) score = 0 for i in range(10): frame = rolls . pop(0) if frame == 10: score += frame + rolls[0] + rolls[1] # Strike! else: frame += rolls . pop(0) score += frame if frame == 10: score += rolls[0] # Spare! return score
Ten-Pin Bowling
5531abe4855bcc8d1f00004c
[ "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/5531abe4855bcc8d1f00004c
4 kyu
# Sentence Smash Write a function that takes an array of words and smashes them together into a sentence and returns the sentence. You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word. **Be careful, there shouldn't be a space at the beginning or the end of the sentence!** ## Example ``` ['hello', 'world', 'this', 'is', 'great'] => 'hello world this is great' ```
reference
def smash(words): return " " . join(words)
Sentence Smash
53dc23c68a0c93699800041d
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/53dc23c68a0c93699800041d
8 kyu
Given two arrays `a` and `b` write a function `comp(a, b)` (or`compSame(a, b)`) that checks whether the two arrays have the "same" elements, with the same *multiplicities* (the multiplicity of a member is the number of times it appears). "Same" means, here, that the elements in `b` are the elements in `a` squared, regardless of the order. #### Examples ##### Valid arrays ``` a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] ``` `comp(a, b)` returns true because in `b` 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on. It gets obvious if we write `b`'s elements in terms of squares: ``` a = [121, 144, 19, 161, 19, 144, 19, 11] b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19] ``` ##### Invalid arrays If, for example, we change the first number to something else, `comp` is not returning true anymore: ``` a = [121, 144, 19, 161, 19, 144, 19, 11] b = [132, 14641, 20736, 361, 25921, 361, 20736, 361] ``` `comp(a,b)` returns false because in `b` 132 is not the square of any number of `a`. ``` a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361] ``` `comp(a,b)` returns false because in `b` 36100 is not the square of any number of `a`. #### Remarks - `a` or `b` might be `[] or {}` (all languages except R, Shell). - `a` or `b` might be `nil` or `null` or `None` or `nothing` (except in C++, COBOL, Crystal, D, Dart, Elixir, Fortran, F#, Haskell, Nim, OCaml, Pascal, Perl, PowerShell, Prolog, PureScript, R, Racket, Rust, Shell, Swift). If `a` or `b` are `nil` (or `null` or `None`, depending on the language), the problem doesn't make sense so return false.
reference
def comp(array1, array2): try: return sorted([i * * 2 for i in array1]) == sorted(array2) except: return False
Are they the "same"?
550498447451fbbd7600041c
[ "Fundamentals" ]
https://www.codewars.com/kata/550498447451fbbd7600041c
6 kyu
Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out. **Example:** Given an input string of: ``` apples, pears # and bananas grapes bananas !apples ``` The output expected would be: ``` apples, pears grapes bananas ``` The code would be called like so: ```javascript var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) // result should == "apples, pears\ngrapes\nbananas" ``` ```kotlin var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", charArrayOf('#', '!')) // result should == "apples, pears\ngrapes\nbananas" ``` ```coffeescript result = stripComments("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) # result should == "apples, pears\nograpes\nbananas" ``` ```ruby result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) # result should == "apples, pears\ngrapes\nbananas" ``` ```crystal result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) # result should == "apples, pears\ngrapes\nbananas" ``` ```python result = strip_comments("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) # result should == "apples, pears\ngrapes\nbananas" ``` ```csharp string stripped = StripCommentsSolution.StripComments("apples, pears # and bananas\ngrapes\nbananas !apples", new [] { "#", "!" }) // result should == "apples, pears\ngrapes\nbananas" ``` ```julia result = stripcomments("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) # result should == "apples, pears\ngrapes\nbananas" ``` ```factor "apples, pears # and bananas\ngrapes\nbananas !apples" "#!" strip-comments ! "apples, pears\ngrapes\nbananas" ``` ```scala val res = stripComments("apples, pears # and bananas\ngrapes\nbananas !apples", Set('#', '!')) // res should be "apples, pears\ngrapes\nbananas" ```
algorithms
def solution(string, markers): parts = string . split('\n') for s in markers: parts = [v . split(s)[0]. rstrip() for v in parts] return '\n' . join(parts)
Strip Comments
51c8e37cee245da6b40000bd
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/51c8e37cee245da6b40000bd
4 kyu
Return a new array consisting of elements which are multiple of their own index in input array (length > 1). ## Some cases: ````if-not:julia ```javascript [22, -6, 32, 82, 9, 25] => [-6, 32, 25] [68, -1, 1, -7, 10, 10] => [-1, 10] [-56,-85,72,-26,-14,76,-27,72,35,-21,-67,87,0,21,59,27,-92,68] => [-85, 72, 0, 68] ``` ```` ````if:julia ```julia [22, -6, 32, 82, 9, 25] => [22, -6] [68, -1, 1, -7, 10, 10] => [68, 10] [-56,-85,72,-26,-14,76,-27,72,35,-21,-67,87,0,21,59,27,-92,68] => [-56, 72, 72, 0] ``` ````
reference
def multiple_of_index(arr): return [j for i, j in enumerate(arr) if (j == 0 and i == 0) or (i != 0 and j % i == 0)]
Multiple of index
5a34b80155519e1a00000009
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a34b80155519e1a00000009
8 kyu
### Issue Looks like some hoodlum plumber and his brother has been running around and damaging your stages again. The `pipes` connecting your level's stages together need to be fixed before you receive any more complaints. The `pipes` are correct when each `pipe` after the first is `1` more than the previous one. ### Task Given a list of unique `numbers` sorted in ascending order, return a new list so that the values increment by 1 for each index from the minimum value up to the maximum value (both included). ### Example `Input: 1,3,5,6,7,8` `Output: 1,2,3,4,5,6,7,8`
reference
def pipe_fix(nums): return list(range(nums[0], nums[- 1] + 1))
Lario and Muigi Pipe Problem
56b29582461215098d00000f
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/56b29582461215098d00000f
8 kyu
Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love. Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren't.
reference
def lovefunc(flower1, flower2): return (flower1 + flower2) % 2
Opposites Attract
555086d53eac039a2a000083
[ "Fundamentals" ]
https://www.codewars.com/kata/555086d53eac039a2a000083
8 kyu
In a small town the population is `p0 = 1000` at the beginning of a year. The population regularly increases by `2 percent` per year and moreover `50` new inhabitants per year come to live in the town. How many years does the town need to see its population greater than or equal to `p = 1200` inhabitants? ``` At the end of the first year there will be: 1000 + 1000 * 0.02 + 50 => 1070 inhabitants At the end of the 2nd year there will be: 1070 + 1070 * 0.02 + 50 => 1141 inhabitants (** number of inhabitants is an integer **) At the end of the 3rd year there will be: 1141 + 1141 * 0.02 + 50 => 1213 It will need 3 entire years. ``` More generally given parameters: `p0, percent, aug (inhabitants coming or leaving each year), p (population to equal or surpass)` the function `nb_year` should return `n` number of entire years needed to get a population greater or equal to `p`. aug is an integer, percent a positive or null floating number, p0 and p are positive integers (> 0) ``` Examples: nb_year(1500, 5, 100, 5000) -> 15 nb_year(1500000, 2.5, 10000, 2000000) -> 10 ``` #### Note: * Don't forget to convert the percent parameter as a percentage in the body of your function: if the parameter percent is 2 you have to convert it to 0.02. * There are no fractions of people. At the end of each year, the population count is an integer: `252.8` people round down to `252` persons.
reference
def nb_year(p0, percent, aug, p): t = 0 while p0 < p: # my mathematical brain hates that I need to round this p0 = int(p0 * (1 + percent / 100)) + aug t += 1 return t
Growth of a Population
563b662a59afc2b5120000c6
[ "Fundamentals" ]
https://www.codewars.com/kata/563b662a59afc2b5120000c6
7 kyu
It's the academic year's end, fateful moment of your school report. The averages must be calculated. All the students come to you and entreat you to calculate their average for them. Easy ! You just need to write a script. Return the average of the given array rounded **down** to its nearest integer. The array will never be empty.
algorithms
def get_average(marks): return sum(marks) / / len(marks)
Get the mean of an array
563e320cee5dddcf77000158
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/563e320cee5dddcf77000158
8 kyu
Write function RemoveExclamationMarks which removes all exclamation marks from a given string.
reference
def remove_exclamation_marks(s): return s . replace('!', '')
Remove exclamation marks
57a0885cbb9944e24c00008e
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57a0885cbb9944e24c00008e
8 kyu
Given an array of integers. Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers. 0 is neither positive nor negative. If the input is an empty array or is null, return an empty array. # Example For input `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]`, you should return `[10, -65]`.
reference
def count_positives_sum_negatives(arr): if not arr: return [] pos = 0 neg = 0 for x in arr: if x > 0: pos += 1 if x < 0: neg += x return [pos, neg]
Count of positives / sum of negatives
576bb71bbbcf0951d5000044
[ "Fundamentals", "Arrays", "Lists" ]
https://www.codewars.com/kata/576bb71bbbcf0951d5000044
8 kyu
In this simple exercise, you will create a program that will take two lists of integers, `a` and `b`. Each list will consist of 3 positive integers above 0, representing the dimensions of cuboids `a` and `b`. You must find the difference of the cuboids' volumes regardless of which is bigger. For example, if the parameters passed are `([2, 2, 3], [5, 4, 1])`, the volume of `a` is 12 and the volume of `b` is 20. Therefore, the function should return 8. Your function will be tested with pre-made examples as well as random ones. ~~~if-not:cobol **If you can, try writing it in one line of code.** ~~~
reference
from numpy import prod def find_difference(a, b): return abs(prod(a) - prod(b))
Difference of Volumes of Cuboids
58cb43f4256836ed95000f97
[ "Fundamentals" ]
https://www.codewars.com/kata/58cb43f4256836ed95000f97
8 kyu
Removed due to copyright infringement. <!-- This kata is from check py.checkio.org You are given an array with positive numbers and a non-negative number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first element has the index 0. Let's look at a few examples: ~~~if-not:factor * array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9; * array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1. ~~~ ~~~if:factor * `{ 1 2 3 4 } :> array` and `2 :> n`, then the result is `3 2 ^ -> 9`; * `{ 1 2 3 } :> array` and `3 :> n`, but N is outside of the array, so the result is `-1`. ~~~ -->
reference
def index(array, n): try: return array[n] * * n except: return - 1
N-th Power
57d814e4950d8489720008db
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/57d814e4950d8489720008db
8 kyu
You're going to provide a needy programmer a utility method that generates an infinite amount of sequential fibonacci numbers. ~~~if:java to do this return an `IntStream` starting with 1 ~~~ ~~~if:typescript to do this return an `Iterator<BigInt> ` starting with 1 ~~~ ~~~if:javascript to do this return an `Iterator<BigInt>` starting with 1 ~~~ ~~~if:python to do this write a 'generator' starting with 1 ~~~ ~~~if:rust to do this write a function returning an `Iterator<Item = BigUint>` starting with 1 ~~~ ~~~if:ocaml to do this create an infinite sequence of big integers (from the `Z` module) with the `Seq` module ~~~ A fibonacci sequence starts with two `1`s. Every element afterwards is the sum of the two previous elements. See: 1, 1, 2, 3, 5, 8, 13, ..., 89, 144, 233, 377, ...
algorithms
def all_fibonacci_numbers(a=0, b=1): while 1: yield b a, b = b, a + b
Fibonacci Streaming
55695bc4f75bbaea5100016b
[ "Algorithms" ]
https://www.codewars.com/kata/55695bc4f75bbaea5100016b
5 kyu
Complete the method/function so that it converts dash/underscore delimited words into [camel casing](https://en.wikipedia.org/wiki/Camel_case). The first word within the output should be capitalized **only** if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case). The next words should be always capitalized. ### Examples `"the-stealth-warrior"` gets converted to `"theStealthWarrior"` `"The_Stealth_Warrior"` gets converted to `"TheStealthWarrior"` `"The_Stealth-Warrior"` gets converted to `"TheStealthWarrior"`
algorithms
def to_camel_case(text): removed = text . replace('-', ' '). replace('_', ' '). split() if len(removed) == 0: return '' return removed[0] + '' . join([x . capitalize() for x in removed[1:]])
Convert string to camel case
517abf86da9663f1d2000003
[ "Regular Expressions", "Algorithms", "Strings" ]
https://www.codewars.com/kata/517abf86da9663f1d2000003
6 kyu
```if-not:perl You will be given an `array` and a `limit` value. You must check that all values in the array are below or equal to the limit value. If they are, return `true`. Else, return `false`. ``` ```if:perl You will be given an `array` and a `limit` value. You must check that all values in the array are below or equal to the limit value. If they are, return `1`. Else, return `0`. ``` You can assume all values in the array are numbers.
reference
def small_enough(array, limit): return max(array) <= limit
Small enough? - Beginner
57cc981a58da9e302a000214
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/57cc981a58da9e302a000214
7 kyu
Given a number `n`, return the number of positive odd numbers below `n`, EASY! ### Examples (Input -> Output) ``` 7 -> 3 (because odd numbers below 7 are [1, 3, 5]) 15 -> 7 (because odd numbers below 15 are [1, 3, 5, 7, 9, 11, 13]) ``` Expect large Inputs! ~~~if:lambdacalc Use `numEncoding BinaryScott` ~~~ ~~~if:bf **Note for Brainfuck:** Input 5 means the input will be a character with ASCII code 5, not the character '5'. Output similarly. The valid input range is 0 <= input <= 127, in order to avoid differences between ASCII and Unicode. You will never have to read more than one byte. ~~~
games
def oddCount(n): return n / / 2
Count Odd Numbers below n
59342039eb450e39970000a6
[ "Performance", "Mathematics" ]
https://www.codewars.com/kata/59342039eb450e39970000a6
8 kyu
# Triple Trouble Create a function that will return a string that combines all of the letters of the three inputed strings in groups. Taking the first letter of all of the inputs and grouping them next to each other. Do this for every letter, see example below! **E.g. Input: "aa", "bb" , "cc" => Output: "abcabc"** *Note: You can expect all of the inputs to be the same length.*
games
def triple_trouble(one, two, three): return '' . join('' . join(a) for a in zip(one, two, three))
Triple Trouble
5704aea738428f4d30000914
[ "Puzzles" ]
https://www.codewars.com/kata/5704aea738428f4d30000914
8 kyu
# Disclaimer This Kata is an insane step-up from [Avanta's Kata](https://www.codewars.com/kata/coloured-triangles), so I recommend to solve it first before trying this one. # Problem Description A coloured triangle is created from a row of colours, each of which is red, green or blue. Successive rows, each containing one fewer colour than the last, are generated by considering the two touching colours in the previous row. If these colours are identical, the same colour is used in the new row. If they are different, the missing colour is used in the new row. This is continued until the final row, with only a single colour, is generated. For example, different possibilities are: ``` Colour here: G G B G R G B R Becomes colour here: G R B G ``` With a bigger example: ``` R R G B R G B B R B R G B R B G G B R G G G R G B G B B R R B G R R B G ``` You will be given the first row of the triangle as a string and its your job to return the final colour which would appear in the bottom row as a string. In the case of the example above, you would be given 'RRGBRGBB', and you should return 'G'. # Constraints `1 <= length(row) <= 10 ** 5` The input string will only contain the uppercase letters 'B', 'G' or 'R'. The exact number of test cases will be as follows: * `100` tests of `100 <= length(row) <= 1000` * `100` tests of `1000 <= length(row) <= 10000` * `100` tests of `10000 <= length(row) <= 100000` # Examples ```javascript triangle('B') == 'B' triangle('GB') == 'R' triangle('RRR') == 'R' triangle('RGBG') == 'B' triangle('RBRGBRB') == 'G' triangle('RBRGBRBGGRRRBGBBBGG') == 'G' ``` ```python triangle('B') == 'B' triangle('GB') == 'R' triangle('RRR') == 'R' triangle('RGBG') == 'B' triangle('RBRGBRB') == 'G' triangle('RBRGBRBGGRRRBGBBBGG') == 'G' ``` ```ruby triangle('B') == 'B' triangle('GB') == 'R' triangle('RRR') == 'R' triangle('RGBG') == 'B' triangle('RBRGBRB') == 'G' triangle('RBRGBRBGGRRRBGBBBGG') == 'G' ``` ```java Kata.triangle("B") == 'B' Kata.triangle("GB") == 'R' Kata.triangle("RRR") == 'R' Kata.triangle("RGBG") == 'B' Kata.triangle("RBRGBRB") == 'G' Kata.triangle("RBRGBRBGGRRRBGBBBGG") == 'G' ``` ```cpp triangle("B") == 'B'; triangle("GB") == 'R'; triangle("RRR") == 'R'; triangle("RGBG") == 'B'; triangle("RBRGBRB") == 'G'; triangle("RBRGBRBGGRRRBGBBBGG") == 'G'; ``` ```haskell -- Input will actually be `Vector Char` instead of `[Char]`. You'll need the access speed. triangle "B" == 'B' triangle "GB" == 'R' triangle "RRR" == 'R' triangle "RGBG" == 'B' triangle "RBRGBRB" == 'G' triangle "RBRGBRBGGRRRBGBBBGG" == 'G' ``` ```elixir Kata.triangle("B") == "B" Kata.triangle("GB") == "R" Kata.triangle("RRR") == "R" Kata.triangle("RGBG") == "B" Kata.triangle("RBRGBRB") == "G" Kata.triangle("RBRGBRBGGRRRBGBBBGG") == "G" ``` ```commonlisp (equal (triangle "B") #\B) (equal (triangle "GB") #\R) (equal (triangle "RRR") #\R) (equal (triangle "RGBG") #\B) (equal (triangle "RBRGBRB") #\G) (equal (triangle "RBRGBRBGGRRRBGBBBGG") #\G) ```
games
def triangle(row): def reduce(a, b): return a if a == b else (set('RGB') - {a, b}). pop() def walk(offset, root, depth): return row[root] if not depth else curry(offset, root, * divmod(depth, 3)) def curry(offset, root, depth, degree): return walk(3 * offset, root, depth) if not degree \ else reduce(curry(offset, root, depth, degree - 1), curry(offset, root + offset, depth, degree - 1)) return walk(1, 0, len(row) - 1)
Insane Coloured Triangles
5a331ea7ee1aae8f24000175
[ "Puzzles", "Performance", "Mathematics" ]
https://www.codewars.com/kata/5a331ea7ee1aae8f24000175
2 kyu
In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out. ### Example ```python filter_list([1,2,'a','b']) == [1,2] filter_list([1,'a','b',0,15]) == [1,0,15] filter_list([1,2,'aasf','1','123',123]) == [1,2,123] ``` ```csharp ListFilterer.GetIntegersFromList(new List<object>(){1, 2, "a", "b"}) => {1, 2} ListFilterer.GetIntegersFromList(new List<object>(){1, "a", "b", 0, 15}) => {1, 0, 15} ListFilterer.GetIntegersFromList(new List<object>(){1, 2, "a", "b", "aasf", "1", "123", 123}) => {1, 2, 231} ``` ```factor { 1 2 "a" "b" } filter-seq ! { 1 2 } { 1 "a" "b" 0 15 } filter-seq ! { 1 0 15 } { 1 2 "aasf" "1" "123" 123 } filter-seq ! { 1 2 123 } ``` ```java Kata.filterList(List.of(1, 2, "a", "b")) => List.of(1,2) Kata.filterList(List.of(1, "a", "b", 0, 15)) => List.of(1,0,15) Kata.filterList(List.of(1, 2, "a", "b", "aasf", "1", "123", 123)) => List.of(1, 2, 123) ``` ```scala filterList(List(1, 2, "a", "b")) == List(1, 2) filterList(List(1, "a", "b", 0, 15)) == List(1, 0, 15) filterList(List(1, 2, "aasf", "1", "123", 123)) == List(1, 2, 123) ``` ```kotlin filterList(ListOf(1, 2, "a", "b")) == [1, 2] filterList(ListOf(1, "a", "b", 0, 15)) == [1, 0, 15] filterList(ListOf(1, 2, "a", "b", "aasf", "1", "123", 123)) == [1, 2, 123] ```
reference
def filter_list(l): 'return a new list with the strings filtered out' return [i for i in l if not isinstance(i, str)]
List Filtering
53dbd5315a3c69eed20002dd
[ "Lists", "Filtering", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/53dbd5315a3c69eed20002dd
7 kyu
When provided with a number between 0-9, return it in words. Input :: 1 Output :: "One". If your language supports it, try using a <a href="https://en.wikipedia.org/wiki/Switch_statement">switch statement</a>.
reference
def switch_it_up(n): return ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'][n]
Switch it Up!
5808dcb8f0ed42ae34000031
[ "Fundamentals" ]
https://www.codewars.com/kata/5808dcb8f0ed42ae34000031
8 kyu
You get an array of numbers, return the sum of all of the positives ones. Example `[1,-4,7,12]` => `1 + 7 + 12 = 20` Note: if there is nothing to sum, the sum is default to `0`.
reference
def positive_sum(arr): return sum(x for x in arr if x > 0)
Sum of positive
5715eaedb436cf5606000381
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5715eaedb436cf5606000381
8 kyu
Philip's just turned four and he wants to know how old he will be in various years in the future such as 2090 or 3044. His parents can't keep up calculating this so they've begged you to help them out by writing a programme that can answer Philip's endless questions. Your task is to write a function that takes two parameters: the year of birth and the year to count years in relation to. As Philip is getting more curious every day he may soon want to know how many years it was until he would be born, so your function needs to work with both dates in the future and in the past. Provide output in this format: For dates in the future: "You are ... year(s) old." For dates in the past: "You will be born in ... year(s)." If the year of birth equals the year requested return: "You were born this very year!" "..." are to be replaced by the number, followed and proceeded by a single space. Mind that you need to account for both "year" and "years", depending on the result. Good Luck!
reference
def calculate_age(year_of_birth, current_year): diff = abs(current_year - year_of_birth) plural = '' if diff == 1 else 's' if year_of_birth < current_year: return 'You are {} year{} old.' . format(diff, plural) elif year_of_birth > current_year: return 'You will be born in {} year{}.' . format(diff, plural) return 'You were born this very year!'
How old will I be in 2099?
5761a717780f8950ce001473
[ "Fundamentals" ]
https://www.codewars.com/kata/5761a717780f8950ce001473
8 kyu
You have to write a function that describe Leo: ```python def leo(oscar): pass ``` ```javascript function leo(oscar) { } ``` ```elixir def leo(oscar) do # ... end ``` if oscar was (integer) 88, you have to return "Leo finally won the oscar! Leo is happy".</br> if oscar was 86, you have to return "Not even for Wolf of wallstreet?!"</br> if it was not 88 or 86 (and below 88) you should return "When will you give Leo an Oscar?"</br> if it was over 88 you should return "Leo got one already!"
reference
def leo(oscar): if oscar == 88: return "Leo finally won the oscar! Leo is happy" elif oscar == 86: return "Not even for Wolf of wallstreet?!" elif oscar < 88: return "When will you give Leo an Oscar?" elif oscar > 88: return "Leo got one already!"
Leonardo Dicaprio and Oscars
56d49587df52101de70011e4
[ "Fundamentals" ]
https://www.codewars.com/kata/56d49587df52101de70011e4
8 kyu
In this kata we want to convert a string into an integer. The strings simply represent the numbers in words. Examples: * "one" => 1 * "twenty" => 20 * "two hundred forty-six" => 246 * "seven hundred eighty-three thousand nine hundred and nineteen" => 783919 Additional Notes: * The minimum number is "zero" (inclusively) * The maximum number, which must be supported is 1 million (inclusively) * The "and" in e.g. "one hundred and twenty-four" is optional, in some cases it's present and in others it's not * All tested numbers are valid, you don't need to validate them
algorithms
ONES = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] def parse_int(string): print(string) numbers = [] for token in string . replace('-', ' '). split(' '): if token in ONES: numbers . append(ONES . index(token)) elif token in TENS: numbers . append((TENS . index(token) + 2) * 10) elif token == 'hundred': numbers[- 1] *= 100 elif token == 'thousand': numbers = [x * 1000 for x in numbers] elif token == 'million': numbers = [x * 1000000 for x in numbers] return sum(numbers)
parseInt() reloaded
525c7c5ab6aecef16e0001a5
[ "Parsing", "Strings", "Algorithms" ]
https://www.codewars.com/kata/525c7c5ab6aecef16e0001a5
4 kyu
## Enough is enough! Alice and Bob were on a holiday. Both of them took many pictures of the places they've been, and now they want to show Charlie their entire collection. However, Charlie doesn't like these sessions, since the motif usually repeats. He isn't fond of seeing the Eiffel tower 40 times. He tells them that he will only sit for the session if they show the same motif at most `N` times. Luckily, Alice and Bob are able to encode the motif as a number. Can you help them to remove numbers such that their list contains each number only up to `N` times, without changing the order? ## Task Given a list and a number, create a new list that contains each number of `list` at most `N` times, without reordering. For example if the input number is `2`, and the input list is `[1,2,3,1,2,1,2,3]`, you take `[1,2,3,1,2]`, drop the next `[1,2]` since this would lead to `1` and `2` being in the result `3` times, and then take `3`, which leads to `[1,2,3,1,2,3]`. With list `[20,37,20,21]` and number `1`, the result would be `[20,37,21]`. ~~~if:nasm ## NASM notes Write the output numbers into the `out` parameter, and return its length. The input array will contain only integers between 1 and 50 inclusive. Use it to your advantage. ~~~ ~~~if:c For C: * Assign the return array length to the pointer parameter `*szout`. * Do not mutate the input array. ~~~ ~~~if:lambdacalc ## Encodings purity: `LetRec` numEncoding: `Church` export constructors `nil, cons` and deconstructor `foldr` for your `List` encoding ~~~
reference
def delete_nth(order, max_e): ans = [] for o in order: if ans . count(o) < max_e: ans . append(o) return ans
Delete occurrences of an element if it occurs more than n times
554ca54ffa7d91b236000023
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/554ca54ffa7d91b236000023
6 kyu
Create a function taking a positive integer between `1` and `3999` (both included) 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 leftmost digit and skipping any digit with a value of zero. There cannot be more than 3 identical symbols in a row. 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: ``` 1 --> "I" 1000 --> "M" 1666 --> "MDCLXVI" ``` Help: ``` Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1,000 ``` [More about roman numerals](https://en.wikipedia.org/wiki/Roman_numerals)
algorithms
def solution(n): roman_numerals = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I' } roman_string = '' for key in sorted(roman_numerals . keys(), reverse=True): while n >= key: roman_string += roman_numerals[key] n -= key return roman_string
Roman Numerals Encoder
51b62bf6a9c58071c600001b
[ "Algorithms" ]
https://www.codewars.com/kata/51b62bf6a9c58071c600001b
6 kyu
Complete the function that accepts a string parameter, and reverses each word in the string. **All** spaces in the string should be retained. ## Examples ``` "This is an example!" ==> "sihT si na !elpmaxe" "double spaces" ==> "elbuod secaps" ```
reference
def reverse_words(str): return ' ' . join(s[:: - 1] for s in str . split(' '))
Reverse words
5259b20d6021e9e14c0010d4
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5259b20d6021e9e14c0010d4
7 kyu
We need a simple function that determines if a plural is needed or not. It should take a number, and return true if a plural should be used with that number or false if not. This would be useful when printing out a string such as `5 minutes`, `14 apples`, or `1 sun`. > You only need to worry about english grammar rules for this kata, where anything that isn't singular (one of something), it is plural (not one of something). All values will be positive integers or floats, or zero.
reference
def plural(n): return n != 1
Plural
52ceafd1f235ce81aa00073a
[ "Fundamentals" ]
https://www.codewars.com/kata/52ceafd1f235ce81aa00073a
8 kyu
The main idea is to count all the occurring characters in a string. If you have a string like `aba`, then the result should be `{'a': 2, 'b': 1}`. What if the string is empty? Then the result should be empty object literal, `{}`.
reference
from collections import Counter def count(string): return Counter(string)
Count characters in your string
52efefcbcdf57161d4000091
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/52efefcbcdf57161d4000091
6 kyu
The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details 8 + 1 = 9 and 9<sup>2</sup> = 81 512 = 5 + 1 + 2 = 8 and 8<sup>3</sup> = 512 We need to make a function that receives a number as argument ```n``` and returns the ```n-th term``` of this sequence of numbers. ### Examples (input --> output) ``` 1 --> 81 2 --> 512 ``` Happy coding!
reference
series = [0] for a in range(2, 99): for b in range(2, 42): c = a * * b if a == sum(map(int, str(c))): series . append(c) power_sumDigTerm = sorted(series). __getitem__
Numbers that are a power of their sum of digits
55f4e56315a375c1ed000159
[ "Algorithms", "Mathematics", "Sorting", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55f4e56315a375c1ed000159
5 kyu
Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. For example: (**Input --> Output**) ``` 10 --> 1 99 --> 18 -32 --> 5 ``` Let's assume that all numbers in the input will be integer values.
reference
def sumDigits(number): return sum(int(d) for d in str(abs(number)))
Summing a number's digits
52f3149496de55aded000410
[ "Fundamentals" ]
https://www.codewars.com/kata/52f3149496de55aded000410
7 kyu
A briefcase has a 4-digit **rolling-lock**. Each digit is a number from `0-9` that can be rolled either forwards or backwards. Create a function that returns the smallest number of turns it takes to transform the lock from the current combination to the target combination. One turn is equivalent to rolling a number forwards or backwards by one. To illustrate: - **current-lock**: 4089 - **target-lock**: 5672 What is the minimum number of turns it takes to transform `4089` to `5672`? ``` 4 ➞ 5 4 ➞ 5 // Forward Turns: 1 <- Min 4 ➞ 3 ➞ 2 ➞ 1 ➞ 0 ➞ 9 ➞ 8 ➞ 7 ➞ 6 ➞ 5 // Backward Turns: 9 0 ➞ 6 0 ➞ 1 ➞ 2 ➞ 3 ➞ 4 ➞ 5 ➞ 6 // Forward Turns: 6 0 ➞ 9 ➞ 8 ➞ 7 ➞ 6 // Backward Turns: 4 <- Min 8 ➞ 7 8 ➞ 9 ➞ 0 ➞ 1 ➞ 2 ➞ 3 ➞ 4 ➞ 5 ➞ 6 ➞ 7 // Forward Turns: 9 8 ➞ 7 // Backward Turns: 1 <- Min 9 ➞ 2 9 ➞ 0 ➞ 1 ➞ 2 // Forward Turns: 3 <- Min 9 ➞ 8 ➞ 7 ➞ 6 ➞ 5 ➞ 4 ➞ 3 ➞ 2 // Backward Turns: 7 ``` It takes `1 + 4 + 1 + 3 = 9` minimum turns to change the lock from `4089` to `5672`. ### Notes - Both locks are in string format. - A `9` rolls forward to `0`, and a `0` rolls backwards to a `9`.
games
def min_turns(current, target): total = 0 for i, j in zip(current, target): a, b = map(int, [i, j]) total += min(abs(a - b), 10 - abs(b - a)) return total
Briefcase Lock
64ef24b0679cdc004d08169e
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/64ef24b0679cdc004d08169e
7 kyu
# Palindromic Numbers A [palindromic number](http://en.wikipedia.org/wiki/Palindromic_number) is a number that remains the same when its digits are reversed. Like 16461, for example, it is "symmetrical". Non-palindromic numbers can be paired with palindromic ones via a series of operations. First, the non-palindromic number is reversed and the result is added to the original number. If the result is not a palindromic number, this is repeated until it gives a palindromic number. ## Lychrel Numbers It is not known whether all non-palindromic numbers can be paired with palindromic numbers in this way. While no number has been proven to be unpaired, many do not appear to be. For example, 196 does not yield a palindrome even after 700,000,000 iterations. Any number that never becomes palindromic in this way is known as a [Lychrel number](http://en.wikipedia.org/wiki/Lychrel_number). This Kata is about actually finding a palindromic number out of an original seed. You will be given a number as input and in the output you must return a string containing the number of iterations (i.e. additions) you had to perform to reach the palindromic result and the palindromic number itself, separated by a space. In Haskell return a tuple `(Int, Integer)`. ```mostlangs palindromize(195) == 4 9339 palindromize(265) == 5 45254 palindromize(750) == 3 6666 ``` ```haskell palindromize 195 == (4, 9339) palindromize 265 == (5, 45254) palindromize 750 == (3, 6666) palindromize 999999991 == (16,43559188195534) ``` ### Some Assumptions You can assume that all numbers provided as input will be actually paired with a palindromic result and that you will reach that result in less than 1000 iterations and yield a palindrome.
algorithms
def palindromize(number): new, n = number, 0 while str(new) != str(new)[:: - 1]: new += int(str(new)[:: - 1]) n += 1 return f' { n } { new } '
Palindromic Numbers
52a0f488852a85c723000aca
[ "Algorithms" ]
https://www.codewars.com/kata/52a0f488852a85c723000aca
6 kyu
The purpose of this kata is to write a higher-order function returning a new function that iterates on a specified function a given number of times. This new function takes in an argument as a seed to start the computation from. ```if-not:haskell For instance, consider the function `getDouble`. When run twice on value `3`, yields `12` as shown below. getDouble(3) => 6 getDouble(6) => 12 Let us name the new function `createIterator` and we should be able to obtain the same result using `createIterator` as shown below: var doubleIterator = createIterator(getDouble, 2); // This means, it runs *getDouble* twice doubleIterator(3) => 12 For the sake of simplicity, all function inputs to `createIterator` would be functions returning a small number and number of iterations would always be integers. ``` ```if:haskell For instance, consider `double = (* 2)`. When run twice on value `3`, it yields `12`: (double . double) 3 -> 12 Using `iterateN :: Int -> (a -> a) -> (a -> a)` we should be able to obtain the same result: doubleTwice = iterateN 2 double -- This means, it runs `double` twice doubleTwice 3 -> 12 Note that `iterateN` is related to `Prelude.iterate` and e.g. `Data.Sequence.iterateN`; however, it only returns one value instead of a list of them. ```
algorithms
def create_iterator(func, n): def f(x): for i in range(n): x = func(x) return x return f
Function iteration
54b679eaac3d54e6ca0008c9
[ "Algorithms" ]
https://www.codewars.com/kata/54b679eaac3d54e6ca0008c9
6 kyu
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher. Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation". ```if:python Please note that using `encode` is considered cheating. ``` ```if:r **Note:** As R is a natively vectorized language, you should write `rot13()` such that the argument `x` may be a character vector of any length. The return value should always be a character vector of the same length as `x`. ```
reference
import string from codecs import encode as _dont_use_this_ def rot13(message): alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" outputMessage = "" for letter in message: if letter in alpha . lower(): outputMessage += alpha[(alpha . lower(). index(letter) + 13) % 26]. lower() elif letter in alpha: outputMessage += alpha[(alpha . index(letter) + 13) % 26] else: outputMessage += letter return outputMessage
Rot13
530e15517bc88ac656000716
[ "Ciphers", "Fundamentals" ]
https://www.codewars.com/kata/530e15517bc88ac656000716
5 kyu