description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
The Collatz Conjecture states that for any positive natural number `n`, this process: * if `n` is even, divide it by `2` * if `n` is odd, multiply it by `3` and add `1` * repeat will eventually reach `n = 1`. For example, if `n = 20`, the resulting sequence will be: [ 20, 10, 5, 16, 8, 4, 2, 1 ] Write a program that will output the length of the Collatz Conjecture for any given `n`. In the example above, the output would be `8`. ~~~if:lambdacalc Use purity `LetRec`, numEncoding `BinaryScott`. ~~~ For more reading see: http://en.wikipedia.org/wiki/Collatz_conjecture
algorithms
def collatz(n): return 1 if n == 1 else 1 + collatz(3 * n + 1 if n % 2 else n / / 2)
Collatz Conjecture Length
54fb963d3fe32351f2000102
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/54fb963d3fe32351f2000102
7 kyu
<h1>Find the anonymous function in the array</h1> Find the anonymous function in the given array and use the function to filter the array <h3>Input</h3> Your input. First Parameter will be an array with an anonymous function somewhere in the lot, The second Parameter will be an array which you will filter using the anonymous function you find. <h3>Output</h3> Your output. Output a filtered version of the second parameter using the function found in the first parameter. Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
reference
def find_function(func, arr): f = next(el for el in func if callable(el)) return [* filter(f, arr)]
Find the anonymous function
55a12bb8f0fac1ba340000aa
[ "Fundamentals" ]
https://www.codewars.com/kata/55a12bb8f0fac1ba340000aa
7 kyu
Description: The mean (or average) is the most popular measure of central tendency; however it does not behave very well when the data is skewed (i.e. wages distribution). In such cases, it's better to use the median. Your task for this kata is to find the median of an array consisting of n elements. You can assume that all inputs are arrays of numbers in integer format. For the empty array your code should return `NaN` (false in JavaScript/`NULL` in PHP/`nil` in Ruby). Examples: Input `[1, 2, 3, 4]` --> Median `2.5` Input `[3, 4, 1, 2, 5]` --> Median `3`
reference
from statistics import median
Median fun fun
582609930626631a9600003e
[ "Fundamentals", "Arrays", "Data Types", "Basic Language Features", "Mathematics", "Algorithms", "Logic", "Numbers" ]
https://www.codewars.com/kata/582609930626631a9600003e
7 kyu
A category page displays a set number of products per page, with pagination at the bottom allowing the user to move from page to page. Given that you know the page you are on, how many products are in the category in total, and how many products are on any given page, how would you output a simple string showing which products you are viewing.. ## Examples In a category of 30 products with 10 products per page, on page 1 you would see `'Showing 1 to 10 of 30 Products.'` In a category of 26 products with 10 products per page, on page 3 you would see `'Showing 21 to 26 of 26 Products.'` In a category of 8 products with 10 products per page, on page 1 you would see `'Showing 1 to 8 of 8 Products.'`
algorithms
def pagination_text(page_number, page_size, total_products): first = page_size * (page_number - 1) + 1 last = min(total_products, first + page_size - 1) return "Showing %d to %d of %d Products." % (first, last, total_products)
Showing X to Y of Z Products.
545cff101288c1d2da0006fb
[ "Algorithms" ]
https://www.codewars.com/kata/545cff101288c1d2da0006fb
7 kyu
Complete the function that takes a string of English-language text and returns the number of consonants in the string. Consonants are all letters used to write English excluding the vowels `a, e, i, o, u`.
reference
def consonant_count(str): return sum(1 for c in str if c . isalpha() and c . lower() not in "aeiou")
Count consonants
564e7fc20f0b53eb02000106
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/564e7fc20f0b53eb02000106
7 kyu
You'll be given a list of two strings, and each will contain exactly one colon (`":"`) in the middle (but not at beginning or end). The length of the strings, before and after the colon, are random. Your job is to return a list of two strings (in the same order as the original list), but with the characters after each colon swapped. ## Examples ``` ["abc:123", "cde:456"] --> ["abc:456", "cde:123"] ["a:12345", "777:xyz"] --> ["a:xyz", "777:12345"] ```
reference
def tail_swap(strings): head0, tail0 = strings[0]. split(':') head1, tail1 = strings[1]. split(':') return [head0 + ':' + tail1, head1 + ':' + tail0]
Tail Swap
5868812b15f0057e05000001
[ "Fundamentals" ]
https://www.codewars.com/kata/5868812b15f0057e05000001
7 kyu
There are two lists, possibly of different lengths. The first one consists of keys, the second one consists of values. Write a function ```createDict(keys, values)``` that returns a dictionary created from keys and values. If there are not enough values, the rest of keys should have a ```None``` (**JS** `null`)value. If there not enough keys, just ignore the rest of values. Example 1: ```python keys = ['a', 'b', 'c', 'd'] values = [1, 2, 3] createDict(keys, values) # returns {'a': 1, 'b': 2, 'c': 3, 'd': None} ``` ```javascript keys = ['a', 'b', 'c', 'd'] values = [1, 2, 3] createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3, 'd': null} ``` Example 2: ```python keys = ['a', 'b', 'c'] values = [1, 2, 3, 4] createDict(keys, values) # returns {'a': 1, 'b': 2, 'c': 3} ``` ```javascript keys = ['a', 'b', 'c'] values = [1, 2, 3, 4] createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3} ```
reference
def createDict(keys, values): while len(keys) > len(values): values . append(None) dic = dict(zip(keys, values)) return dic
Dictionary from two lists
5533c2a50c4fea6832000101
[ "Fundamentals" ]
https://www.codewars.com/kata/5533c2a50c4fea6832000101
7 kyu
You should write a simple function that takes string as input and checks if it is a valid Russian postal code, returning `true` or `false`. A valid postcode should be 6 digits with no white spaces, letters or other symbols. Empty string should also return false. Please also keep in mind that a valid post code **cannot start with** `0, 5, 7, 8 or 9` ## Examples Valid postcodes: * 198328 * 310003 * 424000 Invalid postcodes: * 056879 * 12A483 * 1@63 * 111
reference
def zipvalidate(postcode): return len(postcode) == 6 and postcode . isdigit() and postcode[0] not in "05789"
Russian postal code checker
552e45cc30b0dbd01100001a
[ "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/552e45cc30b0dbd01100001a
7 kyu
The new £5 notes have been recently released in the UK and they've certainly became a sensation! Even those of us who haven't been carrying any cash around for a while, having given in to the convenience of cards, suddenly like to have some of these in their purses and pockets. But how many of them could you get with what's left from your salary after paying all bills? The programme that you're about to write will count this for you! Given a salary and the array of bills, calculate your disposable income for a month and return it as a number of new £5 notes you can get with that amount. If the money you've got (or do not!) doesn't allow you to get any £5 notes return 0. £££ GOOD LUCK! £££
algorithms
def get_new_notes(salary, bills): return max((salary - sum(bills)), 0) / / 5
New £5 notes collectors!
58029cc9af749f80e3001e34
[ "Arrays", "Lists", "Algorithms" ]
https://www.codewars.com/kata/58029cc9af749f80e3001e34
7 kyu
Implement: ```python eight_bit_signed_number() ``` ```csharp .SignedEightBitNumber() ``` ```ruby String.eight_bit_signed_number? ``` ```javascript String.prototype.signedEightBitNumber() ``` ```java StringUtils.isSignedEightBitNumber(String) ``` ```if:python which should return `True` if given object is a number representable by 8 bit signed integer (-128 to -1 or 0 to 127), `False` otherwise. ``` ```if-not:python which should return `true` if given object is a number representable by 8 bit signed integer (-128 to -1 or 0 to 127), `false` otherwise. ``` It should only accept numbers in canonical representation, so no leading `+`, extra `0`s, spaces etc.
reference
import re def signed_eight_bit_number(number): return bool(re . match("(0|-128|-?([1-9]|[1-9]\d|1[01]\d|12[0-7]))\Z", number))
Regexp Basics - is it a eight bit signed number?
567ed73340895395c100002e
[ "Bits", "Binary", "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/567ed73340895395c100002e
7 kyu
You'll be given a string of characters as an input. Complete the function that returns a _list_ of strings: (a) in the reverse order of the original string, and (b) with each successive string starting one character further in from the end of the original string. Assume the original string is at least 3 characters long. _Try to do this using slices and avoid converting the string to a list._ ## Examples ```python '123' ==> ['321', '21', '1'] 'abcde' ==> ['edcba', 'dcba', 'cba', 'ba', 'a'] ```
reference
def reverse_slice(s): return [s[:: - 1][i:] for i in range(len(s))]
String reverse slicing 101
586efc2dcf7be0f217000619
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/586efc2dcf7be0f217000619
7 kyu
Gordon Ramsay shouts. He shouts and swears. There may be something wrong with him. Anyway, you will be given a string of four words. Your job is to turn them in to Gordon language. Rules: Obviously the words should be Caps, Every word should end with '!!!!', Any letter 'a' or 'A' should become '@', Any other vowel should become '*'.
reference
def gordon(a): return '!!!! ' . join(a . upper(). split()). translate(str . maketrans('AEIOU', '@****')) + '!!!!'
Hells Kitchen
57d1f36705c186d018000813
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57d1f36705c186d018000813
7 kyu
A lot of goods have an <a href="https://en.wikipedia.org/wiki/International_Article_Number_%28EAN%29"> International Article Number</a> (formerly known as "European Article Number") abbreviated "EAN". EAN is a 13-digits barcode consisting of 12-digits data followed by a single-digit checksum (EAN-8 is not considered in this kata). <br><br> The single-digit checksum is calculated as followed (based upon the 12-digit data): The digit at the first, third, fifth, etc. position (i.e. at the odd position) has to be multiplied with "1". <br>The digit at the second, fourth, sixth, etc. position (i.e. at the even position) has to be multiplied with "3".<br> Sum these results. <br> If this sum is dividable by 10, the checksum is 0. Otherwise the checksum has the following formula: checksum = 10 - (sum mod 10) For example, calculate the checksum for "400330101839" (= 12-digits data):<br> 4·1 + 0·3 + 0·1 + 3·3 + 3·1 + 0·3 + 1·1 + 0·3 + 1·1 + 8·3 + 3·1 + 9·3<br> = 4 + 0 + 0 + 9 + 3 + 0 + 1 + 0 + 1 + 24 + 3 + 27 <br> = 72<br> 10 - (72 mod 10) = 8 ⇒ Checksum: 8<br> Thus, the EAN-Code is 400330101839<b>8</b> (= 12-digits data followed by single-digit checksum). <h2>Your Task</h2> Validate a given EAN-Code. Return true if the given EAN-Code is valid, otherwise false. <h2>Assumption</h2> You can assume the given code is syntactically valid, i.e. it only consists of numbers and it exactly has a length of 13 characters. <h2>Examples</h2> ```java EANValidator.validate("4003301018398") // true EANValidator.validate("4003301018392") // false ``` ```javascript validateEAN("4003301018398") // true validateEAN("4003301018392") // false ``` ```coffeescript validateEAN('4003301018398') # true validateEAN('4003301018392') # false ``` ```python validate_ean("4003301018398") # => True validate_ean("4003301018392") # => False ``` ```ruby validate_ean("4003301018398") # => true validate_ean("4003301018392") # => false ``` ```clojure (validate-ean "4003301018398") ; => true (validate-ean "4003301018392") ; => false ``` ```csharp EANValidator.Validate("4003301018398") // true EANValidator.Validate("4003301018392") // false ``` Good Luck and have fun.
algorithms
def validate_ean(code): code = map(int, code) return (sum(code[0:: 2]) + sum(code[1:: 2]) * 3) % 10 == 0
EAN Validation
55563df50dda59adf900004d
[ "Algorithms", "Fundamentals", "Mathematics", "Strings" ]
https://www.codewars.com/kata/55563df50dda59adf900004d
7 kyu
Your car is old, it breaks easily. The shock absorbers are gone and you think it can handle about 15 more bumps before it dies totally. Unfortunately for you, your drive is very bumpy! Given a string showing either flat road (`_`) or bumps (`n`). If you are able to reach home safely by encountering `15 bumps or less`, return `Woohoo!`, otherwise return `Car Dead`
reference
def bumps(road): return "Woohoo!" if road . count("n") <= 15 else "Car Dead"
Bumps in the Road
57ed30dde7728215300005fa
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57ed30dde7728215300005fa
7 kyu
The year is 2088 and the Radical Marxist Socialist People's Party (RMSPP) has just seized power in Brazil. Their first act in power is absolute wealth equality through coercive redistribution. Create a function that redistributes all wealth equally among all citizens. Wealth is represented as an array/list where every index is the wealth of a single citizen. The function should mutate the input such that every index has the same amount of wealth. See example: * Input: ```text [5, 10, 6] >>> This represents: # citizen 1 has wealth 5 # citizen 2 has wealth 10 # citizen 3 has wealth 6 ``` * Should be after the test: ```text [7, 7, 7] >>> wealth has now been equally redistributed ``` Info: - **MUTATE the input array/list, don't return anything** - Input is guaranteed to hold at least 1 citizen - Wealth of a citizen will be an integer with minimum equal to 0 (negative wealth is not possible) - Handling of floating point error will not be tested
algorithms
def redistribute_wealth(wealth): wealth[:] = [sum(wealth) / len(wealth)] * len(wealth)
Wealth equality, finally!
5815f7e789063238b30001aa
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5815f7e789063238b30001aa
7 kyu
Given a time in a time format class, return it without year, month and day. It should return a string including milliseconds with 3 decimals. Example: ```ruby Time.new(2016, 2, 8, 16, 42, 59) #Should return: "16:42:59,000" ``` ```python datetime(2016, 2, 8, 16, 42, 59) #Should return: "16:42:59,000" ``` ```javascript new Date(2016, 2, 8, 16, 42, 59) //Should return: "16:42:59,000" ```
refactoring
def convert(time): return time . time(). strftime('%X,%f')[: - 3]
Time Converter: hours, minutes, seconds and milliseconds
56b8b0ae1d36bb86b2000eaa
[ "Date Time", "Parsing", "Refactoring" ]
https://www.codewars.com/kata/56b8b0ae1d36bb86b2000eaa
7 kyu
You and your best friend Stripes have just landed your first high school jobs! You'll be delivering newspapers to your neighbourhood on weekends. For your services you'll be charging a set price depending on the quantity of the newspaper bundles. The cost of deliveries is: - $3.85 for 40 newspapers - $1.93 for 20 - $0.97 for 10 - $0.49 for 5 - $0.10 for 1 Stripes is taking care of the footwork doing door-to-door drops and your job is to take care of the finances. What you'll be doing is providing the cheapest possible quotes for your services. Write a function that's passed an integer representing the amount of newspapers and returns the cheapest price. The returned number must be rounded to two decimal places. ![Paperboy](http://mametesters.org/file_download.php?file_id=1016&type=bug)
algorithms
def cheapest_quote(n): prices = [(40, 3.85), (20, 1.93), (10, 0.97), (5, 0.49), (1, 0.10)] result = 0 for q, c in prices: result += n / / q * c n = n % q return round(result, 2)
Paperboy
56ed5f13c4e5d6c5b3000745
[ "Algorithms" ]
https://www.codewars.com/kata/56ed5f13c4e5d6c5b3000745
7 kyu
On Unix system type files can be identified with the ls -l command which displays the type of the file in the first alphabetic letter of the file system permissions field. You can find more information about file type on Unix system on the [wikipedia page](https://en.wikipedia.org/wiki/Unix_file_types). - '-' A regular file ==> `file`. - 'd' A directory ==> `directory`. - 'l' A symbolic link ==> `symlink`. - 'c' A character special file. It refers to a device that handles data as a stream of bytes (e.g: a terminal/modem) ==> `character_file`. - 'b' A block special file. It refers to a device that handles data in blocks (e.g: such as a hard drive or CD-ROM drive) ==> `block_file`. - 'p' a named pipe ==> `pipe`. - 's' a socket ==> `socket`. - 'D' a door ==> `door`. In this kata you should complete a function that return the `filetype` as a string regarding the `file_attribute` given by the `ls -l` command. For example if the function receive `-rwxr-xr-x` it should return `file`.
reference
dict = {'-': "file", 'd': "directory", 'l': "symlink", 'c': "character_file", 'b': "block_file", 'p': "pipe", 's': "socket", 'D': "door"} def linux_type(file_attribute): return dict[file_attribute[0]]
Unix command line `ls -l` extract the file type.
5822b65bb81f702016000026
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5822b65bb81f702016000026
7 kyu
You are the judge at a competitive eating competition and you need to choose a winner! There are three foods at the competition and each type of food is worth a different amount of points. Points are as follows: - Chickenwings: 5 points - Hamburgers: 3 points - Hotdogs: 2 points Write a function that helps you create a scoreboard. It takes as a parameter a list of objects representing the participants, for example: ``` [ {name: "Habanero Hillary", chickenwings: 5 , hamburgers: 17, hotdogs: 11}, {name: "Big Bob" , chickenwings: 20, hamburgers: 4, hotdogs: 11} ] ``` It should return "name" and "score" properties sorted by score; if scores are equals, sort alphabetically by name. ``` [ {name: "Big Bob", score: 134}, {name: "Habanero Hillary", score: 98} ] ``` Happy judging!
reference
class Person: def __init__(self, person: dict): self . name = person . get('name') self . chickenwings = person . get('chickenwings', 0) self . hamburgers = person . get('hamburgers', 0) self . hotdogs = person . get('hotdogs', 0) def get_score(self): return self . chickenwings * 5 + self . hamburgers * 3 + self . hotdogs * 2 def scoreboard(who_ate_what): scores = [] for person in who_ate_what: p = Person(person) scores . append({"name": p . name, "score": p . get_score()}) return sorted(scores, key=lambda k: (- k["score"], k['name']))
Competitive eating scoreboard
571d2e9eeed4a150d30011e7
[ "Object-oriented Programming", "Fundamentals" ]
https://www.codewars.com/kata/571d2e9eeed4a150d30011e7
7 kyu
Much cooler than your run-of-the-mill Fibonacci numbers, the Triple Shiftian are so defined: `T[n] = 4 * T[n-1] - 5 * T[n-2] + 3 * T[n-3]`. You are asked to create a function which accept a base with the first 3 numbers and then returns the nth element. ```javascript tripleShiftian([1,1,1],25) == 1219856746 tripleShiftian([1,2,3],25) == 2052198929 tripleShiftian([6,7,2],25) == -2575238999 tripleShiftian([3,2,1],35) == 23471258855679 tripleShiftian([1,9,2],2) == 2 ``` ```csharp tripleShiftian(new int[] { 1,1,1 },25) == 1219856746 tripleShiftian(new int[] { 1,2,3 },25) == 2052198929 tripleShiftian(new int[] { 6,7,2 },25) == -2575238999 tripleShiftian(new int[] { 3,2,1 },35) == 23471258855679 tripleShiftian(new int[] { 1,9,2 },2) == 2 ``` ```python triple_shiftian([1,1,1],25) == 1219856746 triple_shiftian([1,2,3],25) == 2052198929 triple_shiftian([6,7,2],25) == -2575238999 triple_shiftian([3,2,1],35) == 23471258855679 triple_shiftian([1,9,2],2) == 2 ``` ```ruby triple_shiftian([1,1,1],25) == 1219856746 triple_shiftian([1,2,3],25) == 2052198929 triple_shiftian([6,7,2],25) == -2575238999 triple_shiftian([3,2,1],35) == 23471258855679 triple_shiftian([1,9,2],2) == 2 ``` ```crystal triple_shiftian([1,1,1],25) == 1219856746 triple_shiftian([1,2,3],25) == 2052198929 triple_shiftian([6,7,2],25) == -2575238999 triple_shiftian([3,2,1],35) == 23471258855679 triple_shiftian([1,9,2],2) == 2 ``` *Note: this is meant to be an interview quiz, so the description is scarce in detail on purpose* Special thanks to the [first person I met in person here in London just because of CW](http://www.codewars.com/users/webtechalex) and that assisted me during the creation of this kata ;)
reference
def triple_shiftian(T, n): for i in range(3, n + 1): T . append(4 * T[i - 1] - 5 * T[i - 2] + 3 * T[i - 3]) return T[n]
Triple Shiftian Numbers
56b7526481290c2ff1000c75
[ "Number Theory", "Fundamentals" ]
https://www.codewars.com/kata/56b7526481290c2ff1000c75
7 kyu
As part of this Kata, you need to find the length of the sequence in an array, between the first and the second occurrence of a specified number. For example, for a given array `arr` [0, -3, 7, 4, 0, 3, 7, 9] Finding length between two `7`s like lengthOfSequence([0, -3, 7, 4, 0, 3, 7, 9], 7) would return `5`. For sake of simplicity, there will only be numbers (positive or negative) in the supplied array. If there are less or more than two occurrences of the number to search for, return `0`, or in Haskell, `Nothing`.
algorithms
def length_of_sequence(arr, n): if arr . count(n) != 2: return 0 a = arr . index(n) b = arr . index(n, a + 1) return b - a + 1
Finding length of the sequence
5566b0dd450172dfc4000005
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5566b0dd450172dfc4000005
7 kyu
Return the magnitude of a vector, given as an array of its component values. The vector (2, 3, 5) would be represented as an array containing three values at indices 0, 1 and 2 respectively.<br> The array will always contain at least 2 and at most 100 elements (2 ≤ vector.Length ≤ 100), each of which will be within the range [-100, 100]. <br> An array containing four elements represents a vector in 4D space. More info on finding the length of a vector: http://farside.ph.utexas.edu/teaching/301/lectures/node28.html
reference
def magnitude(vector): return sum(i * * 2 for i in vector) * * 0.5
N-Dimensional Vector Magnitude
5806c2f897dba05dd900004c
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5806c2f897dba05dd900004c
7 kyu
So you've found a meeting room - phew! You arrive there ready to present, and find that someone has taken one or more of the chairs!! You need to find some quick.... check all the other meeting rooms to see if all of the chairs are in use. Your meeting room can take up to `8` chairs. `need` will tell you how many have been taken. You need to find that many. Find the spare chairs from the array of meeting rooms. Each meeting room tuple will have the number of occupants as a string. Each occupant is represented by `'X'`. The room tuple will also have an integer telling you how many chairs there are in the room. You should return an array of integers that shows how many chairs you take from each room in order, up until you have the required amount. example: `[['XXX', 3], ['XXXXX', 6], ['XXXXXX', 9], ['XXX',2]]` when you need `4` chairs: `result -> [0, 1, 3]` no chairs free in room 0, take `1` from room 1, take `3` from room 2. no need to consider room 3 as you have your `4` chairs already. If you need no chairs, return `"Game On"`. If there aren't enough spare chairs available, return `"Not enough!"`. More in this series: [The Office I - Outed](https://www.codewars.com/kata/the-office-i-outed) [The Office II - Boredeom Score](https://www.codewars.com/kata/the-office-ii-boredom-score) [The Office III - Broken Photocopier](https://www.codewars.com/kata/the-office-iii-broken-photocopier) [The Office IV - Find a Meeting Room](https://www.codewars.com/kata/the-office-iv-find-a-meeting-room)
reference
def meeting(rooms, need): if need == 0: return "Game On" result = [] for people, chairs in rooms: taken = min(max(chairs - len(people), 0), need) result . append(taken) need -= taken if need == 0: return result return "Not enough!"
The Office V - Find a Chair
57f6051c3ff02f3b7300008b
[ "Fundamentals", "Arrays", "Strings" ]
https://www.codewars.com/kata/57f6051c3ff02f3b7300008b
6 kyu
In this kata, you'll be given an integer of range `0 <= x <= 99` and have to return that number spelt out in English. A few examples: ```java nameThatNumber(4) // returns "four" nameThatNumber(19) // returns "nineteen" nameThatNumber(99) // returns "ninety nine" ``` ```python name_that_number(4) # returns "four" name_that_number(19) # returns "nineteen" name_that_number(99) # returns "ninety nine" ``` ```javascript nameThatNumber(4) // returns "four" nameThatNumber(19) // returns "nineteen" nameThatNumber(99) // returns "ninety nine" ``` Words should be separated by only spaces and not hyphens. No need to validate parameters, they will always be in the range [0, 99]. Make sure that the returned String has no leading of trailing spaces. Good luck!
reference
NUMBERS = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen" . split() NUMBERS += ["twenty thirty forty fifty sixty seventy eighty ninety" . split()[n / / 10 - 2] + f" { NUMBERS [ n % 10 ]} " * (n % 10 > 0) for n in range(20, 100)] def name_that_number(n): return NUMBERS[n]
Name That Number!
579ba41ce298a73aaa000255
[ "Fundamentals" ]
https://www.codewars.com/kata/579ba41ce298a73aaa000255
7 kyu
Your colleagues have been looking over you shoulder. When you should have been doing your boring real job, you've been using the work computers to smash in endless hours of codewars. In a team meeting, a terrible, awful person declares to the group that you aren't working. You're in trouble. You quickly have to gauge the feeling in the room to decide whether or not you should gather your things and leave. ```if-not:java Given an object (meet) containing team member names as keys, and their happiness rating out of 10 as the value, you need to assess the overall happiness rating of the group. If <= 5, return 'Get Out Now!'. Else return 'Nice Work Champ!'. ``` ```if:java Given a `Person` array (meet) containing team members, you need to assess the overall happiness rating of the group. If <= 5, return "Get Out Now!". Else return "Nice Work Champ!". The `Person` class looks like: ~~~java class Person { final String name; // team memnber's name final int happiness; // happiness rating out of 10 } ~~~ ``` Happiness rating will be total score / number of people in the room. Note that your boss is in the room (boss), their score is worth double it's face value (but they are still just one person!). <a href='https://www.codewars.com/kata/the-office-ii-boredom-score'>The Office II - Boredom Score</a><br> <a href='https://www.codewars.com/kata/the-office-iii-broken-photocopier'>The Office III - Broken Photocopier</a><br> <a href='https://www.codewars.com/kata/the-office-iv-find-a-meeting-room'>The Office IV - Find a Meeting Room</a><br> <a href='https://www.codewars.com/kata/the-office-v-find-a-chair'>The Office V - Find a Chair</a><br>
reference
def outed(meet, boss): return 'Get Out Now!' if (sum(meet . values()) + meet[boss]) / len(meet) <= 5 else 'Nice Work Champ!'
The Office I - Outed
57ecf6efc7fe13eb070000e1
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/57ecf6efc7fe13eb070000e1
7 kyu
Create a function that checks if the first argument n is divisible by all other arguments (return true if no other arguments) Example: ``` (6,1,3)--> true because 6 is divisible by 1 and 3 (12,2)--> true because 12 is divisible by 2 (100,5,4,10,25,20)--> true (12,7)--> false because 12 is not divisible by 7 ``` This kata is following kata: http://www.codewars.com/kata/is-n-divisible-by-x-and-y
reference
def is_divisible(n, * args): return all(not n % i for i in args)
Is n divisible by (...)?
558ee8415872565824000007
[ "Fundamentals" ]
https://www.codewars.com/kata/558ee8415872565824000007
7 kyu
A binary gap within a positive number ```num``` is any sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of ```num```. <br/> For example:<br/> ```9``` has binary representation ```1001``` and contains a binary gap of length ```2```.<br/> ```529``` has binary representation ```1000010001``` and contains two binary gaps: one of length ```4``` and one of length ```3```.<br/> ```20``` has binary representation ```10100``` and contains one binary gap of length ```1```.<br/> ```15``` has binary representation ```1111``` and has ```0``` binary gaps.<br/> Write ```function gap(num)``` that,  given a positive ```num```,  returns the length of its longest binary gap.<br/> The function should return ```0``` if ```num``` doesn't contain a binary gap.
reference
def gap(num): s = bin(num)[2:]. strip("0") return max(map(len, s . split("1")))
Find the longest gap!
55b86beb1417eab500000051
[ "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/55b86beb1417eab500000051
7 kyu
Your job at E-Corp is both boring and difficult. It isn't made any easier by the fact that everyone constantly wants to have a meeting with you, and that the meeting rooms are always taken! In this kata, you will be given an array. Each value represents a meeting room. Your job? Find the **first** empty one and return its index (N.B. There may be more than one empty room in some test cases). ``` 'X' --> busy 'O' --> empty ``` ~~~if:cpp If all rooms are busy, return `-1` ~~~ ~~~if-not:cpp If all rooms are busy, return `"None available!"` ~~~ More in this series: <a href='https://www.codewars.com/kata/the-office-i-outed'>The Office I - Outed</a><br> <a href='https://www.codewars.com/kata/the-office-ii-boredom-score'>The Office II - Boredeom Score</a><br> <a href='https://www.codewars.com/kata/the-office-iii-broken-photocopier'>The Office III - Broken Photocopier</a><br> <a href='https://www.codewars.com/kata/the-office-v-find-a-chair'>The Office V - Find a Chair</a><br>
reference
def meeting(rooms): try: return rooms . index('O') except ValueError: return 'None available!'
The Office IV - Find a Meeting Room
57f604a21bd4fe771b00009c
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/57f604a21bd4fe771b00009c
7 kyu
Bob is a theoretical coder - he doesn't write code, but comes up with theories, formulas and algorithm ideas. You are his secretary, and he has tasked you with writing the code for his newest project - a method for making the short form of a word. Write a function ```shortForm```(C# ```ShortForm```, Python ```short_form```) that takes a string and returns it converted into short form using the rule: <em>Remove all vowels, except for those that are the first or last letter. </em>Do not count 'y' as a vowel, and ignore case. Also note, the string given will not have any spaces; only one word, and only Roman letters. <br> Example: ``` shortForm("assault"); short_form("assault") ShortForm("assault"); // should return "asslt" ``` <br> <br> Also, FYI: I got all the words with no vowels from <br> https://en.wikipedia.org/wiki/English_words_without_vowels
reference
from re import * def short_form(s): return sub(r"(?<!^)[aeiou](?=.)", '', s, flags=I)
Bob's Short Forms
570cbe88f616a8f4f50011ac
[ "Strings", "Regular Expressions", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/570cbe88f616a8f4f50011ac
7 kyu
You will get an array of numbers. Every preceding number is smaller than the one following it. Some numbers will be missing, for instance: ``` [-3,-2,1,5] //missing numbers are: -1,0,2,3,4 ``` Your task is to return an array of those missing numbers: ``` [-1,0,2,3,4] ```
reference
def find_missing_numbers(arr): return [x for x in range(arr[0], arr[- 1] + 1) if x not in arr] if arr else []
Find missing numbers
56d02e6cc6c8b49c510005bb
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/56d02e6cc6c8b49c510005bb
7 kyu
### Instructions Write a function that takes a negative or positive integer, which represents the number of minutes before (-) or after (+) Sunday midnight, and returns the current day of the week and the current time in 24hr format ('hh:mm') as a string. ### Examples ``` 0 => should return 'Sunday 00:00' -3 => should return 'Saturday 23:57' 45 => should return 'Sunday 00:45' 759 => should return 'Sunday 12:39' 1236 => should return 'Sunday 20:36' 1447 => should return 'Monday 00:07' 7832 => should return 'Friday 10:32' 18876 => should return 'Saturday 02:36' 259180 => should return 'Thursday 23:40' -349000 => should return 'Tuesday 15:20' ```
algorithms
from datetime import timedelta, datetime def day_and_time(mins): return "{:%A %H:%M}" . format(datetime(2017, 1, 1) + timedelta(minutes=mins))
After(?) Midnight
56fac4cfda8ca6ec0f001746
[ "Date Time", "Algorithms" ]
https://www.codewars.com/kata/56fac4cfda8ca6ec0f001746
7 kyu
Given 2 strings, your job is to find out if there is a substring that appears in both strings. You will return true if you find a substring that appears in both strings, or false if you do not. We only care about substrings that are longer than one letter long. #Examples: ```` *Example 1* SubstringTest("Something","Fun"); //Returns false *Example 2* SubstringTest("Something","Home"); //Returns true ```` In the above example, example 2 returns true because both of the inputs contain the substring "me". (so**ME**thing and ho**ME**) In example 1, the method will return false because something and fun contain no common substrings. (We do not count the 'n' as a substring in this Kata because it is only 1 character long) #Rules: Lowercase and uppercase letters are the same. So 'A' == 'a'. We only count substrings that are > 1 in length. #Input: Two strings with both lower and upper cases. #Output: A boolean value determining if there is a common substring between the two inputs.
algorithms
def substring_test(first, second): first = first . lower() second = second . lower() for i in range(len(first) - 2): if first[i: i + 2] in second: return True return False
Common Substrings
5669a5113c8ebf16ed00004c
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5669a5113c8ebf16ed00004c
7 kyu
You love coffee and want to know what beans you can afford to buy it. The first argument to your search function will be a number which represents your budget. The second argument will be an array of coffee bean prices. Your 'search' function should return the stores that sell coffee within your budget. The search function should return a string of prices for the coffees beans you can afford. The prices in this string are to be sorted in ascending order.
reference
def search(budget, prices): return ',' . join(str(a) for a in sorted(prices) if a <= budget)
Filter Coffee
56069d0c4af7f633910000d3
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/56069d0c4af7f633910000d3
7 kyu
A high school has a strange principal. On the first day, he has his students perform an odd opening day ceremony: There are number of lockers "n" and number of students "n" in the school. The principal asks the first student to go to every locker and open it. Then he has the second student go to every second locker and close it. The third goes to every third locker and, if it is closed, he opens it, and if it is open, he closes it. The fourth student does this to every fourth locker, and so on. After the process is completed with the "n"th student, how many lockers are open? The task is to write a function which gets any number as an input and returns the number of open lockers after last sudent complets his activity. So input of the function is just one number which shows number of lockers and number of students. For example if there are 1000 lockers and 1000 students in school then input is 1000 and function returns number of open lockers after 1000th student completes his action. The given input is always an integer greater than or equal to zero that is why there is no need for validation.
reference
# First, I coded a straightforward solution. It would work, but because it had to loop over all # students, and for every student over each locker, it had to do n^2 iterations. With numbers under # 10k this proved no problem, however the test cases apparently tested bigger numbers, since my # program kept getting timed out. I decided to record the number of open lockers for each n in range # 1-500 and discovered a nice pattern: 0 -1-1-1 (3 1's) -2-2-2-2-2 (5 2's) -3-3-3-3-3-3-3 (7 4's) # - et cetera. In other words, the number of consecutive numbers is (2n + 1). This was still not easy # to do so I looked up the sequence in OEIS. There, I discovered that the sequence was the integer # part of the square root of n. Now if that isn't easy to program... more of a maths problem, really. def num_of_open_lockers(n): return int(n * * 0.5)
Strange principal
55fc061cc4f485a39900001f
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/55fc061cc4f485a39900001f
7 kyu
Complete the function that takes an array of words. You must concatenate the `n`th letter from each word to construct a new word which should be returned as a string, where `n` is the position of the word in the list. For example: ``` ["yoda", "best", "has"] --> "yes" ^ ^ ^ n=0 n=1 n=2 ``` **Note:** Test cases contain valid input only - i.e. a string array or an empty array; and each word will have enough letters.
reference
def nth_char(words): return '' . join(w[i] for i, w in enumerate(words))
Substring fun
565b112d09c1adfdd500019c
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/565b112d09c1adfdd500019c
7 kyu
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220. Derive function ```amicableNumbers(num1, num2)``` which returns ```true/True``` if pair ```num1 num2``` are amicable, ```false/False``` if not. See more at https://en.wikipedia.org/wiki/Amicable_numbers
algorithms
def amicable_numbers(n1, n2): s1 = sum([x for x in range(1, n1) if n1 % x == 0]) s2 = sum([x for x in range(1, n2) if n2 % x == 0]) return s1 == n2 and s2 == n1
The Most Amicable of Numbers
56b5ebaa26fd54188b000018
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/56b5ebaa26fd54188b000018
7 kyu
Given an array of numbers, return an array, with each member of input array rounded to a nearest number, divisible by 5. For example: ``` roundToFive([34.5, 56.2, 11, 13]); ``` should return ``` [35, 55, 10, 15] ``` ```if:python Roundings have to be done like "in real life": `22.5 -> 25` ```
algorithms
from decimal import Decimal, ROUND_HALF_UP def round_to_five(numbers): return [(n / 5). quantize(1, ROUND_HALF_UP) * 5 for n in map(Decimal, numbers)]
Round to nearest 0 or 5
582f52208278c6be55000067
[ "Algorithms" ]
https://www.codewars.com/kata/582f52208278c6be55000067
7 kyu
Being a bald man myself, I know the feeling of needing to keep it clean shaven. Nothing worse that a stray hair waving in the wind. You will be given a string(x). Clean shaved head is shown as "-" and stray hairs are shown as "/". Your task is to check the head for stray hairs and get rid of them. You should return the original string, but with any stray hairs removed. Keep count ot them though, as there is a second element you need to return: 0 hairs --> "Clean!"<br> 1 hair --> "Unicorn!"<br> 2 hairs --> "Homer!"<br> 3-5 hairs --> "Careless!"<br> \>5 hairs --> "Hobo!" So for this head: "------/------" you shoud return:<br> ["-------------", "Unicorn"]
reference
def bald(s): hair_names = { 0: "Clean!", 1: "Unicorn!", 2: "Homer!", 3: "Careless!", 4: "Careless!", 5: "Careless!", } return [s . replace("/", "-"), "Hobo!"] if s . count("/") > 5 else [s . replace("/", "-"), hair_names[s . count("/")]]
Slaphead
57efab9acba9daa4d1000b30
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57efab9acba9daa4d1000b30
7 kyu
Enjoying your holiday, you head out on a scuba diving trip! Disaster!! The boat has caught fire!! You will be provided a string that lists many boat related items. If any of these items are "Fire" you must spring into action. Change any instance of "Fire" into "~~". Then return the string. Go to work!
reference
def fire_fight(s): return s . replace('Fire', '~~')
Holiday III - Fire on the boat
57e8fba2f11c647abc000944
[ "Fundamentals", "Arrays", "Strings" ]
https://www.codewars.com/kata/57e8fba2f11c647abc000944
7 kyu
## **Instructions** The goal of this kata is two-fold: 1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided. 2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`. For the sake of this kata, you can assume all input will be a positive integer. ## **Use Cases** Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings. ## **Examples** Input: ```javascript fibsFizzBuzz(5) ``` ```python fibs_fizz_buzz(5) ``` ```php fibs_fizz_buzz(5); ``` Output: ~~~~ [ 1, 1, 2, 'Fizz', 'Buzz' ] ~~~~ Input: ```javascript fibsFizzBuzz(1) ``` ```python fibs_fizz_buzz(1) ``` ```php fibs_fizz_buzz(1); ``` Output: ~~~~ [1] ~~~~ Input: ```javascript fibsFizzBuzz(20) ``` ```python fibs_fizz_buzz(20) ``` ```php fibs_fizz_buzz(20); ``` Output: ~~~~ [1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"] ~~~~ ##Good Luck!##
reference
def fibs_fizz_buzz(n): a, b, out = 0, 1, [] for i in range(n): s = "Fizz" * (b % 3 == 0) + "Buzz" * (b % 5 == 0) out . append(s if s else b) a, b = b, a + b return out
Fibonacci's FizzBuzz
57bf599f102a39bb1e000ae5
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/57bf599f102a39bb1e000ae5
7 kyu
You woke up from a massive headache and can't seem to find your car key. You find a note with a clue that says: > ***"If you're reading this then I have left the state and am well on my way to freedom. Just to make things interesting, I have also provided something for you to track me with. Let the chase begin..."*** Given an array of binary numbers, figure out and return the culprit's message to find out who took the missing car key. ``` ['01000001', '01101100', '01100101', '01111000', '01100001', '01101110', '01100100', '01100101', '01110010'] => 'Alexander' ```
reference
def who_took_the_car_key(message): return '' . join(chr(int(i, 2)) for i in message)
Who Took The Car Key?
57a23c2acf1fa514d0001034
[ "Binary", "Fundamentals" ]
https://www.codewars.com/kata/57a23c2acf1fa514d0001034
7 kyu
Removed due to copyright infringement. <!--- Vasya stands in line with number of people `p (including Vasya)`, but he doesn't know exactly which position he occupies. He can say that there are `no less than b` people standing in front of him and `no more than a` people standing behind him. Find the number of different positions Vasya can occupy. ### Input As an input you have 3 numbers: `1. Total amount of people in the line;` `2. Number of people standing in front of him` `3. Number of people standing behind him ` ### Examples: ```csharp Line.WhereIsHe(3, 1, 1) // => 2 The possible positions are: 2 and 3 Line.WhereIsHe(5, 2, 3) // => 3 The possible positions are: 3, 4 and 5 ``` ```javascript whereIsHe(3, 1, 1) // => 2 The possible positions are: 2 and 3 whereIsHe(5, 2, 3) // => 3 The possible positions are: 3, 4 and 5 ``` ```coffeescript whereIsHe 3, 1, 1 # => 2 The possible positions are: 2 and 3 whereIsHe 5, 2, 3 # => 3 The possible positions are: 3, 4 and 5 ``` ```python where_is_he(3, 1, 1) # => 2 The possible positions are: 2 and 3 where_is_he(5, 2, 3) # => 3 The possible positions are: 3, 4 and 5 ``` ```ruby where_is_he(3, 1, 1) # => 2 The possible positions are: 2 and 3 where_is_he(5, 2, 3) # => 3 The possible positions are: 3, 4 and 5 ``` ```java WhereIsVasya.whereIsHe(3, 1, 1) // => 2 The possible positions are: 2 and 3 WhereIsVasya.whereIsHe(5, 2, 3) // => 3 The possible positions are: 3, 4 and 5 ``` --->
reference
def where_is_he(p, bef, aft): return min(p - bef, aft + 1)
Where is Vasya?
554754ac9d8ac3be120000b2
[ "Fundamentals", "Mathematics", "Algorithms", "Logic", "Numbers", "Puzzles", "Games" ]
https://www.codewars.com/kata/554754ac9d8ac3be120000b2
7 kyu
This kata is about converting numbers to their binary or hexadecimal representation: * If a number is even, convert it to binary. * If a number is odd, convert it to hex. Numbers will be positive. The hexadecimal string should be lowercased.
reference
def evens_and_odds(n): return hex(n)[2:] if n % 2 else bin(n)[2:]
Evens and Odds
583ade15666df5a64e000058
[ "Fundamentals", "Binary" ]
https://www.codewars.com/kata/583ade15666df5a64e000058
7 kyu
In this Kata the aim is to compare each pair of integers from 2 arrays, and return a new array of large numbers. Note: Both arrays have the same dimensions. Example: ```csharp arr1 = new int[] { 13, 64, 15, 17, 88 }; arr2 = new int[] { 23, 14, 53, 17, 80 }; Kata.getLargerNumbers(arr1, arr2); // Returns {23, 64, 53, 17, 88} ``` ```python arr1 = [13, 64, 15, 17, 88] arr2 = [23, 14, 53, 17, 80] get_larger_numbers(arr1, arr2) == [23, 64, 53, 17, 88] ``` ```ruby arr1 = [13, 64, 15, 17, 88] arr2 = [23, 14, 53, 17, 80] get_larger_numbers(arr1, arr2) == [23, 64, 53, 17, 88] ``` ```javascript let arr1 = [13, 64, 15, 17, 88]; let arr2 = [23, 14, 53, 17, 80]; getLargerNumbers(arr1, arr2); // Returns [23, 64, 53, 17, 88] ``` ```coffeescript arr1 = [13, 64, 15, 17, 88] arr2 = [23, 14, 53, 17, 80] getLargerNumbers(arr1, arr2) # Returns [23, 64, 53, 17, 88] ``` ```haskell arr1 = [13, 64, 15, 17, 88] arr2 = [23, 14, 53, 17, 80] getLargerNumbers arr1 arr2 == [23, 64, 53, 17, 88] ``` ```clojure (= arr1 [13, 64, 15, 17, 88]) (= arr2 [23, 14, 53, 17, 80]) (= (getLargerNumbers arr1 arr2) [23 64 53 17 88]) ``` ```cobol a = [13, 64, 15, 17, 88] b = [23, 14, 53, 17, 80] GetLargerNumbers a b => result = [23, 64, 53, 17, 88] ```
reference
def get_larger_numbers(a, b): return [max(x, y) for x, y in zip(a, b)]
Number Pairs
563b1f55a5f2079dc100008a
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/563b1f55a5f2079dc100008a
7 kyu
Create a method (**JS**: function) `every` which returns every nth element of an array. ### Usage With no arguments, `array.every` it returns every element of the array. With one argument, `array.every(interval)` it returns every `interval`th element. With two arguments, `array.every(interval, start_index)` it returns every `interval`th element starting at index `start_index` **Note**: due to fact JS translation ask for a function instead of an Array method the above uses will be : ``` javascript: ruby: every(array) array.every every(array, interval) array.every(interval) every(array, interval, start_index) array.every(interval, start_index) ``` ### Examples ```ruby [0,1,2,3,4].every # [0,1,2,3,4] [0,1,2,3,4].every(1) # [0,1,2,3,4] [0,1,2,3,4].every(2) # [0,2,4] [0,1,2,3,4].every(3) # [0,3] [0,1,2,3,4].every(1,3) # [3,4] [0,1,2,3,4].every(3,1) # [1,4] [0,1,2,3,4].every(3,4) # [4] ``` ```javascript every([0,1,2,3,4]) // [0,1,2,3,4] every([0,1,2,3,4],1) // [0,1,2,3,4] every([0,1,2,3,4],2) // [0,2,4] every([0,1,2,3,4],3) // [0,3] every([0,1,2,3,4],3,1) // [1,4] ``` ```csharp /* C# can work either as "Kata.Every" or "array.Every" due to the nature of extension functions. */ new int []{0,1,2,3,4}.Every()); // [0,1,2,3,4] Kata.Every(new int []{0,1,2,3,4}, 5, 1)); // [1] ``` ### Notes Test cases: `interval` will always be a positive integer (but may be larger than the size of the array). `start_index` will always be within the bounds of the array. Once you have completed this kata, try the **advanced version** (http://www.codewars.com/kata/every-nth-array-element-advanced) which allows negative intervals and unbounded start\_indexes ### Translator notes Ruby is the original language for this kata.
reference
def every(lst, n=1, start=0): return lst[start:: n]
Every nth array element. (Basic)
5753b987aeb792508d0010e2
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5753b987aeb792508d0010e2
7 kyu
Comprised of a team of five incredibly brilliant women, "The ladies of ENIAC" were the first “computors” working at the University of Pennsylvania’s Moore School of Engineering (1945). Through their contributions, we gained the first software application and the first programming classes! The ladies of ENIAC were inducted into the WITI Hall of Fame in 1997! Write a function which reveals "The ladies of ENIAC" names, so that you too can add them to your own hall of tech fame! To keep: only alpha characters, space characters and exclamation marks. To remove: numbers and these characters: ```%$&/£?@``` Result should be all in uppercase.
reference
import re def rad_ladies(name): return "" . join(re . findall("[A-Z\s!]+", name . upper()))
The Ladies of ENIAC
56d31aaefd3a52902a000d66
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/56d31aaefd3a52902a000d66
7 kyu
Implement `String#whitespace?(str)` (Ruby), `String.prototype.whitespace(str)` (JavaScript), `String::whitespace(str)` (CoffeeScript), or `whitespace(str)` (Python), which should return `true/True` if given object consists exclusively of zero or more whitespace characters, `false/False` otherwise.
reference
def whitespace(string): return not string or string . isspace()
Regexp Basics - is it all whitespace?
567de8823fa5eee02100002a
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/567de8823fa5eee02100002a
7 kyu
The bloody photocopier is broken... Just as you were sneaking around the office to print off your favourite binary code! Instead of copying the original, it reverses it: '1' becomes '0' and vice versa. Given a string of binary, return the version the photocopier gives you as a string. <a href='https://www.codewars.com/kata/the-office-i-outed'>The Office I - Outed</a><br> <a href='https://www.codewars.com/kata/the-office-ii-boredom-score'>The Office II - Boredeom Score</a><br> <a href='https://www.codewars.com/kata/the-office-iv-find-a-meeting-room'>The Office IV - Find a Meeting Room</a><br> <a href='https://www.codewars.com/kata/the-office-v-find-a-chair'>The Office V - Find a Chair</a><br>
reference
def broken(inp): """Replace each '0' with '1' and vice versa.""" return inp . translate(str . maketrans("01", "10"))
The Office III - Broken Photocopier
57ed56657b45ef922300002b
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57ed56657b45ef922300002b
7 kyu
This is a follow up from my kata <a href='http://www.codewars.com/kata/55d410c492e6ed767000004f'>The old switcheroo</a> Write the function : ```javascript function encode(str) ``` ```python def encode(str) ``` ```ruby def encode(str) ``` ```coffeescript encode = (str) -> ``` ```csharp public static string Encode(string str) ``` that takes in a string ```str``` and replaces all the letters with their respective positions in the English alphabet.<br/> ```javascript encode('abc') == '123' // a is 1st in English alpabet, b is 2nd and c is 3rd encode('codewars') == '315452311819' encode('abc-#@5') == '123-#@5' ``` ```python encode('abc') == '123' # a is 1st in English alpabet, b is 2nd and c is 3rd encode('codewars') == '315452311819' encode('abc-#@5') == '123-#@5' ``` ```ruby encode('abc') == '123' # a is 1st in English alpabet, b is 2nd and c is 3rd encode('codewars') == '315452311819' encode('abc-#@5') == '123-#@5' ``` ```coffeescript encode 'abc' == '123' # a is 1st in English alpabet, b is 2nd and c is 3rd encode 'codewars' == '315452311819' encode 'abc-#@5' == '123-#@5' ``` ```csharp Encode("abc") == "123" // a is 1st in English alpabet, b is 2nd and c is 3rd Encode("codewars") == "315452311819" Encode("abc-#@5") == "123-#@5" ``` String are case sensitive. ```javascript // Bonus point if you don't use toLowerCase() ``` ```coffeescript # Bonus point if you don't use toLowerCase() ``` ```csharp // Bonus point if you don't use ToLower() ```
reference
def encode(string): return '' . join(str(ord(c . upper()) - 64) if c . isalpha() else c for c in string)
The old switcheroo 2
55d6a0e4ededb894be000005
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/55d6a0e4ededb894be000005
7 kyu
Write a function ```javascript vowel2index(str) ``` ```coffeescript vowel2index(str) ``` ```python vowel_2_index ``` ```ruby vowel_2_index ``` ```csharp Vowel2Index(string s) ``` ```java vowel2Index(String s) ``` ```julia vowel2index(str::String)::String ``` that takes in a string and replaces all the vowels [a,e,i,o,u] with their respective positions within that string. <br/> E.g: <br/> ```javascript vowel2index('this is my string') == 'th3s 6s my str15ng' vowel2index('Codewars is the best site in the world') == 'C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld' vowel2index('') == '' ``` ```python vowel_2_index('this is my string') == 'th3s 6s my str15ng' vowel_2_index('Codewars is the best site in the world') == 'C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld' vowel_2_index('') == '' ``` ```ruby vowel_2_index('this is my string') == 'th3s 6s my str15ng' vowel_2_index('Codewars is the best site in the world') == 'C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld' vowel_2_index('') == '' ``` ```coffeescript vowel2index 'this is my string' == 'th3s 6s my str15ng' vowel2index 'Codewars is the best site in the world' == 'C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld' vowel2index '' == '' ``` ```csharp Kata.Vowel2Index("this is my string") == "th3s 6s my str15ng" Kata.Vowel2Index("Codewars is the best site in the world") == "C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld" ``` ```java Kata.Vowel2Index("this is my string") == "th3s 6s my str15ng" Kata.Vowel2Index("Codewars is the best site in the world") == "C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld" ``` ```haskell vowel2Index "this is my string" == "th3s 6s my str15ng" vowel2Index "Codewars is the best site in the world" == "C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld" ``` ```julia vowel2index("this is my string") == "th3s 6s my str15ng" vowel2index("Codewars is the best site in the world") == "C2d4w6rs 10s th15 b18st s23t25 27n th32 w35rld" ``` <b> Your function should be case insensitive to the vowels.
reference
def vowel_2_index(string): vowels = 'aeiouAEIOU' return '' . join(x if x not in vowels else str(n + 1) for n, x in enumerate(string))
The old switcheroo
55d410c492e6ed767000004f
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/55d410c492e6ed767000004f
7 kyu
Create a function that will trim a string (the first argument given) if it is longer than the requested maximum string length (the second argument given). The result should also end with "..." These dots at the end also add to the string length. For example, `trim("Creating kata is fun", 14)` should return `"Creating ka..."` If the string is smaller or equal than the maximum string length, then simply return the string with no trimming or dots required. e.g. `trim("Code Wars is pretty rad", 50)` should return `"Code Wars is pretty rad"` If the requested string length is smaller than or equal to 3 characters, then the length of the dots is not added to the string length. e.g. `trim("He", 1)` should return `"H..."`, because 1 <= 3 Requested maximum length will be greater than 0. Input string will not be empty.
reference
def trim(phrase, size): if len(phrase) <= size: return phrase elif size <= 3: return phrase[: size] + '...' else: return phrase[: size - 3] + '...'
Trimming a string
563fb342f47611dae800003c
[ "Fundamentals" ]
https://www.codewars.com/kata/563fb342f47611dae800003c
7 kyu
We need a function that receives two arrays, each of them with elements that occur only once. We need to know: * Number of elements that are present in both arrays * Number of elements that are present in only one array * Number of remaining elements in `arr1` after extracting the elements of `arr2` * Number of remaining elements in `arr2` after extracting the elements of `arr1` ## Example ``` arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] arr2 = [2, 4, 6, 8, 10, 12, 14] ``` The result is: `[4, 8, 5, 3]` * `4` elements present in both arrays: 2, 4, 6, 8 * `8` elements present in only one array: 1, 3, 5, 7, 9, 10, 12, 14 * `5` elements remaning in `arr1`: 1, 3, 5, 7, 9 * `3` elements remaning in `arr2`: 10, 12, 14 No doubt, an easy kata to warm up before doing the more complex ones. Enjoy it!
reference
def process_2arrays(arr1, arr2): s1, s2 = set(arr1), set(arr2) return [len(s1 & s2), len(s1 ^ s2), len(s1 - s2), len(s2 - s1)]
Operations With Sets
5609fd5b44e602b2ff00003a
[ "Fundamentals", "Data Structures", "Mathematics" ]
https://www.codewars.com/kata/5609fd5b44e602b2ff00003a
7 kyu
~~~if:cobol Given a table of integers, return the digits that are not present in any of them. ~~~ ~~~if-not:cobol Given a varying number of integer arguments, return the digits that are not present in any of them. ~~~ Example: ``` [12, 34, 56, 78] => "09" [2015, 8, 26] => "3479" ``` **Note**: the digits in the resulting string should be sorted.
reference
def unused_digits(* args): return "" . join(number for number in "0123456789" if number not in str(args))
Filter unused digits
55de6173a8fbe814ee000061
[ "Fundamentals", "Filtering", "Arrays" ]
https://www.codewars.com/kata/55de6173a8fbe814ee000061
7 kyu
<h1>Write a function to calculate compound tax using the following table:</h1> <ul> <li>For $10 and under, the tax rate should be 10%.</li> <li>For $20 and under, the tax rate on the first $10 is %10, and the tax on the rest is 7%.</li> <li>For $30 and under, the tax rate on the first $10 is still %10, the rate for the next $10 is still 7%, and everything else is 5%.</li> <li>Tack on an additional 3% for the portion of the total above $30.</li> <li>Return 0 for invalid input(anything that's not a positive real number). </li> </ul> <h2>Examples:</h2> <ul> <li>An input of 10, should return 1 (1 is 10% of 10)</li> <li>An input of 21, should return 1.75 (10% of 10 + 7% of 10 + 5% of 1)</li> </ul> <p>* Note that the returned value should be rounded to the nearest penny.</p>
reference
def tax_calculator(total): if not isinstance(total, (int, float)) or total < 0: return 0 tax = 0 if total > 30: tax = 2.2 + (total - 30) * 0.03 elif total > 20: tax = 1.7 + (total - 20) * 0.05 elif total > 10: tax = 1 + (total - 10) * 0.07 elif total > 0: tax = total / 10.0 return round(tax, 2)
Tax Calculator
56314d3c326bbcf386000007
[ "Fundamentals" ]
https://www.codewars.com/kata/56314d3c326bbcf386000007
7 kyu
You are given an initial 2-value array (x). You will use this to calculate a score. If both values in (x) are numbers, the score is the sum of the two. If only one is a number, the score is that number. If neither is a number, return 'Void!'. Once you have your score, you must return an array of arrays. Each sub array will be the same as (x) and the number of sub arrays should be equal to the score. For example: if (x) == ['a', 3] you should return [['a', 3], ['a', 3], ['a', 3]].
reference
def explode(arr): numbers = [n for n in arr if type(n) == int] return [arr] * sum(numbers) if numbers else "Void!"
Array Array Array
57eb936de1051801d500008a
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57eb936de1051801d500008a
7 kyu
Write a function that will encrypt a given sentence into International Morse Code, both the input and out puts will be strings. Characters should be separated by a single space. Words should be separated by a triple space. For example, "HELLO WORLD" should return -> ".... . .-.. .-.. --- .-- --- .-. .-.. -.." To find out more about Morse Code follow this link: https://en.wikipedia.org/wiki/Morse_code A preloaded object/dictionary/hash called CHAR_TO_MORSE will be provided to help convert characters to Morse Code.
reference
def encryption(string): return ' ' . join(CHAR_TO_MORSE . get(a, a) for a in string)
International Morse Code Encryption
55b8c0276a7930249e00003c
[ "Fundamentals" ]
https://www.codewars.com/kata/55b8c0276a7930249e00003c
7 kyu
Your job is to figure out the index of which vowel is missing from a given string: * `A` has an index of 0, * `E` has an index of 1, * `I` has an index of 2, * `O` has an index of 3, * `U` has an index of 4. **Notes:** There is no need for string validation and every sentence given will contain all vowels but one. Also, you won't need to worry about capitals. ## Examples ``` "John Doe hs seven red pples under his bsket" => 0 ; missing: "a" "Bb Smith sent us six neatly arranged range bicycles" => 3 ; missing: "o" ```
games
def absent_vowel(x): return ['aeiou' . index(i) for i in 'aeiou' if i not in x][0]
Absent vowel
56414fdc6488ee99db00002c
[ "Arrays", "Strings" ]
https://www.codewars.com/kata/56414fdc6488ee99db00002c
7 kyu
Create a function which accepts one arbitrary string as an argument, and return a string of length 26. The objective is to set each of the 26 characters of the output string to either `'1'` or `'0'` based on the fact whether the Nth letter of the alphabet is present in the input (independent of its case). So if an `'a'` or an `'A'` appears anywhere in the input string (any number of times), set the first character of the output string to `'1'`, otherwise to `'0'`. if `'b'` or `'B'` appears in the string, set the second character to `'1'`, and so on for the rest of the alphabet. For instance: ``` "a **& cZ" => "10100000000000000000000001" ```
reference
def change(st): new = "" st = st . lower() for letter in "abcdefghijklmnopqrstuvwxyz": if letter in st: new += "1" else: new += "0" return new
Search for letters
52dbae61ca039685460001ae
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/52dbae61ca039685460001ae
7 kyu
You get a new job working for Eggman Movers. Your first task is to write a method that will allow the admin staff to enter a person’s name and return what that person's role is in the company. You will be given an array of object literals holding the current employees of the company. You code must find the employee with the matching firstName and lastName and then return the role for that employee or if no employee is not found it should return "Does not work here!" The array is preloaded and can be referenced using the variable `employees` (`$employees` in Ruby). It uses the following structure. ```javascript let employees = [ {firstName: "Dipper", lastName: "Pines", role: "Boss"}, ...... ] ``` ```python employees = [ {'first_name': "Dipper", 'last_name': "Pines", 'role': "Boss"}, ...... ] ``` ```ruby employees = [ {'first_name'=> "Dipper", 'last_name'=> "Pines", 'role'=> "Boss"}, ...... ] ``` There are no duplicate names in the array and the name passed in will be a single string with a space between the first and last name i.e. Jane Doe or just a name.
reference
def find_employees_role(name): for employee in employees: if employee['first_name'] + ' ' + employee['last_name'] == name: return employee['role'] return "Does not work here!"
Find an employees role in the company
55c9fb1b407024afe6000055
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/55c9fb1b407024afe6000055
7 kyu
Your team is really excited with all the contributions you've made to the RuplesJS library. They feel the work you're doing will truly help Ruby developers transition to Javascript! They've assigned you another task. ## String.eachChar() In ruby you can add something after each character in a string like so: ```` "hello".each_char {|c| print c, ' ' } -> "h e l l o " ```` In the spirit of polymorphism, our eachChar method will allow one of two arguments, a callback function or a string. If a string is presented, it will be added after each character of the original string and return the new string. If a function is presented, it will perform a manipulation of each character in the string. Example: ```javascript "hello".eachChar(" "); -> "h e l l o " "hello all".eachChar(function(char) { if (char == "l") { return char.toUpperCase(); } else { return char; } }); -> "heLLo aLL" ``` ```python each_char("hello"," ") -> "h e l l o " def func(c): return 'L' if c=='l' else c each_char("hello all", func) -> "heLLo aLL" ``` ```ruby "hello".each_char(" ") -> "h e l l o " def func(c) return c=='l' ? 'L' : c end "hello all".each_char(:func) -> "heLLo aLL" ``` Please add your contribution to RuplesJS! <div style="width: 320px; text-align: center; color: white; border: white 1px solid;"> Check out my other RuplesJS katas: </div> <div> <a style='text-decoration:none' href='http://www.codewars.com/kata/ruplesjs-number-1-n-times-do'><span style='color:#00C5CD'>RuplesJS #1:</span> N Times Do</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/ruplesjs-number-2-string-delete'><span style='color:#00C5CD'>RuplesJS #2:</span> String Delete</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/ruplesjs-number-3-string-eachchar'><span style='color:#00C5CD'>RuplesJS #3:</span> String EachChar</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/ruplesjs-number-4-string-formatting'><span style='color:#00C5CD'>RuplesJS #4:</span> String Formatting</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/ruplesjs-number-5-range'><span style='color:#00C5CD'>RuplesJS #5:</span> Range</a><br /> </div>
reference
def each_char(s, a): return '' . join(a(x) if callable(a) else x + a for x in s)
RuplesJS #3: String EachChar
56808724e7784d220c00003f
[ "Fundamentals", "Language Features" ]
https://www.codewars.com/kata/56808724e7784d220c00003f
7 kyu
Your retro heavy metal band, VÄxën, originally started as kind of a joke, just because why would anyone want to use the crappy foosball table in your startup's game room when they could be rocking out at top volume in there instead? Yes, a joke, but now all the top tech companies are paying you top dollar to play at their conferences and big product-release events. And just as how in the early days of the Internet companies were naming everything "i"-this and "e"-that, now that VÄxënmänïä has conquered the tech world, any company that doesn't use <a href="https://en.wikipedia.org/wiki/Metal_umlaut">Hëävÿ Mëtäl Ümläüts</a> in ëvëry pössïblë pläcë is looking hopelessly behind the times. Well, with great power chords there must also come great responsibility! You need to help these companies out by writing a function that will guarantee that their web sites and ads and everything else will RÖCK ÄS MÜCH ÄS PÖSSÏBLË! Just think about it -- with the licensing fees you'll be getting from Gööglë, Fäcëböök, Äpplë, and Ämäzön alone, you'll probably be able to end world hunger, make college and Marshall stacks free to all, and invent self-driving bumper cars. Sö lët's gët röckïng and röllïng! Pëdal tö thë MËTÄL! Here's a little cheatsheet that will help you write your function to replace the so-last-year letters a-e-i-o-u-and-sometimes-y with the following totally rocking letters: ``` A = Ä = \u00c4 E = Ë = \u00cb I = Ï = \u00cf O = Ö = \u00d6 U = Ü = \u00dc Y = Ÿ = \u0178 a = ä = \u00e4 e = ë = \u00eb i = ï = \u00ef o = ö = \u00f6 u = ü = \u00fc y = ÿ = \u00ff ``` ```if:python ### Python 2.7 issues First, Python in the Codewars environment has some codec/encoding issues with extended ASCII codes like the umlaut-letters required above. With Python 2.7.6, when writing your solution you can just copy the above umlaut-letters (instead of the unicode sequences) and paste them into your code, but I haven't found something yet that will work for *both* 2.7.6 and 3.4.3 -- hopefully I will find something soon (answers/suggestions are welcome!), and hopefully that part will also be easier with other languages when I add them. Second, along the same lines, don't bother trying to use string translate() and maketrans() to solve this in Python 2.7.6, because maketrans will see the character-mapping strings as being different lengths. Use a different approach instead. ```
reference
UMLAUTS = {'A': 'Ä', 'E': 'Ë', 'I': 'Ï', 'O': 'Ö', 'U': 'Ü', 'Y': 'Ÿ', 'a': 'ä', 'e': 'ë', 'i': 'ï', 'o': 'ö', 'u': 'ü', 'y': 'ÿ'} def heavy_metal_umlauts(s): return '' . join(UMLAUTS . get(a, a) for a in s)
Hëävÿ Mëtäl Ümläüts
57d4e99bec16701a67000033
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57d4e99bec16701a67000033
7 kyu
Create a function that will return ```true``` if the input is in the following date time format ```01-09-2016 01:20``` and ```false``` if it is not. This Kata has been inspired by the Regular Expressions chapter from the book Eloquent JavaScript.
reference
from re import match def date_checker(date): return bool(match(r'\d{2}-\d{2}-\d{4}\s\d{2}:\d{2}', date))
Date Format Validation
57ce0c634001a5f3c7000006
[ "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57ce0c634001a5f3c7000006
7 kyu
This is the simple version of Fastest Code series. If you need some challenges, please try the [Performance version](http://www.codewars.com/kata/5714594d2817ff681c000783) ## Task: Give you a number array ```numbers``` and a number ```c```. Find out a pair of numbers(we called them number a and number b) from the array ```numbers```, let a*b=c, result format is an array ```[a,b]``` The array ```numbers``` is a sorted array, value range: `-100...100` The result will be the first pair of numbers, for example,```findAB([1,2,3,4,5,6],6)``` should return ```[1,6]```, instead of ```[2,3]``` Please see more example in testcases. ### Series: - [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9) - [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008) - [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009) - [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1) - [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3) - [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e) - [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4) - [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947) - [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1) - [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b) - [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba) - [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba) - [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742) - [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c) - [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048) - [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633) - [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a) - [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594) - [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9) - [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001) - [Tidy up the room](http://www.codewars.com/kata/5703ace6e55d30d3e0001029) - [Waiting for a Bus](http://www.codewars.com/kata/57070eff924f343280000015)
games
def find_a_b(numbers, c): for i, a in enumerate(numbers, 1): for b in numbers[i:]: if a * b == c: return [a, b]
Coding 3min : A*B=C
5714803d2817ffce17000a35
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5714803d2817ffce17000a35
7 kyu
Consider a matchmaking system that is designed to deliver jobs to software developers on a continual basis. As more quality jobs are handpicked into the system, they will be matched to all the enrolled developers; affording them better opportunities daily. This means that somewhere in the system there exists functionality to take a job and match it against enrolled candidates. There are several factors that go into this matching, but we'll focus on two for the purposes of this Kata. Create a function `match` which takes a `job`, and filters a list of `candidates` to the ones that match the job. We'll focus on two matching properties for this Kata: equity and location. ### Equity The candidate has a equity property (boolean) indicating if they desire equity, while the job will have a maximum equity property (float) representing the max amount of equity offered. If the maximum equity is zero, we can infer there is no equity offered. A job will match unless the candidate desires equity, but the job does not offer any. ### Location The candidate will have two location properties: current location and desired locations. A job can be located in multiple places as well which will be represented by its locations property. A match is when a job location is either in the candidate's current location or any of the candidate's desired locations. So the candidate list might look like this: ```javascript let candidates = [{ desiresEquity: true, currentLocation: 'New York', desiredLocations: ['San Francisco', 'Los Angeles', 'Colorado'] }, ...]; ``` ```ruby candidates = [{ 'desires_equity' => true, 'current_location' => 'New York', 'desired_locations' => ['San Francisco', 'Los Angeles'] }, ...] ``` ```python candidates = [{ 'desires_equity': True, 'current_location': 'New York', 'desired_locations': ['San Francisco', 'Los Angeles'] }, ...] ``` And a job might look like this: ```javascript let job = { equityMax: 1.2, locations: ['New York', 'Kentucky'] } ``` ```ruby job = { 'equity_max' => 1.2, 'locations' => ['New York', 'Kentucky'] } ``` ```python job = { 'equity_max': 1.2, 'locations': ['New York', 'Kentucky'] } ``` --- Continue on with Kata: - [Job Matching #1][2] - [Job Matching #3][3] [4]:http://www.codewars.com/kata/strive-matching-number-2/discuss/javascript [3]:http://www.codewars.com/kata/strive-matching-number-3 [2]:http://www.codewars.com/kata/strive-matching-number-1
algorithms
def match(j, c): matches = [] for can in c: if (can["desires_equity"] and j["equity_max"] > 0) or can["desires_equity"] == False: for loc in j["locations"]: if loc in [can["current_location"]] + can["desired_locations"]: matches . append(can) break return matches
Job Matching #2
56c2578be8b139bd5c001bd8
[ "Arrays", "Filtering", "Algorithms" ]
https://www.codewars.com/kata/56c2578be8b139bd5c001bd8
7 kyu
## Remove HTML tags and return string without: 1) &lt;tag&gt; and &lt;/tag&gt; 2) &lt;tag/&gt; 3) &lt;tag /&gt; 4) html tags with attributes. Don't trim space, tab etc. **You have to use regexp.** Tests are using function: `String.prototype.replace(your regexp, "")` ## Have fun :)
reference
reg = '<[^>]*>'
Remove HTML tags using regexp
58488e89cc8feac6cb000941
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/58488e89cc8feac6cb000941
7 kyu
You are given an array of non-negative integers, your task is to complete the series from 0 to the highest number in the array. If the numbers in the sequence provided are not in order you should order them, but if a value repeats, then you must return a sequence with only one item, and the value of that item must be 0. like this: ``` inputs outputs [2,1] -> [0,1,2] [1,4,4,6] -> [0] ``` Notes: all numbers are positive integers. This is set of example outputs based on the input sequence. ``` inputs outputs [0,1] -> [0,1] [1,4,6] -> [0,1,2,3,4,5,6] [3,4,5] -> [0,1,2,3,4,5] [0,1,0] -> [0] ```
reference
def complete_series(a): return list(range(max(a) + 1)) if len(a) == len(set(a)) else [0]
Complete Series
580a4001d6df740d61000301
[ "Lists", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/580a4001d6df740d61000301
7 kyu
<h1>Multiplication - Generators #2</h1> Generators can be used to wonderful things. You can use them for numerous things, but here is one specific example. You are studying for a test so you must practice your multiplication, but you don't have a multiplication table showing the different examples. You have decided to create a generator that prints out a limitless list of time tables. <h2>Task</h2> <p> Your generator must take one parameter `a` then everytime the generator is called you must return a string in the format of: `'a x b = c'` where c is the answer. Also, the value of `b`, which starts at 1, must increment by 1 each time! </p> <strong>More Info: </strong>[Generators (JS)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators), <a href="https://wiki.python.org/moin/Generators">Generators (Python)</a>, [Generators (PHP)](http://php.net/manual/en/language.generators.php), [Generators (Java)](https://thecannycoder.wordpress.com/2014/07/04/generators/)
reference
def generator(a): c = 1 while True: yield f" { a } x { c } = { a * c } " c += 1
Multiplication - Generators #2
5637ead70013386e30000027
[ "Fundamentals" ]
https://www.codewars.com/kata/5637ead70013386e30000027
7 kyu
Given n number of people in a room, calculate the probability that any two people in that room have the same birthday (assume 365 days every year = ignore leap year). Answers should be two decimals unless whole (0 or 1) eg 0.05
algorithms
def calculate_probability(n): return round(1 - (364 / 365) * * (n * (n - 1) / 2), 2)
Same Birthday Probability
5419cf8939c5ef0d50000ef2
[ "Algorithms" ]
https://www.codewars.com/kata/5419cf8939c5ef0d50000ef2
7 kyu
## Task You have to write three functions namely - `PNum, GPNum and SPNum` (JS, Coffee), `p_num, g_p_num and s_p_num` (Python and Ruby), `pNum, gpNum and spNum` (Java, C#), `p-num, gp-num and sp-num` (Clojure) - to check whether a given argument `n` is a Pentagonal, Generalized Pentagonal, or Square Pentagonal Number, and return `true` if it is and `false` otherwise. ### Description <p> <img style="float:right;padding-left:10px" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b5/Pentagonal_number.gif/181px-Pentagonal_number.gif"> `Pentagonal Numbers` - The nth pentagonal number Pn is the number of distinct dots in a pattern of dots consisting of the outlines of regular pentagons with sides up to n dots (means the side contains n number of dots), when the pentagons are overlaid so that they share one corner vertex. </p> > First few Pentagonal Numbers are: 1, 5, 12, 22... `Generalized Pentagonal Numbers` - All the Pentagonal Numbers along with the number of dots inside the outlines of all the pentagons of a pattern forming a pentagonal number pentagon are called Generalized Pentagonal Numbers. > First few Generalized Pentagonal Numbers are: 0, 1, 2, 5, 7, 12, 15, 22... `Square Pentagonal Numbers` - The numbers which are Pentagonal Numbers and are also a perfect square are called Square Pentagonal Numbers. > First few are: 1, 9801, 94109401... ### Examples #### Note: * Pn = Nth Pentagonal Number * Gpn = Nth Generalized Pentagonal Number <img style="float:center; padding-top: 5px; padding-right: 5px; padding-bottom: 5px; padding-left: 5px;" src="https://upload.wikimedia.org/wikipedia/commons/5/54/Polygonal_Number_5.gif"> ^ ^ ^ ^ ^ P1=1 P2=5 P3=12 P4=22 P5=35 //Total number of distinct dots used in the Pattern Gp2=1 Gp4=5 Gp6=12 Gp8=22 //All the Pentagonal Numbers are Generalised Gp1=0 Gp3=2 Gp5=7 Gp7=15 //Total Number of dots inside the outermost Pentagon
algorithms
def p_num(n): k = round((1 + (1 + 24 * n) * * .5) / 6) return n != 0 and n == k * (3 * k - 1) / / 2 def g_p_num(n): det = (1 + 24 * n) * * .5 k1, k2 = round((1 + (1 + 24 * n) * * .5) / 6), round((- 1 + (1 + 24 * n) * * .5) / 6) return n == 0 or n == k1 * (3 * k1 - 1) / / 2 or n == k2 * (3 * k2 + 1) / / 2 def s_p_num(n): return p_num(n) and n * * .5 % 1 == 0
Figurate Numbers #1 - Pentagonal Number
55ab9eee6badbdaf72000075
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/55ab9eee6badbdaf72000075
6 kyu
## Task: You have to create a function `isPronic` to check whether the argument passed is a Pronic Number and return true if it is & false otherwise. ### Description: `Pronic Number` -A pronic number, oblong number, rectangular number or heteromecic number, is a number which is the product of two consecutive integers, that is, n(n + 1). > The first few Pronic Numbers are - 0, 2, 6, 12, 20, 30, 42... ### Explanation: 0 = 0 × 1 // ∴ 0 is a Pronic Number 2 = 1 × 2 // ∴ 2 is a Pronic Number 6 = 2 × 3 // ∴ 6 is a Pronic Number 12 = 3 × 4 // ∴ 12 is a Pronic Number 20 = 4 × 5 // ∴ 20 is a Pronic Number 30 = 5 × 6 // ∴ 30 is a Pronic Number 42 = 6 × 7 // ∴ 42 is a Pronic Number ### Note: Negative numbers are tested as well.
algorithms
import math def is_pronic(n): return n >= 0 and math . sqrt(1 + 4 * n) % 1 == 0
Figurate Numbers #2 - Pronic Number
55b1e5c4cbe09e46b3000034
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/55b1e5c4cbe09e46b3000034
7 kyu
Given a string of words (x), you need to return an array of the words, sorted alphabetically by the final character in each. If two words have the same last letter, the returned array should show them in the order they appeared in the given string. All inputs will be valid.
reference
def last(s): return sorted(s . split(), key=lambda x: x[- 1])
Sort by Last Char
57eba158e8ca2c8aba0002a0
[ "Fundamentals", "Strings", "Arrays", "Sorting" ]
https://www.codewars.com/kata/57eba158e8ca2c8aba0002a0
7 kyu
Implement a function called makeAcronym that returns the first letters of each word in a passed in string. Make sure the letters returned are uppercase. If the value passed in is not a string return 'Not a string'. If the value passed in is a string which contains characters other than spaces and alphabet letters, return 'Not letters'. If the string is empty, just return the string itself: "". **EXAMPLES:** ``` 'Hello codewarrior' -> 'HC' 'a42' -> 'Not letters' 42 -> 'Not a string' [2,12] -> 'Not a string' {name: 'Abraham'} -> 'Not a string' ```
reference
def make_acronym(phrase): try: return '' . join(word[0]. upper() if word . isalpha() else 0 for word in phrase . split()) except AttributeError: return 'Not a string' except TypeError: return 'Not letters'
makeAcronym
557efeb04effce569d000022
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/557efeb04effce569d000022
7 kyu
While surfing in web I found interesting math problem called "Always perfect". That means if you add 1 to the product of four consecutive numbers the answer is ALWAYS a perfect square. For example we have: 1,2,3,4 and the product will be 1X2X3X4=24. If we add 1 to the product that would become 25, since the result number is a perfect square the square root of 25 would be 5. So now lets write a function which takes numbers separated by commas in string format and returns the number which is a perfect square and the square root of that number. If string contains other characters than number or it has more or less than 4 numbers separated by comma function returns "incorrect input". If string contains 4 numbers but not consecutive it returns "not consecutive".
reference
def check_root(string): try: a, b, c, d = [int(i) for i in string . split(',')] if not (a == b - 1 and a == c - 2 and a == d - 3): return 'not consecutive' s = a * b * c * d + 1 return str(s) + ', ' + str(int(s * * 0.5)) except: return 'incorrect input'
Always perfect
55f3facb78a9fd5b26000036
[ "Strings", "Arrays", "Mathematics", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/55f3facb78a9fd5b26000036
7 kyu
The borrowers are tiny tiny fictional people. As tiny tiny people they have to be sure they aren't spotted, or more importantly, stepped on. As a result, the borrowers talk very very quietly. They find that `capitals and punctuation` of any sort lead them to raise their voices and put them in danger. The young borrowers have begged their parents to `stop using caps and punctuation`. Change the input text `s` to new borrower speak. Help save the next generation!
reference
def borrow(s): return '' . join(filter(str . isalpha, s . lower()))
Borrower Speak
57d2ba8095497e484e00002e
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57d2ba8095497e484e00002e
7 kyu
Share price =========== You spent all your saved money to buy some shares. You bought it for `invested`, and want to know how much it's worth, but all the info you can quickly get are just the change the shares price made in percentages. Your task: ---------- Write the function `sharePrice()` that calculates, and returns the current price of your share, given the following two arguments: - `invested`(number), the amount of money you initially invested in the given share - `changes`(array of numbers), contains your shares daily movement percentages The returned number, should be in string format, and it's precision should be fixed at 2 decimal numbers. Have fun! >**Hint:** Try to write the function in a functional manner!
algorithms
def share_price(invested, changes): for change in changes: invested = invested * (100 + change) / 100.0 return format(invested, '.2f')
Share prices
5603a4dd3d96ef798f000068
[ "Logic", "Algorithms" ]
https://www.codewars.com/kata/5603a4dd3d96ef798f000068
7 kyu
Write a function `take_umbrella()` that takes two arguments: a string representing the current weather and a float representing the chance of rain today. Your function should return `True` or `False` based on the following criteria. * You should take an umbrella if it's currently raining or if it's cloudy and the chance of rain is over `0.20`. * You shouldn't take an umbrella if it's sunny unless it's more likely to rain than not. The options for the current weather are `sunny`, `cloudy`, and `rainy`. For example, `take_umbrella('sunny', 0.40)` should return `False`. As an additional challenge, consider solving this kata using only logical operaters and not using any `if` statements.
reference
def take_umbrella(weather, rain_chance): # Your code here. return (weather == 'cloudy' and rain_chance > 0.20) or weather == 'rainy' or (weather == 'sunny' and rain_chance > 0.5)
Thinkful - Logic Drills: Umbrella decider
5865a28fa5f191d35f0000f8
[ "Fundamentals" ]
https://www.codewars.com/kata/5865a28fa5f191d35f0000f8
7 kyu
## Description Your job is to create a simple password validation function, as seen on many websites. The rules for a valid password are as follows: - There needs to be at least 1 uppercase letter. - There needs to be at least 1 lowercase letter. - There needs to be at least 1 number. - The password needs to be at least 8 characters long. You are permitted to use any methods to validate the password. ## Examples: ```javascript password("Abcd1234"); ===> true password("Abcd123"); ===> false password("abcd1234"); ===> false password("AbcdefGhijKlmnopQRsTuvwxyZ1234567890"); ===> true password("ABCD1234"); ===> false password("Ab1!@#$%^&*()-_+={}[]|\:;?/>.<,"); ===> true; password("!@#$%^&*()-_+={}[]|\:;?/>.<,"); ===> false; ``` ### Extra info - You will only be passed strings. - The string can contain any standard keyboard character. - Accepted strings can be any length, as long as they are 8 characters or more.
reference
CRITERIA = (str . islower, str . isupper, str . isdigit) def password(s): return len(s) > 7 and all(any(map(f, s)) for f in CRITERIA)
Password validator
56a921fa8c5167d8e7000053
[ "Fundamentals", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/56a921fa8c5167d8e7000053
7 kyu
## Overview [Bubblesort](https://en.wikipedia.org/wiki/Bubble_sort) is an inefficient sorting algorithm that is simple to understand and therefore often taught in introductory computer science courses as an example how _not_ to sort a list. Nevertheless, it is correct in the sense that it eventually produces a sorted version of the original list when executed to completion. At the heart of Bubblesort is what is known as a _pass_. Let's look at an example at how a pass works. Consider the following list: ``` 9, 7, 5, 3, 1, 2, 4, 6, 8 ``` We initiate a pass by comparing the first two elements of the list. Is the first element greater than the second? If so, we swap the two elements. Since `9` is greater than `7` in this case, we swap them to give `7, 9`. The list then becomes: ``` 7, 9, 5, 3, 1, 2, 4, 6, 8 ``` We then continue the process for the 2nd and 3rd elements, 3rd and 4th elements ... all the way up to the last two elements. When the pass is complete, our list becomes: ``` 7, 5, 3, 1, 2, 4, 6, 8, 9 ``` Notice that the largest value `9` "bubbled up" to the end of the list. This is precisely how Bubblesort got its name. ## Task ~~~if-not:riscv Given an array of integers, your function `bubblesortOnce`/`bubblesort_once`/`BubblesortOnce` (or equivalent, depending on your language's naming conventions) should return a *new* array equivalent to performing exactly **1 complete pass** on the original array. Your function should be pure, i.e. it should **not** mutate the input array. ~~~ ~~~if:riscv Implement a function `bubblesort_pass()` that performs exactly 1 complete pass of Bubblesort on the input array. It should return whether any pair of integers have been swapped. The function signature is ```c bool bubblesort_pass(int *arr, size_t n); ``` where `arr` is the input array and `n` is the number of elements in the array. ~~~ ~~~if:lambdacalc ## Encodings purity: `LetRec` numEncoding: `Scott` export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding ~~~
algorithms
def bubblesort_once(l): l = l[:] for i in range(len(l) - 1): if l[i] > l[i + 1]: l[i], l[i + 1] = l[i + 1], l[i] return l
Bubblesort Once
56b97b776ffcea598a0006f2
[ "Algorithms", "Tutorials", "Sorting" ]
https://www.codewars.com/kata/56b97b776ffcea598a0006f2
7 kyu
## Perimeter sequence The first three stages of a sequence are shown. ![blocks](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTVw-YEuGbD31EB47C7PSi_RpBxr5EJSydV9dj5lOmzsDWFsoAs) The blocksize is `a` by `a` and `a ≥ 1`. What is the perimeter of the `n`th shape in the sequence (`n ≥ 1`) ?
games
def perimeter_sequence(a, n): return 4 * n * a
Perimeter sequence
589519d1f0902e01af000054
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/589519d1f0902e01af000054
7 kyu
DropCaps means that the first letter of the starting word of the paragraph should be in caps and the remaining lowercase, just like you see in the newspaper. But for a change, let"s do that for each and every word of the given String. Your task is to capitalize every word that has length greater than 2, leaving smaller words as they are. *should work also on Leading and Trailing Spaces and caps. ``` "apple" => "Apple" "apple of banana" => "Apple of Banana" "one space" => "One Space" " space WALK " => " Space Walk " ``` **Note:** you will be provided atleast one word and should take string as input and return string as output.
reference
def drop_cap(str_): return ' ' . join(w . capitalize() if len(w) > 2 else w for w in str_ . split(' '))
Dropcaps
559e5b717dd758a3eb00005a
[ "Arrays", "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/559e5b717dd758a3eb00005a
7 kyu
#It's show time! Archers have gathered from all around the world to participate in the Arrow Function Faire. But the faire will only start if there are archers signed and if they all have enough arrows in their quivers - at least 5 is the requirement! Are all the archers ready? #Reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions #Argument `archers` is an array of integers, in which each element corresponds to the number of arrows each archer has. #Return Your function must return `true` if the requirements are met or `false` otherwise. #Examples `archersReady([1, 2, 3, 4, 5, 6, 7, 8])` returns `false` because there are archers with not enough arrows. `archersReady([5, 6, 7, 8])` returns `true`.
reference
def archers_ready(archers): return all(i >= 5 for i in archers) if archers else False
Every archer has its arrows
559f89598c0d6c9b31000125
[ "Fundamentals" ]
https://www.codewars.com/kata/559f89598c0d6c9b31000125
7 kyu
Zebulan has worked hard to write all his python code in strict compliance to PEP8 rules. In this kata, you are a mischievous hacker that has set out to sabotage all his good code. Your job is to take PEP8 compatible function names and convert them to camelCase. For example: zebulansNightmare('camel_case') == 'camelCase' zebulansNightmare('zebulans_nightmare') == 'zebulansNightmare' zebulansNightmare('get_string') == 'getString' zebulansNightmare('convert_to_uppercase') == 'convertToUppercase' zebulansNightmare('main') == 'main'
reference
def zebulansNightmare(s): return s[0] + s . title(). replace("_", "")[1:]
Zebulan's Nightmare
570fd7ad34e6130455001835
[ "Fundamentals" ]
https://www.codewars.com/kata/570fd7ad34e6130455001835
7 kyu
Complete the function that takes an array of integers as input and finds the sum of squares of the elements at even positions (i.e. 2nd, 4th, etc.) plus the sum of the rest of the elements at odd position. For empty arrays, result should be zero (except for Haskell). #### Note The values at even *positions* need to be squared. For a language with zero-based indices, this will occur at oddly-indexed locations. For instance, in Python, the values at indices 1, 3, 5, *etc.* should be squared because these are the second, fourth, and sixth positions in the list. ## Example ```ruby [11, 12, 13, 14, 15] --> 379 # 1. 2. 3. 4. 5. position 11 + 12^2 + 13 + 14^2 + 15 = 379 ``` Explanation: Elements at indices 0, 2, 4 are 11, 13, 15 and they are at odd positions as 11 is at position #1, 13 is at position #3 and 15 at #5. Elements at indices 1, 3 are 12 and 14 and they are at even position. So we need to add 11, 13, 15 as they are and square of 12 and 14
reference
def alternate_sq_sum(arr): return sum([x * * 2 if i % 2 == 1 else x for i, x in enumerate(arr)])
Alternate Square Sum
559d7951ce5e0da654000073
[ "Fundamentals", "Arrays", "Lists" ]
https://www.codewars.com/kata/559d7951ce5e0da654000073
7 kyu
Brief ===== In this easy kata your function has to take a **string** as input and **return a string** with everything removed (*whitespaces* included) but the **digits**. As you may have guessed **empty strings** are to be returned as they are & if the input string contains no digits then the output will be an **empty string**.By the way , you have to watch out for **non-string** inputs too.Return **'Invalid input !'** for them. ```python digit_all("are_you_kidding_me_???") --------------> '' digit_all("wai8, where are you goin'?") ----------> '8' digit_all("") ------------------------------------> '' digit_all(['yes','i','am','kidding','you','!']) --> 'Invalid input !' digit_all("1 2 3 4") -----------------------> '1234' ``` Good luck!
algorithms
def digit_all(x): return '' . join(d for d in x if d . isdigit()) if isinstance(x, str) else 'Invalid input !'
DigitAll
57eead3b5f79f6d977001fb7
[ "Fundamentals", "Strings", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/57eead3b5f79f6d977001fb7
7 kyu
Late last night in the Tanner household, ALF was repairing his spaceship so he might get back to Melmac. Unfortunately for him, he forgot to put on the parking brake, and the spaceship took off during repair. Now it's hovering in space. ALF has the technology to bring the spaceship home if he can lock on to its location. Given a map: ```` .......... .......... .......... .......X.. .......... .......... ```` The map will be given in the form of a string with \n separating new lines. The bottom left of the map is [0, 0]. X is ALF's spaceship. In this example: ```javascript findSpaceship(map) => [7, 2] ``` ```coffeescript findSpaceship(map) => [7, 2] ``` ```ruby find_spaceship(map) => [7, 2] ``` ```java findSpaceship(map) => "[7, 2]" ``` ```cpp findSpaceship(map) => "[7, 2]" ``` If you cannot find the spaceship, the result should be ``` "Spaceship lost forever." ``` Can you help ALF? <div style="width: 320px; text-align: center; color: white; border: white 1px solid;"> Check out my other 80's Kids Katas: </div> <div> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-1-how-many-licks-does-it-take'><span style='color:#00C5CD'>80's Kids #1:</span> How Many Licks Does It Take</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-2-help-alf-find-his-spaceship'><span style='color:#00C5CD'>80's Kids #2:</span> Help Alf Find His Spaceship</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-3-punky-brewsters-socks'><span style='color:#00C5CD'>80's Kids #3:</span> Punky Brewster's Socks</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-4-legends-of-the-hidden-temple'><span style='color:#00C5CD'>80's Kids #4:</span> Legends of the Hidden Temple</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-5-you-cant-do-that-on-television'><span style='color:#00C5CD'>80's Kids #5:</span> You Can't Do That on Television</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-6-rock-em-sock-em-robots'><span style='color:#00C5CD'>80's Kids #6:</span> Rock 'Em, Sock 'Em Robots</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-7-shes-a-small-wonder'><span style='color:#00C5CD'>80's Kids #7:</span> She's a Small Wonder</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-8-the-secret-world-of-alex-mack'><span style='color:#00C5CD'>80's Kids #8:</span> The Secret World of Alex Mack</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-9-down-in-fraggle-rock'><span style='color:#00C5CD'>80's Kids #9:</span> Down in Fraggle Rock </a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-10-captain-planet'><span style='color:#00C5CD'>80's Kids #10:</span> Captain Planet </a><br /> </div>
algorithms
def find_spaceship(astromap): lines = astromap . splitlines() for y, line in enumerate(lines): x = line . find('X') if x != - 1: return [x, len(lines) - 1 - y] return 'Spaceship lost forever.'
80's Kids #2: Help ALF Find His Spaceship
5660aa3d5e011dfd6e000063
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5660aa3d5e011dfd6e000063
7 kyu
Not considering number 1, the integer 153 is the first integer having this property: the sum of the third-power of each of its digits is equal to 153. Take a look: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 The next number that experiments this particular behaviour is 370 with the same power. Write the function `eq_sum_powdig()`, that finds the numbers below a given upper limit `hMax` (inclusive) that fulfills this property but with different exponents as the power for the digits. eq_sum_powdig(hMax, exp): ----> sequence of numbers (sorted list) (Number one should not be considered). Let's see some cases: ```python eq_sum_powdig(100, 2) ----> [] eq_sum_powdig(1000, 2) ----> [] eq_sum_powdig(200, 3) ----> [153] eq_sum_powdig(370, 3) ----> [153, 370] ``` ```ruby eq_sum_powdig(100, 2) ----> [] eq_sum_powdig(1000, 2) ----> [] eq_sum_powdig(200, 3) ----> [153] eq_sum_powdig(370, 3) ----> [153, 370] ``` ```javascript eqSumPowdig(100, 2) ----> [] eqSumPowdig(1000, 2) ----> [] eqSumPowdig(200, 3) ----> [153] eqSumPowdig(370, 3) ----> [153, 370] ``` Enjoy it !!
reference
def eq_sum_powdig(h, e): return [i for i in range(2, h + 1) if sum(int(j) * * e for j in str(i)) == i]
Numbers Which Sum of Powers of Its Digits Is The Same Number
560a4962c0cc5c2a16000068
[ "Fundamentals", "Mathematics", "Data Structures" ]
https://www.codewars.com/kata/560a4962c0cc5c2a16000068
7 kyu
Mrs. Frizzle is beginning to plan lessons for her science class next semester, and wants to encourage friendship amongst her students. To accomplish her goal, Mrs. Frizzle will ensure ***each student has a chance to partner with every other student in the class*** in a series of science projects. Mrs. Frizzle does not know who will be in her class next semester, but she does know she will have `n` students total in her class. ## Specifications Create the function `projectPartners` with the parameter `n` representing the number of students in Mrs. Frizzle's class. The function should return the total number of unique pairs she can make with `n` students. ``` projectPartners(2) --> returns 1 projectPartners(4) --> returns 6 ``` ## Remarks - your solution ***should not contain any arrays*** or objects that are used similar to an array. Note that Haskell will use rather large numbers, such as `10^40`, so any list-based solution will autmatically fail the test. - your function will only recieve a single number that is `greater than or equal to 2` -- you do not need to worry about input validation.
algorithms
def projectPartners(n): return n * (n - 1) / 2
Unique Pairs
540c013634e6bac0350000a5
[ "Logic", "Algorithms" ]
https://www.codewars.com/kata/540c013634e6bac0350000a5
7 kyu
Your company, [Congo Pizza](http://interesting-africa-facts.com/Africa-Landforms/Congo-Rainforest-Facts.html), is the second-largest online frozen pizza retailer. You own a number of international warehouses that you use to store your frozen pizzas, and you need to figure out how many crates of pizzas you can store at each location. Congo recently standardized its storage containers: all pizzas fit inside a *cubic crate, 16-inches on a side*. The crates are super tough so you can stack them as high as you want. Write a function `box_capacity()` that figures out how many crates you can store in a given warehouse. The function should take three arguments: the length, width, and height of your warehouse (in feet) and should return an integer representing the number of boxes you can store in that space. For example: a warehouse 32 feet long, 64 feet wide, and 16 feet high can hold 13,824 boxes because you can fit 24 boxes across, 48 boxes deep, and 12 boxes high, so `box_capacity(32, 64, 16)` should return `13824`.
reference
def box_capacity(length, width, height): return (length * 12 / / 16) * (width * 12 / / 16) * (height * 12 / / 16)
Thinkful - Number Drills: Congo warehouses
5862e7c63f8628a126000e18
[ "Fundamentals" ]
https://www.codewars.com/kata/5862e7c63f8628a126000e18
7 kyu
Create a function mispelled(word1, word2): ```javascript mispelled('versed', 'xersed'); // returns true mispelled('versed', 'applb'); // returns false mispelled('versed', 'v5rsed'); // returns true mispelled('1versed', 'versed'); // returns true mispelled('versed', 'versed'); // returns true ``` ```python mispelled('versed', 'xersed') # returns True mispelled('versed', 'applb') # returns False mispelled('versed', 'v5rsed') # returns True mispelled('1versed', 'versed') # returns True mispelled('versed', 'versed') #returns True ``` It checks if the word2 differs from word1 by at most one character. This can include an extra char at the end or the beginning of either of words. In the tests that expect `true`, the mispelled word will always differ mostly by one character. If the two words are the same, return `True`.
reference
def mispelled(word1, word2): l1, l2 = len(word1), len(word2) if l1 == l2: return sum(1 for a, b in zip(word1, word2) if a != b) <= 1 if l1 - l2 == 1: return word1 . startswith(word2) or word1 . endswith(word2) if l1 - l2 == - 1: return word2 . startswith(word1) or word2 . endswith(word1) return False
Mispelled word
5892595f190ca40ad0000095
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5892595f190ca40ad0000095
7 kyu
# Backstory <img src="https://static1.squarespace.com/static/553e1e3ae4b0c7db85dc4fb3/5546810be4b0a65de4f4e04a/563f39b3e4b07bcd9d902110/1446984116886/Alan_Partridge_Minimalist_Posteritty_London.jpg?format=1000w"> Ever the learned traveller, Alan Partridge has pretty strong views on London: ``` "Go to London. I guarantee you'll either be mugged or not appreciated. Catch the train to London, stopping at Rejection, Disappointment, Backstabbing Central and Shattered Dreams Parkway." ``` # Task Your job is to check that the provided `list / array of stations` contains all of the stops Alan mentions. The list of stops are as follows: ``` Rejection Disappointment Backstabbing Central Shattered Dreams Parkway ``` If all the stops appear in the given `list / array`, return `Smell my cheese you mother!`, if not, return `No, seriously, run. You will miss it.`. # Other katas in this series: <a href="https://www.codewars.com/kata/alan-partridge-i-partridge-watch">Alan Partridge I - Partridge Watch</a><br> <a href="https://www.codewars.com/kata/alan-partridge-ii-apple-turnover">Alan Partridge II - Apple Turnover</a><br>
reference
def alan(arr): s = {'Rejection', 'Disappointment', 'Backstabbing Central', 'Shattered Dreams Parkway'} return "Smell my cheese you mother!" if s . issubset(arr) else "No, seriously, run. You will miss it."
Alan Partridge III - London
580a41b6d6df740d6100030c
[ "Fundamentals", "Arrays", "Strings" ]
https://www.codewars.com/kata/580a41b6d6df740d6100030c
7 kyu
Given a string of digits confirm whether the sum of all the individual even digits are greater than the sum of all the indiviudal odd digits. Always a string of numbers will be given. * If the sum of even numbers is greater than the odd numbers return: `"Even is greater than Odd"` * If the sum of odd numbers is greater than the sum of even numbers return: `"Odd is greater than Even"` * If the total of both even and odd numbers are identical return: `"Even and Odd are the same"`
reference
def even_or_odd(s): even_minus_odd = sum([- x if x % 2 else x for x in map(int, s)]) if even_minus_odd > 0: return "Even is greater than Odd" elif even_minus_odd < 0: return "Odd is greater than Even" else: return "Even and Odd are the same"
Even or Odd - Which is Greater?
57f7b8271e3d9283300000b4
[ "Fundamentals" ]
https://www.codewars.com/kata/57f7b8271e3d9283300000b4
7 kyu
## Knight vs King If you are not familiar with chess game you can learn more [Here](https://en.wikipedia.org/wiki/Chess) . Here is the chess board (rows, denoted by numbers, are called *ranks*, columns, denoted by a letter, are called *files*): ![alt text](https://upload.wikimedia.org/wikipedia/commons/5/5b/Chess-board-with-letters_nevit_111.svg) You put a Knight and a King in the board. Complete the method that tell us which one can capture the other one. You are provided with two object array; each contains an integer (the rank, first item) and a string/char (the file, second item) to show the position of the pieces in the chess board. Return: * `"Knight"` if the knight is putting the king in check, * `"King"` if the king is attacking the knight * `"None"` if none of the above occur Example: ``` knight = [7, "B"], king = [6, "C"] ---> "King" ``` Check the test cases and Happy coding :)
reference
def knightVsKing(knightPosition, kingPosition): dx = knightPosition[0] - kingPosition[0] dy = ord(knightPosition[1]) - ord(kingPosition[1]) d = dx * dx + dy * dy if d == 5: return 'Knight' if d < 3: return 'King' return 'None'
Knight vs King
564e1d90c41a8423230000bc
[ "Algorithms", "Games" ]
https://www.codewars.com/kata/564e1d90c41a8423230000bc
7 kyu
Write a function that takes as parameters an array (arr) and 2 integers (x and y). The function should return the mean between the mean of the the first x elements of the array and the mean of the last y elements of the array. The mean should be computed if both x and y have values higher than 1 but less or equal to the array's length. Otherwise the function should return -1. ## Examples ``` [1, 3, 2, 4], 2, 3 => should return 2.5 ``` because: the mean of the the first 2 elements of the array is (1+3)/2=2 and the mean of the last 3 elements of the array is (4+2+3)/3=3 so the mean of those 2 means is (2+3)/2=2.5. ``` [1, 3, 2, 4], 1, 2 => should return -1 ``` because x is not higher than 1. ``` [1, 3, 2, 4], 2, 8 => should return -1 ``` because 8 is higher than the array's length.
reference
def get_mean(arr, x, y): if 1 < x <= len(arr) and 1 < y <= len(arr): return (sum(arr[: x]) / x + sum(arr[- y:]) / y) / 2 return - 1
The mean of two means
583df40bf30065fa9900010c
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/583df40bf30065fa9900010c
7 kyu
I highly recommend listening Vivaldi's Four Seasons as an inspiration to solve this Kata :) In the UK, winter begins on 21 December and ends on 20 March. Spring begins on 21 March and ends on 20 June. Summer begins on 21 June and ends on 20 September. Autumn begins on 21 September and ends on 20 December. Given a date day from `1` (January 1st) to `365` (December 31th) your task is to return the season of the year that corresponds to that day. If the number given is greater than `365`, return ``"The year flew by!"``. Note: We are not considering leap years.
reference
def four_seasons(d): return { d < 80: 'Winter Season', 79 < d < 172: 'Spring Season', 171 < d < 264: 'Summer Season', 263 < d < 355: 'Autumn Season', 354 < d < 366: 'Winter Season', d > 365: 'The year flew by!' }[True]
The Four Seasons
5846174c5955406d02000b59
[ "Fundamentals" ]
https://www.codewars.com/kata/5846174c5955406d02000b59
7 kyu
Write a function named `repeater()` that takes two arguments (a string and a number), and returns a new string where the input string is repeated that many times. ## Example: (Input1, Input2 --> Output) ``` "a", 5 --> "aaaaa" ```
reference
def repeater(string, n): return string * n
Thinkful - String Drills: Repeater
585a1a227cb58d8d740001c3
[ "Fundamentals" ]
https://www.codewars.com/kata/585a1a227cb58d8d740001c3
7 kyu
Write a function that takes in a binary string and returns the equivalent decoded text (the text is ASCII encoded). Each 8 bits on the binary string represent 1 character on the ASCII table. The input string will always be a valid binary string. Characters can be in the range from "00000000" to "11111111" (inclusive) Note: In the case of an empty binary string your function should return an empty string.
reference
def binary_to_string(binary): return "" . join([chr(int(binary[i: i + 8], 2)) for i in range(0, len(binary), 8)])
Binary to Text (ASCII) Conversion
5583d268479559400d000064
[ "Binary", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5583d268479559400d000064
6 kyu
John keeps a backup of his old personal phone book as a text file. On each line of the file he can find the phone number (formated as `+X-abc-def-ghij` where X stands for one or two digits), the corresponding name between `<` and `>` and the address. Unfortunately everything is mixed, things are not always in the same order; parts of lines are cluttered with non-alpha-numeric characters (except inside phone number and name). Examples of John's phone book lines: `"/+1-541-754-3010 156 Alphand_St. <J Steeve>\n"` `" 133, Green, Rd. <E Kustur> NY-56423 ;+1-541-914-3010!\n"` `"<Anastasia> +48-421-674-8974 Via Quirinal Roma\n"` Could you help John with a program that, given the lines of his phone book and a phone number `num` returns a string for this number : `"Phone => num, Name => name, Address => adress"` #### Examples: ``` s = "/+1-541-754-3010 156 Alphand_St. <J Steeve>\n 133, Green, Rd. <E Kustur> NY-56423 ;+1-541-914-3010!\n" phone(s, "1-541-754-3010") should return "Phone => 1-541-754-3010, Name => J Steeve, Address => 156 Alphand St." ``` - It can happen that there are many people for a phone number `num`, then return : `"Error => Too many people: num"` - or it can happen that the number `num` is not in the phone book, in that case return: `"Error => Not found: num"` #### Notes - Codewars stdout doesn't print part of a string when between `<` and `>` - You can see other examples in the test cases. - JavaScript random tests completed by @matt c.
reference
from re import sub def phone(dir, num): if dir . count("+" + num) == 0: return "Error => Not found: " + num if dir . count("+" + num) > 1: return "Error => Too many people: " + num for line in dir . splitlines(): if "+" + num in line: name = sub(".*<(.*)>.*", "\g<1>", line) line = sub("<" + name + ">|\+" + num, "", line) address = " " . join(sub("[^a-zA-Z0-9\.-]", " ", line). split()) return "Phone => %s, Name => %s, Address => %s" % (num, name, address)
Phone Directory
56baeae7022c16dd7400086e
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/56baeae7022c16dd7400086e
5 kyu
Write a method that takes one argument as name and then greets that name, capitalized and ends with an exclamation point. Example: ``` "riley" --> "Hello Riley!" "JACK" --> "Hello Jack!" ```
reference
def greet(name): return f'Hello { name . title ()} !'
Greet Me
535474308bb336c9980006f2
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/535474308bb336c9980006f2
7 kyu
In Russia regular bus tickets usually consist of 6 digits. The ticket is called lucky when the sum of the first three digits equals to the sum of the last three digits. Write a function to find out whether the ticket is lucky or not. Return true if so, otherwise return false. Consider that input is always a string. Watch examples below. ```javascript isLucky('123321') => 1+2+3 = 3+2+1 => true // The ticket is lucky isLucky('12341234') => false // Only six-digit numbers allowed :( isLucky('12a21a') => false // Letters are not allowed :( isLucky('100200') => false // :( isLucky('22') => false // :( isLucky('abcdef') => false // :( ``` ```php isLucky('123321') => 1+2+3 = 3+2+1 => true // The ticket is lucky isLucky('12341234') => false // Only six-digit numbers allowed :( isLucky('12a21a') => false // Letters are not allowed :( isLucky('100200') => false // :( isLucky('22') => false // :( isLucky('abcdef') => false // :( ```
reference
def is_lucky(ticket): if len(ticket) == 6 and ticket . isdigit(): t = list(map(int, ticket)) return sum(t[: 3]) == sum(t[3:]) return False
Lucky Bus Ticket
58902f676f4873338700011f
[ "Fundamentals" ]
https://www.codewars.com/kata/58902f676f4873338700011f
7 kyu
Peter can see a clock in the mirror from the place he sits in the office. When he saw the clock shows 12:22 <svg width="200" height="200"> <circle cx="100" cy="100" r="92" stroke="black" stroke-width="4" fill="white"/> <text x="135" y=" 40" fill="black">1</text> <text x="165" y=" 68" fill="black">2</text> <text x="174" y="105" fill="black">3</text> <text x="165" y="145" fill="black">4</text> <text x="135" y="175" fill="black">5</text> <text x=" 96" y="185" fill="black">6</text> <text x=" 58" y="175" fill="black">7</text> <text x=" 28" y="145" fill="black">8</text> <text x=" 15" y="105" fill="black">9</text> <text x=" 25" y=" 68" fill="black">10</text> <text x=" 55" y=" 40" fill="black">11</text> <text x=" 92" y=" 25" fill="black">12</text> <line x1="100" y1="100" x2="110" y2=" 51" stroke="black" stroke-width="5"/> <line x1="100" y1="100" x2="152" y2="146" stroke="black" stroke-width="5"/> </svg> He knows that the time is 11:38 <svg width="200" height="200"> <circle cx="100" cy="100" r="92" stroke="black" stroke-width="4" fill="white"/> <text x="135" y=" 40" fill="black">1</text> <text x="165" y=" 68" fill="black">2</text> <text x="174" y="105" fill="black">3</text> <text x="165" y="145" fill="black">4</text> <text x="135" y="175" fill="black">5</text> <text x=" 96" y="185" fill="black">6</text> <text x=" 58" y="175" fill="black">7</text> <text x=" 28" y="145" fill="black">8</text> <text x=" 15" y="105" fill="black">9</text> <text x=" 25" y=" 68" fill="black">10</text> <text x=" 55" y=" 40" fill="black">11</text> <text x=" 92" y=" 25" fill="black">12</text> <line x1="100" y1="100" x2="90" y2=" 51" stroke="black" stroke-width="5"/> <line x1="100" y1="100" x2="48" y2="146" stroke="black" stroke-width="5"/> </svg> in the same manner: 05:25 --> 06:35 01:50 --> 10:10 11:58 --> 12:02 12:01 --> 11:59 Please complete the function `WhatIsTheTime(timeInMirror)`, where `timeInMirror` is the mirrored time (what Peter sees) as string. Return the _real_ time as a string. Consider hours to be between 1 <= hour < 13. So there is no 00:20, instead it is 12:20. There is no 13:20, instead it is 01:20.
reference
def what_is_the_time(time_in_mirror): h, m = map(int, time_in_mirror . split(':')) return '{:02}:{:02}' . format(- (h + (m != 0)) % 12 or 12, - m % 60)
Clock in Mirror
56548dad6dae7b8756000037
[ "Fundamentals" ]
https://www.codewars.com/kata/56548dad6dae7b8756000037
6 kyu