description stringlengths 38 154k | category stringclasses 5
values | solutions stringlengths 13 289k | name stringlengths 3 179 | id stringlengths 24 24 | tags listlengths 0 13 | url stringlengths 54 54 | rank_name stringclasses 8
values |
|---|---|---|---|---|---|---|---|
One man (lets call him Eulampy) has a collection of some almost identical Fabergé eggs. One day his friend Tempter said to him:
> + Do you see that skyscraper? And can you tell me a maximal floor that if you drop your egg from will not crack it?
> + No, - said Eulampy.
> + But if you give me N eggs, - says Tempter - I... | algorithms | def height(n, m):
h, t = 0, 1
for i in range(1, n + 1):
t = t * (m - i + 1) / / i
h += t
return h
| Fabergé Easter Eggs crush test | 54cb771c9b30e8b5250011d4 | [
"Mathematics",
"Dynamic Programming",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/54cb771c9b30e8b5250011d4 | 3 kyu |
This kata focuses on the Numpy python package and you can read up on the Numpy array manipulation functions here: https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.array-manipulation.html
You will get two integers `N` and `M`. You must return an array with two sub-arrays with numbers in ranges `[0, N / 2)` an... | reference | import numpy as np
def reorder(a, b):
return np . roll(np . arange(a). reshape(2, - 1), b, 1). tolist()
| Reorder Array 2 | 5a48fab7bdb9b5b3690009b6 | [
"NumPy",
"Fundamentals"
] | https://www.codewars.com/kata/5a48fab7bdb9b5b3690009b6 | 6 kyu |
You task is to implement an simple interpreter for the notorious esoteric language [HQ9+](https://esolangs.org/wiki/HQ9+) that will work for a single character input:
- If the input is `'H'`, return `'Hello World!'`
- If the input is `'Q'`, return the input
- If the input is `'9'`, return the full lyrics of [99 Bottle... | reference | LINES = "{0} of beer on the wall, {0} of beer.\nTake one down and pass it around, {1} of beer on the wall."
SONG = '\n' . join(LINES . format("{} bottles" . format(
n), "{} bottle" . format(n - 1) + "s" * (n != 2)) for n in range(99, 1, - 1))
SONG += """
1 bottle of beer on the wall, 1 bottle of beer.
Take one ... | 8kyu interpreters: HQ9+ | 591588d49f4056e13f000001 | [
"Fundamentals"
] | https://www.codewars.com/kata/591588d49f4056e13f000001 | 8 kyu |
### Sudoku Background
Sudoku is a game played on a 9x9 grid. The goal of the game is to fill all cells of the grid with digits from 1 to 9, so that each column, each row, and each of the nine 3x3 sub-grids (also known as blocks) contain all of the digits from 1 to 9. <br/>
(More info at: http://en.wikipedia.org/wiki/S... | algorithms | correct = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def validSolution(board):
# check rows
for row in board:
if sorted(row) != correct:
return False
# check columns
for column in zip(* board):
if sorted(column) != correct:
return False
# check regions
for i in range(3):
for... | Sudoku Solution Validator | 529bf0e9bdf7657179000008 | [
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/529bf0e9bdf7657179000008 | 4 kyu |
What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:
```
'abba' & 'baab' == true
'abba' & 'bbaa' == true
'abba' & 'abbba' == false
'abba' & 'abca' == false
```
Write a function that will find all the anagrams of a word from a list. You will be given two... | algorithms | def anagrams(word, words): return [
item for item in words if sorted(item) == sorted(word)]
| Where my anagrams at? | 523a86aa4230ebb5420001e1 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/523a86aa4230ebb5420001e1 | 5 kyu |
Alex just got a new hula hoop, he loves it but feels discouraged because his little brother is better than him
Write a program where Alex can input (n) how many times the hoop goes round and it will return him an encouraging message :)
- If Alex gets 10 or more hoops, return the string "Great, now move on to tricks"... | reference | def hoopCount(n):
return "Keep at it until you get it" if n < 10 else "Great, now move on to tricks"
| Keep up the hoop | 55cb632c1a5d7b3ad0000145 | [
"Fundamentals"
] | https://www.codewars.com/kata/55cb632c1a5d7b3ad0000145 | 8 kyu |
Your task is to find the nearest square number, `nearest_sq(n)` or `nearestSq(n)`, of a positive integer `n`.
For example, if `n = 111`, then `nearest\_sq(n)` (`nearestSq(n)`) equals 121, since 111 is closer to 121, the square of 11, than 100, the square of 10.
If the `n` is already the perfect square (e.g. `n = 144`... | reference | def nearest_sq(n):
return round(n * * 0.5) * * 2
| Find Nearest square number | 5a805d8cafa10f8b930005ba | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5a805d8cafa10f8b930005ba | 8 kyu |
Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for [some of his philosophy that he delivers via Twitter](https://twitter.com/jaden). When writing on Twitter, he is known for almost always capitalizing every word. For simplicity, you'll ... | reference | def to_jaden_case(string):
return ' ' . join(word . capitalize() for word in string . split())
| Jaden Casing Strings | 5390bac347d09b7da40006f6 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5390bac347d09b7da40006f6 | 7 kyu |
<div style="border:1px solid;position:relative;padding:1ex 1ex 1ex 11.1em;"><div style="position:absolute;left:0;top:0;bottom:0; width:10em; padding:1ex;text-align:center;border:1px solid;margin:0 1ex 0 0;color:#000;background-color:#eee;font-variant:small-caps">Part of Series 1/3</div><div>This kata is part of a serie... | algorithms | def decodeMorse(morseCode):
return ' ' . join('' . join(MORSE_CODE[letter] for letter in word . split(' ')) for word in morseCode . strip(). split(' '))
| Decode the Morse code | 54b724efac3d5402db00065e | [
"Algorithms"
] | https://www.codewars.com/kata/54b724efac3d5402db00065e | 6 kyu |
Complete the solution so that it reverses all of the words within the string passed in.
Words are separated by exactly one space and there are no leading or trailing spaces.
**Example(Input --> Output):**
```
"The greatest victory is that which requires no battle" --> "battle no requires which that is victory greates... | algorithms | def reverseWords(str):
return " " . join(str . split(" ")[:: - 1])
| Reversed Words | 51c8991dee245d7ddf00000e | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/51c8991dee245d7ddf00000e | 8 kyu |
You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you ... | reference | def isValidWalk(walk):
return len(walk) == 10 and walk . count('n') == walk . count('s') and walk . count('e') == walk . count('w')
| Take a Ten Minutes Walk | 54da539698b8a2ad76000228 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/54da539698b8a2ad76000228 | 6 kyu |
The wide-mouth frog is particularly interested in the eating habits of other creatures.
He just can't stop asking the creatures he encounters what they like to eat. But, then he meets the alligator who just LOVES to eat wide-mouthed frogs!
When he meets the alligator, it then makes a tiny mouth.
Your goal in this ka... | reference | def mouth_size(animal):
return 'small' if animal . lower() == 'alligator' else 'wide'
| The Wide-Mouthed frog! | 57ec8bd8f670e9a47a000f89 | [
"Strings",
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/57ec8bd8f670e9a47a000f89 | 8 kyu |
Complete the method that takes a boolean value and return a `"Yes"` string for `true`, or a `"No"` string for `false`.
| reference | def bool_to_word(bool):
return "Yes" if bool else "No"
| Convert boolean values to strings 'Yes' or 'No'. | 53369039d7ab3ac506000467 | [
"Fundamentals"
] | https://www.codewars.com/kata/53369039d7ab3ac506000467 | 8 kyu |
Given an array of ones and zeroes, convert the equivalent binary value to an integer.
Eg: `[0, 0, 0, 1]` is treated as `0001` which is the binary representation of `1`.
Examples:
```
Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] =... | reference | def binary_array_to_number(arr):
return int("" . join(map(str, arr)), 2)
| Ones and Zeros | 578553c3a1b8d5c40300037c | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/578553c3a1b8d5c40300037c | 7 kyu |
Build a function that returns an array of integers from n to 1 where ```n>0```.
Example : `n=5` --> `[5,4,3,2,1]`
~~~if:nasm
*NOTE: In NASM, the function signature is* `int *reverse_seq(int n, size_t *size)` *where the first parameter* `n` *is as described above and the second parameter* `size` *is a pointer to an "o... | reference | def reverseseq(n):
return list(range(n, 0, - 1))
| Reversed sequence | 5a00e05cc374cb34d100000d | [
"Fundamentals"
] | https://www.codewars.com/kata/5a00e05cc374cb34d100000d | 8 kyu |
Simple challenge - eliminate all bugs from the supplied code so that the code runs and outputs the expected value. Output should be the length of the longest word, as a number.
There will only be one 'longest' word. | bug_fixes | def find_longest(strng):
return max(len(a) for a in strng . split())
| Squash the bugs | 56f173a35b91399a05000cb7 | [
"Debugging",
"Fundamentals"
] | https://www.codewars.com/kata/56f173a35b91399a05000cb7 | 8 kyu |
# Exclusive "or" (xor) Logical Operator
## Overview
In some scripting languages like PHP, there exists a logical operator (e.g. `&&`, `||`, `and`, `or`, etc.) called the "Exclusive Or" (hence the name of this Kata). The exclusive or evaluates two booleans. It then returns `true` if **exactly one of the two expressi... | reference | def xor(a, b):
return a != b
| Exclusive "or" (xor) Logical Operator | 56fa3c5ce4d45d2a52001b3c | [
"Fundamentals"
] | https://www.codewars.com/kata/56fa3c5ce4d45d2a52001b3c | 8 kyu |
You are provided with a function of the form `f(x) = axⁿ`, that consists of a single term only and 'a' and 'n' are integers, e.g `f(x) = 3x²`, `f(x) = 5` etc.
Your task is to create a function that takes f(x) as the argument and returns the result of differentiating the function, that is, the derivative.
If `$ f(x) =... | algorithms | from re import compile
REGEX = compile(r"(-?\d*)(x?)\^?(-?\d*)"). fullmatch
def differentiate(poly):
a, x, n = REGEX(poly). groups()
a, n = int(- 1 if a == '-' else a or 1), int(n or bool(x))
if n == 0 or n == 1:
return f" { a * n } "
if n == 2:
return f" { a * n } x"
return f" { a... | Derivatives of type x^n | 55e2de13b668981d3300003d | [
"Mathematics"
] | https://www.codewars.com/kata/55e2de13b668981d3300003d | 6 kyu |
Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it.
Your task is to write a function `maskify`, which chan... | algorithms | # return masked string
def maskify(cc):
return "#" * (len(cc) - 4) + cc[- 4:]
| Credit Card Mask | 5412509bd436bd33920011bc | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5412509bd436bd33920011bc | 7 kyu |
Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return `true` if the string is valid, and `false` if it's invalid.
This Kata is similar to the [Valid Parentheses](https://www.codewars.com/kata/valid-parentheses-1) Kata, but introduces new characters: brack... | algorithms | def validBraces(string):
braces = {"(": ")", "[": "]", "{": "}"}
stack = []
for character in string:
if character in braces . keys():
stack . append(character)
else:
if len(stack) == 0 or braces[stack . pop()] != character:
return False
return len(stack) == 0
| Valid Braces | 5277c8a221e209d3f6000b56 | [
"Algorithms"
] | https://www.codewars.com/kata/5277c8a221e209d3f6000b56 | 6 kyu |
Write a function which calculates the average of the numbers in a given list.
**Note:** Empty arrays should return 0. | reference | def find_average(array):
return sum(array) / len(array) if array else 0
| Calculate average | 57a2013acf1fa5bfc4000921 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/57a2013acf1fa5bfc4000921 | 8 kyu |
*Inspired by the [Fold an Array](https://www.codewars.com/kata/fold-an-array) kata. This one is sort of similar but a little different.*
---
## Task
You will receive an array as parameter that contains 1 or more integers and a number `n`.
Here is a little visualization of the process:
* Step 1: Split the array in t... | algorithms | def split_and_add(numbers, n):
for _ in range(n):
middle = len(numbers) / / 2
left = numbers[: middle]
right = numbers[middle:]
numbers = [a + b for a,
b in zip((len(right) - len(left)) * [0] + left, right)]
if len(numbers) == 1:
return numbers
return numbers
| Split and then add both sides of an array together. | 5946a0a64a2c5b596500019a | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5946a0a64a2c5b596500019a | 6 kyu |
A normal deck of 52 playing cards contains suits `'H', 'C', 'D', 'S'` - Hearts, Clubs, Diamonds, Spades respectively - and cards with values from Ace (1) to King (13): `1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13`
## Your Task
Complete the function that returns a shuffled deck of 52 playing cards without repeats.
Each... | reference | from random import shuffle
def shuffled_deck():
arr = [f' { x } { i } ' for x in "HCDS" for i in range(1, 14)]
shuffle(arr)
return arr
| Deal a Shuffled Deck of Cards | 5810ad962b321bac8f000178 | [
"Fundamentals"
] | https://www.codewars.com/kata/5810ad962b321bac8f000178 | 6 kyu |
Nathan loves cycling.
Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling.
You get given the time in hours and you need to return the number of litres Nathan will drink, rounded to the smallest value.
For example:
~~~if-not:sql
```
time = 3 ----> litres = 1
time... | reference | def litres(time):
return time / / 2
| Keep Hydrated! | 582cb0224e56e068d800003c | [
"Algorithms",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/582cb0224e56e068d800003c | 8 kyu |
Create a function that gives a personalized greeting. This function takes two parameters: `name` and `owner`.
Use conditionals to return the proper message:
case | return
--- | ---
name equals owner | 'Hello boss'
otherwise | 'Hello guest'
| reference | def greet(name, owner):
return "Hello boss" if name == owner else "Hello guest"
| Grasshopper - Personalized Message | 5772da22b89313a4d50012f7 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5772da22b89313a4d50012f7 | 8 kyu |
The fusc function is defined recursively as follows:
1. fusc(0) = 0
2. fusc(1) = 1
3. fusc(2 * n) = fusc(n)
4. fusc(2 * n + 1) = fusc(n) + fusc(n + 1)
The 4 rules above are sufficient to determine the value of `fusc` for any non-negative input `n`. For example, let's say you want to compute `fusc... | algorithms | def fusc(n):
assert type(n) == int and n >= 0
if n < 2:
return n
if n % 2 == 0:
return fusc(n / / 2)
else:
return fusc(n / / 2) + fusc(n / / 2 + 1)
| The fusc function -- Part 1 | 570409d3d80ec699af001bf9 | [
"Algorithms"
] | https://www.codewars.com/kata/570409d3d80ec699af001bf9 | 7 kyu |
~~~if-not:sql,shell
Create a function that takes an integer as an argument and returns `"Even"` for even numbers or `"Odd"` for odd numbers.
~~~
~~~if:sql
You will be given a table `numbers`, with one column `number`.</br>
Return a dataset with two columns: `number` and `is_even`, where `number` contains the original... | reference | def even_or_odd(number):
return 'Odd' if number % 2 else 'Even'
| Even or Odd | 53da3dbb4a5168369a0000fe | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/53da3dbb4a5168369a0000fe | 8 kyu |
Write a function named `setAlarm`/`set_alarm`/`set-alarm`/`setalarm` (depending on language) which receives two parameters. The first parameter, `employed`, is true whenever you are employed and the second parameter, `vacation` is true whenever you are on vacation.
The function should return true if you are employed ... | reference | def set_alarm(employed, vacation):
return employed and not vacation
| L1: Set Alarm | 568dcc3c7f12767a62000038 | [
"Fundamentals",
"Logic"
] | https://www.codewars.com/kata/568dcc3c7f12767a62000038 | 8 kyu |
You and a friend have decided to play a game to drill your statistical intuitions. The game works like this:
You have a bunch of red and blue marbles. To start the game you grab a handful of marbles of each color and put them into the bag, keeping track of how many of each color go in. You take turns reaching into the... | reference | def guess_blue(blue_start, red_start, blue_pulled, red_pulled):
blue_remaining = blue_start - blue_pulled
red_remaining = red_start - red_pulled
return blue_remaining / (blue_remaining + red_remaining)
| Thinkful - Number Drills: Blue and red marbles | 5862f663b4e9d6f12b00003b | [
"Probability",
"Fundamentals"
] | https://www.codewars.com/kata/5862f663b4e9d6f12b00003b | 8 kyu |
Mr. Scrooge has a sum of money 'P' that he wants to invest. Before he does, he wants to know how many years 'Y' this sum 'P' has to be kept in the bank in order for it to amount to a desired sum of money 'D'.
The sum is kept for 'Y' years in the bank where interest 'I' is paid yearly. After paying taxes 'T' for the ye... | reference | def calculate_years(principal, interest, tax, desired):
years = 0
while principal < desired:
principal += (interest * principal) * (1 - tax)
years += 1
return years
| Money, Money, Money | 563f037412e5ada593000114 | [
"Fundamentals"
] | https://www.codewars.com/kata/563f037412e5ada593000114 | 7 kyu |
Given an array of integers your solution should find the smallest integer.
For example:
- Given `[34, 15, 88, 2]` your solution will return `2`
- Given `[34, -345, -1, 100]` your solution will return `-345`
You can assume, for the purpose of this kata, that the supplied array will not be empty.
| reference | def findSmallestInt(arr):
return min(arr)
| Find the smallest integer in the array | 55a2d7ebe362935a210000b2 | [
"Fundamentals"
] | https://www.codewars.com/kata/55a2d7ebe362935a210000b2 | 8 kyu |
# Instructions
Given a mathematical expression as a string you must return the result as a number.
## Numbers
Number may be both whole numbers and/or decimal numbers. The same goes for the returned result.
## Operators
You need to support the following mathematical operators:
* Multiplication `*`
* Division `/` (... | algorithms | import re
from operator import mul, truediv as div, add, sub
OPS = {'*': mul, '/': div, '-': sub, '+': add}
def calc(expression):
tokens = re . findall(r'[.\d]+|[()+*/-]', expression)
return parse_AddSub(tokens, 0)[0]
def parse_AddSub(tokens, iTok):
v, iTok = parse_MulDiv(tokens, iTok)
... | Evaluate mathematical expression | 52a78825cdfc2cfc87000005 | [
"Mathematics",
"Parsing",
"Algorithms"
] | https://www.codewars.com/kata/52a78825cdfc2cfc87000005 | 2 kyu |
## Find Mean
Find the mean (average) of a list of numbers in an array.
## Information
To find the mean (average) of a set of numbers add all of the numbers together and divide by the number of values in the list.
For an example list of `1, 3, 5, 7`
<span>1.</span> Add all of the numbers
```
1+3+5+7 = 16
```
<spa... | reference | def find_average(nums):
return sum(nums) / len(nums) if nums else 0
| Grasshopper - Array Mean | 55d277882e139d0b6000005d | [
"Arrays",
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/55d277882e139d0b6000005d | 8 kyu |
Write a program that will calculate the number of trailing zeros in a factorial of a given number.
`N! = 1 * 2 * 3 * ... * N`
Be careful `1000!` has 2568 digits...
For more info, see: http://mathworld.wolfram.com/Factorial.html
## Examples
```python
zeros(6) = 1
# 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing ... | algorithms | def zeros(n):
"""
No factorial is going to have fewer zeros than the factorial of a smaller
number.
Each multiple of 5 adds a 0, so first we count how many multiples of 5 are
smaller than `n` (`n // 5`).
Each multiple of 25 adds two 0's, so next we add another 0 for each multiple
of 25... | Number of trailing zeros of N! | 52f787eb172a8b4ae1000a34 | [
"Algorithms",
"Logic",
"Mathematics"
] | https://www.codewars.com/kata/52f787eb172a8b4ae1000a34 | 5 kyu |
Your friend has been out shopping for puppies (what a time to be alive!)... He arrives back with multiple dogs, and you simply do not know how to respond!
By repairing the function provided, you will find out exactly how you should respond, depending on the number of dogs he has.
The number of dogs will always be a n... | bug_fixes | def how_many_dalmatians(n):
dogs = ["Hardly any", "More than a handful!",
"Woah that's a lot of dogs!", "101 DALMATIONS!!!"]
return dogs[0] if n <= 10 else dogs[1] if n <= 50 else dogs[3] if n == 101 else dogs[2]
| 101 Dalmatians - squash the bugs, not the dogs! | 56f6919a6b88de18ff000b36 | [
"Debugging",
"Fundamentals"
] | https://www.codewars.com/kata/56f6919a6b88de18ff000b36 | 8 kyu |
Your classmates asked you to copy some paperwork for them. You know that there are 'n' classmates and the paperwork has 'm' pages.
Your task is to calculate how many blank pages do you need. If `n < 0` or `m < 0` return `0`.
### Example:
```
n= 5, m=5: 25
n=-5, m=5: 0
```
Waiting for translations and Feedback! Th... | reference | def paperwork(n, m):
return n * m if n > 0 and m > 0 else 0
| Beginner Series #1 School Paperwork | 55f9b48403f6b87a7c0000bd | [
"Fundamentals"
] | https://www.codewars.com/kata/55f9b48403f6b87a7c0000bd | 8 kyu |
# How many ways can you make the sum of a number?
From wikipedia: https://en.wikipedia.org/wiki/Partition_(number_theory)
>In number theory and combinatorics, a partition of a positive integer *n*, also called an *integer partition*, is a way of writing n as a sum of positive integers. Two sums that differ only in th... | reference | ANSWERS = {
0: 1,
1: 1,
2: 2,
3: 3,
4: 5,
5: 7,
6: 11,
7: 15,
8: 22,
9: 30,
10: 42,
11: 56,
12: 77,
13: 101,
14: 135,
15: 176,
16: 231,
17: 297,
18: 385,
19: 490,
20: 627,
21: 792,
22: 1002,
23: 1255,... | Explosive Sum | 52ec24228a515e620b0005ef | [
"Algorithms",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/52ec24228a515e620b0005ef | 4 kyu |
Return the number (count) of vowels in the given string.
We will consider `a`, `e`, `i`, `o`, `u` as vowels for this Kata (but not `y`).
The input string will only consist of lower case letters and/or spaces.
| reference | def getCount(inputStr):
return sum(1 for let in inputStr if let in "aeiouAEIOU")
| Vowel Count | 54ff3102c1bad923760001f3 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/54ff3102c1bad923760001f3 | 7 kyu |
You are the greatest chef on earth. No one boils eggs like you! Your restaurant is always full of guests, who love your boiled eggs. But when there is a greater order of boiled eggs, you need some time, because you have only one pot for your job. How much time do you need?
## Your Task
Implement a function, which tak... | algorithms | from math import *
def cooking_time(eggs):
return 5 * ceil(eggs / 8.0)
| Boiled Eggs | 52b5247074ea613a09000164 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/52b5247074ea613a09000164 | 7 kyu |
Create a function that returns the name of the winner in a fight between two fighters.
Each fighter takes turns attacking the other and whoever kills the other first is victorious. Death is defined as having `health <= 0`.
Each fighter will be a `Fighter` object/instance. See the Fighter class below in your chosen la... | reference | def declare_winner(fighter1, fighter2, first_attacker):
cur, opp = (fighter1, fighter2) if first_attacker == fighter1 . name else (
fighter2, fighter1)
while cur . health > 0:
opp . health -= cur . damage_per_attack
cur, opp = opp, cur
return opp . name
| Two fighters, one winner. | 577bd8d4ae2807c64b00045b | [
"Games",
"Algorithms",
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/577bd8d4ae2807c64b00045b | 7 kyu |
In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
### Examples
``` text
Input: "1 2 3 4 5" => Output: "5 1"
Input: "1 2 -3 4 5" => Output: "5 -3"
Input: "1 9 3 4 -5" => Output: "9 -5"
```
```php
highAndLow("1 2 3 4 5"); // return "5 ... | reference | def high_and_low(numbers): # z.
nn = [int(s) for s in numbers . split(" ")]
return "%i %i" % (max(nn), min(nn))
| Highest and Lowest | 554b4ac871d6813a03000035 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/554b4ac871d6813a03000035 | 7 kyu |
Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
### Example
```javascript
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"
```
```cpp
createPhoneNumber(int[10]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}) ... | algorithms | def create_phone_number(n):
return "({}{}{}) {}{}{}-{}{}{}{}".format(*n)
| Create Phone Number | 525f50e3b73515a6db000b83 | [
"Arrays",
"Strings",
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/525f50e3b73515a6db000b83 | 6 kyu |
Write a function that takes an array of numbers and returns the sum of the numbers. The numbers can be negative or non-integer. If the array does not contain any numbers then you should return 0.
### Examples
Input: `[1, 5.2, 4, 0, -1]`
Output: `9.2`
Input: `[]`
Output: `0`
Input: `[-2.398]`
Output: `-2.398`... | reference | def sum_array(a):
return sum(a)
| Sum Arrays | 53dc54212259ed3d4f00071c | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/53dc54212259ed3d4f00071c | 8 kyu |
The two oldest ages function/method needs to be completed. It should take an array of numbers as its argument and return the **two highest numbers within the array**. The returned value should be an array in the format `[second oldest age, oldest age]`.
The order of the numbers passed in could be any order. The arra... | algorithms | def two_oldest_ages(ages):
return sorted(ages)[- 2:]
| Two Oldest Ages | 511f11d355fe575d2c000001 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/511f11d355fe575d2c000001 | 7 kyu |
Complete the function that takes a non-negative integer `n` as input, and returns a list of all the powers of `2` with the exponent ranging from `0` to `n` ( inclusive ).
## Examples
```python
n = 0 ==> [1] # [2^0]
n = 1 ==> [1, 2] # [2^0, 2^1]
n = 2 ==> [1, 2, 4] # [2^0, 2^1, 2^2]
```
```bf
n = Stri... | reference | def powers_of_two(n):
return [2 * * x for x in range(n + 1)]
| Powers of 2 | 57a083a57cb1f31db7000028 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/57a083a57cb1f31db7000028 | 8 kyu |
You are given the `length` and `width` of a 4-sided polygon. The polygon can either be a rectangle or a square.
If it is a square, return its area. If it is a rectangle, return its perimeter.
**Example(Input1, Input2 --> Output):**
```
6, 10 --> 32
3, 3 --> 9
```
**Note:** for the purposes of this kata you will ass... | reference | def area_or_perimeter(l, w):
return l * w if l == w else (l + w) * 2
| Area or Perimeter | 5ab6538b379d20ad880000ab | [
"Fundamentals",
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/5ab6538b379d20ad880000ab | 8 kyu |
You are given a string with results of NBA teams (see the data in "Sample Tests") separated by commas e.g:
r =
`Los Angeles Clippers 104 Dallas Mavericks 88,New York Knicks 101 Atlanta Hawks 112,Indiana Pacers 103 Memphis Grizzlies 112,
Los Angeles Clippers 100 Boston Celtics 120`.
A team name is composed of one, t... | reference | import re
def nba_cup(result_sheet, team):
if not team:
return ""
wins, draws, losses, points, conced = 0, 0, 0, 0, 0
for t1, p1, t2, p2 in re . findall(r'(.+?) (\b[\d.]+\b) (.+?) (\b[\d.]+\b)(?:,|$)', result_sheet):
if '.' in p1 or '.' in p2:
return "Error(float number):{} {} {} {}"... | Ranking NBA teams | 5a420163b6cfd7cde5000077 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5a420163b6cfd7cde5000077 | 6 kyu |
Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. Return the resulting string.
**Note: input will never be an empty string**
| reference | def fake_bin(x):
return '' . join('0' if c < '5' else '1' for c in x)
| Fake Binary | 57eae65a4321032ce000002d | [
"Fundamentals",
"Strings",
"Arrays"
] | https://www.codewars.com/kata/57eae65a4321032ce000002d | 8 kyu |
Complete the function which converts hex number (given as a string) to a decimal number. | reference | def hex_to_dec(s):
return int(s, 16)
| Hex to Decimal | 57a4d500e298a7952100035d | [
"Fundamentals"
] | https://www.codewars.com/kata/57a4d500e298a7952100035d | 8 kyu |
<p>
Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. The check should be case sensitive.
</p>
<p>For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5... | algorithms | def shifted_diff(first, second):
return (second + second). find(first) if len(first) == len(second) else - 1
| Calculate String Rotation | 5596f6e9529e9ab6fb000014 | [
"Strings",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5596f6e9529e9ab6fb000014 | 6 kyu |
If you finish this kata, you can try [Insane Coloured Triangles](http://www.codewars.com/kata/insane-coloured-triangles) by Bubbler, which is a ***much*** harder version of this one.
A coloured triangle is created from a row of colours, each of which is red, green or blue. Successive rows, each containing one fewer co... | algorithms | COLORS = set("RGB")
def triangle(row):
while len(row) > 1:
row = '' . join(a if a == b else (
COLORS - {a, b}). pop() for a, b in zip(row, row[1:]))
return row
| Coloured Triangles | 5a25ac6ac5e284cfbe000111 | [
"Logic",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5a25ac6ac5e284cfbe000111 | 7 kyu |
### A square of squares
You like building blocks. You especially like building blocks that are squares. And what you even like more, is to arrange them into a square of square building blocks!
However, sometimes, you can't arrange them into a square. Instead, you end up with an ordinary rectangle! Those blasted thing... | reference | import math
def is_square(n):
return n > - 1 and math . sqrt(n) % 1 == 0
| You're a square! | 54c27a33fb7da0db0100040e | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/54c27a33fb7da0db0100040e | 7 kyu |
It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry about strings with less than two characters.
| reference | def remove_char(s):
return s[1: - 1]
| Remove First and Last Character | 56bc28ad5bdaeb48760009b0 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/56bc28ad5bdaeb48760009b0 | 8 kyu |
Write function describeList which returns "empty" if the list is empty or "singleton" if it contains only one element or "longer"" if more. | reference | def describeList(lst):
return ["empty", "singleton", "longer"][min(len(lst), 2)]
| Describe a list | 57a4a3e653ba3346bc000810 | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/57a4a3e653ba3346bc000810 | 7 kyu |
Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (`HH:MM:SS`)
* `HH` = hours, padded to 2 digits, range: 00 - 99
* `MM` = minutes, padded to 2 digits, range: 00 - 59
* `SS` = seconds, padded to 2 digits, range: 00 - 59
The maximum time never excee... | algorithms | def make_readable(seconds):
hours, seconds = divmod(seconds, 60 * * 2)
minutes, seconds = divmod(seconds, 60)
return '{:02}:{:02}:{:02}' . format(hours, minutes, seconds)
| Human Readable Time | 52685f7382004e774f0001f7 | [
"Date Time",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/52685f7382004e774f0001f7 | 5 kyu |
The function 'fibonacci' should return an array of fibonacci numbers. The function takes a number as an argument to decide how many no. of elements to produce. If the argument is less than or equal to 0 then return empty array
Example:
```javascript
fibonacci(4) // should return [0,1,1,2]
fibonacci(-1) // should ret... | algorithms | def fibonacci(n):
if n <= 0:
return []
a = 0
b = 1
l = [0]
for i in range(n):
a, b = b, a + b
l . append(a)
return l[0: n]
| Complete Fibonacci Series | 5239f06d20eeab9deb00049b | [
"Algorithms"
] | https://www.codewars.com/kata/5239f06d20eeab9deb00049b | 6 kyu |
Complete the solution so that it reverses the string passed into it.
```
'world' => 'dlrow'
'word' => 'drow'
``` | reference | def solution(str):
return str[:: - 1]
| Reversed Strings | 5168bb5dfe9a00b126000018 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5168bb5dfe9a00b126000018 | 8 kyu |
You ask a small girl,"How old are you?" She always says, "x years old", where x is a random number between 0 and 9.
Write a program that returns the girl's age (0-9) as an integer.
Assume the test input string is always a valid string. For example, the test input may be "1 year old" or "5 years old". The first chara... | reference | def get_age(age):
return int(age[0])
| Parse nice int from char problem | 557cd6882bfa3c8a9f0000c1 | [
"Fundamentals"
] | https://www.codewars.com/kata/557cd6882bfa3c8a9f0000c1 | 8 kyu |
Given a string of words, you need to find the highest scoring word.
Each letter of a word scores points according to its position in the alphabet: `a = 1, b = 2, c = 3` etc.
For example, the score of `abad` is `8` (1 + 2 + 1 + 4).
You need to return the highest scoring word as a string.
If two words score the same,... | reference | def high(x):
return max(x . split(), key=lambda k: sum(ord(c) - 96 for c in k))
| Highest Scoring Word | 57eb8fcdf670e99d9b000272 | [
"Fundamentals",
"Strings",
"Arrays"
] | https://www.codewars.com/kata/57eb8fcdf670e99d9b000272 | 6 kyu |
Removed due to copyright infringement.
<!---
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. The... | algorithms | def whoIsNext(names, r):
while r > 5:
r = (r - 4) / 2
return names[r - 1]
| Double Cola | 551dd1f424b7a4cdae0001f0 | [
"Algorithms",
"Mathematics",
"Logic",
"Numbers"
] | https://www.codewars.com/kata/551dd1f424b7a4cdae0001f0 | 5 kyu |
Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of `numbers` and the second is the `divisor`.
## Example(Input1, Input2 --> Output)
```
[1, 2, 3, 4, 5, 6], 2 --> [2, 4, 6]
```
| algorithms | def divisible_by(numbers, divisor):
return [x for x in numbers if x % divisor == 0]
| Find numbers which are divisible by given number | 55edaba99da3a9c84000003b | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/55edaba99da3a9c84000003b | 8 kyu |
Very simple, given a number (integer / decimal / both depending on the language), find its opposite (additive inverse).
Examples:
```
1: -1
14: -14
-34: 34
```
~~~if:sql
You will be given a table: `opposite`, with a column: `number`. Return a table with a column: `res`.
~~~
| reference | def opposite(number):
return - number
| Opposite number | 56dec885c54a926dcd001095 | [
"Fundamentals"
] | https://www.codewars.com/kata/56dec885c54a926dcd001095 | 8 kyu |
Your task is to split the chocolate bar of given dimension `n` x `m` into small squares.
Each square is of size 1x1 and unbreakable.
Implement a function that will return minimum number of breaks needed.
For example if you are given a chocolate bar of size `2` x `1` you can split it to single squares in just one break... | algorithms | def breakChocolate(n, m):
return max(n * m - 1, 0)
| Breaking chocolate problem | 534ea96ebb17181947000ada | [
"Algorithms"
] | https://www.codewars.com/kata/534ea96ebb17181947000ada | 7 kyu |
Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
### Examples (Input -> Output):
```
* "String" -> "SSttrriinngg"
* "Hello World" -> "HHeelllloo WWoorrlldd"
* "1234!_ " -> "11223344!!__ "
```
Good Luck!
~~~if:riscv
RISC-V: The function signature is
```... | reference | def double_char(s):
return '' . join(c * 2 for c in s)
| Double Char | 56b1f01c247c01db92000076 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/56b1f01c247c01db92000076 | 8 kyu |
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but **exactly** 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return `true`, else return `false`.
## Examples (**Input --> Output)**
```
"1234" --> true
"12345" --> false
"a234" --> false
```
| reference | def validate_pin(pin):
return len(pin) in (4, 6) and pin . isdigit()
| Regex validate PIN code | 55f8a9c06c018a0d6e000132 | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/55f8a9c06c018a0d6e000132 | 7 kyu |
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string.
The words in the input String will onl... | reference | def order(words):
return ' ' . join(sorted(words . split(), key=lambda w: sorted(w)))
| Your order, please | 55c45be3b2079eccff00010f | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/55c45be3b2079eccff00010f | 6 kyu |
Complete the function that takes two integers (`a, b`, where `a < b`) and return an array of all integers between the input parameters, **including** them.
For example:
```
a = 1
b = 4
--> [1, 2, 3, 4]
``` | reference | def between(a, b):
return list(range(a, b + 1))
| What is between? | 55ecd718f46fba02e5000029 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/55ecd718f46fba02e5000029 | 8 kyu |
You have cultivated a plant, and after months of hard work, the time has come to reap the flowers of your hard work. When it was growing, you added water and fertilizer, and kept a constant temperature. It's time check how much your plant has grown.
A plant is represented horizontally, from the base to the left, to th... | reference | def plant(seed, water, fert, temp):
return ('-' * water + seed * fert) * water if temp >= 20 and temp <= 30 else ('-' * water) * water + seed
| Harvest Festival | 606efc6a9409580033837dfb | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/606efc6a9409580033837dfb | 7 kyu |
When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
| reference | def position(alphabet):
return "Position of alphabet: {}" . format(ord(alphabet) - 96)
| Find the position! | 5808e2006b65bff35500008f | [
"Fundamentals"
] | https://www.codewars.com/kata/5808e2006b65bff35500008f | 8 kyu |
Automatons, or Finite State Machines (FSM), are extremely useful to programmers when it comes to software design. You will be given a simplistic version of an FSM to code for a basic TCP session.
The outcome of this exercise will be to return the correct state of the TCP FSM based on the array of events given.
------... | algorithms | STATE_TO_COMMANDS = {
'CLOSED': {
'APP_PASSIVE_OPEN': 'LISTEN',
'APP_ACTIVE_OPEN': 'SYN_SENT'
},
'LISTEN': {
'RCV_SYN': 'SYN_RCVD',
'APP_SEND': 'SYN_SENT',
'APP_CLOSE': 'CLOSED'
},
'SYN_RCVD': {
'APP_CLOSE': 'FIN_WAIT_1',
'RCV_ACK':... | A Simplistic TCP Finite State Machine (FSM) | 54acc128329e634e9a000362 | [
"State Machines",
"Algorithms"
] | https://www.codewars.com/kata/54acc128329e634e9a000362 | 4 kyu |
The goal of this exercise is to convert a string to a new string where each character in the new string is `"("` if that character appears only once in the original string, or `")"` if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
##... | reference | def duplicate_encode(word):
return "" . join(["(" if word . lower(). count(c) == 1 else ")" for c in word . lower()])
| Duplicate Encoder | 54b42f9314d9229fd6000d9c | [
"Strings",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/54b42f9314d9229fd6000d9c | 6 kyu |
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 **below** the number passed in.
~~~if:c,cobol,commonlisp,cpp,csharp,dart,elixir,factor,fsharp,javascript,juli... | algorithms | def solution(number):
return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0)
| Multiples of 3 or 5 | 514b92a657cdc65150000006 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/514b92a657cdc65150000006 | 6 kyu |
A *[Hamming number][1]* is a positive integer of the form 2<sup>*i*</sup>3<sup>*j*</sup>5<sup>*k*</sup>, for some non-negative integers *i,* *j,* and *k.*
Write a function that computes the *n<sup>th</sup>* smallest Hamming number.
Specifically:
- The first smallest Hamming number is 1 = 2<sup>0</sup>3<sup>0</sup... | algorithms | def hamming(n):
bases = [2, 3, 5]
expos = [0, 0, 0]
hamms = [1]
for _ in range(1, n):
next_hamms = [bases[i] * hamms[expos[i]] for i in range(3)]
next_hamm = min(next_hamms)
hamms . append(next_hamm)
for i in range(3):
expos[i] += int(next_hamms[i] == next_hamm)
return ... | Hamming Numbers | 526d84b98f428f14a60008da | [
"Number Theory",
"Algorithms"
] | https://www.codewars.com/kata/526d84b98f428f14a60008da | 4 kyu |
Write a function that checks if a given string (case insensitive) is a [palindrome](https://en.wikipedia.org/wiki/Palindrome).
A palindrome is a word, number, phrase, or other sequence of symbols that reads the same backwards as forwards, such as `madam` or `racecar`. | reference | def is_palindrome(s):
s = s . lower()
return s == s[:: - 1]
| Is it a palindrome? | 57a1fd2ce298a731b20006a4 | [
"Fundamentals"
] | https://www.codewars.com/kata/57a1fd2ce298a731b20006a4 | 8 kyu |
### Description:
Groups of characters decided to make a battle. Help them to figure out which group is more powerful. Create a function that will accept 2 strings and return the one who's stronger.
### Rules:
* Each character have its own power: `A = 1, B = 2, ... Y = 25, Z = 26`
* Strings will consist of uppercase ... | algorithms | def battle(x, y):
# Compute x score using Unicode
x_value = sum(ord(char) - 64 for char in x)
# Compute y score using Unicode
y_value = sum(ord(char) - 64 for char in y)
if x_value < y_value:
return y
if x_value > y_value:
return x
return "Tie!"
| Battle of the characters (Easy) | 595519279be6c575b5000016 | [
"Algorithms"
] | https://www.codewars.com/kata/595519279be6c575b5000016 | 7 kyu |
# Summation
Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0. Your function only needs to return the result, what is shown between parentheses in the example below is how you reach that result and it's not part of it, see the sample tes... | reference | def summation(num):
return sum(range(1, num + 1))
| Grasshopper - Summation | 55d24f55d7dd296eb9000030 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/55d24f55d7dd296eb9000030 | 8 kyu |
## Messi's Goal Total
Use variables to find the sum of the goals Messi scored in 3 competitions
## Information
Messi goal scoring statistics:
Competition | Goals
-----|------
La Liga | 43
Champions League | 10
Copa del Rey | 5
## Task
1) Create these three variables and store the appropriate values using the tabl... | reference | la_liga_goals = 43
champions_league_goals = 10
copa_del_rey_goals = 5
total_goals = la_liga_goals + champions_league_goals + copa_del_rey_goals
| Grasshopper - Messi Goals | 55ca77fa094a2af31f00002a | [
"Fundamentals"
] | https://www.codewars.com/kata/55ca77fa094a2af31f00002a | 8 kyu |
Can you find the needle in the haystack?
Write a function `findNeedle()` that takes an `array` full of junk but containing one `"needle"`
After your function finds the needle it should return a message (as a string) that says:
`"found the needle at position "` plus the `index` it found the needle, so:
**Example(In... | reference | def find_needle(haystack):
return f'found the needle at position { haystack . index ( "needle" )} '
| A Needle in the Haystack | 56676e8fabd2d1ff3000000c | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/56676e8fabd2d1ff3000000c | 8 kyu |
Complete the function `scramble(str1, str2)` that returns `true` if a portion of ```str1``` characters can be rearranged to match ```str2```, otherwise returns ```false```.
**Notes:**
* Only lower case letters will be used (a-z). No punctuation or digits will be included.
* Performance needs to be considered.
```if:... | algorithms | def scramble(s1, s2):
for c in set(s2):
if s1 . count(c) < s2 . count(c):
return False
return True
| Scramblies | 55c04b4cc56a697bb0000048 | [
"Strings",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/55c04b4cc56a697bb0000048 | 5 kyu |
You're at the zoo... all the meerkats look weird. Something has gone terribly wrong - someone has gone and switched their heads and tails around!
Save the animals by switching them back. You will be given an array which will have three values (tail, body, head). It is your job to re-arrange the array so that the anima... | algorithms | def fix_the_meerkat(arr):
return arr[:: - 1]
| My head is at the wrong end! | 56f699cd9400f5b7d8000b55 | [
"Arrays",
"Lists",
"Algorithms"
] | https://www.codewars.com/kata/56f699cd9400f5b7d8000b55 | 8 kyu |
Your task is to remove all duplicate words from a string, leaving only single (first) words entries.
Example:
Input:
'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'
Output:
'alpha beta gamma delta'
| algorithms | def remove_duplicate_words(s):
return ' ' . join(dict . fromkeys(s . split()))
| Remove duplicate words | 5b39e3772ae7545f650000fc | [
"Strings",
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/5b39e3772ae7545f650000fc | 7 kyu |
After a hard quarter in the office you decide to get some rest on a vacation. So you will book a flight for you and your girlfriend and try to leave all the mess behind you.
You will need a rental car in order for you to get around in your vacation. The manager of the car rental makes you some good offers.
Every day ... | reference | def rental_car_cost(d):
result = d * 40
if d >= 7:
result -= 50
elif d >= 3:
result -= 20
return result
| Transportation on vacation | 568d0dd208ee69389d000016 | [
"Fundamentals"
] | https://www.codewars.com/kata/568d0dd208ee69389d000016 | 8 kyu |
The function is not returning the correct values. Can you figure out why?
Example (**Input** --> **Output** ):
```
3 --> "Earth"
``` | bug_fixes | def get_planet_name(id):
return {
1: "Mercury",
2: "Venus",
3: "Earth",
4: "Mars",
5: "Jupiter",
6: "Saturn",
7: "Uranus",
8: "Neptune",
}. get(id, None)
| Get Planet Name By ID | 515e188a311df01cba000003 | [
"Debugging"
] | https://www.codewars.com/kata/515e188a311df01cba000003 | 8 kyu |
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/56f8a648ba792a778a0000b9).
### Task:
Find out "B"(Bug) in a lot of "A"(Apple).
There will always be one bug in apple, not need to consider the situation that with... | games | def sc(apple):
for i in apple:
for j in i:
if j == "B":
return [apple . index(i), i . index(j)]
| Coding 3min: Bug in Apple | 56fe97b3cc08ca00e4000dc9 | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9 | 7 kyu |
Write a function to split a string and convert it into an array of words.
### Examples (Input ==> Output):
```
"Robin Singh" ==> ["Robin", "Singh"]
"I love arrays they are my favorite" ==> ["I", "love", "arrays", "they", "are", "my", "favorite"]
```
```if:c
Words will be separated by exactly one space, without lead... | reference | def string_to_array(string):
return string . split(" ")
| Convert a string to an array | 57e76bc428d6fbc2d500036d | [
"Arrays",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/57e76bc428d6fbc2d500036d | 8 kyu |
Write a function that accepts two square (`NxN`) matrices (two dimensional arrays), and returns the product of the two. Only square matrices will be given.
How to multiply two square matrices:
We are given two matrices, A and B, of size 2x2 (note: tests are not limited to 2x2). Matrix C, the solution, will be equal ... | algorithms | from numpy import matrix
def matrix_mult(a, b):
return (matrix(a) * matrix(b)). tolist()
| Square Matrix Multiplication | 5263a84ffcadb968b6000513 | [
"Matrix",
"Linear Algebra",
"Algorithms"
] | https://www.codewars.com/kata/5263a84ffcadb968b6000513 | 5 kyu |
Complete the solution so that the function will break up camel casing, using a space between words.
### Example
```
"camelCasing" => "camel Casing"
"identifier" => "identifier"
"" => ""
``` | reference | def solution(s):
return '' . join(' ' + c if c . isupper() else c for c in s)
| Break camelCase | 5208f99aee097e6552000148 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5208f99aee097e6552000148 | 6 kyu |
Write a class `Block` that creates a block (Duh..)
## Requirements
The constructor should take an array as an argument,
this will contain 3 integers of the form `[width, length, height]` from which the `Block` should be created.
Define these methods:
```python
`get_width()` return the width of the `Block`
`get_len... | reference | from operator import mul
class Block (object):
def __init__(self, dimensions):
self . dimensions = dimensions
def get_width(self):
return self . dimensions[0]
def get_length(self):
return self . dimensions[1]
def get_height(self):
return self . dimensions[2]
def g... | Building blocks | 55b75fcf67e558d3750000a3 | [
"Object-oriented Programming",
"Fundamentals"
] | https://www.codewars.com/kata/55b75fcf67e558d3750000a3 | 7 kyu |
Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).
For example,
```javascript
[true, true, true, false,
true, true, true, true ,
true, false, true, false,
true, false, false, tru... | reference | def count_sheeps(arrayOfSheeps):
return arrayOfSheeps . count(True)
| Counting sheep... | 54edbc7200b811e956000556 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/54edbc7200b811e956000556 | 8 kyu |
You are given a node that is the beginning of a linked list. This list contains a dangling piece and a loop. Your objective is to determine the length of the loop.
For example in the following picture the size of the dangling piece is 3 and the loop size is 12:
<img width='320px' src='data:image/svg+xml;base64,PHN2... | algorithms | def loop_size(node):
turtle, rabbit = node . next, node . next . next
# Find a point in the loop. Any point will do!
# Since the rabbit moves faster than the turtle
# and the kata guarantees a loop, the rabbit will
# eventually catch up with the turtle.
while turtle != rabbit:
turtle = turtl... | Can you get the loop ? | 52a89c2ea8ddc5547a000863 | [
"Algorithms",
"Linked Lists",
"Performance"
] | https://www.codewars.com/kata/52a89c2ea8ddc5547a000863 | 5 kyu |
Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T').
Ribonucleic acid, RNA, is the primary messenger molecule in cells. RNA differs slightly from DNA its chemical structu... | reference | def DNAtoRNA(dna):
return dna . replace('T', 'U')
| DNA to RNA Conversion | 5556282156230d0e5e000089 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5556282156230d0e5e000089 | 8 kyu |
We are diligently pursuing our elusive operative, **Matthew Knight**, who also goes by the alias **Roy Miller**. He employs a nomadic lifestyle to evade detection, constantly moving from one location to another, with each of his journeys following a perplexing and non-standard sequence of **itineraries**. Our mission i... | algorithms | def find_routes(routes: list) - > str:
d = dict(routes)
res = list(d . keys() - d . values())
while res[- 1] in d:
res . append(d[res[- 1]])
return ', ' . join(res)
| Follow that Spy | 5899a4b1a6648906fe000113 | [
"Algorithms"
] | https://www.codewars.com/kata/5899a4b1a6648906fe000113 | 6 kyu |
In mathematics, the factorial of integer 'n' is written as 'n!'.
It is equal to the product of n and every integer preceding it.
For example: **5! = 1 x 2 x 3 x 4 x 5 = 120**
Your mission is simple: write a function that takes an integer 'n' and returns 'n!'.
You are guaranteed an integer argument. For any valu... | algorithms | import math
def factorial(n):
if n < 0:
return None
return math . factorial(n)
| Factorial Factory | 528e95af53dcdb40b5000171 | [
"Recursion",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/528e95af53dcdb40b5000171 | 7 kyu |
## Welcome to the Codewars Bar!
Codewars Bar recommends you drink 1 glass of water per standard drink so you're not hungover tomorrow morning.
Your fellow coders have bought you several drinks tonight in the form of a string. Return a string suggesting how many glasses of water you should drink to not be hungover.
... | reference | def hydrate(drink_string):
c = sum(int(c) for c in drink_string if c . isdigit())
return "{} {} of water" . format(c, 'glass') if c == 1 else "{} {} of water" . format(c, 'glasses')
| Responsible Drinking | 5aee86c5783bb432cd000018 | [
"Fundamentals"
] | https://www.codewars.com/kata/5aee86c5783bb432cd000018 | 7 kyu |
Wolves have been reintroduced to Great Britain. You are a sheep farmer, and are now plagued by wolves which pretend to be sheep. Fortunately, you are good at spotting them.
Warn the sheep in front of the wolf that it is about to be eaten. Remember that you are standing **at the front of the queue** which is at the en... | reference | def warn_the_sheep(queue):
n = len(queue) - queue . index('wolf') - 1
return f'Oi! Sheep number { n } ! You are about to be eaten by a wolf!' if n else 'Pls go away and stop eating my sheep'
| A wolf in sheep's clothing | 5c8bfa44b9d1192e1ebd3d15 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5c8bfa44b9d1192e1ebd3d15 | 8 kyu |
Take an array and remove every second element from the array. Always keep the first element and start removing with the next element.
### Example:
```if-not:c
`["Keep", "Remove", "Keep", "Remove", "Keep", ...]` --> `["Keep", "Keep", "Keep", ...]`
```
```if:c
~~~c
size_t length = 5;
remove_every_other(&length, {1, 2,... | reference | def remove_every_other(my_list):
return my_list[:: 2]
| Removing Elements | 5769b3802ae6f8e4890009d2 | [
"Lists",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5769b3802ae6f8e4890009d2 | 8 kyu |
## Terminal game move function
In this game, the hero moves from left to right. The player rolls the dice and moves the number of spaces indicated by the dice **two times**.
~~~if-not:sql
Create a function for the terminal game that takes the current position of the hero and the roll (1-6) and return the new position... | reference | def move(position, roll):
return position + 2 * roll
| Grasshopper - Terminal game move function | 563a631f7cbbc236cf0000c2 | [
"Fundamentals"
] | https://www.codewars.com/kata/563a631f7cbbc236cf0000c2 | 8 kyu |
Let us begin with an example:
A man has a rather old car being worth $2000.
He saw a secondhand car being worth $8000. He wants to keep his old car until he can buy the secondhand one.
He thinks he can save $1000 each month but the prices of his old
car and of the new one decrease of 1.5 percent per month.
Furtherm... | reference | def nbMonths(oldCarPrice, newCarPrice, saving, loss):
months = 0
budget = oldCarPrice
while budget < newCarPrice:
months += 1
if months % 2 == 0:
loss += 0.5
oldCarPrice *= (100 - loss) / 100
newCarPrice *= (100 - loss) / 100
budget = saving * months + oldCarPrice
return [months,... | Buying a car | 554a44516729e4d80b000012 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/554a44516729e4d80b000012 | 6 kyu |
# Find the missing letter
Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array.
~~~if:factor
In the case of factor, your array of letters will be a string.
~~~
You will always get an valid array. And it will be always exactly one letter be m... | algorithms | def find_missing_letter(chars):
n = 0
while ord(chars[n]) == ord(chars[n + 1]) - 1:
n += 1
return chr(1 + ord(chars[n]))
| Find the missing letter | 5839edaa6754d6fec10000a2 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5839edaa6754d6fec10000a2 | 6 kyu |
Write a function that removes the spaces from the string, then return the resultant string.
Examples:
```
Input -> Output
"8 j 8 mBliB8g imjB8B8 jl B" -> "8j8mBliB8gimjB8B8jlB"
"8 8 Bi fk8h B 8 BB8B B B B888 c hl8 BhB fd" -> "88Bifk8hB8BB8BBBB888chl8BhBfd"
"8aaaaa dddd r " -> "8aaaaaddddr"
```
~~~if:bf
The ... | reference | def no_space(x):
return x . replace(' ', '')
| Remove String Spaces | 57eae20f5500ad98e50002c5 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/57eae20f5500ad98e50002c5 | 8 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.