description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
sequencelengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
Hector the hacker has stolen some information, but it is encrypted. In order to decrypt it, he needs to write a function that will generate a decryption key from the encryption key which he stole (it is in hexadecimal). To do this, he has to determine the two prime factors `P` and `Q` of the encyption key, and return the product `(P-1) * (Q-1)`. **Note:** the primes used are < 10<sup>5</sup> ## Examples For example if the encryption key is `"47b"`, it is 1147 in decimal. This factors to 31\*37, so the key Hector needs is 1080 (= 30\*36). More examples: * input: `"2533"`, result: 9328 (primes: 89, 107) * input: `"1ba9"`, result: 6912 (primes: 73, 97)
algorithms
def find_key(key): n = int(key, 16) return next((k - 1) * ((n // k) - 1) for k in range(2, int(n**0.5)+1) if n % k == 0)
Hexadecimal Keys
5962ddfc2f9addd52200001d
[ "Algorithms" ]
https://www.codewars.com/kata/5962ddfc2f9addd52200001d
7 kyu
You are given an integer N. Your job is to figure out how many substrings inside of N divide evenly with N. Confused? I'll break it down for you. Let's say that you are given the integer '877692'. ```` 8 does not evenly divide with 877692. 877692/8 = 109711 with 4 remainder. 7 does not evenly divide with 877692. 877692/7 = 125384 with 4 remainder. 7 does not evenly divide with 877692. 877692/7 = 125384 with 4 remainder. 6 evenly divides with 877692. 877692/6 = 146282 with 0 remainder. 9 does not evenly divide with 877692. 877692/9 = 97521 with 3 remainder. 2 evenly divides with 877692. 877692/2 = 438846 with 0 remainder. ```` We aren't going to stop there though. We need to check ALL of the substrings inside of 877692. ```` 87 does not evenly divide with 877692. 877692/87 = 10088 with 36 remainder. 77 does not evenly divide with 877692. 877692/77 = 11398 with 46 remainder. 76 does not evenly divide with 877692. 877692/76 = 11548 with 44 remainder. 69 does not evenly divide with 877692. 877692/69 = 12720 with 12 remainder. etc. ```` # Rules: -If an integer is 0, then it does NOT divide evenly into anything. -Even though N can divide evenly with itself, we do not count it towards the end number. For Example: ```` N = 23, the answer will be 0. ```` -If there are multiple instances of a number, they all get counted. For example: ```` N = 11, the answer will be 2 ```` # Input: A non negative integer. # Output: The number of times you found an integer that was evenly divisible with N.
algorithms
def get_count(n): sn = str(n) count = 0 for i in range(1, len(sn)): for j in range(len(sn) - i + 1): sub = int(sn[j: j + i]) if sub and n % sub == 0: count += 1 return count
Divisible Ints
566859a83557837d9700001a
[ "Algorithms" ]
https://www.codewars.com/kata/566859a83557837d9700001a
6 kyu
## Task A step(x) operation works like this: it changes a number x into x - s(x), where s(x) is the sum of x's digits. You like applying functions to numbers, so given the number n, you decide to build a decreasing sequence of numbers: n, step(n), step(step(n)), etc., with 0 as the last element. Building a single sequence isn't enough for you, so you replace all elements of the sequence with the sums of their digits (s(x)). Now you're curious as to which number appears in the new sequence most often. If there are several answers, return the maximal one. ## Example For `n = 88`, the output should be `9`. Here is the first sequence you built: `88, 72, 63, 54, 45, 36, 27, 18, 9, 0`; And here is s(x) for each of its elements: `16, 9, 9, 9, 9, 9, 9, 9, 9, 0`. As you can see, the most frequent number in the second sequence is 9. For `n = 8`, the output should be `8`. At first you built the following sequence: `8, 0` s(x) for each of its elements is: `8, 0` As you can see, the answer is `8` (it appears as often as 0, but is greater than it). ## Input/Output - `[input]` integer `n` Constraints: 1 ≤ n ≤ 10<sup>5</sup> - `[output]` an integer The most frequent number in the sequence s(n), s(step(n)), s(step(step(n))), etc.
games
def most_frequent_digit_sum(n): d = {} while n: s = sum(map(int, str(n))) d[s] = d . get(s, 0) + 1 n -= s return max(d, key=lambda s: (d[s], s))
Simple Fun #36: Most Frequent Digit Sum
588809279ab1e0e17700002e
[ "Puzzles" ]
https://www.codewars.com/kata/588809279ab1e0e17700002e
6 kyu
# Task Given a string `str`, find the shortest possible string which can be achieved by adding characters to the end of initial string to make it a palindrome. # Example For `str = "abcdc"`, the output should be `"abcdcba"`. # Input/Output - `[input]` string `str` A string consisting of lowercase latin letters. Constraints: `3 ≤ str.length ≤ 10`. - `[output]` a string
games
def build_palindrome(strng): n = 0 while strng[n:] != strng[n:][:: - 1]: n += 1 return strng + strng[: n][:: - 1]
Simple Fun #78: Build Palindrome
58942f9175f2c78f4b000108
[ "Puzzles" ]
https://www.codewars.com/kata/58942f9175f2c78f4b000108
6 kyu
## Task Given an integer `product`, find the smallest positive integer the product of whose digits is equal to product. If there is no such integer, return -1 instead. ## Example For `product = 1`, the output should be `11`; `1 x 1 = 1` (1 is not a valid result, because it has only 1 digit) For `product = 12`, the output should be `26`; `2 x 6 = 12` For `product = 19`, the output should be `-1`. No valid result found. For `product = 450`, the output should be `2559`. `2 x 5 x 5 x 9 = 450` For `product = 581`, the output should be `-1`. No valid result found. Someone says the output should be `783`, because `7 x 83 = 581`. Please note: `83` is not a **DIGIT**. ## Input/Output - `[input]` integer `product` Constraints: `0 ≤ product ≤ 600`. - `[output]` a positive integer ~~~if:rust ## Note for Rust Return type is an `Option<u32>`. Return `None` if no solution can be found. ~~~
games
def digits_product(product): if product < 10: return 10 + product n = '' for d in range(9, 1, - 1): while not product % d: n += str(d) product / /= d return int(n[:: - 1]) if product == 1 else - 1
Simple Fun #81: Digits Product
589436311a8808bf560000f9
[ "Puzzles" ]
https://www.codewars.com/kata/589436311a8808bf560000f9
5 kyu
Every month, a random number of students take the driving test at Fast & Furious (F&F) Driving School. To pass the test, a student cannot accumulate more than 18 demerit points. At the end of the month, F&F wants to calculate the average demerit points accumulated by <b>ONLY</b> the students who have passed, rounded to the nearest integer. Write a function which would allow them to do so. If no students passed the test that month, return 'No pass scores registered.'. <br></br> <u>Example:</u> [10,10,10,18,20,20] --> 12
reference
def passed(lst): a = list(filter(lambda x: x <= 18, lst)) return 'No pass scores registered.' if a == [] else round(sum(a) / len(a))
Driving School Series #1
58999425006ee3f97c00011f
[ "Fundamentals" ]
https://www.codewars.com/kata/58999425006ee3f97c00011f
7 kyu
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple / list (depending on your language) like so: `(index1, index2)`. For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted. The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array). Based on: https://leetcode.com/problems/two-sum/ ```elixir two_sum([1, 2, 3], 4) == {0, 2} two_sum([3, 2, 4], 6) == {1, 2} ``` ```lambdacalc two-sum < 1 2 3 > 4 # returns (0, 2) or (2, 0) two-sum < 3 2 4 > 6 # returns (1, 2) or (2, 1) ``` ```cpp two_sum({1, 2, 3}, 4); // returns {0, 2} or {2, 0} two_sum({3, 2, 4}, 6); // returns {1, 2} or {2, 1} ``` ```go TwoSum([]int{1, 2, 3}, 4) // returns [2]int{0, 2} // the go translation has an issue where random tests accept either [2]int{0, 2} or [2]int{2, 0}, but fixed tests and sample tests demand the resulting slice to be sorted! // untill it's fixed, please sort your result in go. ``` ```haskell twoSum [1, 2, 3] 4 === (0, 2) twoSum [3, 2, 4] 6 === (1, 2) ``` ```javascript twoSum([1, 2, 3], 4) // returns [0, 2] or [2, 0] twoSum([3, 2, 4], 6) // returns [1, 2] or [2, 1] ``` ```python two_sum([1, 2, 3], 4) # returns (0, 2) or (2, 0) two_sum([3, 2, 4], 6) # returns (1, 2) or (2, 1) ``` ```rust two_sum(&[1, 2, 3], 4) // return (0, 2) or (2, 0) two_sum(&[3, 2, 4], 6) // return (1, 2) or (2, 1) ``` ```cobol TwoSum([1, 2, 3], 4) => result = [1, 3] TwoSum([3, 2, 4], 6) => result = [1, 2] ``` ```scala twoSum(List(1, 2, 3), 4) // (0, 2) or (2, 0) twoSum(List(3, 2, 4), 6) // (1, 2) or (2, 1) ``` ~~~if:lambdacalc ### Encodings purity: `LetRec` numEncoding: `BinaryScott` export constructors `nil, cons` for your `List` encoding export deconstructors `fst, snd` for your `Tuple` encoding ~~~
reference
def two_sum(nums, t): for i, x in enumerate(nums): for j, y in enumerate(nums): if i != j and x + y == t: return [i, j]
Two Sum
52c31f8e6605bcc646000082
[ "Arrays", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/52c31f8e6605bcc646000082
6 kyu
#### Task: Your job is to create a function, (`random_ints` in Ruby/Python/Crystal, and `randomInts` in JavaScript/CoffeeScript) that takes two parameters, `n` and `total`, that will randomly identify `n` non-negative integers that sum to the `total`. Note that [1, 2, 3, 4] and [2, 3, 4, 1] are considered to be 'the same array' when it comes to this kata. #### How the function will be called: ```ruby random_ints(n, total) # where n and total are non-negative integers, and the return type is an array of integers ``` ```python random_ints(n, total) # where n and total are non-negative integers, and the return type is an array of integers ``` ```crystal random_ints(n, total) # where n and total are non-negative integers, and the return type is an array of integers ``` ```javascript randomInts(n, total) # where n and total are non-negative integers, and the return type is an array of integers ``` ```coffeescript randomInts(n, total) # where n and total are none-negative integers, and the return type is an array of integers ``` #### Some example cases; however, do note that the integer inputs in the actual test suite are much larger in order to reduce the likelihood of two tests from being equal from chance: ```ruby random_ints(3, 5) # all of the following are valid, but MUST NOT be repeated more than once when testing [1, 2, 2] [2, 3, 0] [1, 1, 3] … random_ints(2, 6) # all of the following are valid, but MUST NOT be repeated more than once when testing [2, 4] [0, 6] [1, 5] … ``` ```crystal random_ints(3, 5) # all of the following are valid, but MUST NOT be repeated more than once when testing [1, 2, 2] [2, 3, 0] [1, 1, 3] … random_ints(2, 6) # all of the following are valid, but MUST NOT be repeated more than once when testing [2, 4] [0, 6] [1, 5] … ``` ```python random_ints(3, 5) # all of the following are valid, but MUST NOT be repeated more than once when testing [1, 2, 2] [2, 3, 0] [1, 1, 3] … random_ints(2, 6) # all of the following are valid, but MUST NOT be repeated more than once when testing [2, 4] [0, 6] [1, 5] … ``` ```javascript randomInts(3, 5) # all of the following are valid, but MUST NOT be repeated more than once when testing [1, 2, 2] [2, 3, 0] [1, 1, 3] … randomInts(2, 6) # all of the following are valid, but MUST NOT be repeated more than once when testing [2, 4] [0, 6] [1, 5] … ``` ```coffeescript randomInts(3, 5) # all of the following are valid, but MUST NOT be repeated more than once when testing [1, 2, 2] [2, 3, 0] [1, 1, 3] … randomInts(2, 6) # all of the following are valid, but MUST NOT be repeated more than once when testing [2, 4] [0, 6] [1, 5] … ``` Although it may seem like overkill, the reason there are so many random tests is to ensure your outputs are 'random enough'; ie. if your code fails repeatedly, it is probably because not enough array elements are randomized fully. As said earlier, due to the size of the inputs, it is highly unlikely (out of 10 submissions, it hasn't happened to me) that your code will fail due to pure chance/unluckiness. But nevertheless, it is still possible, so just to make sure, do run your code again in the event that it fails. Also check out my other creations — [Adding Fractions](https://www.codewars.com/kata/adding-fractions), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2) If you notice any issues/bugs/missing test cases whatsoever (especially for JavaScript), do not hesitate to report an issue or suggestion. Enjoy!
reference
from random import randint def random_ints(n, total): result = [] for _ in range(n - 1): result . append(randint(0, total)) total -= result[- 1] return [* result, total]
Random Integers
580f1a22df91279f09000273
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/580f1a22df91279f09000273
6 kyu
Given a certain array of integers, create a function that may give the minimum number that may be divisible for all the numbers of the array. ```python min_special_mult([2, 3 ,4 ,5, 6, 7]) == 420 ``` ```ruby min_special_mult([2, 3 ,4 ,5, 6, 7]) == 420 ``` The array may have integers that occurs more than once: ```python min_special_mult([18, 22, 4, 3, 21, 6, 3]) == 2772 ``` ```ruby min_special_mult([18, 22, 4, 3, 21, 6, 3]) == 2772 ``` The array should have all its elements integer values. If the function finds an invalid entry (or invalid entries) like strings of the alphabet or symbols will not do the calculation and will compute and register them, outputting a message in singular or plural, depending on the number of invalid entries. ```python min_special_mult([16, 15, 23, 'a', '&', '12']) == "There are 2 invalid entries: ['a', '&']" min_special_mult([16, 15, 23, 'a', '&', '12', 'a']) == "There are 3 invalid entries: ['a', '&', 'a']" min_special_mult([16, 15, 23, 'a', '12']) == "There is 1 invalid entry: a" ``` ```ruby min_special_mult([16, 15, 23, 'a', '&', '12']) == "There are 2 invalid entries: ['a', '&']" min_special_mult([16, 15, 23, 'a', '&', '12', 'a']) == "There are 3 invalid entries: ['a', '&', 'a']" min_special_mult([16, 15, 23, 'a', '12']) == "There is 1 invalid entry: a" ``` If the string is a valid number, the function will convert it as an integer. ```python min_special_mult([16, 15, 23, '12']) == 5520 min_special_mult([16, 15, 23, '012']) == 5520 ``` ```ruby min_special_mult([16, 15, 23, '12']) == 5520 min_special_mult([16, 15, 23, '012']) == 5520 ``` All the `None`/`nil` elements of the array will be ignored: ```python min_special_mult([18, 22, 4, , None, 3, 21, 6, 3]) == 2772 ``` ```ruby min_special_mult([18, 22, 4, , nil, 3, 21, 6, 3]) == 2772 ``` If the array has a negative number, the function will convert to a positive one. ```python min_special_mult([18, 22, 4, , None, 3, -21, 6, 3]) == 2772 min_special_mult([16, 15, 23, '-012']) == 5520 ``` ```ruby min_special_mult([18, 22, 4, , None, 3, -21, 6, 3]) == 2772 min_special_mult([16, 15, 23, '-012']) == 5520 ``` Enjoy it
reference
from fractions import gcd import re def min_special_mult(arr): l = [e for e in arr if not re . match('(None)|([+-]?\d+)', str(e))] if len(l) == 1: return 'There is 1 invalid entry: {}' . format(l[0]) if len(l) > 1: return 'There are {} invalid entries: {}' . format(len(l), l) return reduce(lambda s, e: s * int(e) / gcd(s, int(e)) if e else s, arr, 1)
Find The Minimum Number Divisible by Integers of an Array I
56f245a7e40b70f0e3000130
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/56f245a7e40b70f0e3000130
6 kyu
Implement a function/class, which should return an integer if the input string is in one of the formats specified below, or `null/nil/None` otherwise. Format: * Optional `-` or `+` * Base prefix `0b` (binary), `0x` (hexadecimal), `0o` (octal), or in case of no prefix decimal. * Digits depending on base Any extra character (including whitespace) makes the input invalid, in which case you should return `null/nil/None`. Digits are case insensitive, but base prefix must be lower case. See the test cases for examples.
reference
import re def to_integer(s): if re . match("\A[+-]?(\d+|0b[01]+|0o[0-7]+|0x[0-9a-fA-F]+)\Z", s): return int(s, 10 if s[1:]. isdigit() else 0)
Regexp basics - parsing integers
5682e1082cc7862db5000039
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5682e1082cc7862db5000039
6 kyu
In some countries of former Soviet Union there was a belief about lucky tickets. A transport ticket of any sort was believed to posess luck if sum of digits on the left half of its number was equal to the sum of digits on the right half. Here are examples of such numbers: ``` 003111 # 3 = 1 + 1 + 1 813372 # 8 + 1 + 3 = 3 + 7 + 2 17935 # 1 + 7 = 3 + 5 // if the length is odd, you should ignore the middle number when adding the halves. 56328116 # 5 + 6 + 3 + 2 = 8 + 1 + 1 + 6 ``` Such tickets were either eaten after being used or collected for bragging rights. Your task is to write a funtion ```luck_check(str)```, which returns ```true/True``` if argument is string decimal representation of a lucky ticket number, or ```false/False``` for all other numbers. It should throw errors for empty strings or strings which don't represent a decimal number.
games
def luck_check(s): if not s . isnumeric(): raise ValueError return not sum(int(a) - int(b) for a, b in zip(s[: len(s) / / 2], s[:: - 1]))
Luck check
5314b3c6bb244a48ab00076c
[ "Strings", "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/5314b3c6bb244a48ab00076c
5 kyu
Variation of <a href="https://www.codewars.com/kata/bits-battle/" target="_blank">this nice kata</a>, the war has expanded and become dirtier and meaner; both even and odd numbers will fight with their pointy `1`s. And negative integers are coming into play as well, with, ça va sans dire, a negative contribution (think of them as spies or saboteurs). A number's strength is determined by the number of set bits (`1`s) in its binary representation. Negative integers work against their own side so their strength is negative. For example `-5` = `-101` has strength `-2` and `+5` = `+101` has strength `+2`. The side with the largest cumulated strength wins. Again, three possible outcomes: `odds win`, `evens win` and `tie`. Examples: ```javascript bitsWar([1,5,12]) => "odds win" //1+101 vs 1100, 3 vs 2 bitsWar([7,-3,20]) => "evens win" //111-11 vs 10100, 3-2 vs 2 bitsWar([7,-3,-2,6]) => "tie" //111-11 vs -1+110, 3-2 vs -1+2 ``` ```python bits_war([1,5,12]) => "odds win" #1+101 vs 1100, 3 vs 2 bits_war([7,-3,20]) => "evens win" #111-11 vs 10100, 3-2 vs 2 bits_war([7,-3,-2,6]) => "tie" #111-11 vs -1+110, 3-2 vs -1+2 ``` ```ruby bits_war([1,5,12]) => "odds win" #1+101 vs 1100, 3 vs 2 bits_war([7,-3,20]) => "evens win" #111-11 vs 10100, 3-2 vs 2 bits_war([7,-3,-2,6]) => "tie" #111-11 vs -1+110, 3-2 vs -1+2 ``` ```crystal bits_war([1,5,12]) => "odds win" #1+101 vs 1100, 3 vs 2 bits_war([7,-3,20]) => "evens win" #111-11 vs 10100, 3-2 vs 2 bits_war([7,-3,-2,6]) => "tie" #111-11 vs -1+110, 3-2 vs -1+2 ``` ```php bitsWar([1,5,12]) => "odds win" //1+101 vs 1100, 3 vs 2 bitsWar([7,-3,20]) => "evens win" //111-11 vs 10100, 3-2 vs 2 bitsWar([7,-3,-2,6]) => "tie" //111-11 vs -1+110, 3-2 vs -1+2 ``` ```java bitsWar(new int[]{1,5,12}).equals("odds win") == true // 1+101 vs 1100, 3 vs 2 bitsWar(new int[]{7,-3,20}).equals("evens win") == true // 111-11 vs 10100, 3-2 vs 2 bitsWar(new int[]{7,-3,-2,6}).equals("tie") == true // 111-11 vs -1+110, 3-2 vs -1+2 ```
reference
def bits_war(numbers): odd, even = 0, 0 for number in numbers: if number % 2 == 0: if number > 0: even += bin(number). count('1') else: even -= bin(number). count('1') else: if number > 0: odd += bin(number). count('1') else: odd -= bin(number). count('1') return 'odds win' if odd > even else 'evens win' if even > odd else 'tie'
World Bits War
58865bfb41e04464240000b0
[ "Bits", "Binary", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/58865bfb41e04464240000b0
6 kyu
The odd and even numbers are fighting against each other! You are given a list of positive integers. The odd numbers from the list will fight using their `1` bits from their binary representation, while the even numbers will fight using their `0` bits. If present in the list, number `0` will be neutral, hence not fight for either side. You should return: * `odds win` if number of `1`s from odd numbers is larger than `0`s from even numbers * `evens win` if number of `1`s from odd numbers is smaller than `0`s from even numbers * `tie` if equal, including if list is empty Please note that any prefix that might appear in the binary representation, e.g. `0b`, should not be counted towards the battle. ### Example: For an input list of `[5, 3, 14]`: * odds: `5` and `3` => `101` and `11` => four `1`s * evens: `14` => `1110` => one `0` Result: `odds win` the battle with 4-1 If you enjoyed this kata, you can find a nice variation of it [here](https://www.codewars.com/kata/world-bits-war).
reference
def bits_battle(numbers): x = sum(format(n, 'b'). count('1') if n % 2 else - format(n, 'b'). count('0') for n in numbers if n) return ( 'odds win' if x > 0 else 'evens win' if x < 0 else 'tie' )
Bits Battle
58856a06760b85c4e6000055
[ "Fundamentals", "Binary", "Bits" ]
https://www.codewars.com/kata/58856a06760b85c4e6000055
7 kyu
---- Midpoint Sum ---- For a given list of integers, return the index of the element where the sums of the integers to the left and right of the current element are equal. Ex: ```python ints = [4, 1, 7, 9, 3, 9] # Since 4 + 1 + 7 = 12 and 3 + 9 = 12, the returned index would be 3 ints = [1, 0, -1] # Returns None/nil/undefined/etc (depending on the language) as there # are no indices where the left and right sums are equal ``` __Here are the 2 important rules:__ 1. The element at the index to be returned is __not__ included in either of the sum calculations! 2. Both the first and last index __cannot__ be considered as a "midpoint" (So ```None``` for ```[X]``` and ```[X, X]```)
reference
def midpoint_sum(ints): for i in range(1, len(ints) - 1): if sum(ints[: i]) == sum(ints[i + 1:]): return i
Midpoint Sum
54d3bb4dfc75996c1c000c6d
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/54d3bb4dfc75996c1c000c6d
6 kyu
## Task: Given a list of integers `l`, return the list with each value multiplied by integer `n`. ## Restrictions: The code _must not_: 1. contain `*`. 2. use `eval()` or `exec()` 3. contain `for` 4. modify `l` Happy coding :)
games
def multiply(n, l): return list(map(n . __mul__, l))
Multiply list by integer (with restrictions)
57f7e7617a28db2a2200021a
[ "Puzzles", "Lists", "Functional Programming", "Restricted" ]
https://www.codewars.com/kata/57f7e7617a28db2a2200021a
6 kyu
### vowelOne Write a function that takes a string and outputs a strings of 1's and 0's where vowels become 1's and non-vowels become 0's. All non-vowels including non alpha characters (spaces,commas etc.) should be included. Examples: ```haskell vowelOne "abceios" -- "1001110" vowelOne "aeiou, abc" -- "1111100100" ``` ```javascript vowelOne( "abceios" ) // "1001110" vowelOne( "aeiou, abc" ) // "1111100100" ```
reference
def vowel_one(s): return "" . join("1" if c in "aeiou" else "0" for c in s . lower())
Vowel one
580751a40b5a777a200000a1
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/580751a40b5a777a200000a1
7 kyu
Given a certain integer ```n, n > 0```and a number of partitions, ```k, k > 0```; we want to know the partition which has the maximum or minimum product of its terms. The function ```find_spec_partition() ```, will receive three arguments, ```n```, ```k```, and a command: ```'max' or 'min'``` The function should output the partition that has maximum or minimum value product (it depends on the given command) as an array with its terms in decreasing order. Let's see some cases (Python and Ruby) ``` find_spec_partition(10, 4, 'max') == [3, 3, 2, 2] find_spec_partition(10, 4, 'min') == [7, 1, 1, 1] ``` and Javascript: ``` findSpecPartition(10, 4, 'max') == [3, 3, 2, 2] findSpecPartition(10, 4, 'min') == [7, 1, 1, 1] ``` The partitions of 10 with 4 terms with their products are: ``` (4, 3, 2, 1): 24 (4, 2, 2, 2): 32 (6, 2, 1, 1): 12 (3, 3, 3, 1): 27 (4, 4, 1, 1): 16 (5, 2, 2, 1): 20 (7, 1, 1, 1): 7 <------- min. productvalue (3, 3, 2, 2): 36 <------- max.product value (5, 3, 1, 1): 15 ``` Enjoy it!
reference
def find_spec_partition(n, k, com): x, r = divmod(n, k) return {'max': [x + 1] * r + [x] * (k - r), 'min': [n + 1 - k] + [1] * (k - 1)}[com]
Find the integer Partition of k-Length With Maximum or Minimum Value For Its Product Value
57161cb0b436cf0911000819
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/57161cb0b436cf0911000819
6 kyu
The function sigma 1, σ1 in mathematics, is known as the one that gives the sum of the divisors of an integer number. For example for the number 10, ```python σ1(10) = 18 # because the divisors of 10 are: 1, 2, 5, 10 σ1(10) = 1 + 2 + 5 + 10 = 18 ``` You can see the graph of this important function up to 250: <a href="http://imgur.com/PPn4EGC"><img src="http://i.imgur.com/PPn4EGC.jpg?1" title="source: imgur.com" /></a> The number 528 and its reversed, 825 have equal value for the function σ1. ```python σ1(528) = σ1(825) divisors of 528 are: 1, 2, 3, 4, 6, 8, 11, 12, 16, 22, 24, 33, 44, 48, 66, 88, 132, 176, 264 and 528 the sum of the divisors of 528 is 1488 divisors of 825 are: 1, 3, 5, 11, 15, 25, 33, 55, 75, 165, 275 and 825 the sum of the divisors of 825 is 1488 ``` In fact 528 is the smallest non palindromic integer that has this property. We need a function, ```equal_sigma1()```, that may collect all the positive integers that fulfill the property described above. The function receives an upper limit, ```nMax```, will output the total sum of these numbers and its reversed while are less or equal nMax. Let's see some cases: ```python equal_sigma1(100) = 0 # There are no numbers. equal_sigma1(1000) = 1353 # 528 and its revesed 825 were found, 528 + 825 = 1353 equal_sigma1(2000) = 4565 # There are four numbers_: 528 + 825 + 1561 + 1651 = 4565 equal_sigma1(1600) = 2914 # Now we have three numbers: 528 + 825 + 1561 = 2914 equal_sigma1(1561) = 2914 ``` The palindromic numbers (like 88, 808, 929), numbers that are equal to its reversed should be discarded. Happy coding!! (For more information about the general sigma function see at: https://en.wikipedia.org/wiki/Divisor_function)
reference
def equal_sigma1(n): return sum( filter(n . __ge__, (528, 825, 1561, 1651, 4064, 4604, 5346, 5795, 5975, 6435))) # MAX = 10000 # σ1 = [0] + [1] * MAX # for i in range(2, MAX + 1): # for j in range(i, MAX + 1, i): # σ1[j] += i # # def equal_sigma1(nMax): # s = 0 # for i in range(nMax + 1): # r = int(str(i)[::-1]) # if i != r and σ1[i] == σ1[r]: # s += i # return s
When Sigma1 Function Has Equals Values For an Integer and Its Reversed One
5619dbc22e69620e5a000010
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5619dbc22e69620e5a000010
6 kyu
Write a function that takes an integer in input and outputs a string with currency format. Integer in currency format is expressed by a string of number where every three characters are separated by comma. For example: ``` 123456 --> "123,456" ``` Input will always be an positive integer, so don't worry about type checking or negative/float values.
reference
def to_currency(price): return '{:,}' . format(price)
Converting integer to currency format
54e9554c92ad5650fe00022b
[ "Fundamentals" ]
https://www.codewars.com/kata/54e9554c92ad5650fe00022b
7 kyu
Let us consider integer coordinates x, y in the Cartesian plane and three functions f, g, h defined by: ``` f: 1 <= x <= n, 1 <= y <= n --> f(x, y) = min(x, y) g: 1 <= x <= n, 1 <= y <= n --> g(x, y) = max(x, y) h: 1 <= x <= n, 1 <= y <= n --> h(x, y) = x + y ``` where `n` is a given integer `(n >= 1)` and `x`, `y` are integers. In the table below you can see the value of the function `f` with `n = 6`. ---|x=1|x=2|x=3|x=4|x=5|x=6| -- |--|--|--|--|--|--| y=6|1 |2 |3 |4 |5 |6 | y=5|1 |2 |3 |4 |5 |5 | y=4|1 |2 |3 |4 |4 |4 | y=3|1 |2 |3 |3 |3 |3 | y=2|1 |2 |2 |2 |2 |2 | y=1|1 |1 |1 |1 |1 |1 | The task is to calculate the **sum** of **`f(x, y)`, `g(x, y)` and `h(x, y)`** for all integers `x` and `y` in the domain D: `(1 <= x <= n, 1 <= y <= n)`. - The function **`sumin`** `(sum of f)` will take n as a parameter and return the **`sum`** of **`min(x, y)`** in `D`. - The function **`sumax`** `(sum of g)` will take n as a parameter and return the **`sum`** of **`max(x, y)`** in `D`. - The function **`sumsum`** `(sum of h)` will take n as a parameter and return the **`sum`** of **`x + y`** in `D`. #### Examples: ``` sumin(6) --> 91 (You can verify with the above table for n = 6) sumax(6) --> 161 sumsum(6) --> 252 sumin(45) --> 31395 sumax(45) --> 61755 sumsum(45) --> 93150 sumin(999) --> 332833500 sumax(999) --> 665167500 sumsum(999) --> 998001000 sumin(5000) --> 41679167500 sumax(5000) --> 83345832500 sumsum(5000) --> 125025000000 ```
reference
def sumin(n): return n * (n + 1) * (2 * n + 1) / / 6 def sumax(n): return n * (n + 1) * (4 * n - 1) / / 6 def sumsum(n): return n * n * (n + 1)
Functions of Integers on Cartesian Plane
559e3224324a2b6e66000046
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/559e3224324a2b6e66000046
7 kyu
A new school year is approaching, which also means students will be taking tests. The tests in this kata are to be graded in different ways. A certain number of points will be given for each correct answer and a certain number of points will be deducted for each incorrect answer. For ommitted answers, points will either be awarded, deducted, or no points will be given at all. Return the number of points someone has scored on varying tests of different lengths. The given parameters will be: * An array containing a series of `0`s, `1`s, and `2`s, where `0` is a correct answer, `1` is an omitted answer, and `2` is an incorrect answer. * The points awarded for correct answers * The points awarded for ommitted answers (note that this may be negative) * The points **deducted** for incorrect answers (hint: this value has to be subtracted) **Note:** The input will always be valid (an array and three numbers) ## Examples \#1: ``` [0, 0, 0, 0, 2, 1, 0], 2, 0, 1 --> 9 ``` because: * 5 correct answers: `5*2 = 10` * 1 omitted answer: `1*0 = 0` * 1 wrong answer: `1*1 = 1` which is: `10 + 0 - 1 = 9` \#2: ``` [0, 1, 0, 0, 2, 1, 0, 2, 2, 1], 3, -1, 2) --> 3 ``` because: `4*3 + 3*-1 - 3*2 = 3`
reference
def score_test(tests, right, omit, wrong): points = (right, omit, - wrong) return sum(points[test] for test in tests)
Scoring Tests
55d2aee99f30dbbf8b000001
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/55d2aee99f30dbbf8b000001
7 kyu
Given a non-negative integer, return an array / a list of the individual digits in order. Examples: ```if:c,cpp 123 => {1,2,3} 1 => {1} 8675309 => {8,6,7,5,3,0,9} ``` ```if-not:c,cpp 123 => [1,2,3] 1 => [1] 8675309 => [8,6,7,5,3,0,9] ```
algorithms
def digitize(n): return [int(d) for d in str(n)]
Digitize
5417423f9e2e6c2f040002ae
[ "Lists", "Algorithms" ]
https://www.codewars.com/kata/5417423f9e2e6c2f040002ae
7 kyu
Lot of museum allow you to be a member, for a certain amount `amount_by_year` you can have unlimitted acces to the museum. In this kata you should complete a function in order to know after how many visit it will be better to take an annual pass. The function take 2 arguments `annual_price` and `individual_price`.
reference
from math import ceil def how_many_times(ap, ip): return ceil(ap / ip)
How many times should I go?
57efcb78e77282f4790003d8
[ "Fundamentals" ]
https://www.codewars.com/kata/57efcb78e77282f4790003d8
7 kyu
Write a function that accepts two arguments: an array/list of integers and another integer (`n`). Determine the number of times where two integers in the array have a difference of `n`. For example: ``` [1, 1, 5, 6, 9, 16, 27], n=4 --> 3 # (1,5), (1,5), (5,9) [1, 1, 3, 3], n=2 --> 4 # (1,3), (1,3), (1,3), (1,3) ```
reference
def int_diff(arr, n): num = 0 for i in range(len(arr)): for j in range(i + 1, len(arr)): if abs(arr[i] - arr[j]) == n: num += 1 return num
Integer Difference
57741d8f10a0a66915000001
[ "Fundamentals" ]
https://www.codewars.com/kata/57741d8f10a0a66915000001
7 kyu
The sum of `x` consecutive integers is `y`. What is the consecutive integer at position `n`? Given `x`, `y`, and `n`, solve for the integer. Assume the starting position is 0. For example, if the sum of 4 consecutive integers is 14, what is the consecutive integer at position 3? We find that the consecutive integers are `[2, 3, 4, 5]`, so the integer at position 3 is `5`. ```python position(4, 14, 3) == 5 ``` Assume there will always be a sum of `x` consecutive integers that totals to `y` and `n` will never be indexed out of bounds.
algorithms
def position(x, y, n): return (y - sum(range(x))) / / x + n
Sums of consecutive integers
55b54be931e9ce28bc0000d6
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/55b54be931e9ce28bc0000d6
7 kyu
Given a mixed array of number and string representations of integers, add up the non-string integers and subtract the total of the string integers. Return as a number.
reference
def div_con(lst): return sum(n if isinstance(n, int) else - int(n) for n in lst)
Divide and Conquer
57eaec5608fed543d6000021
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57eaec5608fed543d6000021
7 kyu
Convert integers to binary as simple as that. You would be given an integer as a argument and you have to return its binary form. To get an idea about how to convert a decimal number into a binary number, visit <a href="http://www.wikihow.com/Convert-from-Decimal-to-Binary" title="example">here</a>. **Notes**: negative numbers should be handled as <a href="http://en.wikipedia.org/wiki/Two's_complement" target="_blank" title="two's complement">two's complement</a>; assume all numbers are integers stored using 4 bytes (or 32 bits) in any language. Your output should ignore leading 0s. ### Examples (input --> output): ``` 3 --> "11" -3 -->"11111111111111111111111111111101" ``` *Be Ready for Large Numbers. Happy Coding ^_^*
reference
def to_binary(n): return "{:0b}" . format(n & 0xffffffff)
Convert Integer to Binary
55606aeebf1f0305f900006f
[ "Binary", "Fundamentals" ]
https://www.codewars.com/kata/55606aeebf1f0305f900006f
7 kyu
## Task Write a function that accepts two arguments and generates a sequence containing the integers from the first argument to the second inclusive. ## Input Pair of integers greater than or equal to `0`. The second argument will always be greater than or equal to the first. ## Example ```python generate_integers(2, 5) # --> [2, 3, 4, 5] ``` ```php generate_integers(2, 5) // --> [2, 3, 4, 5] ``` ```ruby generateIntegers(2, 5) # --> [2, 3, 4, 5] ``` ```javascript generateIntegers(2, 5) // --> [2, 3, 4, 5] ``` ```rust integer_series(2, 5) // --> vec![2, 3, 4, 5] ```
reference
def generate_integers(m, n): return list(range(m, n + 1))
Series of integers from m to n
5841f680c5c9b092950001ae
[ "Fundamentals" ]
https://www.codewars.com/kata/5841f680c5c9b092950001ae
7 kyu
Implement a function that receives two integers `m` and `n` and generates a sorted list of pairs `(a, b)` such that `m <= a <= b <= n`. The input `m` will always be smaller than or equal to `n` (e.g., `m <= n`) ## Example ``` m = 2 n = 4 result = [(2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)] ```
reference
def generate_pairs(m, n): return [(i, j) for i in range(m, n + 1) for j in range(i, n + 1)]
Pairs of integers from m to n
588e2a1ad1140d31cb00008c
[ "Fundamentals" ]
https://www.codewars.com/kata/588e2a1ad1140d31cb00008c
7 kyu
Write a function `generatePairs` (Javascript) / `generate_pairs` (Python / Ruby) that accepts an integer argument `n` and generates an array containing the pairs of integers `[a, b]` that satisfy the following conditions: ``` 0 <= a <= b <= n ``` The pairs should be sorted by increasing values of `a` then increasing values of `b`. For example, ``` javascript generatePairs(2) should return [ [0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2] ] ``` ``` python generate_pairs(2) should return [ [0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2] ] ``` ``` ruby generate_pairs(2) should return [ [0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2] ] ``` ```julia generatepairs(2) # should return [ (0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2) ] ``` ```cobol generatePairs(2) --> result = [ [0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2] ] ```
reference
def generate_pairs(n): return [[i, j] for i in range(n + 1) for j in range(i, n + 1)]
Pairs of integers from 0 to n
588e27b7d1140d31cb000060
[ "Fundamentals" ]
https://www.codewars.com/kata/588e27b7d1140d31cb000060
7 kyu
Reverse and invert all integer values in a given list. ``` reverse_invert([1,12,'a',3.4,87,99.9,-42,50,5.6]) = [-1,-21,-78,24,-5] ``` Remove all types other than integer.
reference
from math import copysign as sign def reverse_invert(lst): return [- int(sign(int(str(abs(x))[:: - 1]), x)) for x in lst if isinstance(x, int)]
Reverse and Invert
5899e054aa1498da6b0000cc
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5899e054aa1498da6b0000cc
7 kyu
Create a function that takes one positive three digit integer and rearranges its digits to get the maximum possible number. Assume that the argument is an integer. ```cpp Return -1 if the argument is not valid ``` Return `null` (`nil` for Ruby, `nothing` for Julia) if the argument is not valid. ```maxRedigit(123); // returns 321```
reference
def max_redigit(num): if isinstance(num, int) and 99 < num < 1000: return int("" . join(sorted(str(num), reverse=True)))
Rearrange Number to Get its Maximum
563700da1ac8be8f1e0000dc
[ "Fundamentals", "Arithmetic", "Mathematics", "Algorithms", "Logic", "Numbers", "Control Flow", "Basic Language Features", "Data Types", "Integers" ]
https://www.codewars.com/kata/563700da1ac8be8f1e0000dc
7 kyu
You are given a string of `n` lines, each substring being `n` characters long. For example: `s = "abcd\nefgh\nijkl\nmnop"` We will study the "horizontal" and the "vertical" **scaling** of this square of strings. A k-horizontal scaling of a string consists of replicating `k` times each character of the string (except '\n'). - Example: 2-horizontal scaling of s: => "aabbccdd\neeffgghh\niijjkkll\nmmnnoopp" A v-vertical scaling of a string consists of replicating `v` times each part of the squared string. - Example: 2-vertical scaling of s: => "abcd\nabcd\nefgh\nefgh\nijkl\nijkl\nmnop\nmnop" Function `scale(strng, k, v)` will perform a k-horizontal scaling and a v-vertical scaling. ``` Example: a = "abcd\nefgh\nijkl\nmnop" scale(a, 2, 3) --> "aabbccdd\naabbccdd\naabbccdd\neeffgghh\neeffgghh\neeffgghh\niijjkkll\niijjkkll\niijjkkll\nmmnnoopp\nmmnnoopp\nmmnnoopp" ``` Printed: ``` abcd -----> aabbccdd efgh aabbccdd ijkl aabbccdd mnop eeffgghh eeffgghh eeffgghh iijjkkll iijjkkll iijjkkll mmnnoopp mmnnoopp mmnnoopp ``` #### Task: - Write function `scale(strng, k, v)` k and v will be positive integers. If `strng == ""` return `""`.
reference
def scale(strng, k, n): words = strng . split() words_h = ("" . join(char * k for char in word) for word in words) return "\n" . join("\n" . join(word for _ in range(n)) for word in words_h)
Scaling Squared Strings
56ed20a2c4e5d69155000301
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/56ed20a2c4e5d69155000301
7 kyu
You're operating behind enemy lines, but your decryption device took a bullet and no longer operates. You need to write a code to unscramble the encrypted messages coming in from headquarters. Luckily, you remember how the encryption algorithm works. Each message you receive is a single string, with the blocks for each letter separated by a space. The blocks encoding the characters are made up of seemingly random characters and are of a variable length. For example, a two character word might look like: ```python "x20*6<xY y_r9L" ``` To decode this string, you add up only the numbers in each block: ```python sum of integers in "x20*6<xY" --> 2 + 0 + 6 = 8 sum of integers in "y_r9L" --> 9 ``` Then map these numbers to the corresponding letters of the alphabet, with 0 representing a space: ```python 0 : ' ' 1 : 'a' 2 : 'b' ... 26 : 'z' ``` So we have: ```python "x20*6<xY y_r9L" --> "8 9" --> "hi" ``` Note also, if the sum of the digits goes over 26, loop back to zero (standard modulo / remainder function, such that 27 == 0, 28 == 1, etc.). As such the previous code could have also been: ```python "x20*6<xY y875_r97L" --> "8 36" --> "8 9" --> "hi" ```
reference
from string import ascii_lowercase AZ = ' ' + ascii_lowercase def decrypt(msg): return '' . join( AZ[sum(int(b) for b in a if b . isdigit()) % 27] for a in msg . split())
Spy games - rebuild your decoder
586988b82e8d9cdc520003ac
[ "Fundamentals" ]
https://www.codewars.com/kata/586988b82e8d9cdc520003ac
6 kyu
Given a random string consisting of numbers, letters, symbols, you need to sum up the numbers in the string. Note: - Consecutive integers should be treated as a single number. eg, `2015` should be treated as a single number `2015`, NOT four numbers - All the numbers should be treaded as positive integer. eg, `11-14` should be treated as two numbers `11` and `14`. Same as `3.14`, should be treated as two numbers `3` and `14` - If no number was given in the string, it should return `0` Example: ``` str = "In 2015, I want to know how much does iPhone 6+ cost?" ``` The numbers are `2015`, `6` Sum is `2021`.
reference
import re def sum_from_string(string): d = re . findall("\d+", string) return sum(int(i) for i in d)
Sum up the random string
55da6c52a94744b379000036
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/55da6c52a94744b379000036
7 kyu
Your task is to return an output string that translates an input string `s` by replacing each character in `s` with a number representing the number of times that character occurs in `s` and separating each number with the `sep` character(s). **Example (s, sep --> Output)** ``` "hello world", "-" --> "1-1-3-3-2-1-1-2-1-3-1" "19999999" , ":" --> "1:7:7:7:7:7:7:7" "^^^**$" , "x" --> "3x3x3x2x2x1" ```
reference
def freq_seq(s, sep): return sep . join([str(s . count(i)) for i in s])
Frequency sequence
585a033e3a36cdc50a00011c
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/585a033e3a36cdc50a00011c
7 kyu
Given a string, turn each character into its ASCII character code and join them together to create a number - let's call this number `total1`: ``` 'ABC' --> 'A' = 65, 'B' = 66, 'C' = 67 --> 656667 ``` Then replace any incidence of the number `7` with the number `1`, and call this number 'total2': ``` total1 = 656667 ^ total2 = 656661 ^ ``` Then return the difference between the sum of the digits in `total1` and `total2`: ``` (6 + 5 + 6 + 6 + 6 + 7) - (6 + 5 + 6 + 6 + 6 + 1) ------------------------- 6 ```
reference
def calc(s): total1 = '' . join(map(lambda c: str(ord(c)), s)) total2 = total1 . replace('7', '1') return sum(map(int, total1)) - sum(map(int, total2))
Char Code Calculation
57f75cc397d62fc93d000059
[ "Fundamentals", "Arrays", "Strings", "Mathematics" ]
https://www.codewars.com/kata/57f75cc397d62fc93d000059
7 kyu
Given a string made up of letters a, b, and/or c, switch the position of letters a and b (change a to b and vice versa). Leave any incidence of c untouched. Example: 'acb' --> 'bca'<br> 'aabacbaa' --> 'bbabcabb'
reference
def switcheroo(s): return s . translate(str . maketrans('ab', 'ba'))
Switcheroo
57f759bb664021a30300007d
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57f759bb664021a30300007d
7 kyu
Write a function that takes a list (in Python) or array (in other languages) of numbers, and makes a copy of it. Note that you may have troubles if you do not return an actual copy, item by item, just a pointer or an alias for an existing list or array. If not a list or array is given as a parameter in interpreted languages, the function should raise an error. Examples: ```python t = [1, 2, 3, 4] t_copy = copy_list(t) t[1] += 5 t = [1, 7, 3, 4] t_copy = [1, 2, 3, 4] ``` ```javascript t = [1, 2, 3, 4] tCopy = copyList(t) t[1] += 5 t = [1, 7, 3, 4] tCopy = [1, 2, 3, 4] ``` ```csharp List<int> lst = new int[] {1, 2, 3, 4}.ToList(); List<int> lstCopy = lst.Copy(); lst[1] += 5; lst == {1, 7, 3, 4}; lstCopy == {1, 2, 3, 4}; ```
reference
def copy_list(l): return list(l)
Making Copies
53d2697b7152a5e13d000b82
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/53d2697b7152a5e13d000b82
7 kyu
Positive integers that are divisible exactly by the sum of their digits are called [Harshad numbers](https://en.wikipedia.org/wiki/Harshad_number). The first few Harshad numbers are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, ... We are interested in Harshad numbers where the product of its digit sum `s` and `s` with the digits reversed, gives the original number `n`. For example consider number 1729: * its digit sum, `s` = 1 + 7 + 2 + 9 = 19 * reversing `s` = 91 * and 19 \* 91 = 1729 --> the number that we started with. Complete the function which tests if a positive integer `n` is Harshad number, and returns `True` if the product of its digit sum and its digit sum reversed equals `n`; otherwise return `False`.
reference
def numberJoy(n): d_sum = sum(int(x) for x in list(str(n))) return n == d_sum * int(str(d_sum)[:: - 1])
Especially Joyful Numbers
570523c146edc287a50014b1
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/570523c146edc287a50014b1
7 kyu
Pig Latin is an English language game where the goal is to hide the meaning of a word from people not aware of the rules. So, the goal of this kata is to wite a function that encodes a single word string to pig latin. The rules themselves are rather easy: 1) The word starts with a vowel(a,e,i,o,u) -> return the original string plus "way". 2) The word starts with a consonant -> move consonants from the beginning of the word to the end of the word until the first vowel, then return it plus "ay". 3) The result must be lowercase, regardless of the case of the input. If the input string has any non-alpha characters, the function must return None, null, Nothing (depending on the language). 4) The function must also handle simple random strings and not just English words. 5) The input string has no vowels -> return the original string plus "ay". For example, the word "spaghetti" becomes "aghettispay" because the first two letters ("sp") are consonants, so they are moved to the end of the string and "ay" is appended.
games
def pig_latin(s): vowels = ['a', 'e', 'i', 'o', 'u'] word = s . lower() if not word . isalpha(): # Check for non alpha character return None if word[0] in vowels: # Check if word starts with a vowel return word + 'way' # Find the first vowel and add the beginning to the end for i, letter in enumerate(word): if letter in vowels: return word[i:] + word[: i] + 'ay' return word + 'ay' # No vowels
Single Word Pig Latin
558878ab7591c911a4000007
[ "Strings", "Games", "Regular Expressions" ]
https://www.codewars.com/kata/558878ab7591c911a4000007
6 kyu
For a given positive integer convert it into its English representation. All words are lower case and are separated with one space. No trailing spaces are allowed. To keep it simple, hyphens and the writing of the word 'and' both aren't enforced. (But if you are looking for some extra challenge, such an output will pass the tests.) Large number reference: http://en.wikipedia.org/wiki/Names_of_large_numbers (U.S., Canada and modern British) Input range: 1 -> `10**26` (`10**16` for JS) Examples: ```ruby int_to_english(1) == 'one' int_to_english(10) == 'ten' int_to_english(25161045656) == 'twenty five billion one hundred sixty one million forty five thousand six hundred fifty six' ``` ```python int_to_english(1) == 'one' int_to_english(10) == 'ten' int_to_english(25161045656) == 'twenty five billion one hundred sixty one million forty five thousand six hundred fifty six' ``` ```javascript intToEnglish(1) == 'one' intToEnglish(10) == 'ten' intToEnglish(25161045656) == 'twenty five billion one hundred sixty one million forty five thousand six hundred fifty six' ``` or ```ruby int_to_english(25161045656) == 'twenty five billion one hundred sixty-one million forty-five thousand six hundred and fifty-six' ``` ```python int_to_english(25161045656) == 'twenty five billion one hundred sixty-one million forty-five thousand six hundred and fifty-six' ``` ```javascript intToEnglish(25161045656) == 'twenty five billion one hundred sixty-one million forty-five thousand six hundred and fifty-six' ```
algorithms
WORDS = ((10 * * 24, 'septillion'), (10 * * 21, 'sextillion'), (10 * * 18, 'quintillion'), (10 * * 15, 'quadrillion'), (10 * * 12, 'trillion'), (10 * * 9, 'billion'), (10 * * 6, 'million'), (10 * * 3, 'thousand'), (10 * * 2, 'hundred'), (90, 'ninety'), (80, 'eighty'), (70, 'seventy'), (60, 'sixty'), (50, 'fifty'), (40, 'forty'), (30, 'thirty'), (20, 'twenty'), (19, 'nineteen'), (18, 'eighteen'), (17, 'seventeen'), (16, 'sixteen'), (15, 'fifteen'), (14, 'fourteen'), (13, 'thirteen'), (12, 'twelve'), (11, 'eleven'), (10, 'ten'), (9, 'nine'), (8, 'eight'), (7, 'seven'), (6, 'six'), (5, 'five'), (4, 'four'), (3, 'three'), (2, 'two'), (1, 'one')) def int_to_english(num): result = [] for word_value, word_name in WORDS: q, num = divmod(num, word_value) if q: if word_value >= 100: result . append(int_to_english(q)) result . append(word_name) if not num: return ' ' . join(result)
Integer to English
53c94a82689f84c2dd00007d
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/53c94a82689f84c2dd00007d
5 kyu
Create a function that transforms any positive number to a string representing the number in words. The function should work for all numbers between 0 and 999999. ### Examples ``` number2words(0) ==> "zero" number2words(1) ==> "one" number2words(9) ==> "nine" number2words(10) ==> "ten" number2words(17) ==> "seventeen" number2words(20) ==> "twenty" number2words(21) ==> "twenty-one" number2words(45) ==> "forty-five" number2words(80) ==> "eighty" number2words(99) ==> "ninety-nine" number2words(100) ==> "one hundred" number2words(301) ==> "three hundred one" number2words(799) ==> "seven hundred ninety-nine" number2words(800) ==> "eight hundred" number2words(950) ==> "nine hundred fifty" number2words(1000) ==> "one thousand" number2words(1002) ==> "one thousand two" number2words(3051) ==> "three thousand fifty-one" number2words(7200) ==> "seven thousand two hundred" number2words(7219) ==> "seven thousand two hundred nineteen" number2words(8330) ==> "eight thousand three hundred thirty" number2words(99999) ==> "ninety-nine thousand nine hundred ninety-nine" number2words(888888) ==> "eight hundred eighty-eight thousand eight hundred eighty-eight" ```
reference
words = "zero one two three four five six seven eight nine" + \ " ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty" + \ " thirty forty fifty sixty seventy eighty ninety" words = words . split(" ") def number2words(n): if n < 20: return words[n] elif n < 100: return words[18 + n / / 10] + ('' if n % 10 == 0 else '-' + words[n % 10]) elif n < 1000: return number2words(n / / 100) + " hundred" + (' ' + number2words(n % 100) if n % 100 > 0 else '') elif n < 1000000: return number2words(n / / 1000) + " thousand" + (' ' + number2words(n % 1000) if n % 1000 > 0 else '')
Write out numbers
52724507b149fa120600031d
[ "Fundamentals" ]
https://www.codewars.com/kata/52724507b149fa120600031d
5 kyu
Turn a given number (an integer > 0, < 1000) into the equivalent English words. For the purposes of this kata, no hyphen is needed in numbers 21-99. Examples: ``` wordify(1) == "one" wordify(12) == "twelve" wordify(17) == "seventeen" wordify(56) == "fifty six" wordify(90) == "ninety" wordify(326) == "three hundred twenty six" ``` _Based on "Speech module" mission from Checkio._
algorithms
EN = { # ones 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', # teens 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', # tens 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety' } def wordify(n): hundreds, tens = divmod(n, 100) tens, ones = divmod(tens, 10) tens *= 10 if tens == 10: tens += ones ones = 0 return ' ' . join([f" { EN . get ( hundreds )} hundred"] * bool(hundreds) + [f" { EN . get ( tens )} "] * bool(tens) + [f" { EN . get ( ones )} "] * (bool(ones) or not (bool(hundreds) or bool(tens))))
Wordify an integer
553a2461098c64ae53000041
[ "Algorithms" ]
https://www.codewars.com/kata/553a2461098c64ae53000041
6 kyu
In Math, an improper fraction is a fraction where the numerator (the top number) is greater than or equal to the denominator (the bottom number) For example: ```5/3``` (five third). A mixed numeral is a whole number and a fraction combined into one "mixed" number. For example: ```1 1/2``` (one and a half) is a mixed numeral. ## Task Write a function `convertToMixedNumeral` to convert the improper fraction into a mixed numeral. The input will be given as a ```string``` (e.g. ```'4/3'```). The output should be a ```string```, with a space in between the whole number and the fraction (e.g. ```'1 1/3'```). You do not need to reduce the result to its simplest form. For the purpose of this exercise, there will be no ```0```, ```empty string``` or ```null``` input value. However, the input can be: - a negative fraction - a fraction that does not require conversion - a fraction that can be converted into a whole number ## Example ```javascript convertToMixedNumeral('6/2') // '3' convertToMixedNumeral('74/3') // '24 2/3' convertToMixedNumeral('-504/26') // '-19 10/26' convertToMixedNumeral('9/18') // '9/18' ```
reference
def convert_to_mixed_numeral(parm): a, b = map(int, parm . split('/')) d, r = divmod(abs(a), b) s = (0 < a) - (a < 0) return parm if d == 0 else ('{}' + ' {}/{}' * (r != 0)). format(d * s, r, b)
Convert Improper Fraction to Mixed Numeral
574e4175ff5b0a554a00000b
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/574e4175ff5b0a554a00000b
7 kyu
## Task Complete the function that receives an array of strings (`arr`) as an argument and returns all the valid Roman numerals. Basic Roman numerals are denoted as: ``` I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 ``` For the purposes of this kata we will consider valid only the numbers in range 0 - 5000 (both exclusive) since numbers >= 5000 were written in a different way (you had to place a heavy bar over the numeral that meant it was multiplied with 1000). There are other ways of tackling this problem but the easiest is probably writing a Regular Expression. ### Let's break the problem down: To match a set of characters `/[1-9]/`(single digits) you should take into consideration the Roman numbers `I, II, III, IV, V, VI, VII, VIII, IX`. This could be done by testing with `/IX|IV|V?I{0,3}/`. This part `/I{0,3}/` matches `I, II or III` but we have a `V` appearing 0 or 1 times because of the `?` so `/V?I{0,3}/` would match `I,II,III,V,VI,VII or VIII`. However there is one flaw with this. Do you see it? It is the fact that it would also match an empty string `""` because of the {0,3}. In order to pass the tests you will have to **filter out the empty strings** as well. So the entire part matches `I to IX`(inclusive) but what about larger digits? Use the same logic for the digit in the tens place and the hundreds place. Be sure to wrap each part (units, tens, hundreds, thousands) in a pair of braces `(IX|IV|V?I{0,3})` and for the digit in the thousands place the logic is pretty straight forward, you just have to match `M` 0 to 4 times (since 5000 is not included). Wrap everything up with `^` and `$` to make sure you match the entire string (^ matches from the beginning of the string, while $ denotes the end, meaning there is nothing after that sign. ## Examples ``` ["I", "IIV", "IVI", "IX", "XII", "MCD"] ==> ["I", "IX", "XII", "MCD"] ["MMMMCMXCIX", "MMDCXLIV", "MMCIX", "CLD", "LCD"]) ==> ["MMMMCMXCIX", "MMDCXLIV", "MMCIX"] ``` Good luck!
reference
import re PATTERN = re . compile("^" "M{0,4}" # thousands "(CM|CD|D?C{,3})" # hundreds "(XC|XL|L?X{,3})" # tens "(IX|IV|V?I{,3})" # units "$") def valid_romans(arr): return [e for e in arr if e and PATTERN . match(e)]
Filter valid romans
58334362c5637ad0bb0001c2
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/58334362c5637ad0bb0001c2
6 kyu
Write a function `sum` that accepts an unlimited number of integer arguments, and adds all of them together. The function should reject any arguments that are not **integers**, and sum the remaining integers. ```ruby sum(1, 2, 3) # => 6 sum(1, '2', 3) # => 4 ``` ```python sum(1, 2, 3) ==> 6 sum(1, "2", 3) ==> 4 ``` ```javascript sum(1, 2, 3) // -> 6 sum(1, "2", 3) // -> 4 ```
reference
from __builtin__ import sum as builtin_sum def sum(* args): return builtin_sum(arg for arg in args if isinstance(arg, int))
Unlimited Sum
536c738e49aa8b663b000301
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/536c738e49aa8b663b000301
7 kyu
Our standard numbering system is base-10, that uses digits `0` through `9`. Binary is base-2, using only `1`s and `0`s. And hexadecimal is base-16, using digits `0` to `9` and `A` to `F`. A hexadecimal `F` has a base-10 value of `15`. Base-64 has 64 individual characters ("digits") which translate to the base-10 values of `0` to `63`. These are (in ascending order): ``` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ ``` (so `A` is equal to `0` and `/` is equal to `63`) <!--Just as in standard (Base 10) when you get to the highest individual integer 9 the next number adds an additional place and starts at the beginning 10; so also (Base 64) when you get to the 63rd digit '/' and the next number adds an additional place and starts at the beginning "BA".--> ## Task Complete the method that will take a base-64 number (as a string) and output its base-10 value as an integer. ## Examples ```python "/" --> 63 "BA" --> 64 "BB" --> 65 "BC" --> 66 "WIN" --> 90637 ```
games
DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def base64_to_base10(string): return sum(DIGITS . index(digit) * 64 * * i for i, digit in enumerate(string[:: - 1]))
Base64 Numeric Translator
5632e12703e2037fa7000061
[ "Puzzles" ]
https://www.codewars.com/kata/5632e12703e2037fa7000061
5 kyu
One of the first algorithm used for approximating the integer square root of a positive integer `n` is known as "Hero's method", named after the first-century Greek mathematician Hero of Alexandria who gave the first description of the method. Hero's method can be obtained from Newton's method which came 16 centuries after. We approximate the square root of a number `n` by taking an initial guess `x`, an error `e` and repeatedly calculating a new approximate *integer* value `x` using: `(x + n / x) / 2`; we are finished when the previous `x` and the `new x` have an absolute difference less than `e`. We supply to a function (int_rac) a number `n` (positive integer) and a parameter `guess` (positive integer) which will be our initial `x`. For this kata the parameter 'e' is set to `1`. Hero's algorithm is not always going to come to an exactly correct result! For instance: if n = 25 we get 5 but for n = 26 we also get 5. Nevertheless `5` is the *integer* square root of `26`. The kata is to return the count of the progression of integer approximations that the algorithm makes. Reference: <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method> Some examples: ``` int_rac(25,1): follows a progression of [1,13,7,5] so our function should return 4. int_rac(125348,300): has a progression of [300,358,354] so our function should return 3. int_rac(125348981764,356243): has a progression of [356243,354053,354046] so our function should return 3. ``` # You can use Math.floor (or similar) for each integer approximation. # Note for JavaScript, Coffescript, Typescript: Don't use the double bitwise NOT ~~ at each iteration if you want to have the same results as in the tests and the other languages.
reference
from itertools import count def int_rac(n, guess): for i in count(1): last_guess, guess = guess, (guess + n / / guess) / / 2 if abs(last_guess - guess) < 1: return i
Hero's root
55efecb8680f47654c000095
[ "Fundamentals" ]
https://www.codewars.com/kata/55efecb8680f47654c000095
7 kyu
### Task For a given list of digits `0` to `9`, return a list with the same digits in the same order, but with all `0`s paired. Pairing two `0`s generates one `0` at the location of the first one. ### Examples ``` input: [0, 1, 0, 2] paired: ^-----^ -> [0, 1, 2] kept: ^ input: [0, 1, 0, 0] paired: ^-----^ -> [0, 1, 0] kept: ^ ^ input: [1, 0, 7, 0, 1] paired: ^-----^ -> [1, 0, 7, 1] kept: ^ input: [0, 1, 7, 0, 2, 2, 0, 0, 1, 0] paired: ^--------^ ^--^ -> [0, 1, 7, 2, 2, 0, 1, 0] kept: ^ ^ ^ ``` ### Notes 1. Pairing happens from left to right. For each pairing, the second `0` will always be paired towards the first ( right to left ) 1. `0`s generated by pairing can NOT be paired again 1. ( void where not applicable: ) Don't modify the input array or you may fail to pass the tests ~~~if:lambdacalc ### Encodings purity: `LetRec` numEncoding: `Church` export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding ~~~
algorithms
from itertools import count def pair_zeros(arr, * args): c = count(1) return [elem for elem in arr if elem != 0 or next(c) % 2]
Pair Zeros
54e2213f13d73eb9de0006d2
[ "Algorithms", "Arrays", "Fundamentals", "Functional Programming" ]
https://www.codewars.com/kata/54e2213f13d73eb9de0006d2
7 kyu
Gigi is a clever monkey, living in the zoo, his teacher (animal keeper) recently taught him some knowledge of "0". In Gigi's eyes, "0" is a character contains some circle(maybe one, maybe two). So, a is a "0",b is a "0",6 is also a "0",and 8 have two "0" ,etc... Now, write some code to count how many "0"s in the text. Let us see who is smarter? You ? or monkey? Input always be a string(including words numbers and symbols),You don't need to verify it, but pay attention to the difference between uppercase and lowercase letters. Here is a table of characters: <table border="2" algin="center"><tr algin="center"><td width=100 >one zero</td><td>abdegopq069DOPQR &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; () <-- A pair of braces as a zero</td></tr></table><table border="2"><tr><td width=100 align="center">two zero</td><td>%&B8</td></tr></table> Output will be a number of "0".
games
def countzero(s): return sum(1 if c in 'abdegopq069DOPQR' else 2 if c in '%&B8' else 0 for c in s . replace('()', '0'))
Monkey's MATH 01: How many "ZERO"s?
56c2acc8c44a3ad6e400050a
[ "Strings", "Regular Expressions", "Puzzles" ]
https://www.codewars.com/kata/56c2acc8c44a3ad6e400050a
7 kyu
You have a string that consists of zeroes and ones. Now choose any two *adjacent* positions in the string: if one of them is `0`, and the other one is `1`, remove these two digits from the string. Return the length of the resulting (smallest) string that you can get after applying this operation multiple times? **Note:** after each operation, the remaining digits are separated by spaces and thus *not* adjacent anymore - see the examples below. ## Examples For `"01010"` the result should be `1`: ```python "01010" --> " 010" --> " 0" ``` For `"110100"` the result should be `2`: ```python "110100" --> "1 100" --> "1 0" ``` ## Input/Output - `[input]` string `s` The initial string. - `[output]` an integer The minimum length of the string that may remain after applying the described operations as many times as possible.
games
import re def zero_and_one(s): return len(re . sub("01|10", "", s))
Simple Fun #154: Zero And One
58ad09d6154165a1c80000d1
[ "Puzzles" ]
https://www.codewars.com/kata/58ad09d6154165a1c80000d1
7 kyu
<a href="http://imgur.com/tfJ9UWc"><img src="http://i.imgur.com/tfJ9UWcm.jpg" title="source: imgur.com" /></a> The image shows how we can obtain the Harmonic Conjugated Point of three aligned points A, B, C. - We choose any point L, that is not in the line with A, B and C. We form the triangle ABL - Then we draw a line from point C that intersects the sides of this triangle at points M and N respectively. - We draw the diagonals of the quadrilateral ABNM; they are AN and BM and they intersect at point K - We unit, with a line L and K, and this line intersects the line of points A, B and C at point D The point D is named the Conjugated Harmonic Point of the points A, B, C. You can get more knowledge related with this point at: (https://en.wikipedia.org/wiki/Projective_harmonic_conjugate) If we apply the theorems of Ceva (https://en.wikipedia.org/wiki/Ceva%27s_theorem) and Menelaus (https://en.wikipedia.org/wiki/Menelaus%27_theorem) we will have this formula: <a href="http://imgur.com/PfmzXU4"><img src="http://i.imgur.com/PfmzXU4.jpg?1" title="source: imgur.com" /></a> AC, in the above formula is the length of the segment of points A to C in this direction and its value is: ```AC = xA - xC``` Transform the above formula using the coordinates ```xA, xB, xC and xD``` The task is to create a function ```harmon_pointTrip()```, that receives three arguments, the coordinates of points xA, xB and xC, with values such that : ```xA < xB < xC```, this function should output the coordinates of point D for each given triplet, such that `xA < xD < xB < xC`, or to be clearer let's see some cases: ```python harmon_pointTrip(xA, xB, xC) ------> xD # the result should be expressed up to four decimals (rounded result) harmon_pointTrip(2, 10, 20) -----> 7.1429 # (2 < 7.1429 < 10 < 20, satisfies the constraint) harmon_pointTrip(3, 9, 18) -----> 6.75 ``` ```ruby harmon_pointTrip(xA, xB, xC) ------> xD # the result should be expressed up to four decimals (rounded result) harmon_pointTrip(2, 10, 20) -----> 7.1429 # (2 < 7.1429 < 10 < 20, satisfies the constraint) harmon_pointTrip(3, 9, 18) -----> 6.75 ``` ```javascript harmonPointTrip(xA, xB, xC) ------> xD # the result should be expressed as a string with `.toFixed(2)` harmonPointTrip(2, 10, 20) -----> "7.14" # (2 < 7.14 < 10 < 20, satisfies the constraint) harmonPointTrip(3, 9, 18) -----> "6.75" ``` ```coffeescript harmonPointTrip(xA, xB, xC) ------> xD # the result should be expressed as a string with `.toFixed(2)` harmonPointTrip(2, 10, 20) -----> "7.14" # (2 < 7.14 < 10 < 20, satisfies the constraint) harmonPointTrip(3, 9, 18) -----> "6.75" ``` ```haskell harmonPointTrip(xA, xB, xC) ------> xD # the result should be expressed as a string with the float result rounded to 2 decimal places (you can use: printf "%.2f") harmonPointTrip(2, 10, 20) -----> "7.14" # (2 < 7.14 < 10 < 20, satisfies the constraint) harmonPointTrip(3, 9, 18) -----> "6.75" ``` ```java harmPoints(xA, xB, xC) ------> xD # the result should be expressed up to four decimals (rounded result) harmPoints(2, 10, 20) -----> 7.1429 # (2 < 7.1429 < 10 < 20, satisfies the constraint) harmPoints(3, 9, 18) -----> 6.75 ``` ```csharp HarmPoints(xA, xB, xC) ------> xD # the result should be expressed up to four decimals (rounded result) HarmPoints(2, 10, 20) -----> 7.1429 # (2 < 7.1429 < 10 < 20, satisfies the constraint) HarmPoints(3, 9, 18) -----> 6.75 ``` ```clojure harmon-point-trip(xA, xB, xC) ------> xD # the result should be expressed up to four decimals (rounded result) harmon-point-trip(2, 10, 20) -----> 7.1429 # (2 < 7.1429 < 10 < 20, satisfies the constraint) harmon-point-trip(3, 9, 18) -----> 6.75 ``` Enjoy it and happy coding!!
reference
def harmon_pointTrip(xA, xB, xC): a, b, c = map(float, [xA, xB, xC]) # Yay for algebra! d = ((a * c) + (b * c) - (2 * a * b)) / (2 * c - a - b) return round(d, 4)
Calculate the Harmonic Conjugated Point of a Triplet of Aligned Points
5600e00e42bcb7b9dc00014e
[ "Fundamentals", "Mathematics", "Geometry" ]
https://www.codewars.com/kata/5600e00e42bcb7b9dc00014e
7 kyu
When landing an airplane manually, the pilot knows which runway he is using and usually has up to date wind information (speed and direction). This information alone does not help the pilot make a safe landing; what the pilot really needs to know is the speed of headwind, how much crosswind there is and from which side the crosswind is blowing relative to the plane. Let's imagine there is a system in the ATC tower with speech recognition that works so that when a pilot says "wind info" over the comms, the system will respond with a helpful message about the wind. Your task is to write a function that produces the response before it is fed into the text-to-speech engine. Input: * runway (string: "NN[L/C/R]"). NN is the runway's heading in tens of degrees. A suffix of L, C or R may be present and should be ignored. NN is between 01 and 36. * wind_direction (int). Direction wind is blowing from in degrees. Between 0 and 359. * wind_speed (int). Wind speed in knots Output: * a string in the following format: ```"(Head|Tail)wind N knots. Crosswind N knots from your (left|right)."``` The wind speeds must be correctly rounded integers. If the rounded headwind component is 0, "Head" should be used. Similarly, "right" in case crosswind component is 0. Calculating crosswind and headwind: ``` A = Angle of the wind from the direction of travel (radians) WS = Wind speed CW = Crosswind HW = Headwind CW = sin(A) * WS HW = cos(A) * WS ``` More information about wind component calculation: http://en.wikipedia.org/wiki/Tailwind
algorithms
from math import sin, cos, radians, fabs def wind_info(runway, wind_direction, wind_speed): rw = int(runway[: 2]) * 10 hw = round(cos(radians(wind_direction - rw)) * wind_speed) cw = int(round(sin(radians(wind_direction - rw)) * wind_speed)) return "{}wind {} knots. Crosswind {} knots from your {}." . format( 'Tail' if hw < 0 else 'Head', int(fabs(hw)), int(fabs(cw)), 'left' if cw < 0 else 'right')
Wind component calculation
542c1a6b25808b0e2600017c
[ "Mathematics", "Geometry", "Algorithms" ]
https://www.codewars.com/kata/542c1a6b25808b0e2600017c
6 kyu
Deferring a function execution can sometimes save a lot of execution time in our programs by *postponing* the execution to the latest possible instant of time, when we're sure that the time spent while executing it is worth it. Write a method `make_lazy` that takes in a function (symbol for Ruby) and the arguments to the function and returns another function (lambda for Ruby) which when invoked, returns the result of the original function invoked with the supplied arguments. For example: Given a function `add` function add (a, b) { return a + b; } One could make it *lazy* as: var lazy_value = make_lazy(add, 2, 3); The expression does not get evaluated at the moment, but only when you *invoke* `lazy_value` as: lazy_value() => 5 The above invokation then performs the sum. Please note: The functions that are passed to `make_lazy` may take one or more arguments and the number of arguments is not fixed.
reference
def make_lazy(f, * args, * * kwargs): return lambda: f(* args, * * kwargs)
Lazily executing a function
5458d4d2cbae2a9438000389
[ "Fundamentals" ]
https://www.codewars.com/kata/5458d4d2cbae2a9438000389
7 kyu
# Task Your task is to determine the relationship between the given point and the vector. Direction of the vector is important! To determine if the point is to the left or to the right, you should imagine yourself standing at the beginning of the vector and looking at the end of the vector. # Arguments You are given coordinates of a point and coordinates of a vector on 2D plane: `point = [x, y]` `vector = [[x, y], [x, y]]` (two points, direction is from first to second) Vectors always have non-zero length, so you don't have to check for that at this point. # Return Your function must return: `-1` if the point is to the left of the vector, `0` if the point is on the same line as vector, `1` if the point is to the right of the vector. # Do not repeat yourself! You can consider re-using solution of this kata in some of the next Geometry katas: * [Geometry A-1.1: Similar kata with precision handling and a check for zero vectors](http://www.codewars.com/kata/geometry-a-1-dot-1-modify-point-location-detector-to-handle-zero-length-vectors-and-precision-errors-dry) * [Geometry A-3: Checking if point belongs to the vector](http://www.codewars.com/kata/geometry-a-3-does-point-belong-to-the-vector-dry) * [Geometry B-1: Is point inside or outside a triangle?](http://www.codewars.com/kata/geometry-b-1-point-in-a-triangle)
algorithms
def point_vs_vector(point, vector): [ax, ay], [bx, by] = vector x, y = point cross = (bx - ax) * (y - ay) - (by - ay) * (x - ax) return (cross < 0) - (cross > 0)
[Geometry A-1] Locate point - to the right, to the left or on the vector?
554c8a93e466e794fe000001
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/554c8a93e466e794fe000001
5 kyu
Below is a right-angled triangle: ``` |\ | \ | \ | \ o | \ h | \ | θ \ |_______\ a ``` Your challange is to write a function (```missingAngle``` in C/C#, ```missing_angle``` in Ruby), that calculates the angle θ in degrees to the nearest integer. You will be given three arguments representing each side: o, h and a. One of the arguments equals zero. Use the length of the two other sides to calculate θ. You will not be expected to handle any erronous data in your solution.
algorithms
import math def missing_angle(h, a, o): if h == 0: radians = math . atan(o / a) elif a == 0: radians = math . asin(o / h) else: radians = math . acos(a / h) return round(math . degrees(radians))
Missing Angle
58417e9ab9c25c774500001f
[ "Algorithms", "Mathematics", "Geometry" ]
https://www.codewars.com/kata/58417e9ab9c25c774500001f
6 kyu
Write a simple function that takes polar coordinates (an angle in degrees and a radius) and returns the equivalent cartesian coordinates (rounded to 10 places). ``` For example: coordinates(90,1) => (0.0, 1.0) coordinates(45, 1) => (0.7071067812, 0.7071067812) ``` ~~~if:haskell Haskell: You don't need to round the results; approximate comparison is used in the tests. ~~~
games
from math import cos, sin, radians def coordinates(deg, r, precision=10): x, y = r * cos(radians(deg)), r * sin(radians(deg)) return round(x, precision), round(y, precision)
Cartesian coordinates from degree angle
555f43d8140a6df1dd00012b
[ "Algorithms", "Mathematics", "Geometry" ]
https://www.codewars.com/kata/555f43d8140a6df1dd00012b
7 kyu
Given some points (cartesian coordinates), return true if all of them lie on a line. Treat both an empty set and a single point as a line. ```javascript onLine([[1,2], [7, 4], [22, 9]]); // returns true onLine([[1,2], [-3, -14], [22, 9]]); // returns false ``` ```haskell onLine [(1,2), (7, 4), (22, 9)] `shouldBe` True onLine [(1,2), (-3, -14), (22, 9)] `shouldBe` False ``` ```ruby on_line([[1,2], [7, 4], [22, 9]]) => returns true on_line([[1,2], [-3, -14], [22, 9]]) => returns false ``` ```python on_line(((1,2), (7,4), (22,9)) == True on_line(((1,2), (-3,-14), (22,9))) == False ```
reference
def on_line(points): points = list(set(points)) def cross_product( a, b, c): return a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]) return all(cross_product(p, * points[: 2]) == 0 for p in points[2:])
Points On A Line
53b7bc844db8fde50800020a
[ "Arrays", "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/53b7bc844db8fde50800020a
6 kyu
<a href="http://imgur.com/wgfyNwC"><img src="http://i.imgur.com/wgfyNwC.jpg?1" title="source: imgur.com" /></a> We have a robot that was programmed to take only four directions: ```up, ('U')```, ```down ('D')```, ```right ('R')```, ```left ('L')```. It takes one direction at a time randomly and for each direction that takes, it moves a distance equal to 'length_step'. The field where the robot "walks" has no border lines or limits. You can see the movement of the robot from a starting point ```(0, 0)``` and doing 100 steps. (click "Run"): (Go to https://trinket.io/python/af9037fb12 if you don't see the animation) <iframe src="https://trinket.io/embed/python/af9037fb12?outputOnly=true" width="100%" height="400" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> We want to calculate the final distance from an initial position. For that we have to make the function ``` finaldist_crazyrobot()``` that receives: - a list of tuples(python)(or an array of arrays javascript, ruby), ```moves```. Each tuple (array ,js and ruby) having a direction and the length of the step. - the initial position, ```init_pos```, that are the coordinates (x0, y0) of the point where the robot is standing before it starts moving. Let's see an example in Python ```python init_pos = (0, 0) moves = [('R', 2), ('U', 3), ('L', 1), ('D', 6)] finaldist_crazyrobot(moves, init_pos) == 3.16227766017 ``` In javascript: ```javascript init_pos = [0, 0] moves = [['R', 2], ['U', 3], ['L', 1], ['D', 6]] finalDistCrazyRobot(moves, init_pos) == 3.16227766017 ``` In ruby: ```ruby init_pos = [0, 0] moves = [['R', 2], ['U', 3], ['L', 1], ['D', 6]] finaldist_crazyrobot(moves, init_pos) == 3.16227766017 ``` We read the moves of the above example as it follows: - The robot moves to the right a step two units long. - Then, it goes up a step three units long. - After, it moves to the left one unit length. - And finally, it goes down six units of length. The final point where the robot stops has coordinates ```(1, -3)```. So, the distance between ```(0, 0)``` and ```(1, -3)``` is ```3.16227766017``` Of course that the initial position may be different from ```[0, 0]```. Let's see a case in Python: ```python init_pos = (20, 18) moves = [('R', 32), ('D', 16), ('U', 31), ('L', 26), ('D', 14),('U', 4), ('R', 5), ('L', 16)] finaldist_crazyrobot(moves, init_pos) == 7.07106781187 # distance from (20, 18) to (15, 23) ``` In javacript: ```javascript init_pos = [20, 18] moves = [['R', 32], ['D', 16], ['U', 31], ['L', 26], ['D', 14],['U', 4], ['R', 5], ['L', 16]] finalDistCrazyRobot(moves, init_pos) == 7.07106781187 ``` In ruby: ```ruby init_pos = [20, 18] moves = [['R', 32], ['D', 16], ['U', 31], ['L', 26], ['D', 14],['U', 4], ['R', 5], ['L', 16]] finaldist_crazyrobot(moves, init_pos) == 7.07106781187 # distance from [20, 18] to [15, 23] ``` You do not have to round your result, the tests will do it for you. Your results will be compared to expected ones in terms of relative error. For this problem, our distances will be always positive. Our list, ```moves``` may be up to a thousand long. The units may be feet or meters. Our robot was programmed to "read" both English and International System. Enjoy iy!! (But, what a waste of money just to have a robot to do this.)
reference
def finaldist_crazyrobot(moves, init_pos): count = {"R": 0, "L": 0, "U": 0, "D": 0} for d, n in moves: count[d] += n x = count["R"] - count["L"] y = count["U"] - count["D"] return (x * * 2 + y * * 2) * * 0.5
A Crazy Robot? Who's is behind the scenes to make that?
56a313a0538696bcab000004
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Geometry" ]
https://www.codewars.com/kata/56a313a0538696bcab000004
6 kyu
Your job is to return the volume of a cup when given the diameter of the top, the diameter of the bottom and the height. You know that there is a steady gradient from the top to the bottom. You want to return the volume rounded to 2 decimal places. Exmples: ```python cup_volume(1, 1, 1)==0.79 cup_volume(10, 8, 10)==638.79 cup_volume(1000, 1000, 1000)==785398163.4 cup_volume(13.123, 123.12, 1)==4436.57 cup_volume(5, 12, 31)==1858.51 ``` ```ruby cup_volume(1, 1, 1)==0.79 cup_volume(10, 8, 10)==638.79 cup_volume(1000, 1000, 1000)==785398163.4 cup_volume(13.123, 123.12, 1)==4436.57 cup_volume(5, 12, 31)==1858.51 ``` ```javascript cupVolume(1, 1, 1); //returns 0.79 cupVolume(10, 8, 10); //returns 638.79 cupVolume(1000, 1000, 1000); //returns 785398163.4 cupVolume(13.123, 123.12, 1); //returns 4436.57 cupVolume(5, 12, 31); //returns 1858.51 ``` ```coffeescript cupVolume(1, 1, 1) # returns 0.79 cupVolume(10, 8, 10) # returns 638.79 cupVolume(1000, 1000, 1000) # returns 785398163.4 cupVolume(13.123, 123.12, 1) # returns 4436.57 cupVolume(5, 12, 31) # returns 1858.51 ``` You will only be passed positive numbers.
reference
from math import pi def cup_volume(d1, d2, h): return round(h / 12.0 * pi * (d1 * * 2 + d1 * d2 + d2 * * 2), 2)
Volume of a cup
56a13035eb55c8436a000041
[ "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/56a13035eb55c8436a000041
7 kyu
Given a grid of size m x n, calculate the total number of rectangles contained in this rectangle. All integer sizes and positions are counted. Examples(**Input1, Input2 --> Output**): ``` 3, 2 --> 18 4, 4 --> 100 ``` Here is how the 3x2 grid works (Thanks to GiacomoSorbi for the idea): 1 rectangle of size 3x2: ``` [][][] [][][] ``` 2 rectangles of size 3x1: ``` [][][] ``` 4 rectangles of size 2x1: ``` [][] ``` 2 rectangles of size 2x2 ``` [][] [][] ``` 3 rectangles of size 1x2: ``` [] [] ``` 6 rectangles of size 1x1: ``` [] ``` As you can see (1 + 2 + 4 + 2 + 3 + 6) = 18, and is the solution for the 3x2 grid. There is a very simple solution to this!
games
def number_of_rectangles(m, n): return n * m * (n + 1) * (m + 1) / 4
Number of Rectangles in a Grid
556cebcf7c58da564a000045
[ "Geometry", "Puzzles" ]
https://www.codewars.com/kata/556cebcf7c58da564a000045
7 kyu
For a given 2D vector described by cartesian coordinates of its initial point and terminal point in the following format: ~~~if-not:csharp ``` [[x1, y1], [x2, y2]] ``` ~~~ ~~~if:csharp ```csharp // Argument will be passed as a Vector2 public struct Vector2 { public Point2 Head; public Point2 Tail; public Vector2(Point2 tail, Point2 head) { this.Tail = tail; this.Head = head; } public Point2 this[int i] { get { return new Point2[] {this.Tail, this.Head}[i]; } } } public struct Point2 { public double X; public double Y; public Point2(double x, double y) { this.X = x; this.Y = y; } public double this[int i] { get { return new double[] {this.X, this.Y}[i]; } } } ``` ~~~ Your function must return the vector's length represented as a floating point number. Error must be within 1e-7. Coordinates can be integers or floating point numbers.
reference
def vector_length(vector): (x1, y1), (x2, y2) = vector return ((x1 - x2) * * 2 + (y1 - y2) * * 2) * * .5
[Geometry A-2]: Length of a vector
554dc2b88fbafd2e95000125
[ "Geometry", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/554dc2b88fbafd2e95000125
7 kyu
## Task Your challenge is to write a function named `getSlope`/`get_slope`/`GetSlope` that calculates the slope of the line through two points. ## Input ```if:javascript,python Each point that the function takes in is an array 2 elements long. The first number is the x coordinate and the second number is the y coordinate. If the line through the two points is vertical or if the same point is given twice, the function should return `null`/`None`. ``` ```if:c In C, the function `get_slope` is passed two `point` structures, each consisting of two `double` coordinates: `x` and `y`. double get_slope(point a, point b, bool *is_slope); If the line through the two points is vertical or if the same point is given twice, set the pointer `*is_slope` to `false`. ``` ```if:csharp `GetSlope` will take in two Point objects. If the line through the two points is vertical, or the two points are the same, return `null`. The Point object: ~~~ public class Point : System.Object { public double X; public double Y; public Point(double x, double y) { this.X = x; this.Y = y; } public override string ToString() { return $"({this.X}, {this.Y})"; } public override bool Equals(object point) { // Typechecking if (point == null || point.GetType() != this.GetType()) { return false; } return this.ToString() == point.ToString(); } } ~~~ ```
reference
def getSlope(p1, p2): return None if p1[0] == p2[0] else (p2[1] - p1[1]) / (p2[0] - p1[0])
Slope of a Line
53222010db0eea35ad000001
[ "Graphs", "Mathematics", "Geometry", "Algebra", "Fundamentals" ]
https://www.codewars.com/kata/53222010db0eea35ad000001
7 kyu
Find the length between 2 co-ordinates. The co-ordinates are made of integers between -20 and 20 and will be given in the form of a 2D array: (0,0) and (5,-7) would be [ [ 0 , 0 ] , [ 5, -7 ] ] The function must return the answer rounded to 2 decimal places in the form of a string. ```javascript lengthOfLine([ [ 0 , 0 ] , [ 5, -7 ] ]); => "8.60" ``` ```python length_of_line([[0, 0], [5, -7]]) => "8.60" ``` ```ruby length_of_line([[0, 0], [5, -7]]) # => "8.60" ``` If the 2 given co-ordinates are the same, the returned length should be "0.00"
reference
from math import hypot def length_of_line(((x1, y1), (x2, y2))): return '{:.2f}' . format(hypot(x1 - x2, y1 - y2))
Length of the line segment
55f1786c296de4952f000014
[ "Mathematics", "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/55f1786c296de4952f000014
7 kyu
# Circle area inside square Turn an area of a square in to an area of a circle that fits perfectly inside the square. ![inscribed circle](data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjIwLjEwMyIgaGVpZ2h0PSIyMjAuMTAyIiB2aWV3Qm94PSIwIDAgNTguMjM2IDU4LjIzNSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtNTkuNjg1IC0xMTcuNTE1KSI+PHBhdGggc3R5bGU9ImZpbGw6IzFmMTZjZTtzdHJva2Utd2lkdGg6LjI2NDU4MyIgZD0iTTU5LjY4NiAxMTcuNTE1aDU4LjIzNXY1OC4yMzVINTkuNjg2eiIvPjxjaXJjbGUgc3R5bGU9ImZpbGw6I2QzMGEwZDtzdHJva2Utd2lkdGg6LjQwMzA0MyIgY3g9Ijg4LjgwMyIgY3k9IjE0Ni42MzIiIHI9IjI5LjExOCIvPjwvZz48L3N2Zz4=) You get the blue+red area and need to calculate the red area. Your function gets a number which represents the area of the square and should return the area of the circle. The tests are rounded by 8 decimals to make sure multiple types of solutions work. You don't have to worry about error handling or negative number input: `area >= 0`. This kata might be simpler than you expect, but good luck!
algorithms
from math import pi def square_area_to_circle(size): return size * pi / 4
Circle area inside square
5899aa695401a83a5c0000c4
[ "Mathematics", "Geometry", "Algorithms" ]
https://www.codewars.com/kata/5899aa695401a83a5c0000c4
7 kyu
Write a function `generateIntegers`/`generate_integers` that accepts a single argument `n`/`$n` and generates an array containing the integers from `0` to `n`/`$n` inclusive. For example, `generateIntegers(3)`/`generate_integers(3)` should return `[0, 1, 2, 3]`. `n`/`$n` can be any integer greater than or equal to `0`.
reference
def generate_integers(n): return list(range(0, n + 1))
Series of integers from 0 to n
5841f4fb673ea2a2ae000111
[ "Fundamentals" ]
https://www.codewars.com/kata/5841f4fb673ea2a2ae000111
7 kyu
SMS messages are limited to 160 characters. It tends to be irritating, especially when freshly written message is 164 characters long. Your task is to shorten the message to 160 characters, starting from end, by replacing spaces with camelCase, as much as necessary. If all the spaces are replaced but the resulting message is still longer than 160 characters, just return that resulting message. Example 1: Original message (169 chars): <pre> No one expects the Spanish Inquisition! Our chief weapon is surprise, fear and surprise; two chief weapons, fear, surprise, and ruthless efficiency! And that will be it. </pre> Shortened message (160 chars): <pre> No one expects the Spanish Inquisition! Our chief weapon is surprise, fear and surprise; two chief weapons, fear,Surprise,AndRuthlessEfficiency!AndThatWillBeIt. </pre> Example 2: Original message (269 chars): <pre> SMS messages are limited to 160 characters. It tends to be irritating, especially when freshly written message is 164 characters long. SMS messages are limited to 160 characters. It tends to be irritating, especially when freshly written message is 164 characters long. </pre> Shortened message (228 chars): <pre> SMSMessagesAreLimitedTo160Characters.ItTendsToBeIrritating,EspeciallyWhenFreshlyWrittenMessageIs164CharactersLong.SMSMessagesAreLimitedTo160Characters.ItTendsToBeIrritating,EspeciallyWhenFreshlyWrittenMessageIs164CharactersLong. </pre>
algorithms
def shortener(message): n = len(message) - 160 if n <= 0: return message message = message . rsplit(' ', n) return message[0] + '' . join(w[0]. upper() + w[1:] for w in message[1:])
SMS Shortener
535a69fb36973f2aad000953
[ "Algorithms", "Fundamentals", "Strings" ]
https://www.codewars.com/kata/535a69fb36973f2aad000953
6 kyu
Your job is to write a function which increments a string, to create a new string. - If the string already ends with a number, the number should be incremented by 1. - If the string does not end with a number. the number 1 should be appended to the new string. Examples: `foo -> foo1` `foobar23 -> foobar24` `foo0042 -> foo0043` `foo9 -> foo10` `foo099 -> foo100` *Attention: If the number has leading zeros the amount of digits should be considered.*
reference
def increment_string(strng): head = strng . rstrip('0123456789') tail = strng[len(head):] if tail == "": return strng + "1" return head + str(int(tail) + 1). zfill(len(tail))
String incrementer
54a91a4883a7de5d7800009c
[ "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/54a91a4883a7de5d7800009c
5 kyu
You need to write regex that will validate a password to make sure it meets the following criteria: * At least six characters long * contains a lowercase letter * contains an uppercase letter * contains a digit * only contains alphanumeric characters (note that `'_'` is not alphanumeric)
reference
from re import compile, VERBOSE regex = compile(""" ^ # begin word (?=.*?[a-z]) # at least one lowercase letter (?=.*?[A-Z]) # at least one uppercase letter (?=.*?[0-9]) # at least one number [A-Za-z\d] # only alphanumeric {6,} # at least 6 characters long $ # end word """, VERBOSE)
Regex Password Validation
52e1476c8147a7547a000811
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/52e1476c8147a7547a000811
5 kyu
# Task John was in math class and got bored, so he decided to fold some origami from a rectangular `a × b` sheet of paper (`a > b`). His first step is to make a square piece of paper from the initial rectangular piece of paper by folding the sheet along the bisector of the right angle and cutting off the excess part. <img src="http://codeforces.com/predownloaded/d0/a1/d0a1de56619814593b85b7b1187f50503834f3d0.png" style="background:white;padding:15px;margin:10px;margin-bottom:15px"/> After moving the square piece of paper aside, John wanted to make even more squares! He took the remaining (`a-b`) × `b` strip of paper and went on with the process until he was left with a square piece of paper. Your task is to determine how many square pieces of paper John can make. # Example: For: `a = 2, b = 1`, the output should be `2`. Given `a = 2` and `b = 1`, John can fold a `1 × 1` then another `1 × 1`. So the answer is `2`. For: `a = 10, b = 7`, the output should be `6`. We are given `a = 10` and `b = 7`. The following is the order of squares John folds: `7 × 7, 3 × 3, 3 × 3, 1 × 1, 1 × 1, and 1 × 1`. Here are pictures for the example cases. <img src="http://codeforces.com/predownloaded/51/e1/51e1faa7599f6b1eef93d0066d8942ce900ea774.png" style="background:white;padding:15px;margin:10px;margin-bottom:15px"/> # Input/Output - `[input]` integer `a` `2 ≤ a ≤ 1000` - `[input]` integer `b` `1 ≤ b < a ≤ 1000` - `[output]` an integer The maximum number of squares.
games
def folding(a, b): squares = 1 while a != b: squares += 1 b, a = sorted((a - b, b)) return squares
Simple Fun #190: Folding Paper
58bfa1ea43fadb41840000b4
[ "Puzzles" ]
https://www.codewars.com/kata/58bfa1ea43fadb41840000b4
7 kyu
# Task Let's say that `"g" is happy` in the given string, if there is another "g" immediately to the right or to the left of it. Find out if all "g"s in the given string are happy. # Example For `str = "gg0gg3gg0gg"`, the output should be `true`. For `str = "gog"`, the output should be `false`. # Input/Output - `[input]` string `str` A random string of lower case letters, numbers and spaces. - `[output]` a boolean value `true` if all `"g"`s are happy, `false` otherwise.
games
import re def happy_g(s): return not re . search(r'(?<!g)g(?!g)', s)
Simple Fun #182: Happy "g"
58bcd27b7288983803000002
[ "Puzzles", "Strings", "Regular Expressions" ]
https://www.codewars.com/kata/58bcd27b7288983803000002
7 kyu
# Task You are given a binary string (a string consisting of only '1' and '0'). The only operation that can be performed on it is a Flip operation. It flips any binary character ( '0' to '1' and vice versa) and all characters to the `right` of it. For example, applying the Flip operation to the 4th character of string "1001010" produces the "1000101" string, since all characters from the 4th to the 7th are flipped. Your task is to find the minimum number of flips required to convert the binary string to string consisting of all '0'. # Example For `s = "0101"`, the output should be `3`. It's possible to convert the string in three steps: ``` "0101" -> "0010" ^^^ "0010" -> "0001" ^^ "0001" -> "0000" ^ ``` # Input/Output - `[input]` string `s` A binary string. - `[output]` an integer The minimum number of flips required.
games
def bin_str(input): flips_needed = 0 last_seen = '0' for c in input: if last_seen != c: flips_needed += 1 last_seen = c return flips_needed
Simple Fun #194: Binary String
58c218efd8d3cad11c0000ef
[ "Puzzles" ]
https://www.codewars.com/kata/58c218efd8d3cad11c0000ef
7 kyu
# Task You are given a string `s`. Let us call a substring of `s` with 2 or more adjacent identical letters a *group* (such as `"aa"`, `"bbb"`, `"cccc"`...). Let us call a substring of `s` with 2 or more adjacent *groups* a *big group* (such as `"aabb","bbccc"`...). Your task is to count the number of `big groups` in the given string. # Examples * `"ccccoodeffffiiighhhhhhhhhhttttttts"` => `3` The groups are "cccc", "oo", "ffff", "iii", "hhhhhhhhhh", "ttttttt". The big groups are "ccccoo", "ffffiii", "hhhhhhhhhhttttttt". * `"gztxxxxxggggggggggggsssssssbbbbbeeeeeeehhhmmmmmmmitttttttlllllhkppppp"` => `2` The big groups are : "xxxxxggggggggggggsssssssbbbbbeeeeeeehhhmmmmmmm" and "tttttttlllll" * `"soooooldieeeeeer"` => `0` There is no `big group`. # Input/Output - `[input]` string `s` A string of lowercase Latin letters. - `[output]` an integer The number of big groups.
algorithms
from re import findall def repeat_adjacent(s): return len(findall(r"((.)\2+(?!\2)){2,}", s))
Simple Fun #180: Repeat Adjacent
58b8dccecf49e57a5a00000e
[ "Algorithms" ]
https://www.codewars.com/kata/58b8dccecf49e57a5a00000e
6 kyu
## Overview <a href="https://en.wikipedia.org/wiki/Resistor">Resistors</a> are electrical components marked with colorful stripes/bands to indicate both their resistance value in ohms and how tight a tolerance that value has. If you did my <a href="https://www.codewars.com/kata/57cf3dad05c186ba22000348">Resistor Color Codes</a> kata, you wrote a function which took a string containing a resistor's band colors, and returned a string identifying the resistor's ohms and tolerance values. Well, now you need that in reverse: The previous owner of your "Beyond-Ultimate <a href="https://en.wikipedia.org/wiki/Raspberry_Pi">Raspberry Pi</a> Starter Kit" (as featured in my <a href="https://www.codewars.com/kata/58485a43d750d23bad0000e6">Fizz Buzz Cuckoo Clock</a> kata) had emptied all the tiny labeled zip-lock bags of components into the box, so that for each resistor you need for a project, instead of looking for text on a label, you need to find one with the sequence of band colors that matches the ohms value you need. ## The resistor color codes You can see <a href="https://en.wikipedia.org/wiki/Electronic_color_code#Resistor_color-coding">this Wikipedia page</a> for a colorful chart, but the basic resistor color codes are: 0: black, 1: brown, 2: red, 3: orange, 4: yellow, 5: green, 6: blue, 7: violet, 8: gray, 9: white All resistors have at least three bands, with the first and second bands indicating the first two digits of the ohms value, and the third indicating the power of ten to multiply them by, for example a resistor with a value of 47 ohms, which equals 47 * 10^0 ohms, would have the three bands "yellow violet black". Most resistors also have a fourth band indicating tolerance -- in an electronics kit like yours, the tolerance will always be 5%, which is indicated by a gold band. So in your kit, the 47-ohm resistor in the above paragraph would have the four bands "yellow violet black gold". ## Your mission Your function will receive a string containing the ohms value you need, followed by a space and the word "ohms" (to avoid Codewars unicode headaches I'm just using the word instead of the ohms unicode symbol). The way an ohms value is formatted depends on the magnitude of the value: * For resistors less than 1000 ohms, the ohms value is just formatted as the plain number. For example, with the 47-ohm resistor above, your function would receive the string `"47 ohms"`, and return the string `"yellow violet black gold". * For resistors greater than or equal to 1000 ohms, but less than 1000000 ohms, the ohms value is divided by 1000, and has a lower-case "k" after it. For example, if your function received the string `"4.7k ohms"`, it would need to return the string `"yellow violet red gold"`. * For resistors of 1000000 ohms or greater, the ohms value is divided by 1000000, and has an upper-case "M" after it. For example, if your function received the string `"1M ohms"`, it would need to return the string `"brown black green gold"`. Test case resistor values will all be between 10 ohms and 990M ohms. ## More examples, featuring some common resistor values from your kit ``` "10 ohms" "brown black black gold" "100 ohms" "brown black brown gold" "220 ohms" "red red brown gold" "330 ohms" "orange orange brown gold" "470 ohms" "yellow violet brown gold" "680 ohms" "blue gray brown gold" "1k ohms" "brown black red gold" "10k ohms" "brown black orange gold" "22k ohms" "red red orange gold" "47k ohms" "yellow violet orange gold" "100k ohms" "brown black yellow gold" "330k ohms" "orange orange yellow gold" "2M ohms" "red black green gold" ``` Have fun!
reference
c = 'black brown red orange yellow green blue violet gray white' . split() def encode_resistor_colors(ohms_string): ohms = str(int(eval(ohms_string . replace( 'k', '*1000'). replace('M', '*1000000'). split()[0]))) return '%s %s %s gold' % (c[int(ohms[0])], c[int(ohms[1])], c[len(ohms[2:])])
Resistor Color Codes, Part 2
5855777bb45c01bada0002ac
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5855777bb45c01bada0002ac
5 kyu
## Overview <a href="https://en.wikipedia.org/wiki/Resistor">Resistors</a> are electrical components marked with colorful stripes/bands to indicate both their resistance value in ohms and how tight a tolerance that value has. While you could always get <a href="https://www.wired.com/2013/01/resistor-code-arm-tattoo/">a tattoo like Jimmie Rodgers</a> to help you remember the <a href="https://en.wikipedia.org/wiki/Electronic_color_code#Resistor_color-coding">resistor color codes</a>, in the meantime, you can write a function that will take a string containing a resistor's band colors and return a string identifying the resistor's ohms and tolerance values. ## The resistor color codes You can see <a href="https://en.wikipedia.org/wiki/Electronic_color_code#Resistor_color-coding">this Wikipedia page</a> for a colorful chart, but the basic resistor color codes are: black: 0, brown: 1, red: 2, orange: 3, yellow: 4, green: 5, blue: 6, violet: 7, gray: 8, white: 9 Each resistor will have at least three bands, with the first and second bands indicating the first two digits of the ohms value, and the third indicating the power of ten to multiply them by, for example a resistor with the three bands "yellow violet black" would be 47 * 10^0 ohms, or 47 ohms. Most resistors will also have a fourth band that is either gold or silver, with gold indicating plus or minus 5% tolerance, and silver indicating 10% tolerance. Resistors that do not have a fourth band are rated at 20% tolerance. (There are also more specialized resistors which can have more bands and additional meanings for some of the colors, but this kata will not cover them.) ## Your mission The way the ohms value needs to be formatted in the string you return depends on the magnitude of the value: * For resistors less than 1000 ohms, return a string containing the number of ohms, a space, the word "ohms" followed by a comma and a space, the tolerance value (5, 10, or 20), and a percent sign. For example, for the "yellow violet black" resistor mentioned above, you would return `"47 ohms, 20%"`. * For resistors greater than or equal to 1000 ohms, but less than 1000000 ohms, you will use the same format as above, except that the ohms value will be divided by 1000 and have a lower-case "k" after it. For example, for a resistor with bands of "yellow violet red gold", you would return `"4.7k ohms, 5%"` * For resistors of 1000000 ohms or greater, you will divide the ohms value by 1000000 and have an upper-case "M" after it. For example, for a resistor with bands of "brown black green silver", you would return `"1M ohms, 10%"` Test case resistor values will all be between 10 ohms and 990M ohms. ## More examples, featuring some common resistor values ``` "brown black black" "10 ohms, 20%" "brown black brown gold" "100 ohms, 5%" "red red brown" "220 ohms, 20%" "orange orange brown gold" "330 ohms, 5%" "yellow violet brown silver" "470 ohms, 10%" "blue gray brown" "680 ohms, 20%" "brown black red silver" "1k ohms, 10%" "brown black orange" "10k ohms, 20%" "red red orange silver" "22k ohms, 10%" "yellow violet orange gold" "47k ohms, 5%" "brown black yellow gold" "100k ohms, 5%" "orange orange yellow gold" "330k ohms, 5%" "red black green gold" "2M ohms, 5%" ``` Have fun! And if you enjoy this kata, check out the sequel: <a href="https://www.codewars.com/kata/5855777bb45c01bada0002ac">Resistor Color Codes, Part 2</a>
reference
code = {'black': 0, 'brown': 1, 'red': 2, 'orange': 3, 'yellow': 4, 'green': 5, 'blue': 6, 'violet': 7, 'gray': 8, 'white': 9, 'gold': 5, 'silver': 10, '': 20} def decode_resistor_colors(bands): colors = (bands + ' '). split(' ') value = 10 * code[colors[0]] + code[colors[1]] value *= 10 * * code[colors[2]] tolerance = code[colors[3]] prefix = '' for p in 'kM': if value / / 1000: prefix = p value /= 1000 return "%g%s ohms, %d%%" % (value, prefix, tolerance)
Resistor Color Codes
57cf3dad05c186ba22000348
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57cf3dad05c186ba22000348
7 kyu
Write a function with the signature shown below: ```javascript function isIntArray(arr) { return true } ``` ```python def is_int_array(arr): return True ``` ```ruby def is_int_array(arr) true end ``` * returns `true / True` if every element in an array is an integer or a float with no decimals. * returns `true / True` if array is empty. * returns `false / False` for every other input.
reference
def is_int_array(a): return isinstance(a, list) and all(isinstance(x, (int, float)) and x == int(x) for x in a)
Is Integer Array?
52a112d9488f506ae7000b95
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/52a112d9488f506ae7000b95
6 kyu
An [IPv4 address](http://en.wikipedia.org/wiki/IP_address) is a 32-bit number that identifies a device on the internet. While computers read and write IP addresses as a 32-bit number, we prefer to read them in dotted-decimal notation, which is basically the number split into 4 chunks of 8 bits, converted to decimal, and delmited by a dot. In this kata, you will create the function `ipToNum` (or `ip_to_num`, depending on the language) that takes an `ip` address and converts it to a number, as well as the function `numToIp` (or `num_to_ip`) that takes a number and converts it to an IP address string. Input will always be valid. ## Conversion Example ```javascript //original IP address 192.168.1.1 //breaks down into 4 binary octets 11000000 . 10101000 . 00000001 . 00000001 //which are merged together (unsigned 32-bit binary) 11000000101010000000000100000001 //and finally converted to base 10 3232235777 ``` Note that the binary octets are *unsigned* (so we can't have negative numbers). ```if:javascript,coffeescript,typescript,purescript Be careful: JavaScript does bitwise arithmetic on *signed* 32-bits integers. ``` ## Examples ### ipToNum / ip_to_num ``` '192.168.1.1' converts to 3232235777 '10.0.0.0' converts to 167772160 '176.16.0.1' converts to 2953838593 ``` ### numToIp / num_to_ip ``` 3232235777 converts to '192.168.1.1' 167772160 converts to '10.0.0.0' 2953838593 converts to '176.16.0.1' ```
reference
from ipaddress import IPv4Address def ip_to_num(ip): return int(IPv4Address(ip)) def num_to_ip(num): return str(IPv4Address(num))
IP Address to Number
541a354c39c5efa5fa001372
[ "Strings", "Binary", "Networks", "Fundamentals" ]
https://www.codewars.com/kata/541a354c39c5efa5fa001372
6 kyu
Create `range` generator function that will take up to 3 parameters - start value, step and stop value. This function should return an iterable object with numbers. For simplicity, assume all parameters to be positive numbers. Examples: - range(5) --> 1,2,3,4,5 - range(3, 7) --> 3,4,5,6,7 - range(2, 3, 15) --> 2,5,8,11,14
reference
def range_function(* args, start=1, step=1): if len(args) == 1: stop = args[0] elif len(args) == 2: start, stop = args else: start, step, stop = args return range(start, stop + 1, step)
Range function
584ebd7a044a1520f20000d5
[ "Fundamentals" ]
https://www.codewars.com/kata/584ebd7a044a1520f20000d5
6 kyu
Given an array, find the duplicates in that array, and return a new array of those duplicates. The elements of the returned array should appear in the order when they first appeared as duplicates. __*Note*__: numbers and their corresponding string representations should not be treated as duplicates (i.e., `"1" != 1`). ## Examples ``` [1, 2, 4, 4, 3, 3, 1, 5, 3, "5"] ==> [4, 3, 1] [0, 1, 2, 3, 4, 5] ==> [] ```
reference
def duplicates(array): seen = [] dups = [] for char in array: if char not in seen: seen . append(char) elif char not in dups: dups . append(char) return dups
Find Duplicates
5558cc216a7a231ac9000022
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5558cc216a7a231ac9000022
7 kyu
Say you have a ratings system. People can rate a page, and the average is displayed on the page for everyone to see. One way of storing such a running average is to keep the the current average as well as the total rating that all users have submitted and with how many people rated it, so that the average can be calculated and updated when a new rating has been made. There are a couple of minor problems with this: first, you're keeping 3 columns instead of 1, which isn't ideal. Second is, if you're not careful, the number could get too large and get less and less accurate as the data format tries to keep up. So what you need to do is this: write a function that takes the `current` average, the current number of ratings (data `points`) made, and a new value to `add` to the average; then return the new value. That way, you only need 2 columns in your database, and the number will not get crazy large over time. To be clear: ``` current = 0.5 points = 2 add = 1 --> 0.6666666666666666666666666666666666 // (2/3) ``` There are also plenty of examples in the example tests.
algorithms
def add_to_average(current, points, add): return (current * points + add) / (points + 1)
Differential Averaging
52c32ef251f31ae8f50000ae
[ "Mathematics", "Algebra", "Algorithms" ]
https://www.codewars.com/kata/52c32ef251f31ae8f50000ae
7 kyu
Implement a function which takes a sequence of objects and a property name, and returns a sequence containing the named property of each object. For example: ```javascript pluck([{a:1}, {a:2}], 'a') // -> [1,2] pluck([{a:1, b:3}, {a:2}], 'b') // -> [3, undefined] ``` ```python pluck([{'a':1}, {'a':2}], 'a') # -> [1,2] pluck([{'a':1, 'b':3}, {'a':2}], 'b') # -> [3, None] ``` If an object is missing the property, you should just leave it as `undefined/None` in the output array.
reference
def pluck(objs, name): return [item . get(name) for item in objs]
Pluck
530017aac7c0f49926000084
[ "Functional Programming", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/530017aac7c0f49926000084
7 kyu
You are given an array of `n+1` integers `1` through `n`. In addition there is a single duplicate integer. The array is unsorted. An example valid array would be `[3, 2, 5, 1, 3, 4]`. It has the integers `1` through `5` and `3` is duplicated. `[1, 2, 4, 5, 5]` would not be valid as it is missing `3`. You should return the duplicate value as a single integer.
refactoring
def find_dup(arr): for i in arr: if arr . count(i) != 1: return i
Find The Duplicated Number in a Consecutive Unsorted List
558dd9a1b3f79dc88e000001
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/558dd9a1b3f79dc88e000001
7 kyu
Why would we want to stop to only 50 shades of grey? Let's see to how many we can go. Write a function that takes a number n as a parameter and return an array containing n shades of grey in hexadecimal code (`#aaaaaa` for example). The array should be sorted in ascending order starting with `'#010101'`, `'#020202'`, etc. (using lower case letters). Examples: ``` n = 1: ["#010101"] n = 10: ["#010101", "#020202", "#030303", "#040404", "#050505", "#060606", "#070707", "#080808", "#090909", "#0a0a0a"] ``` As a reminder, the grey color is composed by the same number of red, green and blue: `#010101`, `#aeaeae`, or `#555555`. Black: `#000000` and white: `#ffffff` are not accepted values. When `n` is negative, just return an empty array. If `n` is higher than 254, just return an array of 254 elements. Have fun!
reference
def shades_of_grey(n): return ['#{0:02x}{0:02x}{0:02x}' . format(i + 1) for i in range(min(254, n))]
254 shades of grey
54d22119beeaaaf663000024
[ "Fundamentals", "Strings", "Algorithms" ]
https://www.codewars.com/kata/54d22119beeaaaf663000024
7 kyu
Take the following IPv4 address: `128.32.10.1`. This address has 4 octets where each octet is a single byte (or 8 bits). * 1st octet 128 has the binary representation: 10000000 * 2nd octet 32 has the binary representation: 00100000 * 3rd octet 10 has the binary representation: 00001010 * 4th octet 1 has the binary representation: 00000001 So `128.32.10.1` == `10000000.00100000.00001010.00000001` Because the above IP address has 32 bits, we can represent it as the 32 bit number: 2149583361. Write a function `ip_to_int32(ip)` ( **JS**: `ipToInt32(ip)` ) that takes an IPv4 address and returns a 32 bit number. ### Example ```text "128.32.10.1" => 2149583361 ```
reference
def ip_to_int32(ip): """ Take the following IPv4 address: 128.32.10.1 This address has 4 octets where each octet is a single byte (or 8 bits). 1st octet 128 has the binary representation: 10000000 2nd octet 32 has the binary representation: 00100000 3rd octet 10 has the binary representation: 00001010 4th octet 1 has the binary representation: 00000001 So 128.32.10.1 == 10000000.00100000.00001010.00000001 Because the above IP address has 32 bits, we can represent it as the 32 bit number: 2149583361. Write a function ip_to_int32(ip) ( JS: ipToInt32(ip) ) that takes an IPv4 address and returns a 32 bit number. ip_to_int32("128.32.10.1") => 2149583361 """ addr = ip . split(".") res = int(addr[0]) << 24 res += int(addr[1]) << 16 res += int(addr[2]) << 8 res += int(addr[3]) return res
IPv4 to int32
52ea928a1ef5cfec800003ee
[ "Networks", "Algorithms", "Bits", "Binary", "Fundamentals" ]
https://www.codewars.com/kata/52ea928a1ef5cfec800003ee
6 kyu
Your task is to return the sum of Triangular Numbers up-to-and-including the `nth` Triangular Number. Triangular Number: "any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc." ``` [01] 02 [03] 04 05 [06] 07 08 09 [10] 11 12 13 14 [15] 16 17 18 19 20 [21] ``` e.g. If `4` is given: `1 + 3 + 6 + 10 = 20`. Triangular Numbers cannot be negative so return 0 if a negative number is given.
reference
def sum_triangular_numbers(n): return n * (n + 1) * (n + 2) / 6 if n > 0 else 0
Sum of Triangular Numbers
580878d5d27b84b64c000b51
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/580878d5d27b84b64c000b51
7 kyu
# Task Consider a string of lowercase Latin letters and space characters (" "). First, rearrange the letters in each word `alphabetically`. And then rearrange the words in ascending order of the sum of their characters' `ASCII` values. If two or more words have the same `ASCII` value, rearrange them by their length in ascending order; If their length still equals to each other, rearrange them `alphabetically`. Finally, return the result. # Example For `s = "batman is bruce wayne"`, the result should be `"is bceru aenwy aamntb"`. ``` After rearranging the letters the string turns into "aamntb is bceru aenwy". The ASCII values of each word are: [627, 220, 529, 548]. After sorting the words the following string is obtained: "is bceru aenwy aamntb" (with ASCII values of [220, 529, 548, 627]).``` For `s = "peter parker is spiderman"`, the result should be `"is eeprt aekprr adeimnprs"` `(ASCII values: [220, 554, 645, 963])` # Input/Output - `[input]` string `s` A string of lowercase words. Each word is separated by exactly one space character. - `[output]` a string
reference
def revamp(s): words = ['' . join(sorted(word)) for word in s . split()] words . sort(key=lambda word: (sum(map(ord, word)), len(word), word)) return ' ' . join(words)
Simple Fun #185: Revamp
58bcfe1e23fee9fd95000007
[ "Fundamentals" ]
https://www.codewars.com/kata/58bcfe1e23fee9fd95000007
6 kyu
# Task Imagine a white rectangular grid of `n` rows and `m` columns divided into two parts by a diagonal line running from the upper left to the lower right corner. Now let's paint the grid in two colors according to the following rules: ``` A cell is painted black if it has at least one point in common with the diagonal; Otherwise, a cell is painted white. ``` Count the number of cells painted black. # Example For n = 3 and m = 4, the output should be `6` There are 6 cells that have at least one common point with the diagonal and therefore are painted black. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/countBlackCells/img/example1.jpg?_tm=1474285619565) For n = 3 and m = 3, the output should be `7` 7 cells have at least one common point with the diagonal and are painted black. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/countBlackCells/img/example2.jpg?_tm=1474285619707) # Input/Output - `[input]` integer `n` The number of rows. Constraints: 1 ≤ n ≤ 10000. - `[input]` integer `m` The number of columns. Constraints: 1 ≤ m ≤ 10000. - `[output]` an integer The number of black cells.
games
from fractions import gcd def count_black_cells(h, w): return (h + w) - 2 + gcd(h, w)
Simple Fun #19: Count Black Cells
588475d575431d0a0e000023
[ "Puzzles" ]
https://www.codewars.com/kata/588475d575431d0a0e000023
6 kyu
An orderly trail of ants is marching across the park picnic area. It looks something like this: <pre style="background:black;margin-bottom:20px"> ..ant..ant.ant...ant.ant..ant.ant....ant..ant.ant.ant...ant.. </pre> But suddenly there is a rumour that a dropped chicken sandwich has been spotted on the ground ahead. The ants surge forward! *Oh No, it's an ant stampede!!* Some of the slower ants are trampled, and their poor little ant bodies are broken up into scattered bits. The resulting carnage looks like this: <pre style="background:black;margin-bottom:20px"> ...ant...ant..<span style="color:red">nat</span>.ant.<span style="color:red">t</span>..ant...ant..ant..ant.<span style="color:red">an</span>ant..<span style="color:red">t</span> </pre> Can you find how many ants have died? <hr> ## Notes * When in doubt, assume that the scattered bits are from the same ant. e.g. 2 heads and 1 body = 2 dead ants, not 3
games
def deadAntCount(ants): return max(ants . count('a'), ants . count('n'), ants . count('t')) - ants . count('ant')
Dead Ants
57d5e850bfcdc545870000b7
[ "Algorithms", "Strings", "Puzzles" ]
https://www.codewars.com/kata/57d5e850bfcdc545870000b7
6 kyu
Create two functions to encode and then decode a string using the Rail Fence Cipher. This cipher is used to encode a string by placing each character successively in a diagonal along a set of "rails". First start off moving diagonally and down. When you reach the bottom, reverse direction and move diagonally and up until you reach the top rail. Continue until you reach the end of the string. Each "rail" is then read left to right to derive the encoded string. For example, the string `"WEAREDISCOVEREDFLEEATONCE"` could be represented in a three rail system as follows: ``` W E C R L T E E R D S O E E F E A O C A I V D E N ``` The encoded string would be: ``` WECRLTEERDSOEEFEAOCAIVDEN ``` Write a function/method that takes 2 arguments, a string and the number of rails, and returns the ENCODED string. Write a second function/method that takes 2 arguments, an encoded string and the number of rails, and returns the DECODED string. For both encoding and decoding, assume number of rails >= 2 and that passing an empty string will return an empty string. Note that the example above excludes the punctuation and spaces just for simplicity. There are, however, tests that include punctuation. Don't filter out punctuation as they are a part of the string.
algorithms
from itertools import chain def fencer(what, n): lst = [[] for _ in range(n)] x, dx = 0, 1 for c in what: lst[x]. append(c) if x == n - 1 and dx > 0 or x == 0 and dx < 0: dx *= - 1 x += dx return chain . from_iterable(lst) def encode_rail_fence_cipher(s, n): return '' . join(fencer(s, n)) def decode_rail_fence_cipher(s, n): lst = [''] * len(s) for c, i in zip(s, fencer(range(len(s)), n)): lst[i] = c return '' . join(lst)
Rail Fence Cipher: Encoding and Decoding
58c5577d61aefcf3ff000081
[ "Algorithms", "Ciphers", "Cryptography", "Strings", "Security" ]
https://www.codewars.com/kata/58c5577d61aefcf3ff000081
3 kyu
# Task "AL-AHLY" and "Zamalek" are the best teams in Egypt, but "AL-AHLY" always wins the matches between them. "Zamalek" managers want to know what is the best match they've played so far. The best match is the match they lost with the minimum goal difference. If there is more than one match with the same difference, choose the one "Zamalek" scored more goals in. Given the information about all matches they played, return the `index` of the best match (`0-based`). If more than one valid result, return the smallest index. # Example For `ALAHLYGoals = [6,4] and zamalekGoals = [1,2]`, the output should be 1 (2 in COBOL). Because `4 - 2` is less than `6 - 1` For `ALAHLYGoals = [1,2,3,4,5] and zamalekGoals = [0,1,2,3,4]`, the output should be 4. The goal difference of all matches are 1, but at 4<sup>th</sup> match "Zamalek" scored more goals in. So the result is 4 (5 in COBOL). # Input/Output - `[input]` integer array `ALAHLYGoals` The number of goals "AL-AHLY" scored in each match. - `[input]` integer array `zamalekGoals` The number of goals "Zamalek" scored in each match. It is guaranteed that `zamalekGoals[i] < ALAHLYGoals[i]` for each element. - `[output]` an integer Index of the best match. ~~~if:lambdacalc # Encodings purity: `LetRec` numEncoding: `Church` export constructors `nil, cons` for your `List` encoding ~~~
reference
def best_match(goals1, goals2): return min((a - b, - b, i) for i, (a, b) in enumerate(zip(goals1, goals2)))[2]
Simple Fun #166: Best Match
58b38256e51f1c2af0000081
[ "Fundamentals" ]
https://www.codewars.com/kata/58b38256e51f1c2af0000081
5 kyu
Write a method (or function, depending on the language) that converts a string to camelCase, that is, all words must have their first letter capitalized and spaces must be removed. #### Examples (input --> output): ``` "hello case" --> "HelloCase" "camel case word" --> "CamelCaseWord" ``` Don't forget to rate this kata! Thanks :)
algorithms
def camel_case(string): return string . title(). replace(" ", "")
CamelCase Method
587731fda577b3d1b0001196
[ "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/587731fda577b3d1b0001196
6 kyu
A bookseller has lots of books classified in 26 categories labeled A, B, ... Z. Each book has a code `c` of 3, 4, 5 or more characters. The **1st** character of a code is a capital letter which defines the book category. In the bookseller's stocklist each code `c` is followed by a space and by a positive integer n (int n >= 0) which indicates the quantity of books of this code in stock. For example an extract of a stocklist could be: ``` L = {"ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"}. or L = ["ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"] or .... ``` You will be given a stocklist (e.g. : L) and a list of categories in capital letters e.g : ``` M = {"A", "B", "C", "W"} or M = ["A", "B", "C", "W"] or ... ``` and your task is to find all the books of L with codes belonging to each category of M and to sum their quantity according to each category. For the lists L and M of example you have to return the string (in Haskell/Clojure/Racket/Prolog a list of pairs): ``` (A : 20) - (B : 114) - (C : 50) - (W : 0) ``` where A, B, C, W are the categories, 20 is the sum of the unique book of category A, 114 the sum corresponding to "BKWRK" and "BTSQZ", 50 corresponding to "CDXEF" and 0 to category 'W' since there are no code beginning with W. If L or M are empty return string is `""` (Clojure/Racket/Prolog should return an empty array/list instead). #### Notes: - In the result codes and their values are in the same order as in M. - See "Samples Tests" for the return.
reference
def stock_list(listOfArt, listOfCat): if (len(listOfArt) == 0) or (len(listOfCat) == 0): return "" result = "" for cat in listOfCat: total = 0 for book in listOfArt: if (book[0] == cat[0]): total += int(book . split(" ")[1]) if (len(result) != 0): result += " - " result += "(" + str(cat) + " : " + str(total) + ")" return result
Help the bookseller !
54dc6f5a224c26032800005c
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/54dc6f5a224c26032800005c
6 kyu
Due to another of his misbehaved, the primary school's teacher of the young Gauß, Herr J.G. Büttner, to keep the bored and unruly young schoolboy Karl Friedrich Gauss busy for a good long time, while he teaching arithmetic to his mates, assigned him the problem of adding up all the whole numbers from 1 through a given number `n`. Your task is to help the young Carl Friedrich to solve this problem as quickly as you can; so, he can astonish his teacher and rescue his recreation interval. Here's, an example: ``` f(n=100) // returns 5050 ``` It's your duty to verify that n is a valid positive integer number. If not, please, return false (None for Python, null for C#, 0 for COBOL). > **Note:** the goal of this kata is to invite you to think about some 'basic' mathematic formula and how you can do performance optimization on your code. > Advanced - experienced users should try to solve it in one line, without loops, or optimizing the code as much as they can. ----- **Credits:** this kata was inspired by the farzher's kata <a href="http://www.codewars.com/kata/54c2fc0552791928c9000517">'Sum of large ints' </a>. In fact, it can be seen as a sort of prep kata for that one.
reference
def f(n): return n * (n + 1) / / 2 if (n > 0 and isinstance(n, int)) else None
Gauß needs help! (Sums of a lot of numbers).
54df2067ecaa226eca000229
[ "Fundamentals", "Mathematics", "Performance" ]
https://www.codewars.com/kata/54df2067ecaa226eca000229
7 kyu
You have been employed by the Japanese government to write a function that tests whether or not a building is strong enough to withstand a simulated earthquake. A building will fall if the magnitude of the earthquake is greater than the strength of the building. An earthquake takes the form of a 2D-Array. Each element within the Outer-Array represents a shockwave, and each element within the Inner-Arrays represents a tremor. The magnitude of the earthquake is determined by the product of the values of its shockwaves. A shockwave is equal to the sum of the values of its tremors. Example earthquake --> `[[5,3,7],[3,3,1],[4,1,2]] ((5+3+7) * (3+3+1) * (4+1+2)) = 735` A building begins with a strength value of 1000 when first built, but this value is subject to exponential decay of 1% per year. For more info on exponential decay, follow this link - https://en.wikipedia.org/wiki/Exponential_decay Given an earthquake and the age of a building, write a function that returns "Safe!" if the building is strong enough, or "Needs Reinforcement!" if it falls.
reference
def strong_enough(earthquake, age): idade = 1000 magnitude = sum(earthquake[0]) * sum(earthquake[1]) * sum(earthquake[2]) for i in range(age): idade = idade - (0.01 * idade) if magnitude > idade: return 'Needs Reinforcement!' else: return 'Safe!'
Katastrophe!
55a3cb91d1c9ecaa2900001b
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/55a3cb91d1c9ecaa2900001b
7 kyu
Sequel (probably slighter harder): [Infinite Diceworks: MeanMaxing your rolls (Quantum Mechanically)](https://www.codewars.com/kata/infinite-diceworks-meanmaxing-your-rolls-quantum-mechanically) You recently developed the ability of ~~MinMax~~MeanMax, which means you can reroll a single dice roll as many times as you want, through the power of quantum mechanics or something! This should come in handy in many places where dice are involved, like this kata. But first, we need to talk about parallel universes, and how much better the odds become when you can roll simultaneously in many of them. Given the number of faces of the dice you're rolling `1<=dice<=1000` (the faces have values from 1 to `dice`) and number of rolls `2<=n<=100`, calculate the difference between the mean of *the maximum value of all the dice you rolled* to the mean of the same but for *just 1 roll*. Due to the intrinsic quantum fluctuation among the parallel universes (or so you're told), the error for the calculation results will be noticable. However, you're okay if the results does not differ more than `1/10000` from the actual value. An example: ```javascript meanMax(3,2) // Dice value: (1,2,3), rolls: 2 // Possibilities are: // 1: (1,1) // 2: (1,2), (2,1), (2,2) // 3: (1,3), (2,3), (3,1), (3,2), (3,3) // Mean: (1*1 + 2*3 + 3*5) / 9 = 2.4444... // Rolling the dice once gives a mean of 2, so the answer is // 2.4444... - 2 = 0.4444... ``` ```python mean_max(3,2) # Dice value: (1,2,3), rolls: 2 # Possibilities are: # 1: (1,1) # 2: (1,2), (2,1), (2,2) # 3: (1,3), (2,3), (3,1), (3,2), (3,3) # Mean: (1*1 + 2*3 + 3*5) / 9 = 2.4444... # Rolling the dice once gives a mean of 2, so the answer is # 2.4444... - 2 = 0.4444... ``` Additional challenge: Come up with at least 3 ways to solve this kata.
games
def mean_max(d, n): m = sum(i * (i * * n - (i - 1) * * n) for i in range(1, d + 1)) / (d * * n) return m - (1 + d) / 2
Infinite Diceworks: MeanMaxing your rolls
58db8dc3ac225602610000f2
[ "Mathematics", "Dynamic Programming", "Recursion", "Probability", "Statistics", "Puzzles" ]
https://www.codewars.com/kata/58db8dc3ac225602610000f2
6 kyu
Write the function `resistor_parallel` that receive an undefined number of resistances parallel resistors and return the total resistance. You can assume that there will be no 0 as parameter. Also there will be at least 2 arguments. Formula: `total = 1 / (1/r1 + 1/r2 + .. + 1/rn)` Examples: `resistor_parallel(20, 20)` will return `10.0` `resistor_parallel(20, 20, 40)` will return `8.0`
reference
def resistor_parallel(* rs): return 1 / sum(1.0 / r for r in rs)
Parallel resistors
5723b111101f5f905f0000a5
[ "Fundamentals" ]
https://www.codewars.com/kata/5723b111101f5f905f0000a5
7 kyu
Write a function called `sumIntervals`/`sum_intervals` that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. ### Intervals Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: `[1, 5]` is an interval from `1` to `5`. The length of this interval is `4`. ### Overlapping Intervals List containing overlapping intervals: ```c -- actual language id doesn't matter -- just want syntax highlighting [ [1, 4], [7, 10], [3, 5] ] ``` The sum of the lengths of these intervals is `7`. Since `[1, 4]` and `[3, 5]` overlap, we can treat the interval as `[1, 5]`, which has a length of `4`. ### Examples: ```c -- idem sumIntervals( [ [1, 2], [6, 10], [11, 15] ] ) => 9 sumIntervals( [ [1, 4], [7, 10], [3, 5] ] ) => 7 sumIntervals( [ [1, 5], [10, 20], [1, 6], [16, 19], [5, 11] ] ) => 19 sumIntervals( [ [0, 20], [-100000000, 10], [30, 40] ] ) => 100000030 ``` ### Tests with large intervals Your algorithm should be able to handle large intervals. All tested intervals are subsets of the range `[-1000000000, 1000000000]`. ~~~if:lambdacalc ### Encodings purity: `LetRec` numEncoding: `ScottBinary` ( subsets are actually in range `[0, 2000]` ) export constructor `Pair` for your `Pair` encoding export constructors `nil, cons` for your `List` encoding ~~~
algorithms
def sum_of_intervals(intervals): s, top = 0, float("-inf") for a, b in sorted(intervals): if top < a: top = a if top < b: s, top = s + b - top, b return s
Sum of Intervals
52b7ed099cdc285c300001cd
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/52b7ed099cdc285c300001cd
4 kyu
You are at the airport staring blankly at the arrivals/departures flap display... <div style="width:75%"><img src="http://www.airport-arrivals-departures.com/img/meta/1200_630_arrivals-departures.png"></div> # How it works You notice that each flap character is on some kind of a rotor and the order of characters on each rotor is: ```ABCDEFGHIJKLMNOPQRSTUVWXYZ ?!@#&()|<>.:=-+*/0123456789``` And after a long while you deduce that the display works like this: * Starting from the left, all rotors (from the current one to the end of the line) flap together until the left-most rotor character is correct. * Then the mechanism advances by 1 rotor to the right... * ...REPEAT this rotor procedure until the whole line is updated * ...REPEAT this line procedure from top to bottom until the whole display is updated # Example Consider a flap display with 3 rotors and one 1 line which currently spells ```CAT``` <hr><span style="color:red">Step 1</span>  (current rotor is 1) * Flap x 1 * Now line says ```DBU``` <hr><span style="color:red">Step 2</span>  (current rotor is 2) * Flap x 13 * Now line says ```DO)``` <hr><span style="color:red">Step 3</span>  (current rotor is 3) * Flap x 27 * Now line says ```DOG``` <hr> *This can be represented as* ``` lines // array of strings. Each string is a display line of the initial configuration rotors // array of array-of-rotor-values. Each array-of-rotor-values is applied to the corresponding display line result // array of strings. Each string is a display line of the final configuration ``` *e.g.* ``` lines = ["CAT"] rotors = [[1,13,27]] result = ["DOG"] ``` # Kata Task Given the initial display lines and the rotor moves for each line, determine what the board will say after it has been fully updated. For your convenience the characters of each rotor are in the pre-loaded constant ```ALPHABET``` which is a string. <hr> *And don't forget to try my other flap display Katas!* :-)
algorithms
def flap_display(lines, rotors): return [ # Find new string '' . join([ # Get new character by moving index of old # by sum of rotor values up to current symbol ALPHABET[(ALPHABET . index(smb) + sum(rot[: sid + 1])) % len(ALPHABET)] # Loop trough each character(smb) and its index(sid(from symbol id)) for sid, smb in enumerate(line) ]) # Loop trough each line and rotors, assigned to that line for line, rot in zip(lines, rotors) ]
Airport Arrivals/Departures - #1
57feb00f08d102352400026e
[ "Algorithms" ]
https://www.codewars.com/kata/57feb00f08d102352400026e
5 kyu
You're in a restaurant with your friends and it's time to go, but there's still one big problem...the bill. Who will pay what? Lucky for you, you've got your computer handy! One simple function and the bill is paid——fairly, too! The function should take one parameter: an object/dict with two or more name-value pairs that represent the members of the group and the amount spent by each. Your function should return an object/dict with the same names, showing how much money the members should pay or receive. **Further points:** * The values should be positive numbers if the person should receive money from the group, negative numbers if they owe money to the group. * If value is a decimal, round to two decimal places. Translations and comments (and upvotes!) welcome. ### Example 3 friends go out together: A spends £20, B spends £15, and C spends £10. The function should return an object/dict showing that A should receive £5, B should receive £0, and C should pay £5. ```javascript var group = { A: 20, B: 15, C: 10 } splitTheBill(group) // returns {A: 5, B: 0, C: -5} ``` ```python group = { 'A': 20, 'B': 15, 'C': 10 } split_the_bill(group) # returns {'A': 5, 'B': 0, 'C': -5} ``` ```ruby group = { 'A'=>20, 'B'=>15, 'C'=>10 } split_the_bill(group) # returns {'A'=>5, 'B'=>0, 'C'=>-5} ``` ```elixir group = %{ :A => 20, :B => 15, :C => 10 } split_the_bill(group) # returns %{:A => 5, :B => 0, :C => -5} ``` Good Luck and Happy Eats!
reference
def split_the_bill(x): diff = sum(x . values()) / float(len(x)) return {k: round(x[k] - diff, 2) for k in x}
Split The Bill
5641275f07335295f10000d0
[ "Fundamentals", "Data Structures" ]
https://www.codewars.com/kata/5641275f07335295f10000d0
7 kyu