description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
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 t...
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. 877...
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 se...
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 let...
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`...
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 ...
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)`. ...
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 s...
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: ```pyth...
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) retur...
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 char...
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 81337...
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...
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') ...
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 figh...
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...
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"...
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...
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...
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]) #...
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...
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` ar...
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 eit...
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), (...
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 ...
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**: negativ...
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_intege...
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 v...
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); /...
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 (excep...
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 e...
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`...
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-...
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 ...
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 la...
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...
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 orig...
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, lett...
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 pa...
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, 'seven...
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) ==> ...
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...
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 twe...
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'...
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 n...
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 (bot...
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 a...
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...
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 value...
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 ...
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: ^-----^ ...
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 tex...
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? **Not...
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 l...
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...
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...
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 ...
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 ...
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 re...
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 ...
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...
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 tha...
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)=...
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: ``` [...
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 Vec...
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 coord...
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 ...
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,PHN2ZyB3aWR0aD0iMjIwLjEwMyIgaGVpZ2h0PSIyMjAuMTAyIiB2aWV3Qm94PSIwIDAgNTguMjM2IDU4LjIzNSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyB0cmFuc2Zvcm09In...
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 me...
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` `foo004...
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. ...
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...
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 ...
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 gro...
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 ...
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...
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...
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 `tru...
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, a...
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) ...
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`)....
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 calcu...
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') ...
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 retu...
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'`,...
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 re...
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 representatio...
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...
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 the...
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 diag...
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. T...
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 unt...
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): retur...
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 differenc...
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 k...
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 ...
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 += " - " r...
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 give...
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 elem...
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 ...
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(...
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 alw...
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 ...
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...
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 ...
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