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 |
|---|---|---|---|---|---|---|---|
# Rock Paper Scissors
Let's play! You have to return which player won! In case of a draw return `Draw!`.
**Examples(Input1, Input2 --> Output):**
```
"scissors", "paper" --> "Player 1 won!"
"scissors", "rock" --> "Player 2 won!"
"paper", "paper" --> "Draw!"
```
 | reference | def rps(p1, p2):
beats = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}
if beats[p1] == p2:
return "Player 1 won!"
if beats[p2] == p1:
return "Player 2 won!"
return "Draw!"
| Rock Paper Scissors! | 5672a98bdbdd995fad00000f | [
"Fundamentals"
] | https://www.codewars.com/kata/5672a98bdbdd995fad00000f | 8 kyu |
This code should store `"codewa.rs"` as a variable called `name` but it's not working. Can you figure out why? | bug_fixes | a = "code"
b = "wa.rs"
name = a + b
| Basic variable assignment | 50ee6b0bdeab583673000025 | [
"Debugging"
] | https://www.codewars.com/kata/50ee6b0bdeab583673000025 | 8 kyu |
## Task
* **_Given_** *three integers* `a` ,`b` ,`c`, **_return_** *the **_largest number_** obtained after inserting the following operators and brackets*: `+`, `*`, `()`
* In other words , **_try every combination of a,b,c with [*+()] , and return the Maximum Obtained_** <span style="color:red">(Read the notes for mo... | reference | def expression_matter(a, b, c):
return max(a * b * c, a + b + c, (a + b) * c, a * (b + c))
| Expressions Matter | 5ae62fcf252e66d44d00008e | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/5ae62fcf252e66d44d00008e | 8 kyu |
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.
~~~if-not:racket
```
invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []
```
~~~
```if:javascript,python,ruby,php,elixir,dart,go
You can assume... | reference | def invert(lst):
return [- x for x in lst]
| Invert values | 5899dc03bc95b1bf1b0000ad | [
"Lists",
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5899dc03bc95b1bf1b0000ad | 8 kyu |
Who remembers back to their time in the schoolyard, when girls would take a flower and tear its petals, saying each of the following phrases each time a petal was torn:
1. "I love you"
2. "a little"
3. "a lot"
4. "passionately"
5. "madly"
6. "not at all"
If there are more than 6 petals, you start over with `"I love y... | reference | def how_much_i_love_you(nb_petals):
return ["I love you", "a little", "a lot", "passionately", "madly", "not at all"][nb_petals % 6 - 1] # g
| I love you, a little , a lot, passionately ... not at all | 57f24e6a18e9fad8eb000296 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57f24e6a18e9fad8eb000296 | 8 kyu |
Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
| reference | def find_short(s):
return min(len(x) for x in s . split())
| Shortest Word | 57cebe1dc6fdc20c57000ac9 | [
"Fundamentals"
] | https://www.codewars.com/kata/57cebe1dc6fdc20c57000ac9 | 7 kyu |
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
**Example: (Input --> Output)**
```if-not:factor
"Dermatoglyphics" --> true
"aba... | reference | def is_isogram(string):
return len(string) == len(set(string . lower()))
| Isograms | 54ba84be607a92aa900000f1 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/54ba84be607a92aa900000f1 | 7 kyu |
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer `N`. Write a method that takes the array as an argument and returns this "outlier" `N`.
... | algorithms | def find_outlier(int):
odds = [x for x in int if x % 2 != 0]
evens = [x for x in int if x % 2 == 0]
return odds[0] if len(odds) < len(evens) else evens[0]
| Find The Parity Outlier | 5526fc09a1bbd946250002dc | [
"Algorithms"
] | https://www.codewars.com/kata/5526fc09a1bbd946250002dc | 6 kyu |
A hero is on his way to the castle to complete his mission. However, he's been told that the castle is surrounded with a couple of powerful dragons! each dragon takes 2 bullets to be defeated, our hero has no idea how many bullets he should carry.. Assuming he's gonna grab a specific given number of bullets and move fo... | reference | def hero(bullets, dragons):
return bullets >= dragons * 2
| Is he gonna survive? | 59ca8246d751df55cc00014c | [
"Fundamentals"
] | https://www.codewars.com/kata/59ca8246d751df55cc00014c | 8 kyu |
~~~if:bf
Write a program which accepts a single byte `n` and then a sequence of bytes `string` and outputs the `string` exactly `n` times.
The first input byte will be `n`. Following bytes will be characters of `string`. The end of the input `string` will be indicated with a null byte `\0`.
### Examples:
"\6I" -> "I... | reference | def repeat_str(repeat, string):
return repeat * string
| String repeat | 57a0e5c372292dd76d000d7e | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/57a0e5c372292dd76d000d7e | 8 kyu |
I'm new to coding and now I want to get the sum of two arrays... Actually the sum of all their elements. I'll appreciate for your help.
P.S. Each array includes only integer numbers. Output is a number too. | bug_fixes | def array_plus_array(arr1, arr2):
return sum(arr1 + arr2)
| Array plus array | 5a2be17aee1aaefe2a000151 | [
"Fundamentals",
"Arrays",
"Debugging"
] | https://www.codewars.com/kata/5a2be17aee1aaefe2a000151 | 8 kyu |
Given a positive integer `n: 0 < n < 1e6`, remove the last digit until you're left with a number that is a multiple of three.
Return `n` if the input is already a multiple of three, and if no such number exists, return `null`, a similar empty value, or `-1`.
## Examples
```
1 => null
25 => null
36 => 36... | reference | def prev_mult_of_three(n):
while n % 3:
n / /= 10
return n or None
| Previous multiple of three | 61123a6f2446320021db987d | [
"Fundamentals"
] | https://www.codewars.com/kata/61123a6f2446320021db987d | 7 kyu |
An **anagram** is the result of rearranging the letters of a word to produce a new word (see [wikipedia](https://en.wikipedia.org/wiki/Anagram)).
**Note:** anagrams are case insensitive
Complete the function to return `true` if the two arguments given are anagrams of each other; return `false` otherwise.
## Example... | reference | def is_anagram(test, original):
return sorted(original . lower()) == sorted(test . lower())
| Anagram Detection | 529eef7a9194e0cbc1000255 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/529eef7a9194e0cbc1000255 | 7 kyu |
### Unfinished Loop - Bug Fixing #1
Oh no, Timmy's created an infinite loop! Help Timmy find and fix the bug in his unfinished for loop!
| bug_fixes | def create_array(n):
res = []
i = 1
while i <= n:
res += [i]
i += 1
return res
| Unfinished Loop - Bug Fixing #1 | 55c28f7304e3eaebef0000da | [
"Debugging"
] | https://www.codewars.com/kata/55c28f7304e3eaebef0000da | 8 kyu |
### The Story:
Bob is working as a bus driver. However, he has become extremely popular amongst the city's residents. With so many passengers wanting to get aboard his bus, he sometimes has to face the problem of not enough space left on the bus! He wants you to write a simple program telling him if he will be able to ... | reference | def enough(cap, on, wait):
return max(0, wait - (cap - on))
| Will there be enough space? | 5875b200d520904a04000003 | [
"Fundamentals"
] | https://www.codewars.com/kata/5875b200d520904a04000003 | 8 kyu |
# altERnaTIng cAsE <=> ALTerNAtiNG CaSe
Define `String.prototype.toAlternatingCase` (or a similar function/method *such as* `to_alternating_case`/`toAlternatingCase`/`ToAlternatingCase` in your selected language; **see the initial solution for details**) such that each lowercase letter becomes uppercase and each uppe... | reference | def to_alternating_case(string):
return string . swapcase()
| altERnaTIng cAsE <=> ALTerNAtiNG CaSe | 56efc695740d30f963000557 | [
"Fundamentals"
] | https://www.codewars.com/kata/56efc695740d30f963000557 | 8 kyu |
Write a class called User that is used to calculate the amount that a user will progress through a ranking system similar to the one Codewars uses.
##### Business Rules:
* A user starts at rank -8 and can progress all the way to 8.
* There is no 0 (zero) rank. The next rank after -1 is 1.
* Users will complete acti... | algorithms | class User:
Ranks = [- 8, - 7, - 6, - 5, - 4, - 3, - 2, - 1, 1, 2, 3, 4, 5, 6, 7, 8]
def __init__(self):
self . __rank = - 8
self . __progress = 0
@ property
def rank(self):
return self . __rank
@ property
def progress(self):
return self . __progress
def inc_prog... | Codewars style ranking system | 51fda2d95d6efda45e00004e | [
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/51fda2d95d6efda45e00004e | 4 kyu |
Your start-up's BA has told marketing that your website has a large audience in Scandinavia and surrounding countries. Marketing thinks it would be great to welcome visitors to the site in their own language. Luckily you already use an API that detects the user's location, so this is an easy win.
### The Task
- Think... | reference | def greet(language):
return {
'czech': 'Vitejte',
'danish': 'Velkomst',
'dutch': 'Welkom',
'english': 'Welcome',
'estonian': 'Tere tulemast',
'finnish': 'Tervetuloa',
'flemish': 'Welgekomen',
'french': 'Bienvenue',
'german': 'Willkomm... | Welcome! | 577ff15ad648a14b780000e7 | [
"Fundamentals"
] | https://www.codewars.com/kata/577ff15ad648a14b780000e7 | 8 kyu |
According to the creation myths of the Abrahamic religions, Adam and Eve were the first Humans to wander the Earth.
You have to do God's job. The creation method must return an array of length 2 containing objects (representing Adam and Eve). The first object in the array should be an instance of the class `Man`. The ... | reference | def God():
return [Man(), Woman()]
class Human (object):
pass
class Man (Human):
pass
class Woman (Human):
pass
| Basic subclasses - Adam and Eve | 547274e24481cfc469000416 | [
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/547274e24481cfc469000416 | 8 kyu |
In this kata, your task is to create all permutations of a non-empty input string and remove duplicates, if present.
Create as many "shufflings" as you can!
Examples:
```
With input 'a':
Your function should return: ['a']
With input 'ab':
Your function should return ['ab', 'ba']
With input 'abc':
Your function sho... | algorithms | import itertools
def permutations(string):
return list("" . join(p) for p in set(itertools . permutations(string)))
| So Many Permutations! | 5254ca2719453dcc0b00027d | [
"Permutations",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5254ca2719453dcc0b00027d | 4 kyu |
In a factory a printer prints labels for boxes. For one kind of boxes
the printer has to use colors which, for the sake of simplicity,
are named with letters from `a to m`.
The colors used by the printer are
recorded in a control string. For example a "good" control string would be
`aaabbbbhaijjjm` meaning that the p... | reference | from re import sub
def printer_error(s):
return "{}/{}" . format(len(sub("[a-m]", '', s)), len(s))
| Printer Errors | 56541980fa08ab47a0000040 | [
"Fundamentals"
] | https://www.codewars.com/kata/56541980fa08ab47a0000040 | 7 kyu |
It's bonus time in the big city! The fatcats are rubbing their paws in anticipation... but who is going to make the most money?
Build a function that takes in two arguments (salary, bonus). Salary will be an integer, and bonus a boolean.
If bonus is true, the salary should be multiplied by 10. If bonus is false, the... | algorithms | def bonus_time(salary, bonus):
return "${}" . format(salary * (10 if bonus else 1))
| Do I get a bonus? | 56f6ad906b88de513f000d96 | [
"Strings",
"Logic"
] | https://www.codewars.com/kata/56f6ad906b88de513f000d96 | 8 kyu |
# Task Overview
Given a non-negative integer `n`, write a function `to_binary`/`ToBinary` which returns that number in a binary format.
<!-- C# documentation -->
```if:csharp
<h1>Documentation:</h1>
<h2>Kata.ToBinary Method (Int32)</h2>
Returns the binary representation of a non-negative integer as an integer.
<spa... | reference | def to_binary(n):
return int(f' { n : b } ')
| Convert to Binary | 59fca81a5712f9fa4700159a | [
"Mathematics",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/59fca81a5712f9fa4700159a | 8 kyu |
We need a function that can transform a number (integer) into a string.
What ways of achieving this do you know?
```if:c
In C, return a dynamically allocated string that will be freed by the test suite.
```
#### Examples (input --> output):
```
123 --> "123"
999 --> "999"
-100 --> "-100"
```
~~~if:riscv
RISC-V: ... | reference | def number_to_string(num):
return str(num)
| Convert a Number to a String! | 5265326f5fda8eb1160004c8 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5265326f5fda8eb1160004c8 | 8 kyu |
Write a function that finds the sum of all its arguments.
eg:
```javascript
sum(1, 2, 3) // => 6
sum(8, 2) // => 10
sum(1, 2, 3, 4, 5) // => 15
```
```php
sum(1, 2, 3) // => 6
sum(8, 2) // => 10
sum(1, 2, 3, 4, 5) // => 15
```
```python
sum_args(1, 2, 3) # => 6
sum_args(8, 2) # => 10
sum_args(1, 2, 3, 4, 5) # => 15
``... | reference | def sum_args(* args):
return sum(args)
| Sum of all arguments | 540c33513b6532cd58000259 | [
"Fundamentals"
] | https://www.codewars.com/kata/540c33513b6532cd58000259 | 7 kyu |
You take your son to the forest to see the monkeys. You know that there are a certain number there (n), but your son is too young to just appreciate the full number, he has to start counting them from 1.
As a good parent, you will sit and count with him. Given the number (n), populate an array with all numbers up to a... | algorithms | def monkey_count(n):
return range(1, n + 1)
| Count the Monkeys! | 56f69d9f9400f508fb000ba7 | [
"Arrays",
"Fundamentals",
"Lists",
"Algorithms"
] | https://www.codewars.com/kata/56f69d9f9400f508fb000ba7 | 8 kyu |
The purpose of this kata is to work out just how many bottles of duty free whiskey you would have to buy such that the savings over the normal high street price would effectively cover the cost of your holiday.
You will be given the high street price (normPrice, in £ (Pounds)), the duty free discount (discount, in per... | reference | def duty_free(price, discount, holiday_cost):
saving = price * discount / 100.0
return int(holiday_cost / saving)
| Holiday VIII - Duty Free | 57e92e91b63b6cbac20001e5 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/57e92e91b63b6cbac20001e5 | 8 kyu |
Create a function that checks if a number `n` is divisible by two numbers `x` **AND** `y`. All inputs are positive, non-zero numbers.
```text
Examples:
1) n = 3, x = 1, y = 3 => true because 3 is divisible by 1 and 3
2) n = 12, x = 2, y = 6 => true because 12 is divisible by 2 and 6
3) n = 100, x = 5, y = 3 =>... | refactoring | def is_divisible(n, x, y):
return n % x == 0 and n % y == 0
| Is n divisible by x and y? | 5545f109004975ea66000086 | [
"Refactoring"
] | https://www.codewars.com/kata/5545f109004975ea66000086 | 8 kyu |
~~~if:java
Create an endless stream of prime numbers - a bit like `IntStream.of(2,3,5,7,11,13,17)`, but infinite. The stream must be able to produce a million primes in a few seconds.
~~~
~~~if:csharp
Create an endless stream of prime numbers - a bit like `IEnumerable<int>(2,3,5,7,11,13,17)`, but infinite. The stream m... | algorithms | import numpy as np
class PrimeSieve:
def __init__(self, maximum):
self . primes = [2, 3]
# self.sieve = [0] * (maximum + 1)
self . sieve = np . zeros(maximum + 1, dtype=np . int8)
for p in self . primes:
self . sieve[p * p:: p] = 1
def extend(self):
p = self . primes[- 1] + ... | Prime Streaming (PG-13) | 5519a584a73e70fa570005f5 | [
"Algorithms"
] | https://www.codewars.com/kata/5519a584a73e70fa570005f5 | 3 kyu |
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.
Implement the function which takes an array containing the names of people that like an item. It must return the display te... | reference | def likes(names):
n = len(names)
return {
0: 'no one likes this',
1: '{} likes this',
2: '{} and {} like this',
3: '{}, {} and {} like this',
4: '{}, {} and {others} others like this'
}[min(4, n)]. format(* names[: 3], others=n - 2)
| Who likes it? | 5266876b8f4bf2da9b000362 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5266876b8f4bf2da9b000362 | 6 kyu |
Removed due to copyright infringement.
<!---
# It's too hot, and they can't even…
One hot summer day Pete and his friend Billy decided to buy watermelons. They chose the biggest crate. They rushed home, dying of thirst, and decided to divide their loot, however they faced a hard problem.
Pete and Billy are great fa... | reference | def divide(weight):
return weight > 2 and weight % 2 == 0
| Watermelon | 55192f4ecd82ff826900089e | [
"Fundamentals",
"Mathematics",
"Algorithms",
"Logic",
"Numbers"
] | https://www.codewars.com/kata/55192f4ecd82ff826900089e | 8 kyu |
Fibonacci numbers are generated by setting F<sub>0</sub> = 0, F<sub>1</sub> = 1, and then using the formula:
# F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub>
Your task is to efficiently calculate the **n**th element in the Fibonacci sequence and then count the occurrence of each digit in the number. Return a list ... | algorithms | from collections import Counter
def fib_digits(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return sorted(((b, int(a)) for a, b in Counter(str(a)). items()), reverse=True)
| Calculate Fibonacci return count of digit occurrences | 5779f894ec8832493f00002d | [
"Algorithms"
] | https://www.codewars.com/kata/5779f894ec8832493f00002d | 5 kyu |
You're writing code to control your town's traffic lights. You need a function to handle each change from `green`, to `yellow`, to `red`, and then to `green` again.
Complete the function that takes a string as an argument representing the current state of the light and returns a string representing the state the ligh... | reference | def update_light(current):
return {"green": "yellow", "yellow": "red", "red": "green"}[current]
| Thinkful - Logic Drills: Traffic light | 58649884a1659ed6cb000072 | [
"Fundamentals"
] | https://www.codewars.com/kata/58649884a1659ed6cb000072 | 8 kyu |
Complete the square sum function so that it squares each number passed into it and then sums the results together.
For example, for `[1, 2, 2]` it should return `9` because `$1^2 + 2^2 + 2^2 = 9$`.
```if:racket
In Racket, use a list instead of an array, so '(1 2 2) should return 9.
```
| reference | def square_sum(numbers):
return sum(x * * 2 for x in numbers)
| Square(n) Sum | 515e271a311df0350d00000f | [
"Arrays",
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/515e271a311df0350d00000f | 8 kyu |
Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not.
Valid examples, should return true:
```javascript
isDigit("3")
isDigit(" 3 ")
isDigit("-3.23")
```
should return false:
```javascript
isDigit("3-4")
isDigit(" 3 5")
isDigit("3... | reference | def isDigit(string):
try:
float(string)
return True
except:
return False
| Is it a number? | 57126304cdbf63c6770012bd | [
"Fundamentals"
] | https://www.codewars.com/kata/57126304cdbf63c6770012bd | 8 kyu |
Your task is to write function `factorial`.
https://en.wikipedia.org/wiki/Factorial
| reference | from math import factorial
| Factorial | 57a049e253ba33ac5e000212 | [
"Fundamentals"
] | https://www.codewars.com/kata/57a049e253ba33ac5e000212 | 7 kyu |
Implement a function which convert the given boolean value into its string representation.
Note: Only valid inputs will be given.
| reference | def boolean_to_string(b):
return str(b)
| Convert a Boolean to a String | 551b4501ac0447318f0009cd | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/551b4501ac0447318f0009cd | 8 kyu |
write me a function `stringy` that takes a `size` and returns a `string` of alternating `1`s and `0`s.
the string should start with a `1`.
a string with `size` 6 should return :`'101010'`.
with `size` 4 should return : `'1010'`.
with `size` 12 should return : `'101010101010'`.
The size will always be positive and ... | algorithms | def stringy(size):
return ('10' * size)[: size]
| Stringy Strings | 563b74ddd19a3ad462000054 | [
"Strings",
"Binary",
"Algorithms"
] | https://www.codewars.com/kata/563b74ddd19a3ad462000054 | 8 kyu |
Write a function that accepts a square matrix (`N x N` 2D array) and returns the determinant of the matrix.
How to take the determinant of a matrix -- it is simplest to start with the smallest cases:
A 1x1 matrix `|a|` has determinant `a`.
A 2x2 matrix `[ [a, b], [c, d] ]` or
```
|a b|
|c d|
```
has determinant: `... | algorithms | import numpy as np
def determinant(a):
return round(np . linalg . det(np . matrix(a)))
| Matrix Determinant | 52a382ee44408cea2500074c | [
"Matrix",
"Linear Algebra",
"Mathematics",
"Recursion",
"Algorithms"
] | https://www.codewars.com/kata/52a382ee44408cea2500074c | 4 kyu |
What could be easier than comparing integer numbers? However, the given piece of code doesn't recognize some of the special numbers for a reason to be found. Your task is to find the bug and eliminate it. | bug_fixes | def what_is(x):
if x == 42:
return 'everything'
elif x == 42 * 42:
return 'everything squared'
else:
return 'nothing'
| How do I compare numbers? | 55d8618adfda93c89600012e | [
"Fundamentals",
"Debugging"
] | https://www.codewars.com/kata/55d8618adfda93c89600012e | 8 kyu |
~~~if:pascal
Make a simple function called `Greet` that returns the most-famous "hello world!".
~~~
~~~if-not:pascal
Make a simple function called `greet` that returns the most-famous "hello world!".
~~~
### Style Points
Sure, this is about as easy as it gets. But how clever can you be to create the most creative "he... | reference | def greet():
return "hello world!"
| Function 1 - hello world | 523b4ff7adca849afe000035 | [
"Fundamentals"
] | https://www.codewars.com/kata/523b4ff7adca849afe000035 | 8 kyu |
Just like in the ["father" kata](http://www.codewars.com/kata/find-fibonacci-last-digit/), you will have to return the last digit of the nth element in the Fibonacci sequence (starting with 1,1, to be extra clear, not with 0,1 or other numbers).
You will just get much bigger numbers, so good luck bruteforcing your way... | algorithms | def last_fib_digit(n):
return [0, 1, 1, 2, 3, 5, 8, 3, 1, 4, 5, 9, 4, 3, 7, 0, 7, 7, 4, 1, 5, 6, 1, 7, 8, 5, 3, 8, 1, 9, 0, 9, 9, 8, 7, 5, 2, 7, 9, 6, 5, 1, 6, 7, 3, 0, 3, 3, 6, 9, 5, 4, 9, 3, 2, 5, 7, 2, 9, 1][n % 60]
| Find last Fibonacci digit [hardcore version] | 56b7771481290cc283000f28 | [
"Algorithms"
] | https://www.codewars.com/kata/56b7771481290cc283000f28 | 6 kyu |
### Problem Context
The [Fibonacci](http://en.wikipedia.org/wiki/Fibonacci_number) sequence is traditionally used to explain tree recursion.
```javascript
function fibonacci(n) {
if(n==0 || n == 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}
```
```ruby
def fibonacci(n)
return n if (0..1).... | refactoring | def memoized(f):
cache = {}
def wrapped(k):
v = cache . get(k)
if v is None:
v = cache[k] = f(k)
return v
return wrapped
@ memoized
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
| Memoized Fibonacci | 529adbf7533b761c560004e5 | [
"Memoization",
"Refactoring"
] | https://www.codewars.com/kata/529adbf7533b761c560004e5 | 5 kyu |
Write two functions that convert a roman numeral to and from an integer value. Multiple roman numeral values will be tested for each function.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals:
* `1990`... | algorithms | from collections import OrderedDict
import re
ROMAN_NUMERALS = OrderedDict([
('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1),
])
DECIMAL_TO_ROMAN =... | Roman Numerals Helper | 51b66044bce5799a7f000003 | [
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/51b66044bce5799a7f000003 | 4 kyu |
Some numbers have funny properties. For example:
* 89 --> 8¹ + 9² = 89 * 1
* 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
* 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given two positive integers `n` and `p`, we want to find a positive integer `k`, if it exists, such that the sum of the digits of `n` raised to con... | reference | def dig_pow(n, p):
s = 0
for i, c in enumerate(str(n)):
s += pow(int(c), p + i)
return s / n if s % n == 0 else - 1
| Playing with digits | 5552101f47fc5178b1000050 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5552101f47fc5178b1000050 | 6 kyu |
Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
### Examples:
Input: `42145`
Output: `54421`
Input: `145263`
Output: `654321`
Input: `123456789`
Output: ... | reference | def Descending_Order(num):
return int("" . join(sorted(str(num), reverse=True)))
| Descending Order | 5467e4d82edf8bbf40000155 | [
"Fundamentals"
] | https://www.codewars.com/kata/5467e4d82edf8bbf40000155 | 7 kyu |
Write a function called `LCS` that accepts two sequences and returns the longest subsequence common to the passed in sequences.
### Subsequence
A subsequence is different from a substring. The terms of a subsequence need not be consecutive terms of the original sequence.
### Example subsequence
Subsequences of `"abc"... | algorithms | def lcs(x, y):
if len(x) == 0 or len(y) == 0:
return ''
if x[- 1] == y[- 1]:
return lcs(x[: - 1], y[: - 1]) + x[- 1]
else:
lcs1 = lcs(x, y[: - 1])
lcs2 = lcs(x[: - 1], y)
if len(lcs1) > len(lcs2):
return lcs1
else:
return lcs2
| Longest Common Subsequence | 52756e5ad454534f220001ef | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/52756e5ad454534f220001ef | 5 kyu |
- A friend of mine takes the sequence of all numbers from 1 to n (where n > 0).
- Within that sequence, he chooses two numbers, a and b.
- He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b.
- Given a number n, could you tell me the numbers he excluded from ... | games | def removNb(n):
total = n * (n + 1) / 2
sol = []
for a in range(1, n + 1):
b = (total - a) / (a + 1.0)
if b . is_integer() and b <= n:
sol . append((a, int(b)))
return sol
| Is my friend cheating? | 5547cc7dcad755e480000004 | [
"Fundamentals",
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5547cc7dcad755e480000004 | 5 kyu |
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```javascript
solution('abc', 'bc') // returns true
solution('abc', 'd') // returns false
```
```coffeescript
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns... | reference | def solution(string, ending):
return string . endswith(ending)
| String ends with? | 51f2d1cafc9c0f745c00037d | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/51f2d1cafc9c0f745c00037d | 7 kyu |
Given a month as an integer from 1 to 12, return to which quarter of the year it belongs as an integer
number.
For example: month 2 (February), is part of the first quarter; month 6 (June), is part of the second quarter; and month 11 (November), is part of the fourth quarter.
Constraint:
* `1 <= month <= 12` | reference | def quarter_of(month):
# your code here
if month in range(1, 4):
return 1
elif month in range(4, 7):
return 2
elif month in range(7, 10):
return 3
elif month in range(10, 13):
return 4
| Quarter of the year | 5ce9c1000bab0b001134f5af | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5ce9c1000bab0b001134f5af | 8 kyu |
Complete the function, which calculates how much you need to tip based on the total amount of the bill and the service.
You need to consider the following ratings:
- Terrible: tip 0%
- Poor: tip 5%
- Good: tip 10%
- Great: tip 15%
- Excellent: tip 20%
The rating is **case insensitive** (so "great" = "GREAT"). If an... | reference | from math import ceil
def calculate_tip(amount, rating):
tips = {
'terrible': 0,
'poor': .05,
'good': .1,
'great': .15,
'excellent': .2
}
if rating . lower() in tips:
return ceil(amount * tips[rating . lower()])
else:
return 'Rating not rec... | Tip Calculator | 56598d8076ee7a0759000087 | [
"Fundamentals"
] | https://www.codewars.com/kata/56598d8076ee7a0759000087 | 8 kyu |
Removed due to copyright infringement.
<!---
Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words (that don't con... | reference | def song_decoder(song):
return " " . join(song . replace('WUB', ' '). split())
| Dubstep | 551dc350bf4e526099000ae5 | [
"Fundamentals",
"Strings",
"Data Types"
] | https://www.codewars.com/kata/551dc350bf4e526099000ae5 | 6 kyu |
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
*Example*: The binary representation of `1234` is `10011010010`, so the function should return `5` in this case
| algorithms | def countBits(n):
return bin(n). count("1")
| Bit Counting | 526571aae218b8ee490006f4 | [
"Bits",
"Algorithms"
] | https://www.codewars.com/kata/526571aae218b8ee490006f4 | 6 kyu |
You are going to be given a string. Your job is to return that string in a certain order that I will explain below:
Let's say you start with this: `"012345"`
The first thing you do is reverse it:`"543210"`
Then you will take the string from the 1st position and reverse it again:`"501234"`
Then you will take the s... | algorithms | def reverse_fun(n):
for i in range(len(n)):
n = n[: i] + n[i:][:: - 1]
return n
| Reversing Fun | 566efcfbf521a3cfd2000056 | [
"Strings",
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/566efcfbf521a3cfd2000056 | 7 kyu |
Nickname Generator
Write a function, `nicknameGenerator` that takes a string name as an argument and returns the first 3 or 4 letters as a nickname.
If the 3rd letter is a consonant, return the first 3 letters.
```javascript
nickname("Robert") //=> "Rob"
nickname("Kimberly") //=> "Kim"
nickname("Samantha") //=> "Sam... | reference | def nickname_generator(name):
return "Error: Name too short" if len(name) < 4 else name[: 3 + (name[2] in "aeiuo")]
| Nickname Generator | 593b1909e68ff627c9000186 | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/593b1909e68ff627c9000186 | 7 kyu |
<h1>How many bees are in the beehive?</h1>
* bees can be facing UP, DOWN, LEFT, or RIGHT
* bees can share parts of other bees
<h1>Examples</h1>
Ex1
```
bee.bee
.e..e..
.b..eeb
```
*Answer: 5*
<hr>
Ex2
```
bee.bee
e.e.e.e
eeb.eeb
```
*Answer: 8*
# Notes
* The hive may be empty or null/None/nil/...
* Pyt... | reference | from itertools import chain
def how_many_bees(hive):
return bool(hive) and sum(s . count('bee') + s . count('eeb') for s in map('' . join, chain(hive, zip(* hive))))
| Spelling Bee | 57d6b40fbfcdc5e9280002ee | [
"Fundamentals"
] | https://www.codewars.com/kata/57d6b40fbfcdc5e9280002ee | 6 kyu |
All of the animals are having a feast! Each animal is bringing one dish. There is just one rule: the dish must start and end with the same letters as the animal's name. For example, the great blue heron is bringing garlic naan and the chickadee is bringing chocolate cake.
Write a function `feast` that takes the animal... | reference | def feast(beast, dish):
return beast[0] == dish[0] and dish[- 1] == beast[- 1]
| The Feast of Many Beasts | 5aa736a455f906981800360d | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5aa736a455f906981800360d | 8 kyu |
## Grade book
Complete the function so that it finds the average of the three scores passed to it and returns the letter value associated with that grade.
Numerical Score | Letter Grade
--- | ---
90 <= score <= 100 | 'A'
80 <= score < 90 | 'B'
70 <= score < 80 | 'C'
60 <= score < 70 | 'D'
0 <... | reference | def get_grade(s1, s2, s3):
m = (s1 + s2 + s3) / 3.0
if 90 <= m <= 100:
return 'A'
elif 80 <= m < 90:
return 'B'
elif 70 <= m < 80:
return 'C'
elif 60 <= m < 70:
return 'D'
return "F"
| Grasshopper - Grade book | 55cbd4ba903825f7970000f5 | [
"Fundamentals"
] | https://www.codewars.com/kata/55cbd4ba903825f7970000f5 | 8 kyu |
Write a function that takes a positive integer n, sums all the cubed values from 1 to n (inclusive), and returns that sum.
Assume that the input n will always be a positive integer.
Examples: **(Input --> output)**
```
2 --> 9 (sum of the cubes of 1 and 2 is 1 + 8)
3 --> 36 (sum of the cubes of 1, 2, and 3 is 1 + 8 +... | reference | def sum_cubes(n):
return sum(i * * 3 for i in range(0, n + 1))
| Sum of Cubes | 59a8570b570190d313000037 | [
"Fundamentals"
] | https://www.codewars.com/kata/59a8570b570190d313000037 | 7 kyu |
## Snail Sort
Given an `n x n` array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
```
array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
```
For better understanding, please follow the numbers of the next array consecu... | algorithms | import numpy as np
def snail(array):
m = []
array = np . array(array)
while len(array) > 0:
m += array[0]. tolist()
array = np . rot90(array[1:])
return m
| Snail | 521c2db8ddc89b9b7a0000c1 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1 | 4 kyu |
Your task is to find the first element of an array that is not consecutive.
By not consecutive we mean not exactly 1 larger than the previous element of the array.
E.g. If we have an array `[1,2,3,4,6,7,8]` then `1` then `2` then `3` then `4` are all consecutive but `6` is not, so that's the first non-consecutive num... | reference | def first_non_consecutive(arr):
if not arr:
return 0
for i, x in enumerate(arr[: - 1]):
if x + 1 != arr[i + 1]:
return arr[i + 1]
| Find the first non-consecutive number | 58f8a3a27a5c28d92e000144 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/58f8a3a27a5c28d92e000144 | 8 kyu |
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
#Examples:
```
Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.... | reference | def get_middle(s):
index, odd = divmod(len(s), 2)
return s[index] if odd else s[index - 1: index + 1]
| Get the Middle Character | 56747fd5cb988479af000028 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/56747fd5cb988479af000028 | 7 kyu |
Write a function which converts the input string to uppercase.
~~~if:bf
For BF all inputs end with \0, all inputs are lowercases and there is no space between.
~~~
~~~if:riscv
RISC-V: The function signature is
```c
void to_upper_case(const char *str, char *out);
```
`str` is the input string. Write your result to `... | reference | def make_upper_case(s): return s . upper()
| MakeUpperCase | 57a0556c7cb1f31ab3000ad7 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/57a0556c7cb1f31ab3000ad7 | 8 kyu |
Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array.
For example:
```r
solution(c(1, 2, 3, 10, 5)) # should return c(1, 2, 3, 5, 10)
solution(NULL) # should return NULL
```
```php
solution([1,... | reference | def solution(nums):
return sorted(nums) if nums else []
| Sort Numbers | 5174a4c0f2769dd8b1000003 | [
"Fundamentals"
] | https://www.codewars.com/kata/5174a4c0f2769dd8b1000003 | 7 kyu |
# Remove Duplicates
You are to write a function called `unique` that takes an array of integers and returns the array with duplicates removed. It must return the values in the same order as first seen in the given array. Thus no sorting should be done, if 52 appears before 10 in the given array then it should also be ... | reference | from collections import OrderedDict
def unique(integers):
return list(OrderedDict . fromkeys(integers))
| Remove Duplicates | 53e30ec0116393fe1a00060b | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/53e30ec0116393fe1a00060b | 7 kyu |
## Too long, didn't read
You get a list of integers, and you have to write a function `mirror` that returns the "mirror" (or symmetric) version of this list: i.e. the middle element is the greatest, then the next greatest on both sides, then the next greatest, and so on...
## More info
The list will always consist ... | reference | def mirror(data: list) - > list:
arr = sorted(data)
return arr + arr[- 2:: - 1]
| Mirror, mirror, on the wall... | 5f55ecd770692e001484af7d | [
"Algorithms",
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5f55ecd770692e001484af7d | 7 kyu |
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
### Examples
``` text
Input: 1 => Output: -1
Input: -5 => Output: -5
Input: 0 => Output: 0
```
``` c
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // retu... | reference | def make_negative(number):
return - abs(number)
| Return Negative | 55685cd7ad70877c23000102 | [
"Fundamentals"
] | https://www.codewars.com/kata/55685cd7ad70877c23000102 | 8 kyu |
Given a positive number n > 1 find the prime factor decomposition of n.
The result will be a string with the following form :
```
"(p1**n1)(p2**n2)...(pk**nk)"
```
with the p(i) in increasing order and n(i) empty if
n(i) is 1.
```
Example: n = 86240 should return "(2**5)(5)(7**2)(11)"
```
| reference | def primeFactors(n):
i = 2
r = ''
while n != 1:
k = 0
while n % i == 0:
n = n / i
k += 1
if k == 1:
r = r + '(' + str(i) + ')'
elif k == 0:
pass
else:
r = r + '(' + str(i) + '**' + str(k) + ')'
i += 1
return r
| Primes in numbers | 54d512e62a5e54c96200019e | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/54d512e62a5e54c96200019e | 5 kyu |
[Digital root](https://en.wikipedia.org/wiki/Digital_root) is the _recursive sum of all the digits in a number._
Given `n`, take the sum of the digits of `n`. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
## Exam... | algorithms | def digital_root(n):
return n if n < 10 else digital_root(sum(map(int, str(n))))
| Sum of Digits / Digital Root | 541c8630095125aba6000c00 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/541c8630095125aba6000c00 | 6 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 2/3</div>
<div>
This kata is part of a s... | algorithms | def decodeBits(bits):
import re
# remove trailing and leading 0's
bits = bits . strip('0')
# find the least amount of occurrences of either a 0 or 1, and that is the time hop
time_unit = min(len(m) for m in re . findall(r'1+|0+', bits))
# hop through the bits and translate to morse
... | Decode the Morse code, advanced | 54b72c16cd7f5154e9000457 | [
"Algorithms"
] | https://www.codewars.com/kata/54b72c16cd7f5154e9000457 | 4 kyu |
Given the triangle of consecutive odd numbers:
```
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
```
Calculate the sum of the numbers in the n<sup>th</sup> row of this triangle (starting at index 1) e.g.: (**Input --> Output**)
```
1 --> 1
2 --> 3 + 5 =... | reference | def row_sum_odd_numbers(n):
# your code here
return n * * 3
| Sum of odd numbers | 55fd2d567d94ac3bc9000064 | [
"Arrays",
"Lists",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/55fd2d567d94ac3bc9000064 | 7 kyu |
Clock shows `h` hours, `m` minutes and `s` seconds after midnight.
Your task is to write a function which returns the time since midnight in milliseconds.
## Example:
```
h = 0
m = 1
s = 1
result = 61000
```
Input constraints:
* `0 <= h <= 23`
* `0 <= m <= 59`
* `0 <= s <= 59`
~~~if:riscv
RISC-V: The function si... | reference | def past(h, m, s):
return (3600 * h + 60 * m + s) * 1000
| Beginner Series #2 Clock | 55f9bca8ecaa9eac7100004a | [
"Fundamentals"
] | https://www.codewars.com/kata/55f9bca8ecaa9eac7100004a | 8 kyu |
## Intro:
I was doing a coding challenge. It was one of those multi-step challenges. I don't know if my approach was good or bad, but in one of these steps I was writing a function to convert word to numbers. I did it.. eventually, but... I didn't like how it was written. So I thought why not create kata and check how... | reference | def convert(s):
w2n = dict(zip(dict . fromkeys(s . upper()), '1023456789'))
return int('0' + '' . join([w2n[ch] for ch in s . upper()]))
| Word to initial number | 5bb148b840196d1be50000b1 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5bb148b840196d1be50000b1 | 6 kyu |
You're on your way to the market when you hear beautiful music coming from a nearby street performer. The notes come together like you wouln't believe as the musician puts together patterns of tunes. As you wonder what kind of algorithm you could use to shift octaves by 8 pitches or something silly like that, it dawns ... | reference | def is_lock_ness_monster(s):
return any(i in s for i in ('tree fiddy', 'three fifty', '3.50'))
| A Strange Trip to the Market | 55ccdf1512938ce3ac000056 | [
"Regular Expressions",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/55ccdf1512938ce3ac000056 | 8 kyu |
## Debugging sayHello function
The starship Enterprise has run into some problem when creating a program to greet everyone as they come aboard. It is your job to fix the code and get the program working again!
Example output:
```
Hello, Mr. Spock
``` | reference | def say_hello(name):
return f"Hello, { name } "
| Grasshopper - Debug sayHello | 5625618b1fe21ab49f00001f | [
"Fundamentals"
] | https://www.codewars.com/kata/5625618b1fe21ab49f00001f | 8 kyu |
Consider a sequence `u` where u is defined as follows:
1. The number `u(0) = 1` is the first one in `u`.
2. For each `x` in `u`, then `y = 2 * x + 1` and `z = 3 * x + 1` must be in `u` too.
3. There are no other numbers in `u`.
Ex:
`u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]`
1 gives 3 and 4, then 3 gives... | algorithms | from collections import deque
def dbl_linear(n):
h = 1
cnt = 0
q2, q3 = deque([]), deque([])
while True:
if (cnt >= n):
return h
q2 . append(2 * h + 1)
q3 . append(3 * h + 1)
h = min(q2[0], q3[0])
if h == q2[0]:
h = q2 . popleft()
if h == q3[0]:
... | Twice linear | 5672682212c8ecf83e000050 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5672682212c8ecf83e000050 | 4 kyu |
Write function bmi that calculates body mass index (bmi = weight / height<sup>2</sup>).
if bmi <= 18.5 return "Underweight"
if bmi <= 25.0 return "Normal"
if bmi <= 30.0 return "Overweight"
if bmi > 30 return "Obese" | reference | def bmi(weight, height):
bmi = weight / height * * 2
if bmi <= 18.5:
return "Underweight"
elif bmi <= 25:
return "Normal"
elif bmi <= 30:
return "Overweight"
else:
return "Obese"
| Calculate BMI | 57a429e253ba3381850000fb | [
"Fundamentals"
] | https://www.codewars.com/kata/57a429e253ba3381850000fb | 8 kyu |
You are given a method called `main`, make it print the line `Hello World!`, (yes, that includes a new line character at the end) and don't return anything
Note that for some languages, the function `main` is the entry point of the program.
Here's how it will be tested:
```java
java Solution.class parameter1 para... | reference | class Solution:
@ staticmethod
def main(self, * args):
print("Hello World!")
| Classic Hello World | 57036f007fd72e3b77000023 | [
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/57036f007fd72e3b77000023 | 8 kyu |
### Story
Ben has a very simple idea to make some profit: he buys something and sells it again. Of course, this wouldn't give him any profit at all if he was simply to buy and sell it at the same price. Instead, he's going to buy it for the lowest possible price and sell it at the highest.
### Task
Write a function ... | reference | def min_max(lst):
return [min(lst), max(lst)]
| The highest profit wins! | 559590633066759614000063 | [
"Lists",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/559590633066759614000063 | 7 kyu |
And here is Fibonacci again. This time we want to go one step further. Our `fib()` function must be faster! Can you do it?
In case you don't know, what the Fibonacci number is:
The `n`th Fibonacci number is defined by the sum of the two previous Fibonacci numbers. In our case: `fib(1) := 0` and `fib(2) := 1`. With th... | algorithms | def fib(n):
a, b = 0, 1
for _ in range(n - 1):
a, b = b, a + b
return a
| Fibonacci Reloaded | 52549d3e19453df56f0000fe | [
"Algorithms"
] | https://www.codewars.com/kata/52549d3e19453df56f0000fe | 6 kyu |
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example:
5! = 5 \* 4 \* 3 \* 2 \* 1 = 120. By convention the value of 0! is 1.
~~~if-not:factor
Write a function to calculate factorial for a given input. If input is below 0 o... | reference | def factorial(n):
if n < 0 or n > 12:
raise ValueError
return 1 if n <= 1 else n * factorial(n - 1)
| Factorial | 54ff0d1f355cfd20e60001fc | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/54ff0d1f355cfd20e60001fc | 7 kyu |
# Are the numbers in order?
In this Kata, your function receives an array of integers as input. Your task is to determine whether the numbers are in ascending order. An array is said to be in ascending order if there are no two adjacent integers where the left integer exceeds the right integer in value.
For the pur... | algorithms | def in_asc_order(arr):
return arr == sorted(arr)
| Are the numbers in order? | 56b7f2f3f18876033f000307 | [
"Fundamentals",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/56b7f2f3f18876033f000307 | 7 kyu |
````if:cobol
Implement a function called **`mult`**, which takes two numbers and returns their product:
```
call 'mult' using by content 10 20 by reference result
result = 200
call 'mult' using by content 0 758 by reference result
result = 0
call 'mult' using by content 154 99 by reference result
result = 15246
```
... | reference | def multiply(x, y):
return x * y
| Function 3 - multiplying two numbers | 523b66342d0c301ae400003b | [
"Fundamentals"
] | https://www.codewars.com/kata/523b66342d0c301ae400003b | 8 kyu |
Create a function which answers the question "Are you playing banjo?".
If your name starts with the letter "R" or lower case "r", you are playing banjo!
The function takes a name as its only argument, and returns one of the following strings:
```
name + " plays banjo"
name + " does not play banjo"
```
Names given a... | reference | def areYouPlayingBanjo(name):
if name[0]. lower() == 'r':
return name + ' plays banjo'
else:
return name + ' does not play banjo'
| Are You Playing Banjo? | 53af2b8861023f1d88000832 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/53af2b8861023f1d88000832 | 8 kyu |
Your task is to create a function that does four basic mathematical operations.
The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.
### Examples(Operator, value1, value2) --> output
~~~i... | reference | def basic_op(operator, value1, value2):
if operator == '+':
return value1 + value2
if operator == '-':
return value1 - value2
if operator == '/':
return value1 / value2
if operator == '*':
return value1 * value2
| Basic Mathematical Operations | 57356c55867b9b7a60000bd7 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/57356c55867b9b7a60000bd7 | 8 kyu |
Given an array of integers, return a new array with each value doubled.
For example:
`[1, 2, 3] --> [2, 4, 6]`
~~~if:racket
```racket
;for racket you are given a list
(maps '(1 2 3)) ; returns '(2 4 6)
```
~~~ | reference | def maps(a):
return [2 * x for x in a]
| Beginner - Lost Without a Map | 57f781872e3d8ca2a000007e | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/57f781872e3d8ca2a000007e | 8 kyu |
Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.
If you want to know more: http://en.wikipedia.org/wiki/DNA
In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G".
Your function r... | reference | import string
def DNA_strand(dna):
return dna . translate(string . maketrans("ATCG", "TAGC"))
# Python 3.4 solution || you don't need to import anything :)
# return dna.translate(str.maketrans("ATCG","TAGC"))
| Complementary DNA | 554e4a2f232cdd87d9000038 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/554e4a2f232cdd87d9000038 | 7 kyu |
```if-not:javascript
Find the sum of the odd numbers within an array, after cubing the initial integers. The function should return `undefined`/`None`/`nil`/`NULL` if any of the values aren't numbers.
```
```if:javascript
Find the sum of the odd numbers within an array, after cubing the initial integers. The function s... | reference | def cube_odd(arr):
return sum(n * * 3 for n in arr if n % 2) if all(type(n) == int for n in arr) else None
| Sum of Odd Cubed Numbers | 580dda86c40fa6c45f00028a | [
"Fundamentals",
"Functional Programming",
"Arrays"
] | https://www.codewars.com/kata/580dda86c40fa6c45f00028a | 7 kyu |
In computer science, cycle detection is the algorithmic problem of finding a cycle in a sequence of iterated function values.
For any function `$f$`, and any initial value `$x_0$` in S, the sequence of iterated function values
```math
x_0, x_1 = f(x_0), \dots ,x_i = f(x_{i-1}), \dots
```
may eventually use the sa... | algorithms | def cycle(sequence):
for j, x in enumerate(sequence):
i = sequence . index(x)
if 0 <= i < j:
return [i, j - i]
return []
| Cycle Detection: greedy algorithm | 5416f1834c24604c46000696 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5416f1834c24604c46000696 | 6 kyu |
### Introduction
The first century spans from the **year 1** up to *and including* the year 100, the second century - from the year 101 up to *and including* the year 200, etc.
### Task
Given a year, return the century it is in.
### Examples
```
1705 --> 18
1900 --> 19
1601 --> 17
2000 --> 20
2742 --> 28
```
``... | reference | def century(year):
return (year + 99) / / 100
| Century From Year | 5a3fe3dde1ce0e8ed6000097 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5a3fe3dde1ce0e8ed6000097 | 8 kyu |
In this Kata we are passing a number (n) into a function.
Your code will determine if the number passed is even (or not).
The function needs to return either a true or false.
Numbers may be positive or negative, integers or floats.
Floats with decimal part non equal to zero are considered UNeven for this kata. | reference | def is_even(n):
return n % 2 == 0
| Is it even? | 555a67db74814aa4ee0001b5 | [
"Fundamentals"
] | https://www.codewars.com/kata/555a67db74814aa4ee0001b5 | 8 kyu |
# Dot Calculator
You have to write a calculator that receives strings for input.
The dots will represent the number in the equation.
There will be dots on one side, an operator, and dots again after the operator.
The dots and the operator will be separated by one space.
Here are the following valid operators :
- `+`... | reference | def calculator(txt):
a, op, b = txt . split()
a, b = len(a), len(b)
return '.' * eval(f' { a } { op } { b } ')
| Dot Calculator | 6071ef9cbe6ec400228d9531 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/6071ef9cbe6ec400228d9531 | 7 kyu |
This is an easy twist to the example kata (provided by Codewars when learning how to create your own kata).
Add the value "codewars" to the array `websites` 1,000 times.
| reference | websites = ["codewars"] * 1000
| Kata Example Twist | 525c1a07bb6dda6944000031 | [
"Fundamentals"
] | https://www.codewars.com/kata/525c1a07bb6dda6944000031 | 8 kyu |
Create a function that accepts a string and a single character, and returns an integer of the count of occurrences the 2nd argument is found in the first one.
If no occurrences can be found, a count of 0 should be returned.
```
("Hello", "o") ==> 1
("Hello", "l") ==> 2
("", "z") ==> 0
```
```c
str_count("H... | reference | def strCount(string, letter):
return string . count(letter)
| All Star Code Challenge #18 | 5865918c6b569962950002a1 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5865918c6b569962950002a1 | 8 kyu |
There was a test in your class and you passed it. Congratulations!
But you're an ambitious person. You want to know if you're better than the average student in your class.
You receive an array with your peers' test scores. Now calculate the average and compare your score!
~~~if-not:nasm,racket
Return `true` if... | reference | def better_than_average(class_points, your_points):
return your_points > sum(class_points) / len(class_points)
| How good are you really? | 5601409514fc93442500010b | [
"Fundamentals"
] | https://www.codewars.com/kata/5601409514fc93442500010b | 8 kyu |
Write a function that determines whether a string is a valid guess in a Boggle board, as per the rules of Boggle. A Boggle board is a 2D array of individual characters, e.g.:
```javascript
[ ["I","L","A","W"],
["B","N","G","E"],
["I","U","A","O"],
["A","S","R","L"] ]
```
```python
[ ["I","L","A","W"],
["B","N",... | games | def find_word(board, word):
grid = [l + [''] for l in board] + [[''] * (len(board[0]) + 1)]
def rc(x, y, i):
if i == len(word):
return True
if grid[x][y] != word[i]:
return False
grid[x][y] = ''
r = any(rc(x + u, y + v, i + 1)
for u in range(- 1, 2)
... | Boggle Word Checker | 57680d0128ed87c94f000bfd | [
"Arrays",
"Recursion",
"Puzzles"
] | https://www.codewars.com/kata/57680d0128ed87c94f000bfd | 4 kyu |
Note: This kata is inspired by [Convert a Number to a String!](http://www.codewars.com/kata/convert-a-number-to-a-string/). Try that one too.
## Description
We need a function that can transform a string into a number. What ways of achieving this do you know?
Note: Don't worry, all inputs will be strings, and every ... | reference | def string_to_number(s):
return int(s)
| Convert a String to a Number! | 544675c6f971f7399a000e79 | [
"Parsing",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/544675c6f971f7399a000e79 | 8 kyu |
Born a misinterpretation of [this kata](https://www.codewars.com/kata/simple-fun-number-334-two-beggars-and-gold/), your task here is pretty simple: given an array of values and an amount of beggars, you are supposed to return an array with the sum of what each beggar brings home, assuming they all take regular turns, ... | reference | def beggars(values, n):
return [sum(values[i:: n]) for i in range(n)]
| English beggars | 59590976838112bfea0000fa | [
"Queues",
"Arrays",
"Lists",
"Recursion",
"Fundamentals"
] | https://www.codewars.com/kata/59590976838112bfea0000fa | 6 kyu |
Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.
The output should be two capital letters with a dot separating them.
It should look like this:
`Sam Harris` => `S.H`
`patrick feeney` => `P.F`
~~~if:riscv
RISC-V: The function signature is:
```c
ch... | reference | def abbrevName(name):
return '.' . join(w[0] for w in name . split()). upper()
| Abbreviate a Two Word Name | 57eadb7ecd143f4c9c0000a3 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/57eadb7ecd143f4c9c0000a3 | 8 kyu |
Given a non-empty array of integers, return the result of multiplying the values together in order. Example:
```
[1, 2, 3, 4] => 1 * 2 * 3 * 4 = 24
```
| reference | def grow(arr):
product = 1
for i in arr :
product *= i
return product | Beginner - Reduce but Grow | 57f780909f7e8e3183000078 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/57f780909f7e8e3183000078 | 8 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.