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
<h1>Story</h1> Imagine a frog sitting on the top of a staircase which has <code>steps</code> number of steps in it. </br> A frog can jump down over the staircase and at 1 single jump it can go from 1 to <code>maxJumpLength</code> steps down. <img src="https://t4.ftcdn.net/jpg/05/63/41/31/360_F_563413161_oGBZ26aTsBgWVI7...
algorithms
def get_number_of_ways(steps, mjl): res = [2 * * k for k in range(mjl)] for _ in range(steps - mjl): res . append(sum(res[- mjl:])) return res[steps - 1]
Jumping down the staircase
647d08a2c736e3777c9ae1db
[ "Dynamic Programming" ]
https://www.codewars.com/kata/647d08a2c736e3777c9ae1db
6 kyu
The **[Prime](https://codegolf.stackexchange.com/questions/144695/the-prime-ant) [ant](https://math.stackexchange.com/questions/2487116/does-the-prime-ant-ever-backtrack)** ([A293689](http://oeis.org/A293689)) is an obstinate animal that navigates the integers and divides them until there are only primes left, accordin...
reference
def smallerDiv(n): return next((x for x in range(2, int(n * * .5) + 1) if not n % x), 0) def prime_ant(turns): p, lst = 0, [2, 3] for _ in range(turns): if p == len(lst): lst . append(p + 2) sDiv = smallerDiv(lst[p]) if sDiv: lst[p - 1] += sDiv lst[p] / /= sDiv p -= 1 ...
Prime ant
5a2c084ab6cfd7f0840000e4
[ "Mathematics", "Logic", "Arrays", "Games", "Fundamentals" ]
https://www.codewars.com/kata/5a2c084ab6cfd7f0840000e4
6 kyu
# Task You are given two numbers `a` and `b` where `0 ≤ a ≤ b`. Imagine you construct an array of all the integers from `a` to `b` inclusive. You need to count the number of `1`s in the binary representations of all the numbers in the array. # Example For a = 2 and b = 7, the output should be `11` Given a = 2 and...
games
def range_bit_count(a, b): return sum(bin(i). count('1') for i in range(a, b + 1))
Simple Fun #10: Range Bit Counting
58845748bd5733f1b300001f
[ "Bits", "Binary", "Algorithms" ]
https://www.codewars.com/kata/58845748bd5733f1b300001f
7 kyu
This function should take two string parameters: a person's name (`name`) and a quote of theirs (`quote`), and return a string attributing the quote to the person in the following format: ```python '[name] said: "[quote]"' ``` For example, if `name` is `'Grae'` and `'quote'` is `'Practice makes perfect'` then your fu...
bug_fixes
def quotable(name, quote): return '{} said: "{}"' . format(name, quote)
Thinkful - String Drills: Quotable
5859c82bd41fc6207900007a
[ "Debugging" ]
https://www.codewars.com/kata/5859c82bd41fc6207900007a
7 kyu
Your coworker was supposed to write a simple helper function to capitalize a string (that contains a single word) before they went on vacation. Unfortunately, they have now left and the code they gave you doesn't work. Fix the helper function they wrote so that it works as intended (i.e. it must make the first charact...
bug_fixes
def capitalizeWord(word): return word . capitalize()
Capitalization and Mutability
595970246c9b8fa0a8000086
[ "Strings", "Debugging" ]
https://www.codewars.com/kata/595970246c9b8fa0a8000086
8 kyu
Complete the function `nato` that takes a word in parameter and returns a string that spells the word using the [NATO phonetic alphabet](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet). There should be a space between each word in the returned string, and the first letter of each word should be capitalized. For...
reference
letters = { "A": "Alpha", "B": "Bravo", "C": "Charlie", "D": "Delta", "E": "Echo", "F": "Foxtrot", "G": "Golf", "H": "Hotel", "I": "India", "J": "Juliett", "K": "Kilo", "L": "Lima", "M": "Mike", "N": "November", "O": "Oscar", "P": "Papa", "Q": "Quebec", "R": "Romeo", "S": "Sierra", "T...
NATO Phonetic Alphabet
54530f75699b53e558002076
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/54530f75699b53e558002076
7 kyu
I've got a crazy mental illness. I dislike numbers a lot. But it's a little complicated: The number I'm afraid of depends on which day of the week it is... This is a concrete description of my mental illness: Monday --> 12 Tuesday --> numbers greater than 95 Wednesday --> 34 Thursday --> 0 Friday -->...
reference
def am_I_afraid(day, num): return { 'Monday': num == 12, 'Tuesday': num > 95, 'Wednesday': num == 34, 'Thursday': num == 0, 'Friday': num % 2 == 0, 'Saturday': num == 56, 'Sunday': num == 666 or num == - 666, }[day]
Selective fear of numbers
55b1fd84a24ad00b32000075
[ "Fundamentals" ]
https://www.codewars.com/kata/55b1fd84a24ad00b32000075
7 kyu
# Task Let's define a `parameter` of number `n` as the least common multiple (LCM) of the sum of its digits and their product. Calculate the parameter of the given number `n`. # Input/Output `[input]` integer `n` A positive integer. It is guaranteed that no zero appears in `n`. `[output]` an integer The paramet...
games
from math import gcd def parameter(n): s, p = 0, 1 for m in str(n): s += int(m) p *= int(m) return (s * p / (gcd(s, p)))
Simple Fun #223: Parameter Of Number
5902f1839b8e720287000028
[ "Puzzles" ]
https://www.codewars.com/kata/5902f1839b8e720287000028
7 kyu
# Task You are given a string representing a number in binary. Your task is to delete all the **unset** bits in this string and return the corresponding number (after keeping only the '1's). In practice, you should implement this function: ~~~if:nasm ```c unsigned long eliminate_unset_bits(const char* number); ``` ...
reference
def eliminate_unset_bits(string): return 2 * * (string . count('1')) - 1
Eliminate the intruders! Bit manipulation
5a0d38c9697598b67a000041
[ "Bits", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a0d38c9697598b67a000041
7 kyu
## If/else syntax debug While making a game, your partner, Greg, decided to create a function to check if the user is still alive called `checkAlive`/`CheckAlive`/`check_alive`. Unfortunately, Greg made some errors while creating the function. `checkAlive`/`CheckAlive`/`check_alive` should return true if the player's...
bug_fixes
def check_alive(health: int) - > bool: """ Return `true` if the player's health is greater than 0 or `false` if it is 0 or below. """ return health > 0
Grasshopper - If/else syntax debug
57089707fe2d01529f00024a
[ "Debugging" ]
https://www.codewars.com/kata/57089707fe2d01529f00024a
8 kyu
~~~if:javascript,dart,ruby,groovy,scala,csharp Can a value be both `true` and `false`? Define `omniBool` so that it returns `true` for the following: ~~~ ~~~if:python Can a value be both `True` and `False`? Define `omnibool` so that it returns `True` for the following: ~~~ ~~~if:cpp Can a value be both `true` and `fa...
games
class Omnibool: def __eq__(self, _): return True omnibool = Omnibool()
Schrödinger's Boolean
5a5f9f80f5dc3f942b002309
[ "Language Features", "Metaprogramming", "Puzzles" ]
https://www.codewars.com/kata/5a5f9f80f5dc3f942b002309
6 kyu
Write a function `titleToNumber(title) or title_to_number(title) or titleToNb title ...` (depending on the language) that given a column title as it appears in an Excel sheet, returns its corresponding column number. All column titles will be uppercase. Examples: ``` titleTonumber('A') === 1 titleTonumber('Z') ===...
algorithms
def title_to_number(title): ret = 0 for i in title: ret = ret * 26 + ord(i) - 64 return ret
Excel sheet column numbers
55ee3ebff71e82a30000006a
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/55ee3ebff71e82a30000006a
7 kyu
A person's full name is usually composed of a first name, middle name and last name; however in some cultures (for example in South India) there may be more than one middle name. Write a function that takes the full name of a person, and returns the initials, separated by dots (`'.'`). The initials must be uppercase. ...
reference
def initials(name): names = name . split() return '.' . join(x[0]. upper() for x in names) + names[- 1][1:]
C.Wars
55968ab32cf633c3f8000008
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/55968ab32cf633c3f8000008
7 kyu
Take a string and return a hash with all the ascii values of the characters in the string. Returns nil if the string is empty. The key is the character, and the value is the ascii value of the character. Repeated characters are to be ignored and non-alphebetic characters as well.
reference
def char_to_ascii(string): return {c: ord(c) for c in set(string) if c . isalpha()} if len(string) else None
char_to_ascii
55e9529cbdc3b29d8c000016
[ "Strings", "Parsing", "Fundamentals" ]
https://www.codewars.com/kata/55e9529cbdc3b29d8c000016
7 kyu
Given a string `s`, your task is to return another string such that even-indexed and odd-indexed characters of `s` are grouped and the groups are space-separated. Even-indexed group comes as first, followed by a space, and then by the odd-indexed part. ### Examples ```text input: "CodeWars" => "CdWr oeas" ...
reference
def sort_my_string(s): return '{} {}' . format(s[:: 2], s[1:: 2])
Odd-Even String Sort
580755730b5a77650500010c
[ "Strings", "Fundamentals", "Sorting" ]
https://www.codewars.com/kata/580755730b5a77650500010c
7 kyu
Write a function ```insert_dash(num)``` / ```insertDash(num)``` / ```InsertDash(int num)``` that will insert dashes ('-') between each two odd digits in num. For example: if num is 454793 the output should be 4547-9-3. Note that the number will always be non-negative (>= 0).
reference
import re def insert_dash(num): # your code here return re . sub(r'([13579])(?=[13579])', r'\1-', str(num))
Insert dashes
55960bbb182094bc4800007b
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/55960bbb182094bc4800007b
7 kyu
This kata is all about adding numbers. You will create a function named add. It will return the sum of all the arguments. Sounds easy, doesn't it? Well Here's the Twist. The inputs will gradually decrease with their index as parameter to the function. ```javascript add(3,4,6); /* returns ( 3 / 1 ) + ( 4 / 2 ...
reference
def add(* args): return round(sum(x / i for i, x in enumerate(args, 1)))
Decreasing Inputs
555de49a04b7d1c13c00000e
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/555de49a04b7d1c13c00000e
7 kyu
This kata is all about adding numbers. You will create a function named add. This function will return the sum of all the arguments. Sounds easy, doesn't it?? Well here's the twist. The inputs will gradually increase with their index as parameter to the function. ```javascript add(3,4,5); /* returns ( 3 * 1 )...
reference
def add(* args): return sum(n * i for i, n in enumerate(args, 1))
Gradually Adding Parameters
555b73a81a6285b6ce000047
[ "Fundamentals" ]
https://www.codewars.com/kata/555b73a81a6285b6ce000047
7 kyu
My washing machine uses ```water``` amount of water to wash ```load``` (in JavaScript and Python) or ```max_load``` (in Ruby) amount of clothes. You are given a ```clothes``` amount of clothes to wash. For each single item of clothes above the load, the washing machine will use 10% more water (multiplicative) to clean...
reference
def how_much_water(water, clothes, load): if load > 2 * clothes: return "Too much clothes" if load < clothes: return "Not enough clothes" for i in range(load - clothes): water *= 1.1 return round(water, 2)
How much water do I need?
575fa9afee048b293e000287
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/575fa9afee048b293e000287
8 kyu
Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat. Your task is to write a function that takes a string and return a new string with all vowels removed. For example, the string "This website is for los...
reference
def disemvowel(string): return "" . join(c for c in string if c . lower() not in "aeiou")
Disemvowel Trolls
52fba66badcd10859f00097e
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/52fba66badcd10859f00097e
7 kyu
The goal is to create a function of two inputs `number` and `power`, that "raises" the `number` up to `power` (*ie* multiplies `number` by itself `power` times). ### Examples ```javascript numberToPower(3, 2) // -> 9 ( = 3 * 3 ) numberToPower(2, 3) // -> 8 ( = 2 * 2 * 2 ) numberToPower(10, 6) // -> 1000000 ``` ```py...
reference
def number_to_pwr(number, p): result = 1 for i in range(p): result *= number return result
Power
562926c855ca9fdc4800005b
[ "Restricted" ]
https://www.codewars.com/kata/562926c855ca9fdc4800005b
8 kyu
To find the volume (centimeters cubed) of a cuboid you use the formula: ```volume = Length * Width * Height``` But someone forgot to use proper record keeping, so we only have the volume, and the length of a single side! It's up to you to find out whether the cuboid has equal sides (= is a cube). Return `true` ...
reference
def cube_checker(volume, side): return 0 < volume == side * * 3
Find out whether the shape is a cube
58d248c7012397a81800005c
[ "Fundamentals" ]
https://www.codewars.com/kata/58d248c7012397a81800005c
8 kyu
In this kata, your task is to implement an extended version of the famous rock-paper-scissors game. The rules are as follows: * **Scissors** cuts **Paper** * **Paper** covers **Rock** * **Rock** crushes **Lizard** * **Lizard** poisons **Spock** * **Spock** smashes **Scissors** * **Scissors** decapitates **Lizard** * *...
reference
ORDER = "rock lizard spock scissors paper spock rock scissors lizard paper rock" def rpsls(p1, p2): return ("Player 1 Won!" if f" { p1 } { p2 } " in ORDER else "Player 2 Won!" if f" { p2 } { p1 } " in ORDER else "Draw!")
Rock Paper Scissors Lizard Spock
57d29ccda56edb4187000052
[ "Fundamentals", "Logic" ]
https://www.codewars.com/kata/57d29ccda56edb4187000052
7 kyu
Complete the function which returns the weekday according to the input number: * `1` returns `"Sunday"` * `2` returns `"Monday"` * `3` returns `"Tuesday"` * `4` returns `"Wednesday"` * `5` returns `"Thursday"` * `6` returns `"Friday"` * `7` returns `"Saturday"` * Otherwise returns `"Wrong, please enter a number betwee...
reference
WEEKDAY = { 1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday', 5: 'Thursday', 6: 'Friday', 7: 'Saturday'} ERROR = 'Wrong, please enter a number between 1 and 7' def whatday(n): return WEEKDAY . get(n, ERROR)
Return the day
59dd3ccdded72fc78b000b25
[ "Fundamentals" ]
https://www.codewars.com/kata/59dd3ccdded72fc78b000b25
8 kyu
The objective of [Duck, duck, goose](https://en.wikipedia.org/wiki/Duck,_duck,_goose) is to _walk in a circle_, tapping on each player's head until one is chosen. ---- Task: Given an array of Player objects (an array of associative arrays in PHP) and an index (**1-based**), return the `name` of the chosen Player(`nam...
reference
def duck_duck_goose(players, goose): return players[(goose % len(players)) - 1]. name
Duck Duck Goose
582e0e592029ea10530009ce
[ "Arrays", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/582e0e592029ea10530009ce
8 kyu
Inspired by the development team at Vooza, write the function that * accepts the name of a programmer, and * returns the number of lightsabers owned by that person. The only person who owns lightsabers is Zach, by the way. He owns 18, which is an awesome number of lightsabers. Anyone else owns 0. ```if-not:c,clojur...
reference
def how_many_light_sabers_do_you_own(name=""): return (18 if name == "Zach" else 0)
How many lightsabers do you own?
51f9d93b4095e0a7200001b8
[ "Fundamentals" ]
https://www.codewars.com/kata/51f9d93b4095e0a7200001b8
8 kyu
Make a function that returns the value multiplied by 50 and increased by 6. If the value entered is a string it should return "Error". ```if:csharp Note: in `C#`, you'll always get the input as a string, so the above applies if the string isn't representing a double value. ```
reference
def problem(a): try: return a * 50 + 6 except TypeError: return "Error"
Super Duper Easy
55a5bfaa756cfede78000026
[ "Fundamentals" ]
https://www.codewars.com/kata/55a5bfaa756cfede78000026
8 kyu
# Is the string uppercase? ## Task Create a method to see whether the string is ALL CAPS. ### Examples (input -> output) ``` "c" -> False "C" -> True "hello I AM DONALD" -> False "HELLO I AM DONALD" -> True "ACSKLDFJSgSKLDFJSKLDFJ" -> False "ACSKLDFJSGSKLDFJSKLDFJ" -> True ``` In this Kata, a string is said to be...
reference
def is_uppercase(inp): return inp . upper() == inp
Is the string uppercase?
56cd44e1aa4ac7879200010b
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/56cd44e1aa4ac7879200010b
8 kyu
If I were to ask you the size of `"hello"`, what would you say? Wait, let me rephrase the question: If I were to ask you the **total byte size** of `"hello"`, how many bytes do you think it takes up? I'll give you a hint: it's not 5. ``` len("hello") --> 5 byte size --> 54 ``` 54? What?! Here's why: every strin...
games
import sys # return the total byte size of the object. def total_bytes(object): return sys . getsizeof(object)
Byte me!
636f26f52aae8fcf3fa35819
[ "Puzzles" ]
https://www.codewars.com/kata/636f26f52aae8fcf3fa35819
8 kyu
<img src="https://media.giphy.com/media/13AN8X7jBIm15m/giphy.gif" style="width:463px;height:200px;"> Every budding hacker needs an alias! `The Phantom Phreak`, `Acid Burn`, `Zero Cool` and `Crash Override` are some notable examples from the film `Hackers`. Your task is to create a function that, given a proper first ...
reference
def alias_gen(f_name, l_name): try: return FIRST_NAME[f_name . upper()[0]] + ' ' + SURNAME[l_name . upper()[0]] except: return 'Your name must start with a letter from A - Z.'
Crash Override
578c1e2edaa01a9a02000b7f
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/578c1e2edaa01a9a02000b7f
8 kyu
```if:csharp ## Terminal Game - Create Hero Class In this first kata in the series, you need to define a Hero class to be used in a terminal game. The hero should have the following attributes: attribute | type | value ---|---|--- Name | string | user argument or "Hero" Position | string | "00" Health | float | 100 D...
reference
class Hero (object): def __init__(self, name='Hero'): self . name = name self . position = '00' self . health = 100 self . damage = 5 self . experience = 0
Grasshopper - Terminal Game #1
55e8aba23d399a59500000ce
[ "Fundamentals" ]
https://www.codewars.com/kata/55e8aba23d399a59500000ce
8 kyu
This function should return an object, but it's not doing what's intended. What's wrong?
bug_fixes
def mystery(): return {'sanity': 'Hello'}
Return to Sanity
514a7ac1a33775cbb500001e
[ "Debugging" ]
https://www.codewars.com/kata/514a7ac1a33775cbb500001e
8 kyu
What if we need the length of the words separated by a space to be added at the end of that same word and have it returned as an array? **Example(Input --> Output)** ``` "apple ban" --> ["apple 5", "ban 3"] "you will win" -->["you 3", "will 4", "win 3"] ``` Your task is to write a function that takes a String and ret...
reference
def add_length(str_): return ["{} {}" . format(i, len(i)) for i in str_ . split(' ')]
Add Length
559d2284b5bb6799e9000047
[ "Arrays", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/559d2284b5bb6799e9000047
8 kyu
Create a class `Ball`. Ball objects should accept one argument for "ball type" when instantiated. If no arguments are given, ball objects should instantiate with a "ball type" of "regular." ```javascript ball1 = new Ball(); ball2 = new Ball("super"); ball1.ballType //=> "regular" ball2.ballType //=> "super" ...
reference
class Ball (object): def __init__(self, type="regular"): self . ball_type = type
Regular Ball Super Ball
53f0f358b9cb376eca001079
[ "Fundamentals" ]
https://www.codewars.com/kata/53f0f358b9cb376eca001079
8 kyu
Create a function called `_if` which takes 3 arguments: a value `bool` and 2 functions (which do not take any parameters): `func1` and `func2` When `bool` is truthy, `func1` should be called, otherwise call the `func2`. ### Example: ```coffeescript _if(true, (() -> console.log 'true'), (() -> console.log 'false'))...
reference
def _if(bool, func1, func2): func1() if bool else func2()
The 'if' function
54147087d5c2ebe4f1000805
[ "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/54147087d5c2ebe4f1000805
8 kyu
Your task, is to create N×N multiplication table, of size provided in parameter. For example, when given `size` is 3: ``` 1 2 3 2 4 6 3 6 9 ``` For the given example, the return value should be: ```js [[1,2,3],[2,4,6],[3,6,9]] ``` ```julia [1 2 3; 2 4 6; 3 6 9] ``` ```if:c Note: in C, you must return an allocated ...
reference
def multiplicationTable(size): return [[j * i for j in range(1, size + 1)] for i in range(1, size + 1)]
Multiplication table
534d2f5b5371ecf8d2000a08
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/534d2f5b5371ecf8d2000a08
6 kyu
This is the SUPER performance version of [This kata](https://www.codewars.com/kata/faberge-easter-eggs-crush-test). You task is exactly the same as that kata. But this time, you should output `result % 998244353`, or otherwise the result would be too large. # Data range ``` sometimes n <= 80000 m <= 100000 while...
algorithms
MOD = 998244353 def height(n, m): m %= MOD inv = [0] * (n + 1) last = 1 ans = 0 for i in range(1, n + 1): inv[i] = - (MOD / / i) * inv[MOD % i] % MOD if i > 1 else 1 last = last * (m - i + 1) * inv[i] % MOD ans = (ans + last) % MOD return ans
Faberge easter eggs crush test [linear]
5976c5a5cd933a7bbd000029
[ "Performance", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5976c5a5cd933a7bbd000029
1 kyu
Define a method/function that removes from a given array of integers all the values contained in a second array. ### Examples (input -> output): ``` * [1, 1, 2, 3, 1, 2, 3, 4], [1, 3] -> [2, 2, 4] * [1, 1, 2, 3, 1, 2, 3, 4, 4, 3, 5, 6, 7, 2, 8], [1, 3, 4, 2] -> [5, 6, 7, 8] * [8, 2, 7, 2, 3, 4, 6, 5, 4, 4, 1, 2, 3], [...
reference
class List (object): def remove_(self, integer_list, values_list): return [i for i in integer_list if i not in values_list]
Remove All The Marked Elements of a List
563089b9b7be03472d00002b
[ "Fundamentals", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/563089b9b7be03472d00002b
7 kyu
If you can't sleep, just count sheep!! ## Task: Given a non-negative integer, `3` for example, return a string with a murmur: `"1 sheep...2 sheep...3 sheep..."`. Input will always be valid, i.e. no negative integers.
reference
def count_sheep(n): return '' . join(f" { i } sheep..." for i in range(1, n + 1))
If you can't sleep, just count sheep!!
5b077ebdaf15be5c7f000077
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5b077ebdaf15be5c7f000077
8 kyu
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 <br>110011 <br>54322345 You'll be given 2 numbers as arguments: ```(num,s)```. Write a function which returns an array of ```s``` number of numerical palindr...
reference
def palindrome(num, s): if not (type(num) == type(s) == int) or num < 0 or s < 0: return "Not valid" ans, num = [], max(num, 11) while len(ans) != s: if num == int(str(num)[:: - 1]): ans . append(num) num += 1 return ans
Numerical Palindrome #1.5
58e09234ca6895c7b300008c
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/58e09234ca6895c7b300008c
6 kyu
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 110011 54322345 For a given number `num`, write a function to test if it's a numerical palindrome or not and return a boolean (true if it is and false if ...
reference
def palindrome(num): if type(num) is not int or num < 1: return "Not valid" return num == int(str(num)[:: - 1])
Numerical Palindrome #1
58ba6fece3614ba7c200017f
[ "Fundamentals" ]
https://www.codewars.com/kata/58ba6fece3614ba7c200017f
7 kyu
Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return `true` if the string is valid, and `false` if it's invalid. ## Examples ``` "()" => true ")(()))" => false "(" => false "(())((()())())" => ...
algorithms
def valid_parentheses(string): cnt = 0 for char in string: if char == '(': cnt += 1 if char == ')': cnt -= 1 if cnt < 0: return False return True if cnt == 0 else False
Valid Parentheses
52774a314c2333f0a7000688
[ "Algorithms" ]
https://www.codewars.com/kata/52774a314c2333f0a7000688
5 kyu
You have a two-dimensional list in the following format: ```python data = [[2, 5], [3, 4], [8, 7]] ``` Each sub-list contains two items, and each item in the sub-lists is an integer. Write a function `process_data()`/`processData()` that processes each sub-list like so: * `[2, 5]` --> `2 - 5` --> `-3` * `[3, 4]` ...
reference
def process_data(data): r = 1 for d in data: r *= d[0] - d[1] return r
Thinkful - List and Loop Drills: Lists of lists
586e1d458cb711f0a800033b
[ "Fundamentals" ]
https://www.codewars.com/kata/586e1d458cb711f0a800033b
7 kyu
Implement the function `generateRange` which takes three arguments `(start, stop, step)` and returns the range of integers from `start` to `stop` (inclusive) in increments of `step`. ### Examples ```javascript (1, 10, 1) -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (-10, 1, 1) -> [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1] ...
algorithms
def generate_range(min, max, step): return list(range(min, max + 1, step))
Generate range of integers
55eca815d0d20962e1000106
[ "Algorithms" ]
https://www.codewars.com/kata/55eca815d0d20962e1000106
8 kyu
Given 2 strings, `a` and `b`, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty ( `zero` length ). Hint for R users: <blockquote>The length of string is not always the same as the numb...
algorithms
def solution(a, b): return a + b + a if len(a) < len(b) else b + a + b
Short Long Short
50654ddff44f800200000007
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/50654ddff44f800200000007
8 kyu
Write a function to get the first element(s) of a sequence. Passing a parameter `n` (default=`1`) will return the first `n` element(s) of the sequence. If `n` == `0` return an empty sequence `[]` ### Examples ```javascript var arr = ['a', 'b', 'c', 'd', 'e']; first(arr) //=> ['a']; first(arr, 2) //=> ['a', 'b'] fir...
reference
def first(seq, n=1): return seq[: n]
pick a set of first elements
572b77262bedd351e9000076
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/572b77262bedd351e9000076
8 kyu
Make multiple functions that will return the sum, difference, modulus, product, quotient, and the exponent respectively. Please use the following function names: ```if-not:csharp addition = **add** multiply = **multiply** division = **divide** (both integer and float divisions are accepted) modulus = **mod** expo...
reference
def add(a, b): return a + b def multiply(a, b): return a * b def divide(a, b): return a / b def mod(a, b): return a % b def exponent(a, b): return a * * b def subt(a, b): return a - b
Fundamentals: Return
55a5befdf16499bffb00007b
[ "Fundamentals" ]
https://www.codewars.com/kata/55a5befdf16499bffb00007b
8 kyu
Given a string, write a function that returns the string with a question mark ("?") appends to the end, unless the original string ends with a question mark, in which case, returns the original string. For example (**Input --> Output**) ``` "Yes" --> "Yes?" "No?" --> "No?" ```
reference
def ensure_question(s): return s if s . endswith('?') else s + '?'
Ensure question
5866fc43395d9138a7000006
[ "Fundamentals" ]
https://www.codewars.com/kata/5866fc43395d9138a7000006
8 kyu
You can print your name on a billboard ad. Find out how much it will cost you. Each character has a default price of £30, but that can be different if you are given 2 parameters instead of 1 (allways 2 for Java). You can not use multiplier "*" operator. If your name would be Jeong-Ho Aristotelis, ad would cost £600. ...
reference
def billboard(name, price=30): return sum(price for letter in name)
Name on billboard
570e8ec4127ad143660001fd
[ "Fundamentals", "Restricted", "Strings" ]
https://www.codewars.com/kata/570e8ec4127ad143660001fd
8 kyu
Define a function that removes duplicates from an array of non negative numbers and returns it as a result. The order of the sequence has to stay the same. Examples: ``` Input -> Output [1, 1, 2] -> [1, 2] [1, 2, 1, 1, 3, 2] -> [1, 2, 3] ```
reference
def distinct(seq): return sorted(set(seq), key=seq . index)
Remove duplicates from list
57a5b0dfcf1fa526bb000118
[ "Fundamentals", "Arrays", "Lists" ]
https://www.codewars.com/kata/57a5b0dfcf1fa526bb000118
8 kyu
You received a whatsup message from an unknown number. Could it be from that girl/boy with a foreign accent you met yesterday evening? Write a simple function to check if the string contains the word hallo in different languages. These are the languages of the possible people you met the night before: * hello - engl...
reference
def validate_hello(greetings): return any(x in greetings . lower() for x in ['hello', 'ciao', 'salut', 'hallo', 'hola', 'ahoj', 'czesc'])
Did she say hallo?
56a4addbfd4a55694100001f
[ "Fundamentals" ]
https://www.codewars.com/kata/56a4addbfd4a55694100001f
8 kyu
In this kata, your job is to return the two distinct highest values in a list. If there're less than 2 unique values, return as many of them, as possible. The result should also be ordered from highest to lowest. Examples: ``` [4, 10, 10, 9] => [10, 9] [1, 1, 1] => [1] [] => [] ```
reference
def two_highest(arg1): return sorted(set(arg1), reverse=True)[: 2]
Return Two Highest Values in List
57ab3c09bb994429df000a4a
[ "Fundamentals", "Lists" ]
https://www.codewars.com/kata/57ab3c09bb994429df000a4a
8 kyu
Now you have to write a function that takes an argument and returns the square of it.
reference
def square(n): return n * * 2
Function 2 - squaring an argument
523b623152af8a30c6000027
[ "Fundamentals" ]
https://www.codewars.com/kata/523b623152af8a30c6000027
8 kyu
# Grasshopper - Function syntax debugging A student was working on a function and made some syntax mistakes while coding. Help them find their mistakes and fix them.
reference
def main(verb, noun): return verb + noun
Grasshopper - Function syntax debugging
56dae9dc54c0acd29d00109a
[ "Fundamentals" ]
https://www.codewars.com/kata/56dae9dc54c0acd29d00109a
8 kyu
## Debug celsius converter Your friend is traveling abroad to the United States so he wrote a program to convert fahrenheit to celsius. Unfortunately his code has some bugs. Find the errors in the code to get the celsius converter working properly. To convert fahrenheit to celsius: ``` celsius = (fahrenheit - 32) * ...
bug_fixes
def weather_info(temp): c = convertToCelsius(temp) if (c <= 0): return (str(c) + " is freezing temperature") else: return (str(c) + " is above freezing temperature") def convertToCelsius(temperature): celsius = (temperature - 32) * (5.0 / 9.0) return celsius
Grasshopper - Debug
55cb854deb36f11f130000e1
[ "Debugging" ]
https://www.codewars.com/kata/55cb854deb36f11f130000e1
8 kyu
### Variable assignment Fix the variables assigments so that this code stores the string 'devLab' in the variable `name`.
reference
a = "dev" b = "Lab" name = a + b
Grasshopper - Variable Assignment Debug
5612e743cab69fec6d000077
[ "Fundamentals" ]
https://www.codewars.com/kata/5612e743cab69fec6d000077
8 kyu
Your task is to create the function```isDivideBy``` (or ```is_divide_by```) to check if an integer `number` is divisible by both integers `a` and `b`. A few cases: ``` (-12, 2, -6) -> true (-12, 2, -5) -> false (45, 1, 6) -> false (45, 5, 15) -> true (4, 1, 4) -> true (15, -5, 3) -> true ```
reference
def is_divide_by(number, a, b): return number % a == 0 and number % b == 0
Can we divide it?
5a2b703dc5e2845c0900005a
[ "Fundamentals" ]
https://www.codewars.com/kata/5a2b703dc5e2845c0900005a
8 kyu
Americans are odd people: in their buildings, the first floor is actually the ground floor and there is no 13th floor (due to superstition). Write a function that given a floor in the american system returns the floor in the european system. With the 1st floor being replaced by the ground floor and the 13th floor bei...
reference
def get_real_floor(n): if n <= 0: return n if n < 13: return n - 1 if n > 13: return n - 2
What's the real floor?
574b3b1599d8f897470018f6
[ "Fundamentals" ]
https://www.codewars.com/kata/574b3b1599d8f897470018f6
8 kyu
# Story: You are going to make toast fast, you think that you should make multiple pieces of toasts and once. So, you try to make 6 pieces of toast. ___ # Problem: You forgot to count the number of toast you put into there, you don't know if you put exactly six pieces of toast into the toasters. Define a function ...
algorithms
def six_toast(num): return abs(num - 6)
BASIC: Making Six Toast.
5834fec22fb0ba7d080000e8
[ "Algorithms" ]
https://www.codewars.com/kata/5834fec22fb0ba7d080000e8
8 kyu
Create a function finalGrade, which calculates the final grade of a student depending on two parameters: a grade for the exam and a number of completed projects. This function should take two arguments: exam - grade for exam (from 0 to 100); projects - number of completed projects (from 0 and above); This function sh...
reference
def final_grade(exam, projects): if exam > 90 or projects > 10: return 100 if exam > 75 and projects >= 5: return 90 if exam > 50 and projects >= 2: return 75 return 0
Student's Final Grade
5ad0d8356165e63c140014d4
[ "Fundamentals" ]
https://www.codewars.com/kata/5ad0d8356165e63c140014d4
8 kyu
You'll be given a string, and have to return the sum of all characters as an int. The function should be able to handle all printable ASCII characters. Examples: uniTotal("a") == 97 uniTotal("aaa") == 291
reference
def uni_total(string): return sum(map(ord, string))
ASCII Total
572b6b2772a38bc1e700007a
[ "Fundamentals" ]
https://www.codewars.com/kata/572b6b2772a38bc1e700007a
8 kyu
Create a function called `shortcut` to remove the **lowercase** vowels (`a`, `e`, `i`, `o`, `u` ) in a given string. ## Examples ```python "hello" --> "hll" "codewars" --> "cdwrs" "goodbye" --> "gdby" "HELLO" --> "HELLO" ``` * don't worry about uppercase vowels * `y` is not considered a vowel for this...
reference
def shortcut(s): return '' . join(c for c in s if c not in 'aeiou')
Vowel remover
5547929140907378f9000039
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5547929140907378f9000039
8 kyu
Add an item to the list: **AddExtra** method adds a new item to the list and returns the list. The new item can be any object, and it does not matter. (lets say you add an integer value, like 13) In our test case we check to assure that the returned list has one more item than the input list. However the method needs...
reference
def AddExtra(listOfNumbers): return listOfNumbers + [1]
Add new item (collections are passed by reference)
566dc05f855b36a031000048
[ "Fundamentals" ]
https://www.codewars.com/kata/566dc05f855b36a031000048
8 kyu
Write a function that will check if two given characters are the same case. * If either of the characters is not a letter, return `-1` * If both characters are the same case, return `1` * If both characters are letters, but not the same case, return `0` ## Examples `'a'` and `'g'` returns `1` `'A'` and `'C'` return...
reference
def same_case(a, b): return a . isupper() == b . isupper() if a . isalpha() and b . isalpha() else - 1
Check same case
5dd462a573ee6d0014ce715b
[ "Fundamentals" ]
https://www.codewars.com/kata/5dd462a573ee6d0014ce715b
8 kyu
In this kata you have to write a function that determine the number of magazines that every soldier has to have in his bag. You will receive the weapon and the number of streets that they have to cross. Considering that every street the soldier shoots 3 times. Bellow there is the relation of weapons: PT92 - 17 bull...
reference
from typing import Tuple from math import ceil weapons = { "PT92": 17, "M4A1": 30, "M16A2": 30, "PSG1": 5 } def mag_number(info: Tuple[str, int]) - > int: return ceil(info[1] * 3 / weapons[info[0]])
Calculate the number of magazines
5ab52526379d20736b00000e
[ "Fundamentals" ]
https://www.codewars.com/kata/5ab52526379d20736b00000e
null
## Task: Write a function that accepts two integers and returns the remainder of dividing the larger value by the smaller value. ```if:cobol Divison by zero should return `-1`. ``` ```if:csharp Divison by zero should throw a `DivideByZeroException`. ``` ```if:coffeescript,javascript Division by zero should return...
reference
def remainder(a, b): if min(a, b) == 0: return None elif a > b: return a % b else: return b % a
Find the Remainder
524f5125ad9c12894e00003f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/524f5125ad9c12894e00003f
8 kyu
Ahoy Matey! Welcome to the seven seas. You are the captain of a pirate ship. You are in battle against the royal navy. You have cannons at the ready.... or are they? Your task is to check if the gunners are loaded and ready, if they are: ```Fire!``` If they aren't ready: ```Shiver me timbers!``` Your gunners for...
algorithms
def cannons_ready(gunners): return 'Shiver me timbers!' if 'nay' in gunners . values() else 'Fire!'
Pirates!! Are the Cannons ready!??
5748a883eb737cab000022a6
[ "Algorithms" ]
https://www.codewars.com/kata/5748a883eb737cab000022a6
8 kyu
Define a method ```hello``` that ```returns``` "Hello, Name!" to a given ```name```, or says Hello, World! if name is not given (or passed as an empty String). Assuming that ```name``` is a ```String``` and it checks for user typos to return a name with a first capital letter (Xxxx). Examples: ``` * With `name` = "jo...
reference
def hello(name=''): return f"Hello, { name . title () or 'World' } !"
Hello, Name or World!
57e3f79c9cb119374600046b
[ "Fundamentals" ]
https://www.codewars.com/kata/57e3f79c9cb119374600046b
8 kyu
Your task is to determine how many files of the copy queue you will be able to save into your Hard Disk Drive. The files must be saved in the order they appear in the queue. Zero size files can always be saved even HD full. ### Input: * Array of file sizes `(0 <= s <= 100)` * Capacity of the HD `(0 <= c <= 500)` ...
reference
def save(sizes, hd): for i, s in enumerate(sizes): if hd < s: return i hd -= s return len(sizes)
Computer problem series #1: Fill the Hard Disk Drive
5d49c93d089c6e000ff8428c
[ "Lists", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5d49c93d089c6e000ff8428c
7 kyu
You get any card as an argument. Your task is to return the suit of this card (in lowercase). Our deck (is preloaded): ```javascript,c deck = ['2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣', '2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦', '2♥','3♥','4♥','5♥','6♥','...
reference
def define_suit(card): d = {'C': 'clubs', 'S': 'spades', 'D': 'diamonds', 'H': 'hearts'} return d[card[- 1]]
Define a card suit
5a360620f28b82a711000047
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5a360620f28b82a711000047
8 kyu
# Description: Remove an exclamation mark from the end of a string. For a beginner kata, you can assume that the input data is always a string, no need to verify it. # Examples ``` "Hi!" ---> "Hi" "Hi!!!" ---> "Hi!!" "!Hi" ---> "!Hi" "!Hi!" ---> "!Hi" "Hi! Hi!" ---> "Hi! Hi" "Hi" ---> "Hi" ```
reference
def remove(s): return s[: - 1] if s . endswith('!') else s
Exclamation marks series #1: Remove an exclamation mark from the end of string
57fae964d80daa229d000126
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57fae964d80daa229d000126
8 kyu
Create a function that takes 2 integers in form of a string as an input, and outputs the sum (also as a string): Example: (**Input1, Input2 -->Output**) ``` "4", "5" --> "9" "34", "5" --> "39" "", "" --> "0" "2", "" --> "2" "-5", "3" --> "-2" ``` Notes: - If either input is an empty string, consider it as zero. - ...
reference
def sum_str(a, b): return str(int(a or 0) + int(b or 0))
Sum The Strings
5966e33c4e686b508700002d
[ "Fundamentals" ]
https://www.codewars.com/kata/5966e33c4e686b508700002d
8 kyu
In this kata you will create a function that takes in a list and returns a list with the reverse order. ### Examples (Input -> Output) ``` * [1, 2, 3, 4] -> [4, 3, 2, 1] * [9, 2, 0, 7] -> [7, 0, 2, 9] ```
reference
def reverse_list(l): return l[:: - 1]
Reverse List Order
53da6d8d112bd1a0dc00008b
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/53da6d8d112bd1a0dc00008b
8 kyu
Create a function that converts US dollars (USD) to Chinese Yuan (CNY) . The input is the amount of USD as an integer, and the output should be a string that states the amount of Yuan followed by 'Chinese Yuan' ### Examples (Input -> Output) ``` 15 -> '101.25 Chinese Yuan' 465 -> '3138.75 Chinese Yuan' ``` The conve...
reference
def usdcny(usd): return f" {( usd * 6.75 ): .2 f } Chinese Yuan"
USD => CNY
5977618080ef220766000022
[ "Fundamentals" ]
https://www.codewars.com/kata/5977618080ef220766000022
8 kyu
We have implemented a function wrap(value) that takes a value of arbitrary type and wraps it in a new JavaScript Object or Python Dict setting the 'value' key on the new Object or Dict to the passed-in value. So, for example, if we execute the following code: ```python wrapper_obj = wrap("my_wrapped_string"); # w...
bug_fixes
def wrap(value): return {"value": value}
Semi-Optional
521cd52e790405a74800032c
[ "Debugging" ]
https://www.codewars.com/kata/521cd52e790405a74800032c
8 kyu
You are given two sorted arrays that both only contain integers. Your task is to find a way to merge them into a single one, sorted in asc order. Complete the function mergeArrays(arr1, arr2), where arr1 and arr2 are the original sorted arrays. You don't need to worry about validation, since arr1 and arr2 must be arra...
reference
def merge_arrays(arr1, arr2): return sorted(set(arr1 + arr2))
Merge two sorted arrays into one
5899642f6e1b25935d000161
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5899642f6e1b25935d000161
8 kyu
Write a function that takes a list of strings as an argument and returns a filtered list containing the same elements but with the 'geese' removed. The geese are any strings in the following array, which is pre-populated in your solution: ``` ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"] ``` F...
reference
geese = {"African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"} def goose_filter(birds): return [bird for bird in birds if bird not in geese]
Filter out the geese
57ee4a67108d3fd9eb0000e7
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/57ee4a67108d3fd9eb0000e7
8 kyu
You have to find maximum sum of numbers from top left corner of a matrix to bottom right corner. You can only go down or right. ## Input data * Matrix will be square M x M, 4 ≤ M ≤ 60 * Matrix will have only positive integers N. * 10 ≤ N ≤ 200 ## Example ``` matrix = [[20, 20, 10, 10], [10, 20, 10, 10]...
algorithms
def find_sum(m): p = [0] * (len(m) + 1) for l in m: for i, v in enumerate(l, 1): p[i] = v + max(p[i - 1], p[i]) return p[- 1]
Biggest Sum
5741df13077bdf57af00109c
[ "Dynamic Programming", "Algorithms" ]
https://www.codewars.com/kata/5741df13077bdf57af00109c
5 kyu
The prime factorization of a positive integer is a list of the integer's prime factors, together with their multiplicities; the process of determining these factors is called integer factorization. The fundamental theorem of arithmetic says that every positive integer has a single unique prime factorization. The prime...
algorithms
class PrimeFactorizer: def __init__(self, num): self . factor = {} for i in xrange(2, num + 1): if (num < i): break while (num % i == 0): num /= i self . factor[i] = self . factor . get(i, 0) + 1
Prime factorization
534a0c100d03ad9772000539
[ "Algorithms" ]
https://www.codewars.com/kata/534a0c100d03ad9772000539
6 kyu
## Prime Factors _Inspired by one of Uncle Bob's TDD Kata_ Write a function that generates factors for a given number. The function takes an `integer` as parameter and returns a list of integers (ObjC: array of `NSNumber`s representing integers). That list contains the prime factors in numerical sequence. ## Examp...
algorithms
def prime_factors(n): primes = [] candidate = 2 while n > 1: while n % candidate == 0: primes . append(candidate) n /= candidate candidate += 1 return primes
Prime Factors
542f3d5fd002f86efc00081a
[ "Algorithms" ]
https://www.codewars.com/kata/542f3d5fd002f86efc00081a
6 kyu
Find the greatest common divisor of two positive integers. The integers can be large, so you need to find a clever solution. The inputs `x` and `y` are always greater or equal to 1, so the greatest common divisor will always be an integer that is also greater or equal to 1.
algorithms
# Try to make your own gcd method without importing stuff def mygcd(x, y): # GOOD LUCK while y: x, y = y, x % y return x
Greatest common divisor
5500d54c2ebe0a8e8a0003fd
[ "Algorithms", "Fundamentals", "Recursion" ]
https://www.codewars.com/kata/5500d54c2ebe0a8e8a0003fd
7 kyu
Define a function that takes an integer argument and returns a logical value `true` or `false` depending on if the integer is a prime. Per Wikipedia, a prime number ( or a prime ) is a natural number greater than `1` that has no positive divisors other than `1` and itself. ## Requirements * You can assume you will b...
algorithms
# This is the Miller-Rabin test for primes, which works for super large n import random def even_odd(n): s, d = 0, n while d % 2 == 0: s += 1 d >>= 1 return s, d def Miller_Rabin(a, p): s, d = even_odd(p - 1) a = pow(a, d, p) if a == 1: return True for i in range(s): ...
Is a number prime?
5262119038c0985a5b00029f
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5262119038c0985a5b00029f
6 kyu
Write a function that calculates the *least common multiple* of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return `1`. If any argument is `0`, return `0`. ~~~if:objc,c NOTE: The first (and only na...
algorithms
from math import lcm
Least Common Multiple
5259acb16021e9d8a60010af
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5259acb16021e9d8a60010af
5 kyu
Who is the killer? = ### Some people have been killed! You have managed to narrow the suspects down to just a few. Luckily, you know every person who those suspects have seen on the day of the murders. ### Task. Given a dictionary with all the names of the suspects and everyone that they have seen on that day which ma...
reference
def killer(info, dead): for name, seen in info . items(): if set(dead) <= set(seen): return name
Who is the killer?
5f709c8fb0d88300292a7a9d
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5f709c8fb0d88300292a7a9d
7 kyu
This kata honors a recurring troupe of many online games. The origin of this tradition can be traced to the classic Black Isle pc game Baldur's Gate. The very first quest requires you to kill 10 rats. One **rat**her humble start for what later becomes a epic adventure. Honor awaits! Its intended to be a easy but ent...
reference
def world_quest(): world = World() world . talk('npc', 'hello') world . talk('npc', 'player') world . talk('npc', 'yes') kill = 0 while kill < 10: world . pickup('rock') hit = world . throw('rat') if hit: kill += 1 world . talk('npc') return world
Quest: Kill ten rats!
58985ffa8b43145ac900015a
[ "Fundamentals", "Puzzles", "Games" ]
https://www.codewars.com/kata/58985ffa8b43145ac900015a
7 kyu
Let's imagine we have a popular online RPG. A player begins with a score of 0 in class E5. A1 is the highest level a player can achieve. Now let's say the players wants to rank up to class E4. To do so the player needs to achieve at least 100 points to enter the qualifying stage. Write a script that will check to see...
reference
def playerRankUp(pts): msg = "Well done! You have advanced to the qualifying stage. Win 2 out of your next 3 games to rank up." return msg if pts >= 100 else False
Online RPG: player to qualifying stage?
55849d76acd73f6cc4000087
[ "Fundamentals" ]
https://www.codewars.com/kata/55849d76acd73f6cc4000087
8 kyu
#### Description You are Saitama (a.k.a One Punch Man), and you are fighting against the monsters! You are strong enough to kill them with one punch, but after you punch 3 times, one of the remaining monsters will hit you once. Your health is `health`; number of monsters is `monsters`, damage that monster can give yo...
reference
def kill_monsters(health, monsters, damage): hits = (monsters - 1) / / 3 damage *= hits health -= damage return f'hits: { hits } , damage: { damage } , health: { health } ' if health > 0 else 'hero died'
Kill The Monsters!
5b36137991c74600f200001b
[ "Arrays", "Fundamentals", "Mathematics", "Strings" ]
https://www.codewars.com/kata/5b36137991c74600f200001b
7 kyu
- Kids drink toddy. - Teens drink coke. - Young adults drink beer. - Adults drink whisky. Make a function that receive age, and return what they drink. **Rules:** - Children under 14 old. - Teens under 18 old. - Young under 21 old. - Adults have 21 or more. **Examples: (Input --> Output)** ``` 13 --> "drink toddy"...
reference
def people_with_age_drink(age): if age > 20: return 'drink whisky' if age > 17: return 'drink beer' if age > 13: return 'drink coke' return 'drink toddy'
Drink about
56170e844da7c6f647000063
[ "Fundamentals" ]
https://www.codewars.com/kata/56170e844da7c6f647000063
8 kyu
# Background My TV remote control has arrow buttons and an `OK` button. I can use these to move a "cursor" on a logical screen keyboard to type "words"... The screen "keyboard" layout looks like this <style> #tvkb { width : 300px; border: 5px solid gray; border-collapse: collapse; } #tvkb td { col...
algorithms
KEYBOARD = "abcde123fghij456klmno789pqrst.@0uvwxyz_/" MAP = {c: (i / / 8, i % 8) for i, c in enumerate(KEYBOARD)} def manhattan(* pts): return sum(abs(z2 - z1) for z1, z2 in zip(* pts)) def tv_remote(word): return len(word) + sum(manhattan(MAP[was], MAP[curr]) for was, curr in zip('a' + word, word))
TV Remote
5a5032f4fd56cb958e00007a
[ "Algorithms" ]
https://www.codewars.com/kata/5a5032f4fd56cb958e00007a
7 kyu
The distance formula can be used to find the distance between two points. What if we were trying to walk from point **A** to point **B**, but there were buildings in the way? We would need some other formula..but which? ### Manhattan Distance [Manhattan distance](http://en.wikipedia.org/wiki/Manhattan_distance) is t...
algorithms
def manhattan_distance(pointA, pointB): return abs(pointA[0] - pointB[0]) + abs(pointA[1] - pointB[1])
Manhattan Distance
52998bf8caa22d98b800003a
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/52998bf8caa22d98b800003a
6 kyu
Write a function that takes a string and an an integer `n` as parameters and returns a list of all words that are longer than `n`. Example: ``` * With input "The quick brown fox jumps over the lazy dog", 4 * Return ['quick', 'brown', 'jumps'] ```
reference
def filter_long_words(sentence, long): return [word for word in sentence . split() if len(word) > long]
Filter Long Words
5697fb83f41965761f000052
[ "Fundamentals" ]
https://www.codewars.com/kata/5697fb83f41965761f000052
7 kyu
Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way. The function must accept a non-negative integer. If it is zero, it just returns `"now"`. Otherwise, the duration is expressed as a combination of `years`, `days`, `hours`, `...
algorithms
times = [("year", 365 * 24 * 60 * 60), ("day", 24 * 60 * 60), ("hour", 60 * 60), ("minute", 60), ("second", 1)] def format_duration(seconds): if not seconds: return "now" chunks = [] for name, secs in times: qty = seconds // secs if qty: ...
Human readable duration format
52742f58faf5485cae000b9a
[ "Strings", "Date Time", "Algorithms" ]
https://www.codewars.com/kata/52742f58faf5485cae000b9a
4 kyu
Code as fast as you can! You need to double the integer and return it.
reference
def doubleInteger(i): return i * 2
You Can't Code Under Pressure #1
53ee5429ba190077850011d4
[ "Fundamentals" ]
https://www.codewars.com/kata/53ee5429ba190077850011d4
8 kyu
Suppose a student can earn 100% on an exam by getting the answers all correct or all incorrect. Given a potentially incomplete answer key and the student's answers, write a function that determines whether or not a student can still score 100%. Incomplete questions are marked with an underscore, "_". ``` ["A", "_", "C...
reference
def possibly_perfect(key, answers): a = [k==a for k, a in zip(key, answers) if k!='_'] return all(a) or not any(a)
All or Nothing
65112af7056ad6004b5672f8
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/65112af7056ad6004b5672f8
7 kyu
You are an adventurous hiker planning to traverse a mountain range. The mountain range is represented by an array of integers, where each element corresponds to the height of a mountain at that position. Your goal is to find the longest mountain pass you can take based on your initial energy level. ## Problem Descript...
algorithms
def longest_mountain_pass(mountains, E): n = len(mountains) if n < 2: if n == 0: return (0, 0) else: return (1, 0) # Precompute energy costs energy_cost = [0] * n for i in range(1, n): energy_cost[i] = max(0, mountains[i] - mountains[i - 1] ...
Longest Mountain Pass
660595d3bd866805d00ec4af
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/660595d3bd866805d00ec4af
5 kyu
Your task is to write a function that takes two arguments `n`, `m` and returns a sorted array of all numbers from `n` to `m` inclusive, which have only 3 divisors (1 and the number itself are not included). #### Example: ``` solution(2, 20) -> [16] ``` `16` has 3 divisors: `2, 4, 8` (`1` and `16` aren't included) ##...
algorithms
from gmpy2 import next_prime from bisect import bisect_left, bisect_right PS, L, P = [], 1e18, 2 while True: Q = P * * 4 PS . append(Q) P = next_prime(P) if Q > L: break def solution(n, m): i = bisect_left(PS, n) j = bisect_right(PS, m) return PS[i: j]
Find numbers with 3 divisors
65eb2c4c274bd91c27b38d32
[]
https://www.codewars.com/kata/65eb2c4c274bd91c27b38d32
5 kyu
In this kata, you will have to return the continued fraction<sup>[wiki](https://en.wikipedia.org/wiki/Continued_fraction)</sup> of a fraction. For example, if the numerator is `311` and the denominator is `144`, then you would have to return `[2, 6, 3, 1, 5]`, because: ```math 311 / 144 = 2 + \cfrac { 1 } { 6 ...
algorithms
def continued_fraction(nu: int, de: int) - > list[int]: l = [] while nu and de: l . append(nu / / de) nu, de = de, nu % de return l
Continued Fraction
660e5631b673a8004b71d208
[]
https://www.codewars.com/kata/660e5631b673a8004b71d208
6 kyu
In this kata, you need to code a function that takes two parameters, A and B, both representing letters from the English alphabet. It is guaranteed that: <ol> <li>Both letters are the same case (Either both are uppercase or both are lowercase, never a mix)</li> <li>B is always a letter that comes after A in the al...
games
slice = f = lambda a, b: a * (a == b) or f(a, chr(ord(b) - 1)) + b
Alphabet slice puzzle!
660d55d0ba01e5016c85cfeb
[ "Puzzles", "Strings", "Functional Programming", "Restricted" ]
https://www.codewars.com/kata/660d55d0ba01e5016c85cfeb
6 kyu
Given an increasing sequence where each element is an integer composed of digits from a given set `t`. For example, if `t = { 1, 5 }`, the sequence would be: `1, 5, 11, 15, 51, 55, 111, 115, ...` Another example, if `t = { 4, 0, 2 }`, the sequence would be: `0, 2, 4, 20, 22, 24, 40, 42, ...` ## Task In this kata, yo...
games
def findpos(n, t): z = 0 in t b = len(t) m = {x: y for x, y in zip(sorted(t), range(1 - z, b + 1 - z))} s, i = 0, 0 while n > 0: n, d = divmod(n, 10) s += b * * i * m[d] i += 1 return s + z
Find Position in Sequence
660323a44fe3e41cff41e4e9
[ "Combinatorics" ]
https://www.codewars.com/kata/660323a44fe3e41cff41e4e9
5 kyu
### Task You have a list *arrays* of N arrays of positive integers, each of which is sorted in ascending order. Your taks is to return the median value all of the elements of the combined lists. ### Example `arrays =[[1,2,3],[4,5,6],[7,8,9]]` In this case the median is 5 `arrays =[[1,2,3],[4,5],[100,101,102]]` In ...
algorithms
from bisect import bisect_left as bl from bisect import bisect_right as br def f(a, n): p = [0 for e in a] q = [len(e) for e in a] for i, e in enumerate(a): while p[i] < q[i]: m = (p[i] + q[i]) >> 1 x = sum(bl(f, e[m]) for f in a) y = sum(br(f, e[m]) for f in a) if x <= n <...
Median Value in N Sorted Arrays
65fc93001bb13a2074cb4ee8
[ "Arrays", "Performance" ]
https://www.codewars.com/kata/65fc93001bb13a2074cb4ee8
4 kyu