description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
sequencelengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
<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_oGBZ26aTsBgWVI7kvnBTXOWrvXP0Q8AY.jpg" width="150"/> <h1>Task</h1> Your task is to write a function which will calculate <strong>the total amount of all possible ways</strong> that the frog can go from top to the bottom.</br></br> <h1>Example</h1> For staircase with <code>steps=3</code> and <code>maxJumpLength=3</code> a frog can jump steps like:</br> 1-1-1 or 1-2 or 2-1 or 3. Which gives 4 possible jump ways.</br> And for staircase with <code>steps=4</code> and <code>maxJumpLength=3</code> a frog can jump steps like:</br> 1-1-1-1 or 1-1-2 or 1-2-1 or 2-1-1 or 2-2 or 3-1 or 1-3. Which gives 7 possible jump ways.</br></br> <h1>Function type</h1> Function will receive as parameters:</br> <code>steps</code> a number from 1 to 200 : amount of steps in a staircase.</br> <code>maxJumpLength</code> a number from 1 to 200 : top limit of how many steps a frog can jump down at 1 time.</br> Function should return a number - <strong>BigInt</strong> (because some results can be really big) of all possible ways the frog can go down the staircase.</br> All inputs will be valid. <code>maxJumpLength</code> can be bigger than <code>steps</code> but you should consider the real amount of steps passed over. <strong>Good luck!</strong>
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, according to the following procedure: * An infinite array/list `A` is initialized to contain all the integers greater than 1: `[2, 3, 4, 5, 6, …]` * Let `p` be the position of the ant on the array/list. Initially `p = 0`, so the ant is at `A[0] = 2` * At each turn, the ant moves as follows: * If `A[p]` is prime, move the ant one position forward, so `p ← p + 1` * Otherwise (if `A[p]` is composite): * Let `q` be its smallest divisor greater than 1 * Replace `A[p]` with `A[p] / q` * Replace `A[pβˆ’1]` with `A[pβˆ’1] + q` * Move the ant one position backward, so `p ← p βˆ’ 1` Your task is to comlete the function that computes the position of the prime ant after n turns. ## Examples ```python prime_ant(2) # => 2 prime_ant(11) # => 5 prime_ant(47) # => 9 ``` ```ruby prime_ant(2) # => 2 prime_ant(11) # => 5 prime_ant(47) # => 9 ``` ```javascript primeAnt(2) // => 2 primeAnt(11) // => 5 primeAnt(47) // => 9 ``` --- When you're done solving this, you should also try solving [Prime ant - Performance Version](https://www.codewars.com/kata/prime-ant-performance-version/)
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 else: p += 1 return p
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 b = 7 the array is: [2, 3, 4, 5, 6, 7]. Converting the numbers to binary, we get [10, 11, 100, 101, 110, 111], which contains 1 + 2 + 1 + 2 + 2 + 3 = 11 1s. # Input/Output - `[input]` integer `a` Constraints: 0 ≀ a ≀ b. - `[input]` integer `b` Constraints: a ≀ b ≀ 100. - `[output]` an integer
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 function should return the string ```python 'Grae said: "Practice makes perfect"' ``` Unfortunately, something is wrong with the instructions in the function body. Your job is to fix it so the function returns correctly formatted quotes. Click the "Train" button to get started, and be careful with your quotation marks.
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 character in the string upper case). The string will always start with a letter and will never be empty. Examples: ``` "hello" --> "Hello" "Hello" --> "Hello" (the first letter was already capitalized) "a" --> "A" ```
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 those of you that don't want your fingers to bleed, this kata already has a dictionary typed out for you. ## Examples ``` "hi" --> "Hotel India" "abc" --> "Alpha Bravo Charlie" "babble" --> "Bravo Alpha Bravo Bravo Lima Echo" "Banana" --> "Bravo Alpha November Alpha November Alpha" ```
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": "Tango", "U": "Uniform", "V": "Victor", "W": "Whiskey", "X": "X-ray", "Y": "Yankee", "Z": "Zulu" } def nato(word): return ' ' . join(letters[c] for c in word . upper())
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 --> numbers divisible by 2 Saturday --> 56 Sunday --> 666 or -666 Write a function which takes a string (day of the week) and an integer (number to be tested) so it tells the doctor if I'm afraid or not. (return a boolean)
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 parameter of the given number. # Example For `n = 22`, the output should be `4`. Both the sum and the product of digits equal 4, and LCM(4, 4) = 4. For `n = 1234`, the output should be `120`. `1+2+3+4=10` and `1*2*3*4=24`, LCM(10,24)=120
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); ``` ~~~ ~~~if-not:nasm ```c long eliminate_unset_bits(const char* number); ``` ```python def eliminate_unset_bits(number): ``` ```javascript function eliminateUnsetBits(number); ``` ```coffeescript eliminateUnsetBits = (number) -> ``` ```haskell eliminateUnsetBits :: String -> Integer ``` ```ruby def eliminate_set_bits number ``` ```crystal def eliminate_set_bits(number) ``` ```java public long eliminateUnsetBits(String number); ``` ```cpp long eliminate_unset_bits(string number); ``` ```scala def eliminateUnsetBits(number: String): Long ``` ~~~ ## Examples ~~~if:java,ruby,javascript,coffeescript,crystal,haskell,scala ```java eliminateUnsetBits("11010101010101") -> 255 (= 11111111) eliminateUnsetBits("111") -> 7 eliminateUnsetBits("1000000") -> 1 eliminateUnsetBits("000") -> 0 ``` ```ruby eliminate_set_bits("11010101010101") -> 255 (= 11111111) eliminate_set_bits("111") -> 7 eliminate_set_bits("1000000") -> 1 eliminate_set_bits("000") -> 0 ``` ```crystal eliminate_set_bits("11010101010101") -> 255 (= 11111111) eliminate_set_bits("111") -> 7 eliminate_set_bits("1000000") -> 1 eliminate_set_bits("000") -> 0 ``` ```javascript eliminateUnsetBits("11010101010101") -> 255 (= 11111111) eliminateUnsetBits("111") -> 7 eliminateUnsetBits("1000000") -> 1 eliminateUnsetBits("000") -> 0 ``` ```coffeescript eliminateUnsetBits("11010101010101") -> 255 (= 11111111) eliminateUnsetBits("111") -> 7 eliminateUnsetBits("1000000") -> 1 eliminateUnsetBits("000") -> 0 ``` ```haskell eliminateUnsetBits "11010101010101" -> 255 (= 11111111) eliminateUnsetBits "111" -> 7 eliminateUnsetBits "1000000" -> 1 eliminateUnsetBits "000" -> 0 ``` ```scala eliminateUnsetBits("11010101010101") -> 255 (= 11111111) eliminateUnsetBits("111") -> 7 eliminateUnsetBits("1000000") -> 1 eliminateUnsetBits("000") -> 0 ``` ~~~ ~~~if-not:java,ruby,javascript,crystal,coffeescript,haskell ```c eliminate_unset_bits("11010101010101") -> 255 (= 11111111) eliminate_unset_bits("111") -> 7 eliminate_unset_bits("1000000") -> 1 eliminate_unset_bits("000") -> 0 ``` ~~~
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 health is greater than 0 or false if it is 0 or below. ```if-not:csharp The function receives one parameter `health` which will always be a whole number between -10 and 10. ```
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 `false`? Define `omnibool` so that it returns `true` for the following: ~~~ ~~~if:rust Can a value be both `true` and `false`? Define `omnibool` so that it returns `true` for the following: ~~~ ~~~if:haskell Can a value be both `True` and `False`? Define `OmniBool` so that it returns `True` for the following: ~~~ ~~~if:nim Can a value be both `true` and `false`? Define `omnibool` so that it returns `true` for the following: ~~~ ~~~if:crystal Can a value be both `true` and `false`? Define `Omnibool.omnibool` so that it returns `true` for the following: ~~~ ~~~if:clojure Can a value be both `true` and `false`? Define `omnibool` so that the following evaluates to `true`: ~~~ ~~~if:factor Can a value be both `t` and `f`? Define an object `omnibool` so that the following evaluates to `t`: ~~~ ```javascript omniBool == true && omniBool == false ``` ```dart omniBool == true && omniBool == false ``` ```python omnibool == True and omnibool == False ``` ```rust omnibool == true && Omnibool == false ``` ```haskell omniBool == True && omniBool == False ``` ```nim omnibool == true and omnibool == false ``` ```crystal Omnibool.omnibool == true && Omnibool.omnibool == false ``` ```clojure (and (= omnibool true) (= omnibool false)) ``` ```factor t omnibool = f omnibool = and ``` If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
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') === 26 titleTonumber('AA') === 27 ``` ```clojure Note for Clojure: Don't use Java Math/pow (even with bigint) because there is a loss of precision when the length of "title" is growing. Write your own function "exp [x n]". ```
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. The last name of the person must appear in full, with its first letter in uppercase as well. See the pattern below: ``` "code wars" ---> "C.Wars" "Barack hussein obama" ---> "B.H.Obama" ``` Names in the full name are separated by exactly one space (`' '` ) ; without leading or trailing spaces. Names will always be lowercase, except optionally their first letter.
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" |||||||| |||| |||| indices: 01234567 0246 1357 ``` Even indices 0, 2, 4, 6, so we have `"CdWr"` as the first group. Odd indices are 1, 3, 5, 7, so the second group is `"oeas"`. And the final string to return is `"Cdwr oeas"`. ### Notes Tested strings are at least 8 characters long.
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 ) + ( 6 / 3 ) = 7 */ ``` ```ruby add(3,4,6) #returns (3/1)+(4/2)+(6/3)=7 ``` ```python add(3,4,6) #returns (3/1)+(4/2)+(6/3)=7 ``` Remember the function will return 0 if no arguments are passed and it must round the result if sum is a float. Example ```javascript add(); //=> 0 add(1,2,3); //=> 3 add(1,4,-6,20); //=> 6 ``` ```ruby add() #=> 0 add(1,2,3) #=> 3 add(1,4,-6,20) #=> 6 ``` ```python add() #=> 0 add(1,2,3) #=> 3 add(1,4,-6,20) #=> 6 ``` Check my another kata here!! http://www.codewars.com/kata/555b73a81a6285b6ce000047
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 ) + ( 4 * 2 ) + ( 5 * 3 ) = 26 */ ``` ```ruby add(3,4,5) #returns (3*1)+(4*2)+(5*3)=26 ``` ```python add(3,4,5) #returns (3*1)+(4*2)+(5*3)=26 ``` ```haskell add(3,4,5) `shouldBe` 3 * 1 + 4 * 2 + 5 * 3 -- = 26 ``` ```rust add(&[3,4,5]); // returns (3*1)+(4*2)+(5*3)=26 ``` Remember the function will return 0 if no arguments are passed. ## Example ```javascript add(); //=> 0 add(1,2,3); //=> 14 add(1,4,-5,5); //=> 14 ``` ```ruby add() #=> 0 add(1,2,3) #=> 14 add(1,4,-5,5) #=> 14 ``` ```python add() #=> 0 add(1,2,3) #=> 14 add(1,4,-5,5) #=> 14 ``` ```haskell add [ ] `shouldBe` 0 add [1,2,3 ] `shouldBe` 14 add [1,4,-5,5] `shouldBe` 14 ``` ```rust add(&[]); //=> 0 add(&[1,2,3]); //=> 14 add(&[1,4,-5,5]); //=> 14 ```
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. For example, if the load is ```10```, the amount of water it requires is ```5``` and the amount of clothes to wash is ```14```, then you need ```5 * 1.1 ^ (14 - 10)``` amount of water. Write a function ```howMuchWater``` (JS)/```how_much_water``` (Python and Ruby) to work out how much water is needed if you have a ```clothes``` amount of clothes. The function will accept 3 arguments: - `water`, `load` (or `max_load`in Ruby) and `clothes`. My washing machine is an old model that can only handle double the amount of ```load``` (or ```max_load```). If the amount of ```clothes``` is more than 2 times the standard amount of ```load``` (```max_load```), return ```'Too much clothes'```. The washing machine also cannot handle any amount of clothes less than ```load``` (```max_load```). If that is the case, return ```'Not enough clothes'```. The answer should be rounded to the nearest 2 decimal places.
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 losers LOL!" would become "Ths wbst s fr lsrs LL!". Note: for this kata `y` isn't considered a vowel.
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 ``` ```python number_to_pwr(3, 2) # -> 9 ( = 3 * 3 ) number_to_pwr(2, 3) # -> 8 ( = 2 * 2 * 2 ) number_to_pwr(10, 6) # -> 1000000 ``` ~~~if:javascript **Note**: `Math.pow` and some other `Math` functions like `eval()` and `**` are disabled. ~~~ ~~~if:python **Note**: `math.pow` and some others `math` functions are disabled on final tests. ~~~
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` if the cuboid could have equal sides, return `false` otherwise. Return `false` for invalid numbers too (e.g volume or side is less than or equal to 0). Note: side will be an integer
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** * **Lizard** eats **Paper** * **Paper** disproves **Spock** * **Spock** vaporizes **Rock** * **Rock** crushes **Scissors** ## Task: ~~~if-not:haskell,csharp,lambdacalc Given two values from the above game, return the Player result as `"Player 1 Won!"`, `"Player 2 Won!"`, or `"Draw!"`. ## Inputs Values will be given as one of `"rock", "paper", "scissors", "lizard", "spock"`. ~~~ ~~~if:haskell,csharp,lambdacalc Given two values from the above game, return the Player result as an `Ordering` ( `GT`, `LT` or `EQ` ). ## Inputs Values will be given as one of `Rock, Paper, Scissors, Lizard, Spock`. ~~~ ![](https://i.imgur.com/BWDszrL.jpg) ~~~if:lambdacalc ## Encodings: purity: `Let` numEncoding: `None` `RPSLS` and `Ordering` will be `Preloaded` in Scott encoding. Constructor ordering is given in `Initial Code`. ~~~
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 between 1 and 7"`
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(`name` is a property of `Player` objects, e.g `Player.name`) ---- Example: ``` duck_duck_goose([a, b, c, d], 1) should return a.name duck_duck_goose([a, b, c, d], 5) should return a.name duck_duck_goose([a, b, c, d], 4) should return d.name ``` ```php // PHP only duck_duck_goose([$a, $b, $c, $d], 1); // => $a["name"] duck_duck_goose([$a, $b, $c, $d], 5); // => $a["name"] duck_duck_goose([$a, $b, $c, $d], 4); // => $d["name"] ```
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,clojure,c#,elixir,haskell,racket,rust **Note**: your function should have a default parameter. ``` For example(**Input --> Output**): ``` "anyone else" --> 0 "Zach" --> 18 ```
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 in ALL CAPS whenever it does not contain any lowercase letter so any string containing no letters at all is trivially considered to be in ALL CAPS. ~~~if:riscv RISC-V: The function signature is ```c bool is_uppercase(const char *); ``` ~~~
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 string has to have an encoding (e.g ASCII),the info that makes it an object, as well as all of it's other properites... it would have to take up a bit more than 5 bytes, wouldn't it? This might be useful for sending something over a network, where you need to represent the memory size the item takes up. --- ## Task: In this kata, you need to return the number of bytes (aka. memory size) a given `object` takes up. Different variable types will be given, but they will all be valid. Also, random generation for strings takes out of Unicode, not the regular 255 ascii letters. *p.s: Don't be afraid to use the internet. It "byte" come in handy :)* **Other Examples:** ``` Object Bytes Why? ---- ---- ---- "龘" 76 Other character sets take up more room. 123 28 Numbers don't have as much info in them. [1,2] 72 Lists have more info stored (e.g index). (1,2) 56 Tuples are (kind of) just bowls of data. ```
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 and last name, will return the correct alias. #### Notes: * Two objects that return a one word name in response to the first letter of the first name and one for the first letter of the surname are already given. See the examples below for further details. * If the first character of either of the names given to the function is not a letter from `A - Z`, you should return `"Your name must start with a letter from A - Z."` * Sometimes people might forget to capitalize the first letter of their name so your function should accommodate for these grammatical errors. --- ## Examples ```javascript // These two objects are preloaded, you need to use them in your code var firstName = {A: 'Alpha', B: 'Beta', C: 'Cache' ...} var surname = {A: 'Analogue', B: 'Bomb', C: 'Catalyst' ...} aliasGen('Larry', 'Brentwood') === 'Logic Bomb' aliasGen('123abc', 'Petrovic') === 'Your name must start with a letter from A - Z.' ``` ```ruby # These two hashes are preloaded, you need to use them in your code FIRST_NAME = {'A': 'Alpha', 'B': 'Beta', 'C': 'Cache', ...} SURNAME = {'A': 'Analogue', 'B': 'Bomb', 'C': 'Catalyst' ...} alias_gen('Larry', 'Brentwood') == 'Logic Bomb' alias_gen('123abc', 'Petrovic') == 'Your name must start with a letter from A - Z.' ``` ```python # These two dictionaries are preloaded, you need to use them in your code FIRST_NAME = {'A': 'Alpha', 'B': 'Beta', 'C': 'Cache', ...} SURNAME = {'A': 'Analogue', 'B': 'Bomb', 'C': 'Catalyst' ...} alias_gen('Larry', 'Brentwood') == 'Logic Bomb' alias_gen('123abc', 'Petrovic') == 'Your name must start with a letter from A - Z.' ``` ```csharp FirstName = {{"A", "Alpha"}, {"B", "Beta"}, {"C", "Cache"}, ...} Surname = {{"A", "Analogue"}, {"B", "Bomb"}, {"C", "Catalyst"} ...} // These dictionaries are defined on other partial Kata class AliasGen('Larry', 'Brentwood') == 'Logic Bomb' AliasGen('123abc', 'Petrovic') == 'Your name must start with a letter from A - Z.' ``` Happy hacking!
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 Damage | float | 5 Experience | int | 0 ``` ```if-not:csharp ## Terminal Game - Create Hero Prototype In this first kata in the series, you need to define a Hero prototype to be used in a terminal game. The hero should have the following attributes: attribute | value ---|--- name | user argument or 'Hero' position | '00' health | 100 damage | 5 experience | 0 ```
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 returns an Array/list with the length of each word added to each element . **Note:** String will have at least one element; words will always be separated by a space.
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" ``` ```coffeescript ball1 = new Ball() ball2 = new Ball("super") ball1.ballType #=> "regular" ball2.ballType #=> "super" ``` ```ruby ball1 = Ball.new ball2 = Ball.new "super" ball1.ball_type #=> "regular" ball2.ball_type #=> "super" ``` ```python ball1 = Ball() ball2 = Ball("super") ball1.ball_type #=> "regular" ball2.ball_type #=> "super" ``` ```scala 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')) // Logs 'true' to the console. ``` ```c void the_true() { printf("true"); } void the_false() { printf("false"); } _if(true, the_true, the_false); /* Logs "true" to the console */ ``` ```nasm the_true: mov rdi .true jmp printf .true: db `true\0` the_false: mov rdi, .false jmp printf .false: db `false\0` mov dil, 1 mov rsi, the_true mov rdx, the_false call _if ; Logs "true" to the console ``` ```cpp void TheTrue() { std::cout << "true" } void TheFalse() { std::cout << "false" } _if(true, TheTrue, TheFalse); // Logs 'true' to the console. ``` ``` csharp Kata.If(true, () => Console.WriteLine("True"), () => Console.WriteLine("False")); // write "True" to console ``` ```elixir _if(true, fn -> IO.puts "true" end, fn -> IO.puts "false" end) # prints "true" to the console ``` ```haskell main = _if True (putStrLn "You spoke the truth") (putStrLn "liar") -- puts "You spoke the truth" to the console. _if False "Hello" "Goodbye" -- "Goodbye" ``` ```javascript _if(true, function(){console.log("True")}, function(){console.log("false")}) // Logs 'True' to the console. ``` ```ruby _if(true, proc{puts "True"}, proc{puts "False"}) # Logs 'True' to the console. ``` ```python def truthy(): print("True") def falsey(): print("False") _if(True, truthy, falsey) # prints 'True' to the console ``` ```rust _if(true, || println!("true"), || println!("false")) # prints "true" to the console ``` ```lua kata._if(true, function() print("true") end, function() print("false") end) -- prints "true" to the console ```
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 table of allocated rows ```
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 sometimes n <= 3000 m <= 2^200 ``` There are `150` random tests. You will need more than just a naive linear algorithm for this task :D
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], [2, 4, 3] -> [8, 7, 6, 5, 1] ``` Enjoy it!!
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 palindromes that come after ```num```. If ```num``` is a palindrome itself, it should be included in the count. Return "Not valid" instead if any one of the inputs is not an integer or is less than 0. For this kata, single digit numbers will <u>NOT</u> be considered numerical palindromes. ``` palindrome(6,4) => [11,22,33,44] palindrome(59,3) => [66,77,88] palindrome(101,2) => [101,111] palindrome("15651",5) => "Not valid" palindrome(1221,"8") => "Not valid" ``` ~~~if:haskell In Haskell, the return type is a Maybe which returns Nothing if either of the inputs is negative." ~~~ ~~~if:cobol In COBOL, `num` and `s` will always be an integer. Return an empty table if `num` is negative. ~~~ <h2><u>Other Kata in this Series:</u></h2> <a href="https://www.codewars.com/kata/58ba6fece3614ba7c200017f">Numerical Palindrome #1</a> <br><b>Numerical Palindrome #1.5 </b> <br><a href="https://www.codewars.com/kata/58de819eb76cf778fe00005c">Numerical Palindrome #2</a> <br><a href="https://www.codewars.com/kata/58df62fe95923f7a7f0000cc">Numerical Palindrome #3</a> <br><a href="https://www.codewars.com/kata/58e2708f9bd67fee17000080">Numerical Palindrome #3.5</a> <br><a href="https://www.codewars.com/kata/58df8b4d010a9456140000c7">Numerical Palindrome #4</a> <br><a href="https://www.codewars.com/kata/58e26b5d92d04c7a4f00020a">Numerical Palindrome #5</a>
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 not). ```if-not:haskell,cobol Return "Not valid" if the input is not an integer or less than `0`. ``` ```if:haskell Return `Nothing` if the input is less than `0` and `Just True` or `Just False` otherwise. ``` ```if:cobol Return `0` if the input is not a palindrome or is strictly negative `0` and `1` otherwise. ``` <h2><u>Other Kata in this Series:</u></h2> <b>Numerical Palindrome #1</b> <br><a href="https://www.codewars.com/kata/numerical-palindrome-number-1-dot-5">Numerical Palindrome #1.5</a> <br><a href="https://www.codewars.com/kata/58de819eb76cf778fe00005c">Numerical Palindrome #2</a> <br><a href="https://www.codewars.com/kata/58df62fe95923f7a7f0000cc">Numerical Palindrome #3</a> <br><a href="https://www.codewars.com/kata/58e2708f9bd67fee17000080">Numerical Palindrome #3.5</a> <br><a href="https://www.codewars.com/kata/58df8b4d010a9456140000c7">Numerical Palindrome #4</a> <br><a href="https://www.codewars.com/kata/58e26b5d92d04c7a4f00020a">Numerical Palindrome #5</a>
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 "(())((()())())" => true ``` ## Constraints `0 <= input.length <= 100` ~~~if-not:javascript,go,cobol Along with opening (`(`) and closing (`)`) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do **not** treat other forms of brackets as parentheses (e.g. `[]`, `{}`, `<>`). ~~~
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]` --> `3 - 4` --> `-1` * `[8, 7]` --> `8 - 7` --> `1` and then returns the product of all the processed sub-lists: `-3 * -1 * 1` --> `3`. For input, you can trust that neither the main list nor the sublists will be empty.
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] (1, 15, 20) -> [1] ``` ### Note - start < stop - step > 0
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 number of characters</blockquote> For example: **(Input1, Input2) --> output** ``` ("1", "22") --> "1221" ("22", "1") --> "1221" ```
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'] first(arr, 3) //=> ['a', 'b', 'c']; first(arr, 0) //=> []; ``` ```csharp var arr = new object[] { 'a', 'b', 'c', 'd', 'e' }; Kata.TakeFirstElements(arr); //=> new object[] { 'a' } Kata.TakeFirstElements(arr, 2);// => new object[] { 'a', 'b' } Kata.TakeFirstElements(arr, 3); //=> new object[] { 'a', 'b', 'c' } Kata.TakeFirstElements(arr, 0); //=> new object[] { } ``` ```python arr = ['a', 'b', 'c', 'd', 'e'] first(arr) # --> ['a'] first(arr, 2) # --> ['a', 'b'] first(arr, 3) # --> ['a', 'b', 'c'] first(arr, 0) # --> [] ```
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** exponential = **exponent** subtraction = **subt** ``` ```if:csharp addition = **Add** multiply = **Multiply** division = **Divide** modulus = **Mod** exponential = **Exponent** subtraction = **Subt** **Note: All funcitons can return int and all will recieve 2 integers.** ``` *Note: All math operations will be: a (operation) b*
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. 20 leters * 30 = 600 (Space counts as a character).
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 - english * ciao - italian * salut - french * hallo - german * hola - spanish * ahoj - czech republic * czesc - polish Notes * you can assume the input is a string. * to keep this a beginner exercise you don't need to check if the greeting is a subset of word (`Hallowen` can pass the test) * function should be case insensitive to pass the tests
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) * (5/9) ``` ```if-not:ruby,typescript Remember that typically temperatures in the current weather conditions are given in whole numbers. It is possible for temperature sensors to report temperatures with a higher accuracy such as to the nearest tenth. Instrument error though makes this sort of accuracy unreliable for many types of temperature measuring sensors. ``` ```if:ruby Please round to 5dp (use `.round(5)`) ``` ```if:typescript Please round to 5dp (use `Math.round()`) ```
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 being removed, the numbers move down to take their place. In case of above 13, they move down by two because there are two omitted numbers below them. Basements (negatives) stay the same as the universal level. [More information here](https://en.wikipedia.org/wiki/Storey#European_scheme) ## Examples ``` 1 => 0 0 => 0 5 => 4 15 => 13 -3 => -3 ```
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 that counts how many more (or less) pieces of toast you need in the toasters. Even though you need more or less, the number will still be positive, not negative. ## Examples: You must return the number of toast the you need to put in (or to take out). In case of `5` you can still put `1` toast in: ``` six_toast(5) == 1 ``` And in case of `12` you need `6` toasts less (but not `-6`): ``` six_toast(12) == 6 ``` ___ Good luck!
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 should return a number (final grade). There are four types of final grades: - 100, if a grade for the exam is more than 90 or if a number of completed projects more than 10. - 90, if a grade for the exam is more than 75 and if a number of completed projects is minimum 5. - 75, if a grade for the exam is more than 50 and if a number of completed projects is minimum 2. - 0, in other cases Examples(**Inputs**-->**Output**): ``` 100, 12 --> 100 99, 0 --> 100 10, 15 --> 100 85, 5 --> 90 55, 3 --> 75 55, 0 --> 0 20, 2 --> 0 ``` *Use Comparison and Logical Operators.
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 kata
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 some modification to pass this test. P.S. You have to create a new list and add a new item to that. (This Kata is originally designed for C# language and it shows that adding a new item to the input list is not going to work, even though the parameter is passed by value, but the value is poining to the **reference** of list and any change on parameter will be seen by caller)
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'` returns `1` `'b'` and `'G'` returns `0` `'B'` and `'g'` returns `0` `'0'` and `'?'` returns `-1`
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 bullets </br> M4A1 - 30 bullets </br> M16A2 - 30 bullets </br> PSG1 - 5 bullets </br> Example: ["PT92", 6] => 2 (6 streets 3 bullets each) </br> ["M4A1", 6] => 1 The return Will always be an integer so as the params. ~~~if:fortran *NOTE: In Fortran the weapon and number of streets are passed in as two separater arguments (the first one a string, the second an integer) instead of a single array.* ~~~ ~~~if:c *NOTE: In C the weapon and number of streets are passed in as two separate arguments (the first one a string, the second an integer) instead of a single array.* ~~~
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 `NaN`. ``` ```if:php,python,ruby Division by zero should return an empty value. ``` ### Examples: ``` n = 17 m = 5 result = 2 (remainder of `17 / 5`) n = 13 m = 72 result = 7 (remainder of `72 / 13`) n = 0 m = -1 result = 0 (remainder of `0 / -1`) n = 0 m = 1 result - division by zero (refer to the specifications on how to handle this in your language) ```
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 each test case are 2, 3 or 4. When you check if they are ready their answers are in a dictionary and will either be: ```aye``` or ```nay``` Firing with less than all gunners ready is non-optimum (this is not fire at will, this is fire by the captain's orders or walk the plank, dirty sea-dog!) If all answers are 'aye' then Fire! if one or more are 'nay' then Shiver me timbers! Also, check out the new Pirates!! Kata: https://www.codewars.com/kata/57e2d5f473aa6a476b0000fe
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` = "john" => return "Hello, John!" * With `name` = "aliCE" => return "Hello, Alice!" * With `name` not given or `name` = "" => return "Hello, World!" ```
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)` ### Output: * Number of files that can be fully saved in the HD. ### Examples: ``` save([4,4,4,3,3], 12) -> 3 # 4+4+4 <= 12, but 4+4+4+3 > 12 ``` ``` save([4,4,4,3,3], 11) -> 2 # 4+4 <= 11, but 4+4+4 > 11 ``` ``` save([12, 0, 0, 1], 12) -> 3 # 12+0+0 <= 12, but 12+0+0+1 > 12 ``` Do not expect any negative or invalid inputs.
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β™₯','7β™₯','8β™₯','9β™₯','10β™₯','Jβ™₯','Qβ™₯','Kβ™₯','Aβ™₯', '2β™ ','3β™ ','4β™ ','5β™ ','6β™ ','7β™ ','8β™ ','9β™ ','10β™ ','Jβ™ ','Qβ™ ','Kβ™ ','Aβ™ ']; ``` ```ruby DECK = ['2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS', '2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD', '2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH', '2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC'] ``` ```python DECK = ['2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS', '2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD', '2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH', '2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC'] ``` ```csharp string[] 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β™₯", "7β™₯", "8β™₯", "9β™₯", "10β™₯", "Jβ™₯", "Qβ™₯", "Kβ™₯", "Aβ™₯", "2β™ ", "3β™ ", "4β™ ", "5β™ ", "6β™ ", "7β™ ", "8β™ ", "9β™ ", "10β™ ", "Jβ™ ", "Qβ™ ", "Kβ™ ", "Aβ™ " }; ``` ```lua local DECK = {'2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS', '2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD', '2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH', '2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC'} ``` ```javascript ('3♣') -> return 'clubs' ('3♦') -> return 'diamonds' ('3β™₯') -> return 'hearts' ('3β™ ') -> return 'spades' ``` ```ruby ('3C') -> return 'clubs' ('3D') -> return 'diamonds' ('3H') -> return 'hearts' ('3S') -> return 'spades' ``` ```python ('3C') -> return 'clubs' ('3D') -> return 'diamonds' ('3H') -> return 'hearts' ('3S') -> return 'spades' ``` ```csharp DefineSuit("3♣") -> return "clubs" DefineSuit("3♦") -> return "diamonds" DefineSuit("3β™₯") -> return "hearts" DefineSuit("3β™ ") -> return "spades" ``` ```lua ('3C') -> return 'clubs' ('3D') -> return 'diamonds' ('3H') -> return 'hearts' ('3S') -> return 'spades' ```
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. - Inputs and the expected output will never exceed the signed 32-bit integer limit (`2^31 - 1`)
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 conversion rate you should use is 6.75 CNY for every 1 USD. All numbers should be represented as a string with 2 decimal places. (e.g. "21.00" NOT "21.0" or "21")
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"); # wrapper_obj should be {"value":"my_wrapped_string"} ``` We would then expect the following statement to be true: ```python wrapper_obj["value"] == "my_wrapped_string" ``` Unfortunately, the code is not working as designed. Please fix the code so that it behaves as specified.
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 arrays with 0 or more Integers. If both arr1 and arr2 are empty, then just return an empty array. Note: arr1 and arr2 may be sorted in different orders. Also arr1 and arr2 may have same integers. Remove duplicated in the returned result. ## Examples (input -> output) ``` * [1, 2, 3, 4, 5], [6, 7, 8, 9, 10] -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * [1, 3, 5, 7, 9], [10, 8, 6, 4, 2] -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * [1, 3, 5, 7, 9, 11, 12], [1, 2, 3, 4, 5, 10, 12] -> [1, 2, 3, 4, 5, 7, 9, 10, 11, 12] ``` Happy coding!
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"] ``` For example, if this array were passed as an argument: ``` ["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"] ``` Your function would return the following array: ``` ["Mallard", "Hook Bill", "Crested", "Blue Swedish"] ``` The elements in the returned array should be in the same order as in the initial array passed to your function, albeit with the 'geese' removed. Note that all of the strings will be in the same case as those provided, and some elements may be repeated.
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], [10, 20, 20, 20], [10, 10, 10, 20]] ``` ## Solution ``` S: start E: end matrix = [[S, ↓, -, -], [-, ↓, -, -], [-, β†’, β†’, ↓], [-, -, -, E]] matrix = [[20, 20, , ], [, 20, , ], [, 20, 20, 20], [, , , 20]] Top Left Corner, Right, Down, Down, Right, Right, Bottom Right Corner 20 + 20 + 20 + 20 + 20 + 20 + 20 = 140 ```
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 factorization of 24, for instance, is (2^3) * (3^1). ~~~if:java Write a class called `PrimeFactorizer` whose constructor takes no arguments and has an instance method `factor` accepting exactly 1 `long` which returns a `Map<Long, Integer>` where the keys are prime numbers and the values are the multiplicities. ~~~ ~~~if:ruby Without using the prime library, write a class called `PrimeFactorizer` whose constructor accepts exactly 1 integer and has an instance method `factor` returning a hash where the keys are prime numbers and the values are the multiplicities. ~~~ ~~~if:javascript Write a class called `PrimeFactorizer` whose constructor accepts exactly 1 number (a positive integer) and has a property `factor` containing an object where the keys are prime numbers **as strings** and the values are the multiplicities. ~~~ ~~~if:python Write a class called `PrimeFactorizer` (inheriting directly from `object`) whose constructor accepts exactly 1 `int` and has a property `factor` containing a dictionary where the keys are prime numbers and the values are the multiplicities. ~~~ ~~~if:objc Write a function `prime_factors` accepting exactly 1 `long long` and returns a dictionary (i.e. `NSDictionary *`) where the keys are prime numbers **as strings** (i.e. `NSString *`) and the values are the multiplicities are `NSNumber *`s representing integers. ~~~ ```ruby PrimeFactorizer.new(24).factor #should return { 2 => 3, 3 => 1 } ``` ```python PrimeFactorizer(24).factor #should return { 2: 3, 3: 1 } ``` ```javascript new PrimeFactorizer(24).factor //should return { '2': 3, '3': 1 } ``` ```java new PrimeFactorizer().factor(24) //should return { 2 => 3, 3 => 1 } ``` ```objc prime_factors(24); // => @{@"2": @3, @"3": @1} ```
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. ## Examples ``` 1 ==> [] 3 ==> [3] 8 ==> [2, 2, 2] 9 ==> [3, 3] 12 ==> [2, 2, 3] ```
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 be given an integer input. * You can not assume that the integer will be only positive. You may be given negative numbers as well ( or `0` ). * **NOTE on performance**: There are no fancy optimizations required, but still _the_ most trivial solutions might time out. Numbers go up to 2^31 ( or similar, depending on language ). Looping all the way up to `n`, or `n/2`, will be too slow. ## Example ```c is_prime(1) /* false */ is_prime(2) /* true */ is_prime(-1) /* false */ ``` ```nasm mov edi, 1 call is_prime ; EAX <- 0 (false) mov edi, 2 call is_prime ; EAX <- 1 (true) mov edi, -1 call is_prime ; EAX <- 0 (false) ``` ```c++ bool isPrime(5) = return true ``` ```d bool isPrime(5) = return true ``` ```pascal IsPrime(1) = false IsPrime(2) = true IsPrime(-1) = false ``` ```perl is_prime(1) # 0 is_prime(2) # 1 is_prime(-1) # 0 ``` ```lambdacalc is-prime 1 -> False is-prime 2 -> True ``` ~~~if:lambdacalc ## Encodings purity: `LetRec` numEncoding: `BinaryScott` ( so, no negative numbers ) export deconstructor `if` for your `Boolean` encoding ~~~
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): if a == p - 1: return True a = pow(a, 2, p) return False def is_prime(p): if p == 2: return True if p <= 1 or p % 2 == 0: return False return all(Miller_Rabin(random . randint(2, p - 1), p) for _ in range(40))
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 named) argument of the function `n` specifies the number of arguments in the variable-argument list. Do **not** take `n` into account when computing the LCM of the numbers. ~~~ ~~~if:lambdacalc ### Encodings `purity: LetRec` `numEncoding: BinaryScott` export constructors `nil, cons` for your `List` encoding ~~~
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 may look like this: ```python {'James': ['Jacob', 'Bill', 'Lucas'], 'Johnny': ['David', 'Kyle', 'Lucas'], 'Peter': ['Lucy', 'Kyle']} ``` ```javascript {'James': ['Jacob', 'Bill', 'Lucas'], 'Johnny': ['David', 'Kyle', 'Lucas'], 'Peter': ['Lucy', 'Kyle']} ``` and also a list of the names of the dead people: ```python ['Lucas', 'Bill'] ``` ```javascript ['Lucas', 'Bill'] ``` return the name of the one killer, in our case ```'James'``` because he is the only person that saw both ```'Lucas'``` and ```'Bill'```
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 entertaining exercise on classes and conditions. You must instantiate and interact with a `World()` object. On this kata the following methods are available: `talk(target, what)`: Interact with npcs. The only valid npc on this kata has the name "npc". `pickup(what)`: Pickup a thing to throw. Default is "rock". `throw(target)`: If you are holding a thing, throw it at a target. The throw may miss. Will return True if hit, False if missed. Ex.: `world.talk("npc", "hello")` `world.pickup("rock")` `world.throw("rat")` Talking to the "npc" will give you further instructions on what to do. The `talk` replies will be in the Output panel. Be careful when using `while` loops because if the script timeouts you wont see any output. Your function should return the world object instance after all tasks are completed. The tests will call the `done()` method on the returned object. This method will check the internal flags of the object to see if you completed the quest line. Replacing or changing the World class and instance (other than calling the documented methods) is not allowed. The full tests include a few type checks.
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 if the player has achieved at least 100 points in his class. If so, he enters the qualifying stage. In that case, we return, ```"Well done! You have advanced to the qualifying stage. Win 2 out of your next 3 games to rank up."```. Otherwise return, ```False/false``` (according to the language in use). <h2>NOTE</h1>: Remember, in <b>C#</b> you have to cast your output value to <b>Object</b> type!
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 you is `damage`. #### Task Write a function that will calculate: how many hits you received, how much damage you received and your remaining health. if your health is <= 0, you die and function should return `"hero died"`. #### Examples ``` (100, 3, 33) => "hits: 0, damage: 0, health: 100" ( 50, 7, 10) => "hits: 2, damage: 20, health: 30" ``` #### Note All numbers are strictly positive. Your function should always return a string. Have fun :) #### Credits [One Punch Man (Anime)](http://onepunchman.wikia.com/wiki/One-Punch_Man_Wiki)
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" 17 --> "drink coke" 18 --> "drink beer" 20 --> "drink beer" 30 --> "drink whisky" ```
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 { color : orange; background-color : black; text-align : right; border: 3px solid gray; border-collapse: collapse; } </style> <table id = "tvkb"> <tr><td>a<td>b<td>c<td>d<td>e<td>1<td>2<td>3</tr> <tr><td>f<td>g<td>h<td>i<td>j<td>4<td>5<td>6</tr> <tr><td>k<td>l<td>m<td>n<td>o<td>7<td>8<td>9</tr> <tr><td>p<td>q<td>r<td>s<td>t<td>.<td>@<td>0</tr> <tr><td>u<td>v<td>w<td>x<td>y<td>z<td>_<td>/</tr> </table> # Kata task How many button presses on my remote are required to type a given `word`? ## Notes * The cursor always starts on the letter `a` (top left) * Remember to also press `OK` to "accept" each character. * Take a direct route from one character to the next * The cursor does not wrap (e.g. you cannot leave one edge and reappear on the opposite edge) * A "word" (for the purpose of this Kata) is any sequence of characters available on my virtual "keyboard" # Example word = `codewars` * c => `a`-`b`-`c`-OK = 3 * o => `c`-`d`-`e`-`j`-`o`-OK = 5 * d => `o`-`j`-`e`-`d`-OK = 4 * e => `d`-`e`-OK = 2 * w => `e`-`j`-`o`-`t`-`y`-`x`-`w`-OK = 7 * a => `w`-`r`-`m`-`h`-`c`-`b`-`a`-OK = 7 * r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6 * s => `r`-`s`-OK = 2 Answer = 3 + 5 + 4 + 2 + 7 + 7 + 6 + 2 = 36 <hr style="background-color:orange;height:2px;width:75%;margin-top:30px;margin-bottom:30px;"/> <span style="color:orange;"> *Good Luck!<br/> DM.* </span> <hr> Series * TV Remote * <a href=https://www.codewars.com/kata/tv-remote-shift-and-space>TV Remote (shift and space) * <a href=https://www.codewars.com/kata/tv-remote-wrap>TV Remote (wrap)</a> * <a href=https://www.codewars.com/kata/tv-remote-symbols>TV Remote (symbols)</a> </a>
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 the distance between two points in a grid (like the grid-like street geography of the New York borough of Manhattan) calculated by only taking a vertical and/or horizontal path. Complete the function that accepts two points and returns the Manhattan Distance between the two points. The points are arrays or tuples containing the `x` and `y` coordinate in the grid. You can think of `x` as the row in the grid, and `y` as the column. ### Examples ``` * Input [1, 1], [1, 1] => Output 0 * Input [5, 4], [3, 2] => Output 4 * Input [1, 1], [0, 3] => Output 3 ```
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`, `minutes` and `seconds`. It is much easier to understand with an example: ```text * For seconds = 62, your function should return "1 minute and 2 seconds" * For seconds = 3662, your function should return "1 hour, 1 minute and 2 seconds" ``` **For the purpose of this Kata, a year is 365 days and a day is 24 hours.** Note that spaces are important. ### Detailed rules The resulting expression is made of components like `4 seconds`, `1 year`, etc. In general, a positive integer and one of the valid units of time, separated by a space. The unit of time is used in plural if the integer is greater than 1. The components are separated by a comma and a space (`", "`). Except the last component, which is separated by `" and "`, just like it would be written in English. A more significant units of time will occur before than a least significant one. Therefore, `1 second and 1 year` is not correct, but `1 year and 1 second` is. Different components have different unit of times. So there is not repeated units like in `5 seconds and 1 second`. A component will not appear at all if its value happens to be zero. Hence, `1 minute and 0 seconds` is not valid, but it should be just `1 minute`. A unit of time must be used "as much as possible". It means that the function should not return `61 seconds`, but `1 minute and 1 second` instead. Formally, the duration specified by of a component must not be greater than any valid more significant unit of time.
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: if qty > 1: name += "s" chunks.append(str(qty) + " " + name) seconds = seconds % secs return ', '.join(chunks[:-1]) + ' and ' + chunks[-1] if len(chunks) > 1 else chunks[0]
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", "_", "B"] # answer key ["A", "D", "C", "E", "B"] # student's solution ➞ True # Possible for student to get all questions correct. ["B", "_", "B"] # answer key ["B", "D", "C"] # student's solution ➞ False # First question is correct but third is wrong, so not possible to score 100%. ["T", "_", "F", "F", "F"] # answer key ["F", "F", "T", "T", "T"] # student's solution ➞ True # Possible for student to get all questions incorrect. ``` **Examples** ``` (["B", "A", "_", "_"], ["B", "A", "C", "C"]) ➞ True (["A", "B", "A", "_"], ["B", "A", "C", "C"]) ➞ True (["A", "B", "C", "_"], ["B", "A", "C", "C"]) ➞ False (["B", "_"], ["C", "A"]) ➞ True (["B", "A"], ["C", "A"]) ➞ False (["B"], ["B"]) ➞ True (["_"], ["B"]) ➞ True ``` **Notes** - Test has at least one question. - len(key) == len(answers)
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 Description - You are given an array of mountains, where each element represents the height of the mountain. - A mountain pass is defined as a subarray of the mountain array. The length of a mountain pass is the length of the subarray. - You have an initial energy level `E`. - You start at any initial index of your choice. - Going up a mountain (i.e., moving from a lower height to a higher height) costs you energy equal to the difference in heights. - Going down a mountain or staying at the same height does not cost you any energy. - You can only move to the mountains on your right (i.e., the next index). Your task is to find the longest mountain pass you can take based on your initial energy level. Return the length of the longest mountain pass and the initial index from where you should start. ## Input - `mountains`: An array of integers representing the heights of the mountains. - `E`: An integer representing your initial energy level. **Note:** The length of the mountain array can be very large, up to `10^7`. ## Output Return a tuple `(max_length, start_index)`, where: - `max_length`: The length of the longest mountain pass you can take. - `start_index`: The initial index from where you should start the mountain pass. If there are multiple mountain passes with the same length, return the one with the smallest initial index.
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] ) + energy_cost[i - 1] # Sliding window max_length = 0 start_index = 0 left = 0 for right in range(n): while energy_cost[right] - (energy_cost[left] if left > 0 else 0) > E: left += 1 if right - left + 1 > max_length: max_length = right - left + 1 start_index = left return (max_length, start_index)
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) #### Input: - `n` - integer `(2 ≀ n ≀ 10^10)` - `m` - integer `(20 ≀ m ≀ 10^18)` #### Output: - `result` - array of integers
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 + \cfrac { 1 } { 3 + \cfrac { 1 } { 1 + \cfrac { 1 } { 5 } } } } ``` If the numerator is `0`, you should return `[]`. ~~~if:lambdacalc #### Encodings purity: `LetRec` numEncoding: `Binary-Scott` export `foldr` for your `List` encoding ~~~
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 alphabet (or is the same letter). For instance (A="A", B="F") and (A="g", B = "g") are valid parameter sets for the function. On the other hand (a="N" b="H") is not</li> </ol> Your mission, if you accept it, is to write a function slice() that returns the inclusive slice of the English alphabet starting at A and ending at B. A few examples are provided for clarity: ``` slice("A", "B") --> "AB" slice("D", "H") --> "DEFGH" slice("f", "f") --> "f" slice("x", "z") --> "xyz" ``` Astute readers will probably think there may be a catch given the Kyu rating on this Kata. And you would be wrong! There is not ONE catch, not TWO, But THREE catches (a-ha-ha) <ol> <li>Your code can at most be two lines long</li> <li>You code can at most be 100 charaters long</li> <li>Finally, you may not use the quoting characters (' and ") as well as "str" or square braces in your code</li> </ol> (Note to contributors: Please inform me if there is any hack I might have missed that would allow a too-trivial solution for this to exist.) </ol> Happy coding!
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, you need to implement a function `findpos(n, t)` that receives a integer `n` and a table/set `t` representing the set of digits, and returns the position of `n` in the sequence. ## Examples ``` findpos(11, { 1 }) --> 2 findpos(55, { 1, 5 }) --> 6 findpos(42, { 4, 0, 2 }) --> 8 findpos(1337, { 1, 3, 7 }) --> 54 findpos(123456789, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }) --> 123456790 ``` ## Note The integer `n` will always be in the sequence.
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 this case the median is 4.5 Some of the arrays may be empty, but there will always be at least one non-empty array in the list ### Tests * 50 Small Tests: 5 arrays, each with up to 20 elements * 50 Medium Tests: 10 arrays, each with up to 1,000 elements * 50 Large Tests: Up to 15 arrays, each with up to 2,000,000 elements
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 < y: return e[m] elif x > n: q[i] = m else: p[i] = m + 1 def median_from_n_arrays(a): n = sum(len(e) for e in a) return (f(a, n >> 1) + f(a, (n - 1) >> 1)) / 2
Median Value in N Sorted Arrays
65fc93001bb13a2074cb4ee8
[ "Arrays", "Performance" ]
https://www.codewars.com/kata/65fc93001bb13a2074cb4ee8
4 kyu