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 |
|---|---|---|---|---|---|---|---|
In this kata you have to write a method to verify the validity of IPv4 addresses.
Example of valid inputs:
"1.1.1.1"
"127.0.0.1"
"255.255.255.255"
Example of invalid input:
"1444.23.9"
"153.500.234.444"
"-12.344.43.11" | bug_fixes | from ipaddress import ip_address
def ipValidator(address):
try:
ip_address(address)
return True
except ValueError:
return False
| IPv4 Validator | 57193694938fcdfe3a001dd7 | [
"Fundamentals",
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/57193694938fcdfe3a001dd7 | 7 kyu |
# Fix the bug in Filtering method
The method is supposed to remove even numbers from the list and return a list that contains the odd numbers.
However, there is a bug in the method that needs to be resolved. | bug_fixes | def kata_13_december(lst):
return [item for item in lst if item & 1]
| Filtering even numbers (Bug Fixes) | 566dc566f6ea9a14b500007b | [
"Fundamentals",
"Debugging"
] | https://www.codewars.com/kata/566dc566f6ea9a14b500007b | 8 kyu |
# The museum of incredibly dull things
The museum of incredibly dull things wants to get rid of some exhibits. Miriam, the interior architect, comes up with a plan to remove the most boring exhibits. She gives them a rating, and then removes the one with the lowest rating.
However, just as she finished rating all exh... | reference | def remove_smallest(numbers):
a = numbers[:]
if a:
a . remove(min(a))
return a
| Remove the minimum | 563cf89eb4747c5fb100001b | [
"Lists",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/563cf89eb4747c5fb100001b | 7 kyu |
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.
For example, when an array is passed like `[19, 5, 42, 2, 77]`, the output should be `7`.
`[10, 343445353, 3453445, 3453545353453]` should return ... | reference | def sum_two_smallest_numbers(numbers):
return sum(sorted(numbers)[: 2])
| Sum of two lowest positive integers | 558fc85d8fd1938afb000014 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/558fc85d8fd1938afb000014 | 7 kyu |
You are given an array(list) `strarr` of strings and an integer `k`. Your task is to return the **first** longest string
consisting of k **consecutive** strings taken in the array.
#### Examples:
```
strarr = ["tree", "foling", "trashy", "blue", "abcdef", "uvwxyz"], k = 2
Concatenate the consecutive strings of strarr... | reference | def longest_consec(strarr, k):
result = ""
if k > 0 and len(strarr) >= k:
for index in range(len(strarr) - k + 1):
s = '' . join(strarr[index: index + k])
if len(s) > len(result):
result = s
return result
| Consecutive strings | 56a5d994ac971f1ac500003e | [
"Fundamentals"
] | https://www.codewars.com/kata/56a5d994ac971f1ac500003e | 6 kyu |
Be u(n) a sequence beginning with:
```
u[1] = 1, u[2] = 1, u[3] = 2, u[4] = 3, u[5] = 3, u[6] = 4,
u[7] = 5, u[8] = 5, u[9] = 6, u[10] = 6, u[11] = 6, u[12] = 8,
u[13] = 8, u[14] = 8, u[15] = 10, u[16] = 9, u[17] = 10, u[18] = 11,
u[19] = 11, u[20] = 12, u[21] = 12, u[22] = 12, u[23] = 12 etc...... | reference | from itertools import islice, count
def u1():
a = {1: 1, 2: 1}
yield a[1]
yield a[2]
for n in count(3):
a[n] = a[n - a[n - 1]] + a[n - a[n - 2]]
yield a[n]
def length_sup_u_k(n, k):
return len(list(filter(lambda x: x >= k, islice(u1(), 1, n))))
def comp(n):
ret... | Fibo akin | 5772382d509c65de7e000982 | [
"Algorithms",
"Recursion"
] | https://www.codewars.com/kata/5772382d509c65de7e000982 | 5 kyu |
You are given an array of integers. Implement a function which creates a complete binary tree from the array (*complete* meaning that every level of the tree, except possibly the last, is completely filled).
The elements of the array are to be taken left-to-right, and put into the tree top-to-bottom, left-to-right.
F... | algorithms | from preloaded import Node
def array_to_tree(arr, i=0):
if i >= len(arr):
return None
return Node(arr[i], array_to_tree(arr, 2 * i + 1), array_to_tree(arr, 2 * i + 2))
| Fun with trees: array to tree | 57e5a6a67fbcc9ba900021cd | [
"Trees",
"Arrays",
"Binary Trees",
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/57e5a6a67fbcc9ba900021cd | 5 kyu |
John and his wife Ann have decided to go to Codewars. On the first day Ann will do one kata and John - he wants to know how it is working - 0 kata.
Let us call `a(n)` - and `j(n)` - the number of katas done by Ann - and John - at day `n`. We have `a(0) = 1` and in the same manner `j(0) = 0`.
They have chosen the fol... | algorithms | def j_n(n):
j = [0]
a = [1]
for i in range(1, n):
j . append((i - a[j[i - 1]]))
a . append((i - j[a[i - 1]]))
return j, a
def john(n):
return j_n(n)[0]
def ann(n):
return j_n(n)[1]
def sum_john(n):
return sum(john(n))
def sum_ann(n):
return... | John and Ann sign up for Codewars | 57591ef494aba64d14000526 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/57591ef494aba64d14000526 | 5 kyu |
A **perfect binary tree** is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level.
You are given a class called TreeNode.
Implement the method `isPerfect` which determines if a given tree denoted by its root node is perfect.
Note: **TreeNode** class contains hel... | algorithms | from preloaded import TreeNode
def is_perfect(tree: TreeNode) - > bool:
def check_lvl(n: int, lvl: list[TreeNode]):
return not lvl or len(lvl) == n and check_lvl(
2 * n, [x for node in lvl for x in (node . left, node . right) if x]
)
return check_lvl(1, [tree] if tree else [])
| Fun with trees: is perfect | 57dd79bff6df9b103b00010f | [
"Trees",
"Recursion",
"Binary Trees",
"Binary Search Trees",
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/57dd79bff6df9b103b00010f | 5 kyu |
You are given a binary tree. Implement a function that returns the maximum sum of a route from root to leaf.
For example, given the following tree:
```
17
/ \
3 -10
/ / \
2 16 1
/
13
```
The function should return `23`, since `17 -> -10 -> 16` is the route from root to leaf wit... | algorithms | from preloaded import TreeNode
def max_sum(root: TreeNode) - > int:
if root is None:
return 0
elif root . left is None:
return root . value + max_sum(root . right)
elif root . right is None:
return root . value + max_sum(root . left)
else:
return root . value + max(max_sum(r... | Fun with trees: max sum | 57e5279b7cf1aea5cf000359 | [
"Trees",
"Recursion",
"Binary Trees",
"Binary Search Trees",
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/57e5279b7cf1aea5cf000359 | 6 kyu |
The Mormons are trying to find new followers and in order to do that they embark on missions.
Each time they go on a mission, each Mormon converts a fixed number of people (`reach`) into followers. This continues and every freshly converted Mormon as well as every original Mormon go on another mission and convert the ... | reference | def mormons(starting_number, reach, target):
missions = 0
while starting_number < target:
starting_number += starting_number * reach
missions += 1
return missions
# def mormons(start, reach, target, missions=0):
# if start >= target:
# return missions
# return mormons(start + (start ... | The Book of Mormon | 58373ba351e3b615de0001c3 | [
"Fundamentals",
"Mathematics",
"Recursion"
] | https://www.codewars.com/kata/58373ba351e3b615de0001c3 | 6 kyu |
Write a function that counts how many different ways you can make change for an amount of money, given an array of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2:
```
1+1+1+1, 1+1+2, 2+2.
```
The order of coins does not matter:
```
1+1+2 == 2+1+1
```
... | games | def count_change(money, coins):
if money < 0:
return 0
if money == 0:
return 1
if money > 0 and not coins:
return 0
return count_change(money - coins[- 1], coins) + count_change(money, coins[: - 1])
| Counting Change Combinations | 541af676b589989aed0009e7 | [
"Puzzles",
"Recursion"
] | https://www.codewars.com/kata/541af676b589989aed0009e7 | 4 kyu |
Given the string representations of two integers, return the string representation of the sum of those integers.
For example:
```javascript
sumStrings('1','2') // => '3'
```
```c
strsum("1", "2") /* => 3 */
```
A string representation of an integer will contain no characters besides the ten numerals "0" to "9".
I... | algorithms | def sum_strings(x, y):
l, res, carry = max(len(x), len(y)), "", 0
x, y = x . zfill(l), y . zfill(l)
for i in range(l - 1, - 1, - 1):
carry, d = divmod(int(x[i]) + int(y[i]) + carry, 10)
res += str(d)
return ("1" * carry + res[:: - 1]). lstrip("0") or "0"
| Sum Strings as Numbers | 5324945e2ece5e1f32000370 | [
"Strings",
"Big Integers",
"Algorithms"
] | https://www.codewars.com/kata/5324945e2ece5e1f32000370 | 4 kyu |
If you have completed the <a href="http://www.codewars.com/kata/tribonacci-sequence" target="_blank" title="Tribonacci sequence">Tribonacci sequence kata</a>, you would know by now that mister Fibonacci has at least a bigger brother. If not, give it a quick look to get how things work.
Well, time to expand the family ... | reference | def Xbonacci(signature, n):
output, x = signature[: n], len(signature)
while len(output) < n:
output . append(sum(output[- x:]))
return output
| Fibonacci, Tribonacci and friends | 556e0fccc392c527f20000c5 | [
"Arrays",
"Lists",
"Number Theory",
"Fundamentals"
] | https://www.codewars.com/kata/556e0fccc392c527f20000c5 | 6 kyu |
Well met with Fibonacci bigger brother, AKA Tribonacci.
As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :(
... | reference | def tribonacci(signature, n):
res = signature[: n]
for i in range(n - 3):
res . append(sum(res[- 3:]))
return res
| Tribonacci Sequence | 556deca17c58da83c00002db | [
"Number Theory",
"Arrays",
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/556deca17c58da83c00002db | 6 kyu |
Removed due to copyright infringement.
<!----
The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single `100`, `50` or `25` dollar bill. An "Avengers" ticket costs `25 dollars`.
Vasya is currently working as a clerk. He want... | reference | def tickets(people):
till = {100.0: 0, 50.0: 0, 25.0: 0}
for paid in people:
till[paid] += 1
change = paid - 25.0
for bill in (50, 25):
while (bill <= change and till[bill] > 0):
till[bill] -= 1
change -= bill
if change != 0:
return 'NO'
return 'YES'
| Vasya - Clerk | 555615a77ebc7c2c8a0000b8 | [
"Fundamentals",
"Mathematics",
"Algorithms",
"Logic",
"Numbers",
"Games"
] | https://www.codewars.com/kata/555615a77ebc7c2c8a0000b8 | 6 kyu |
We've got a message from the **Librarian**. As usual there're many `o` and `k` in it and, as all codewarriors don't know "Ook" language we need that you translate this message.
**tip** : it seems traditional "Hello World!" would look like :
`Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk? Ok, ... | games | SCORE = {'O': '0', 'o': '0', 'k': '1'}
def okkOokOo(s):
return '' . join(chr(int('' . join(SCORE . get(a, '') for a in word), 2))
for word in s . split('?'))
| Ookkk, Ok, O? Ook, Ok, Ooo! | 55035eb47451fb61c0000288 | [
"Strings",
"Binary",
"Puzzles"
] | https://www.codewars.com/kata/55035eb47451fb61c0000288 | 5 kyu |
Coding decimal numbers with factorials is a way of writing out numbers
in a base system that depends on factorials, rather than powers of numbers.
In this system, the last digit is always `0` and is in base 0!. The digit before that is either `0 or 1` and is in base 1!. The digit before that is either `0, 1, or 2` a... | algorithms | from math import factorial
from itertools import dropwhile
DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
BASIS = [factorial(n) for n in range(len(DIGITS))]
def dec2FactString(nb):
representation = []
for b in reversed(BASIS):
representation . append(DIGITS[nb / / b])
nb %= b
return ""... | Decimal to Factorial and Back | 54e320dcebe1e583250008fd | [
"Algorithms"
] | https://www.codewars.com/kata/54e320dcebe1e583250008fd | 5 kyu |
Removed due to copyright infringement.
<!---
Bob is preparing to pass IQ test. The most frequent task in this test is `to find out which one of the given numbers differs from the others`. Bob observed that one number usually differs from the others in **evenness**. Help Bob — to check his answers, he needs a program ... | reference | def iq_test(numbers):
e = [int(i) % 2 == 0 for i in numbers . split()]
return e . index(True) + 1 if e . count(True) == 1 else e . index(False) + 1
| IQ Test | 552c028c030765286c00007d | [
"Fundamentals",
"Logic"
] | https://www.codewars.com/kata/552c028c030765286c00007d | 6 kyu |
#### Once upon a time, on a way through the old wild *mountainous* west,…
… a man was given directions to go from one point to another. The directions were "NORTH", "SOUTH", "WEST", "EAST". Clearly "NORTH" and "SOUTH" are opposite, "WEST" and "EAST" too.
Going to one direction and coming back the opposite direction ... | reference | opposite = {'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'}
def dirReduc(plan):
new_plan = []
for d in plan:
if new_plan and new_plan[- 1] == opposite[d]:
new_plan . pop()
else:
new_plan . append(d)
return new_plan
| Directions Reduction | 550f22f4d758534c1100025a | [
"Fundamentals"
] | https://www.codewars.com/kata/550f22f4d758534c1100025a | 5 kyu |
From Wikipedia:
"A divisibility rule is a shorthand way of determining whether a given integer is divisible by a fixed divisor without performing the division, usually by examining its digits."
When you divide the successive powers of `10` by `13` you get the following remainders of the integer divisions:
`1, 10, ... | reference | array = [1, 10, 9, 12, 3, 4]
def thirt(n):
total = sum([int(c) * array[i % 6]
for i, c in enumerate(reversed(str(n)))])
if n == total:
return total
return thirt(total)
| A Rule of Divisibility by 13 | 564057bc348c7200bd0000ff | [
"Fundamentals",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/564057bc348c7200bd0000ff | 6 kyu |
Consider the following numbers (where `n!` is `factorial(n)`):
```
u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
...
un = (1 / n!) * (1! + 2! + 3! + ... + n!)
```
Which will win: `1 / n!` or `(1! + 2! + 3! + ... + n!)`?
Are these numbers going to `0` because of `1/n!` or to infinity du... | algorithms | def going(n):
s = 1.0
for i in range(2, n + 1):
s = s / i + 1
return int(s * 1e6) / 1e6
| Going to zero or to infinity? | 55a29405bc7d2efaff00007c | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/55a29405bc7d2efaff00007c | 5 kyu |
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infecte... | reference | def epidemic(tm, n, s, i, b, a):
def f(s, i, r):
dt = tm / n
for t in range(n):
s, i, r = s - dt * b * s * i, i + dt * (b * s * i - a * i), r + dt * i * a
yield i
return int(max(f(s, i, 0)))
| Disease Spread | 566543703c72200f0b0000c9 | [
"Fundamentals"
] | https://www.codewars.com/kata/566543703c72200f0b0000c9 | 6 kyu |
This is a follow-up from my previous Kata which can be found here: http://www.codewars.com/kata/5476f4ca03810c0fc0000098
This time, for any given linear sequence, calculate the function [f(x)] and return it as a function in Javascript or Lambda/Block in Ruby.
For example:
```javascript
getFunction([0, 1, 2, 3, 4])(5... | reference | def get_function(sequence):
slope = sequence[1] - sequence[0]
for x in range(1, 5):
if sequence[x] - sequence[x - 1] != slope:
return "Non-linear sequence"
return lambda a: slope * a + sequence[0]
| Calculate the function f(x) for a simple linear sequence (Medium) | 54784a99b5339e1eaf000807 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/54784a99b5339e1eaf000807 | 6 kyu |
Write a method, that will get an integer array as parameter and will process every number from this array.
Return a new array with processing every number of the input-array like this:
If the number has an integer square root, take this, otherwise square the number.
#### Example
```
[4,3,9,7,2,1] -> [2,9,3,49,4,1]
... | algorithms | def square_or_square_root(arr):
result = []
for x in arr:
root = x * * 0.5
if root . is_integer():
result . append(root)
else:
result . append(x * x)
return result
| To square(root) or not to square(root) | 57f6ad55cca6e045d2000627 | [
"Mathematics",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/57f6ad55cca6e045d2000627 | 8 kyu |
You need to write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples:
As the input may have trailing spaces, you will also need to ignore unneccesary whitespace.
Example (**Input** --> **Output**)
```
"Hello World" --> "World... | reference | def reverse(st):
# Your Code Here
return " " . join(st . split()[:: - 1])
| Reversing Words in a String | 57a55c8b72292d057b000594 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/57a55c8b72292d057b000594 | 8 kyu |
You were given a string of integer temperature values. Create a function `lowest_temp(t)` and return the lowest value or `None/null/Nothing` if the string is empty. | reference | def lowest_temp(t):
return min((int(x) for x in t . split()), default=None)
| Temperature analysis I | 588e0f11b7b4a5b373000041 | [
"Fundamentals"
] | https://www.codewars.com/kata/588e0f11b7b4a5b373000041 | 7 kyu |
The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8.
It's easy to see that the sum of the perimeters of these squares is :
` 4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80 `
Could you give the sum of the perimeters of all the squares in a rectangle when ... | algorithms | def fib(n):
a, b = 0, 1
for i in range(n + 1):
if i == 0:
yield b
else:
a, b = b, a + b
yield b
def perimeter(n):
return sum(fib(n)) * 4
| Perimeter of squares in a rectangle | 559a28007caad2ac4e000083 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/559a28007caad2ac4e000083 | 5 kyu |
The action of a Caesar cipher is to replace each plaintext letter (plaintext letters are from 'a' to 'z' or from 'A' to 'Z') with a different one a fixed number of places up or down the alphabet.
This program performs a variation of the Caesar shift. The shift increases by 1 for each **character** (on each iteration).... | reference | from string import ascii_lowercase as abc, ascii_uppercase as ABC
from math import ceil
def _code(string, shift, mode):
return '' . join(
abc[(abc . index(c) + i * mode + shift) % len(abc)] if c in abc else
ABC[(ABC . index(c) + i * mode + shift) % len(ABC)] if c in ABC else c
for ... | First Variation on Caesar Cipher | 5508249a98b3234f420000fb | [
"Fundamentals",
"Ciphers",
"Strings"
] | https://www.codewars.com/kata/5508249a98b3234f420000fb | 5 kyu |
At a job interview, you are challenged to write an algorithm to check if a given string, `s`, can be formed from two other strings, `part1` and `part2`.
The restriction is that the characters in `part1` and `part2` should be in the same order as in `s`.
The interviewer gives you the following example and tells you to... | algorithms | def is_merge(s, part1, part2):
if not part1:
return s == part2
if not part2:
return s == part1
if not s:
return part1 + part2 == ''
if s[0] == part1[0] and is_merge(s[1:], part1[1:], part2):
return True
if s[0] == part2[0] and is_merge(s[1:], part1, part2[1:]):
return T... | Merged String Checker | 54c9fcad28ec4c6e680011aa | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/54c9fcad28ec4c6e680011aa | 5 kyu |
In this kata you have to implement a base converter, which converts **positive integers** between arbitrary bases / alphabets. Here are some pre-defined alphabets:
```javascript
var Alphabet = {
BINARY: '01',
OCTAL: '01234567',
DECIMAL: '0123456789',
HEXA_DECIMAL: '0123456789abcdef',
AL... | algorithms | def convert(input, source, target):
base_in = len(source)
base_out = len(target)
acc = 0
out = ''
for d in input:
acc *= base_in
acc += source . index(d)
while acc != 0:
d = target[acc % base_out]
acc = acc / base_out
out = d + out
return out if out else targe... | Base Conversion | 526a569ca578d7e6e300034e | [
"Strings",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/526a569ca578d7e6e300034e | 6 kyu |
# Task
Given a string representing a simple fraction `x/y`, your function must return a string representing the corresponding [mixed fraction](http://en.wikipedia.org/wiki/Fraction_%28mathematics%29#Mixed_numbers) in the following format:
```[sign]a b/c```
where `a` is integer part and `b/c` is irreducible proper fra... | reference | def gcd(a, b): return b if not a else gcd(b % a, a)
def sign(a): return a if a == 0 else abs(a) / a
def mixed_fraction(s):
a, b = [int(x) for x in s . split("/")]
if int(b) == 0:
raise ZeroDivisionError
d, m = divmod(abs(a), abs(b))
g = gcd(m, b)
s = "-" if sign(a) * sign(b) ... | Simple fraction to mixed number converter | 556b85b433fb5e899200003f | [
"Fundamentals"
] | https://www.codewars.com/kata/556b85b433fb5e899200003f | 5 kyu |
Write a function named `first_non_repeating_letter`<sup>†</sup> that takes a string input, and returns the first character that is not repeated anywhere in the string.
For example, if given the input `'stress'`, the function should return `'t'`, since the letter *t* only occurs once in the string, and occurs first in ... | algorithms | def first_non_repeating_letter(string):
string_lower = string . lower()
for i, letter in enumerate(string_lower):
if string_lower . count(letter) == 1:
return string[i]
return ""
| First non-repeating character | 52bc74d4ac05d0945d00054e | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/52bc74d4ac05d0945d00054e | 5 kyu |
The drawing below gives an idea of how to cut a given "true" rectangle into squares ("true" rectangle meaning that the two dimensions are different).

Can you translate this drawing into an algorithm?
You will be given two dimensions
1. a positive integer length... | games | def sqInRect(lng, wdth):
if lng == wdth:
return None
if lng < wdth:
wdth, lng = lng, wdth
res = []
while lng != wdth:
res . append(wdth)
lng = lng - wdth
if lng < wdth:
wdth, lng = lng, wdth
res . append(wdth)
return res
| Rectangle into Squares | 55466989aeecab5aac00003e | [
"Fundamentals",
"Geometry",
"Puzzles"
] | https://www.codewars.com/kata/55466989aeecab5aac00003e | 6 kyu |
Build Tower
---
Build a pyramid-shaped tower, as an array/list of strings, given a positive integer `number of floors`. A tower block is represented with `"*"` character.
For example, a tower with `3` floors looks like this:
```
[
" * ",
" *** ",
"*****"
]
```
And a tower with `6` floors looks like this:
... | reference | def tower_builder(n):
return [("*" * (i * 2 - 1)). center(n * 2 - 1) for i in range(1, n + 1)]
| Build Tower | 576757b1df89ecf5bd00073b | [
"Strings",
"ASCII Art",
"Fundamentals"
] | https://www.codewars.com/kata/576757b1df89ecf5bd00073b | 6 kyu |
Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help.
## Task
You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (`*`) characters. Trailing space... | reference | def diamond(n):
if n < 0 or n % 2 == 0:
return None
result = "*" * n + "\n"
spaces = 1
n = n - 2
while n > 0:
current = " " * spaces + "*" * n + "\n"
spaces = spaces + 1
n = n - 2
result = current + result + current
return result
| Give me a Diamond | 5503013e34137eeeaa001648 | [
"Strings",
"ASCII Art",
"Fundamentals"
] | https://www.codewars.com/kata/5503013e34137eeeaa001648 | 6 kyu |
Everyone knows passphrases. One can choose passphrases from poems, songs, movies names and so on but frequently
they can be guessed due to common cultural references.
You can get your passphrases stronger by different means. One is the following:
choose a text in capital letters including or not digits and non alphab... | algorithms | def play_pass(s, n):
# Step 1, 2, 3
shiftText = ""
for char in s:
if char . isdigit():
shiftText += str(9 - int(char))
elif char . isalpha():
shifted = ord(char . lower()) + n
shiftText += chr(shifted) if shifted <= ord('z') else chr(shifted - 26)
else:
shiftText += c... | Playing with passphrases | 559536379512a64472000053 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/559536379512a64472000053 | 6 kyu |
# Description
Middle Earth is about to go to war. The forces of good will have many battles with the forces of evil. Different races will certainly be involved. Each race has a certain `worth` when battling against others. On the side of good we have the following races, with their associated `worth`:
* Hobbits: 1
... | algorithms | def goodVsEvil(good, evil):
points_good = [1, 2, 3, 3, 4, 10]
points_evil = [1, 2, 2, 2, 3, 5, 10]
good = sum([int(x) * y for x, y in zip(good . split(), points_good)])
evil = sum([int(x) * y for x, y in zip(evil . split(), points_evil)])
result = 'Battle Result: '
if good < evil:
... | Good vs Evil | 52761ee4cffbc69732000738 | [
"Algorithms"
] | https://www.codewars.com/kata/52761ee4cffbc69732000738 | 6 kyu |
Common denominators
You will have a list of rationals in the form
```
{ {numer_1, denom_1} , ... {numer_n, denom_n} }
or
[ [numer_1, denom_1] , ... [numer_n, denom_n] ]
or
[ (numer_1, denom_1) , ... (numer_n, denom_n) ]
```
where all numbers are positive ints.
You have to produce a result in the form:
```
(N... | reference | import math
import functools
def convertFracts(lst):
def lcm(a, b): return abs(a * b) / / math . gcd(a, b)
tmp_list = list(map(lambda x: x[1], list(lst)))
lcm_num = functools . reduce(lcm, tmp_list)
return list(map(lambda x: [x[0] * lcm_num / / x[1], lcm_num], list(lst)))
| Common Denominators | 54d7660d2daf68c619000d95 | [
"Fundamentals",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/54d7660d2daf68c619000d95 | 5 kyu |
There is a queue for the self-checkout tills at the supermarket. Your task is write a function to calculate the total time required for all the customers to check out!
### input
```if-not:c
* customers: an array of positive integers representing the queue. Each integer represents a customer, and its value is the amoun... | reference | def queue_time(customers, n):
l = [0] * n
for i in customers:
l[l . index(min(l))] += i
return max(l)
| The Supermarket Queue | 57b06f90e298a7b53d000a86 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57b06f90e298a7b53d000a86 | 6 kyu |
You might know some pretty large perfect squares. But what about the NEXT one?
Complete the `findNextSquare` method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.
If the argument is itself ... | reference | def find_next_square(sq):
root = sq ** 0.5
if root.is_integer():
return (root + 1)**2
return -1 | Find the next perfect square! | 56269eb78ad2e4ced1000013 | [
"Algebra",
"Fundamentals"
] | https://www.codewars.com/kata/56269eb78ad2e4ced1000013 | 7 kyu |
Implement a function that accepts 3 integer values a, b, c. The function should return true if a triangle can be built with the sides of given length and false in any other case.
(In this case, all triangles must have surface greater than 0 to be accepted).
Examples:
```
Input -> Output
1,2,2 -> true
4,2,3 -> true
2,... | reference | def is_triangle(a, b, c):
return (a<b+c) and (b<a+c) and (c<a+b) | Is this a triangle? | 56606694ec01347ce800001b | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/56606694ec01347ce800001b | 7 kyu |
You throw a ball vertically upwards with an initial speed `v (in km per hour)`. The height `h` of the ball at each time `t`
is given by `h = v*t - 0.5*g*t*t` where `g` is Earth's gravity `(g ~ 9.81 m/s**2)`. A device is recording at every **tenth of second** the height of the ball.
For example with `v = 15 km/h` the de... | reference | """
h = vt-0.5gt^2
let h = 0 [that is, when the ball has returned to the ground]
=> 0 = vt-0.5gt^2
=> 0.5gt^2 = vt
=> 0.5gt = v
=> t = 2v/g - the total time the ball is in the air.
=> t at max height = v/g
"""
def max_ball(v0):
return round(10*v0/9.81/3.6) | Ball Upwards | 566be96bb3174e155300001b | [
"Fundamentals"
] | https://www.codewars.com/kata/566be96bb3174e155300001b | 6 kyu |
Remember all those quadratic equations you had to solve by hand in highschool? Well, no more! You're going to solve all the quadratic equations you might ever[1] have to wrangle with in the future once and for all by coding up the [quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula) to handle them autom... | reference | from math import sqrt
def quadratic_formula(a, b, c):
delta = b * b - 4 * a *c
root1 = (-b - sqrt(delta)) / (2 * a)
root2 = (-b + sqrt(delta)) / (2 * a)
return [root1, root2] | Thinkful - Number Drills: Quadratic formula | 58635f1b2489549be50003f1 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/58635f1b2489549be50003f1 | 7 kyu |
John has some amount of money of which he wants to deposit a part `f0` to the bank at the beginning
of year `1`. He wants to withdraw each year for his living an amount `c0`.
Here is his banker plan:
- deposit `f0` at beginning of year 1
- his bank account has an interest rate of `p` percent per year, constant over t... | algorithms | def fortune(f, p, c, n, i):
for _ in range(n - 1):
f = int(f * (100 + p) / 100 - c)
c = int(c * (100 + i) / 100)
if f < 0:
return False
return True
| Banker's Plan | 56445c4755d0e45b8c00010a | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/56445c4755d0e45b8c00010a | 6 kyu |
Make a program that filters a list of strings and returns a list with only your friends name in it.
If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not...
~~~if-not:factor
Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yo... | reference | def friend(x):
return [f for f in x if len(f) == 4]
| Friend or Foe? | 55b42574ff091733d900002f | [
"Fundamentals"
] | https://www.codewars.com/kata/55b42574ff091733d900002f | 7 kyu |
This code does not execute properly. Try to figure out why. | bug_fixes | def multiply(a, b):
return a * b
| Multiply | 50654ddff44f800200000004 | [
"Debugging",
"Fundamentals"
] | https://www.codewars.com/kata/50654ddff44f800200000004 | 8 kyu |
#### Task
Allocate customers to hotel rooms based on their arrival and departure days. Each customer wants their own room, so two customers can stay in the same room only if the departure day of the first customer is earlier than the arrival day of the second customer. The number of rooms used should be minimized.
#... | algorithms | def allocate_rooms(customers):
res = [0] * len(customers)
dep = [0] * len(customers)
for i, (a, d) in sorted(enumerate(customers), key=lambda x: x[1]):
n = next(r for r, d in enumerate(dep) if d < a)
dep[n] = d
res[i] = n + 1
return res
| Allocating Hotel Rooms | 6638277786032a014d3e0072 | [
"Sorting"
] | https://www.codewars.com/kata/6638277786032a014d3e0072 | 6 kyu |
This kata was created as a contender for the EPIC Challenge 2024.
## Background
It's your dream to have a magical wedding day, and you're willing to spend *every last penny on it* — while simultaneously planning for a stable retirement income.
## Task
Your monthly surplus income (i.e., income after all taxes and ma... | reference | def max_wedding_cost(C, r, S, T, W):
p = 1 + r / 100
curr, req = 0, S
for _ in range(12 * (T - W)):
req = max((req - C) / p, 0)
for _ in range(12 * W):
curr = curr * p + C
return curr - req
| Plan Your Dream Wedding | 66314d6b7cb7030393dddf8a | [
"Mathematics"
] | https://www.codewars.com/kata/66314d6b7cb7030393dddf8a | 7 kyu |
This is an extreme version of [Chain Reaction - Minimum Bombs Needed]( https://www.codewars.com/kata/64c8a9b8f7c1b7000fdcdafb). You will be given a string that represents a 2D "map" such as this:
```
0+000x000xx
++000++000+
00x0x00000x
0+000000x+0
```
The string consists of three different characters (in addition to n... | algorithms | def min_bombs_needed(grid):
G = grid_to_graph(grid)
order = topologic_sort_with_scc(G)
return count_roots(G, order)
NEIGHS = {
'+': [(- 1, 0), (1, 0), (0, - 1), (0, 1)],
'x': [(- 1, 1), (1, 1), (- 1, - 1), (1, - 1)],
}
def grid_to_graph(grid):
grid = grid . split... | Chain Reaction - Minimum Bombs Needed (Extreme Version) | 65c420173817127b06ff7ea7 | [
"Algorithms",
"Graph Theory"
] | https://www.codewars.com/kata/65c420173817127b06ff7ea7 | 2 kyu |
### Disclaimer
This kata is in accordance with the EPIC challenge in relation to Andela's 10 year anniversary celebration. You can find more info [here](https://www.codewars.com/post/introducing-the-epic-challenge-2024)
### Story
ejini战神 has recently quit his programming job and is now opting in for a career change.... | reference | def cake_visualizer(s):
return '\n' . join(r[0] + ' ' * (len(r) - 3 >> 1) + '|' + ' ' * (len(r) - 3 >> 1) + r[- 1] for r in s . split('\n'))
| Visualization of Wedding Cakes | 662f64adf925ebceb6c5a4e4 | [
"Strings"
] | https://www.codewars.com/kata/662f64adf925ebceb6c5a4e4 | 7 kyu |
# Background
Today is the special day you've been waiting for — it's your birthday! It's 8 AM and you're setting up your birthday cake for the party. It's time to put the candles on top.
You take out all the candles you've bought. As you are about to put them on the cake, you just realize that there are numbers on ea... | algorithms | def blow_candles(st):
blow2 = blow1 = blows = 0
for candle in map(int, st):
blow0 = max(0, candle - blow1 - blow2)
blows += blow0
blow2, blow1 = blow1, blow0
return blows
| Blowing Birthday Candles | 6630da20f925eb3007c5a498 | [
"Algorithms"
] | https://www.codewars.com/kata/6630da20f925eb3007c5a498 | 7 kyu |
*Inspired by the emojify custom Python module.*
You are given a string made up of chains of emotes separated by **1** space each, with chains having **2** spaces in-between each.
Each emote represents a digit:
```
:) | 0
:D | 1
>( | 2
>:C | 3
:/ | 4
:| | 5
:O | 6
;) | 7
^.^ | 8
:( | 9
```
Each emote chain re... | games | def deemojify(string):
digits = {
':)': '0',
':D': '1',
'>(': '2',
'>:C': '3',
':/': '4',
':|': '5',
':O': '6',
';)': '7',
'^.^': '8',
':(': '9',
}
result = ''
for group in string . split(' '):
number = ''... | De-Emojify | 6627696c86b953001280675e | [
"Strings"
] | https://www.codewars.com/kata/6627696c86b953001280675e | 7 kyu |
Based off the game Counter-Strike
The bomb has been planted and you are the last CT (Counter Terrorist) alive
You need to defuse the bomb in time!
___
__Task:__
Given a matrix m and an integer time representing the seconds left before the bomb detonates, determine if it is possible to defuse the bomb in time. Th... | reference | def bomb_has_been_planted(m, time):
def dist(p1, p2): return max(abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))
p_ct = next((x, y) for x, row in enumerate(m)
for y, el in enumerate(row) if el == 'CT')
p_b = next((x, y) for x, row in enumerate(m)
for y, el in enumerate(row) if ... | Bomb has been planted! | 6621b92d6d4e8800178449f5 | [
"Arrays",
"Games"
] | https://www.codewars.com/kata/6621b92d6d4e8800178449f5 | 6 kyu |
# Task
Given a string `s` representing a 2D rectangular grid with rows separated by `'\n'`, empty tiles as `'.'`, the starting point `'p'` and a path from this point using arrows in <a href="https://en.wikipedia.org/wiki/Moore_neighborhood">Moore neighborhood</a> `'←↑→↓↖↗↘↙'`, return a string depicting that **same pat... | algorithms | d = {'←': (0, - 1), '↑': (- 1, 0), '→': (0, 1), '↓': (1, 0),
'↖': (- 1, - 1), '↗': (- 1, 1), '↘': (1, 1), '↙': (1, - 1)}
def transform(s):
s = s . splitlines()
t = [['q.' [c == '.'] for c in r] for r in s]
for y, r in enumerate(s):
for x, c in enumerate(r):
try:
dy, dx = d[c... | Arrow in/out transformation | 661bb565f54fde005b8e3d6c | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/661bb565f54fde005b8e3d6c | 6 kyu |
This kata is a generalization of the ["A Man And His Umbrellas"](https://www.codewars.com/kata/58298e19c983caf4ba000c8d) kata by [mattlub](https://www.codewars.com/users/mattlub). If you haven't completed that kata, you may wish to do so before attempting this one.
A man travels to different locations. If it is rainy,... | algorithms | def required_umbrellas(travels: list[tuple[str, str]]) - > dict[str, int]:
res = {place: 0 for place, _ in travels} | {'home': 0}
cur_state, cur_place = {k: 0 for k in res}, 'home'
for place, state in travels:
if state == 'rainy':
if cur_state[cur_place] == 0:
res[cur_place] += 1
cur_state[c... | A Wandering Man and his Umbrellas | 661aa2008fa7ab015ee33529 | [
"Logic",
"Arrays"
] | https://www.codewars.com/kata/661aa2008fa7ab015ee33529 | 6 kyu |
<h2> Description: </h2>
Jury has a list called `lis` consisting of <b>integers</b> that you have to guess. Your function is passed two arguments: `n - length of lis` and `guess - the function that takes three arguments a, b and c`, and returns:
```python
min(lis[a],lis[b]) if c = "min"
max(lis[a],lis[b]) if c = "max"... | algorithms | def guesser(n, guess):
A, B = {guess(0, 1, "min"), guess(0, 1, "max")}, {
guess(1, 2, "min"), guess(1, 2, "max")}
if len(A) == len(B) == 1:
res = [A . pop()] * 3
elif len(A) == 1:
c = (B - A). pop()
res = [A . pop()] * 2 + [c]
elif len(B) == 1:
res = [(A - B). pop()] + [... | Guess the array with min and max | 66124f9efe0da490adb4afb6 | [
"Arrays"
] | https://www.codewars.com/kata/66124f9efe0da490adb4afb6 | 5 kyu |
Thanks for checking out my kata - in the below problem - the highest n can be is 200.
Example summation of a number -
summation of the number 5
1+2+3+4+5 = 15
summation of the number 6
1+2+3+4+5+6 = 21
You are sat with two frogs on a log, Chris and Tom. They are arguing about who ate the most flies (Poor flies, but w... | algorithms | def frog_contest(x):
def f(n): return n * (n + 1) / / 2
a = f(x)
b = f(a / / 2)
c = f(a + b)
return f"Chris ate { a } flies, Tom ate { b } flies and Cat ate { c } flies"
| Frog's Dinner | 65f361be2b30ec19b78d758f | [
"Mathematics",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/65f361be2b30ec19b78d758f | 7 kyu |
### Description
A centrifuge is a laboratory device used to separate fluids based on density. This is achieved through centrifugal force by spinning a collection of test tubes at high speeds. All holes on the centrifuge are equally distanced from their neighbouring holes and have the same distance to the center.
<im... | reference | def remove_symmetry(storage: list, divisor: int):
pattern_size = len(storage) / / divisor
for i in range(pattern_size):
temp_storage = []
for sub_i in range(divisor):
temp_storage . append(storage[i + sub_i * pattern_size])
if len(set(temp_storage)) == 1:
for sub_i in range(divisor):
... | Balanced centrifuge verification | 65d8f6b9e3a87b313c76d807 | [
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/65d8f6b9e3a87b313c76d807 | 6 kyu |
### Introduction
This is the start of a series of kata's concerning sudoku strategies available for human (as opposed to computer) players. Before we move on to implementing actual strategies, we'll introduce you to the concept of **Pencil Marks**.
Sudoku players often use pencil marks to visualise all remaining cand... | algorithms | from re import sub as S
def draw_pencil_marks(board):
grid = [[int(s) if s in "123456789" else set(range(1, 10)) for s in r]
for r in S(r"[^\.\d\n]", "", board . strip()). splitlines() if r]
for r in range(9):
for c in range(9):
if isinstance(grid[r][c], int):
n = grid[r][c]
for i ... | Sudoku Strategies - Pencil Marks | 65ec2fd162762513a643b2e6 | [
"Algorithms",
"Puzzles",
"Set Theory",
"Strings"
] | https://www.codewars.com/kata/65ec2fd162762513a643b2e6 | 5 kyu |
## Task
> Can you save the damsel (young lady) in distress?
Given a string depicting the road ahead for our warrior (you) to get to the young lady, return a boolean indicating whether you succeed or not.
## Specification
### Game
- The world exists of surface <code>'.'</code>, obstacles <code>'#'</code> and water ... | algorithms | def solve(game: str) - > bool:
n, target = len(game), game . index('p')
def try_jump(pos, jump, oxygen):
j = pos + jump
if j >= n:
return n
if game[j] == '~':
return try_swim(j, 0, oxygen)
return j if game[j] not in 'p#' else n
def try_swim(pos, jump, oxygen):
i = pos
... | Damsel in Distress | 65b65ef7b5154156604ed782 | [
"Algorithms",
"Simulation"
] | https://www.codewars.com/kata/65b65ef7b5154156604ed782 | 5 kyu |
You will be given a rectangular array representing a "map" with three types of spaces:
- "+" bombs: when activated, their explosion activates any bombs directly above, below, left, or right of the "+" bomb.
- "x" bombs: when activated, their explosion activates any bombs placed in any of the four diagonal directions ne... | reference | def min_bombs_needed(grid):
def flood(i, j):
seen = set()
bag = {(i, j)}
while bag:
seen |= bag
bag = {(x, y) for i, j in bag for x, y in neighs_of(i, j)
if (x, y) not in seen and is_ok(x, y)}
return seen
def is_ok(x, y): return 0 <= x < X and 0 <= y < Y and grid[x]... | Chain Reaction - Minimum Bombs Needed | 64c8a9b8f7c1b7000fdcdafb | [] | https://www.codewars.com/kata/64c8a9b8f7c1b7000fdcdafb | 5 kyu |
## Introduction
There is a war and nobody knows - the alphabet war!
There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began.
The battlefield is a complete chaos, riddled with trenches and full of scattered troops. We need a good map of what... | reference | def trench_assault(bf: str) - > str:
power = {c: p for p, c in enumerate('wpbs zdqm', - 4)}
s = '' . join(b if b . isalpha() or b == '|' else a for a,
b in zip(* bf . split('\n')))
out = []
is_up = bf[0]. isalpha()
p, go_trench = 0, 1
for c in s:
if c == '|':
... | Alphabet wars - trench assault | 60df8c24fe1db50031d04e02 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/60df8c24fe1db50031d04e02 | 4 kyu |
_Note:_
This Kata is intended to be a more difficult version of [Getting the Letter with Tail](https://www.codewars.com/kata/649debb7eee1d126c2dcfe56), finding the pattern for the linked Kata might help this one.
___
### Letter with Tail/Head:
We got a string of letters made up by __`O`s and/or `X`s (or an empty st... | algorithms | def total_possible_amount(s):
arr = [0, 0]
for j, (c1, c2) in enumerate(zip(s, s[1:])):
i = j - 1
while i >= 0 and s[i] == c1:
i -= 1
acc = j - i + sum(arr[i + 1: j + 1]
) if c1 != c2 else 0 if i == - 1 else arr[i] + 1
arr . append(arr[- 1] + acc)
return ar... | Getting the Letter with Tail/Head | 64b59f845cce08157b725b12 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/64b59f845cce08157b725b12 | 5 kyu |
### Letter with Tail
We got a string of letters made up by __`O`s and/or `X`s (or an empty string).__
In this Kata, a `Letter with Tail` can be either one of the following:
1. `O` followed by 1 or more `X`, such as `OX`, `OXX`, `OXXX`, etc.
2. `X` followed by 1 or more `O`, such as `XO`, `XOO`, `XOOO`, etc.
___
#... | algorithms | import re
def total_possible_amount(s):
x = y = 1
for i in map(len, reversed(re . findall('O+|X+', s . lstrip(s[: 1])))):
x, y = x * i + y, x
return x - 1
| Getting the Letter with Tail | 649debb7eee1d126c2dcfe56 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/649debb7eee1d126c2dcfe56 | 5 kyu |
<h1 style="color:#74f"> Task </h1>
Can you decide whether or not some `walls` divide a rectangular `room` into two or more
partitions?
<br>
<h1 style="color:#74f"> Input </h1>
`width` - The width of the room
`height` - The height of the room
`walls` - A list of line segments
<br>
<h1 style="color:#74f"> Output </... | algorithms | from fractions import Fraction
from collections import namedtuple
Point = namedtuple("Point", "x y")
def delete_dots(lines):
return [line for line in lines if line . p1 != line . p2]
class Line:
def __init__(self, p1, p2, width, height) - > None:
self . p1, self . p2 = sorted([p1, p2])
... | Partition Detection | 60f5868c7fda34000d556f30 | [
"Geometry"
] | https://www.codewars.com/kata/60f5868c7fda34000d556f30 | 2 kyu |
# Background
This kata is inspired by [Don't give me five! Really! by zappa78](https://www.codewars.com/kata/621f89cc94d4e3001bb99ef4), which is a step-up from the original [Don't give me five by user5036852](https://www.codewars.com/kata/5813d19765d81c592200001a).
The current kata is much harder than both of those.... | algorithms | from bisect import bisect_left
def not_has_or_div_by_5_up_to(n_as_str): # n >= 0; inclusive of n
if len(n_as_str) == 0 or n_as_str == "0":
return 0
if n_as_str[0] == '0':
return not_has_or_div_by_5_up_to(n_as_str[1:])
i = int(n_as_str[0])
if len(n_as_str) == 1:
return i if i <... | No More 5's, Ever | 6465e051c6ec5c000f3e67c4 | [
"Number Theory",
"Mathematics",
"Memoization"
] | https://www.codewars.com/kata/6465e051c6ec5c000f3e67c4 | 3 kyu |
This kata is a variation of [Cody Block's Pro Skater](https://www.codewars.com/kata/5ba0adafd6b09fd23c000255). Again, you are given a list of `N` possible skateboarding tricks, and you need to design a run where each trick `i` is performed `t_i` times (`i = 1, ..., N`), optimally chosen to amaze your judges.
Performin... | games | from math import fsum, log
def continuum(ss, ms, ps):
xs = [s / (1 - m) for s, m in zip(ss, ms)]
ys = [log(p, m) for m, p in zip(ms, ps)]
t = fsum(xs) / (fsum(ys) + 1)
return [log(y * t / x, m) for m, x, y in zip(ms, xs, ys)]
| Cody Block's Continuum | 5fe24a97c1fc140017920a7f | [
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5fe24a97c1fc140017920a7f | 5 kyu |
# Description:
You are playing a simple slot machine that only contains exclamation marks and question marks. Every time the slot machine is started, a string of 5 length is obtained. If you're lucky enough to get a Special permutation, you'll win the bonus.
Give you a string `s`, return the highest bonus.
Bouns l... | reference | from itertools import groupby
def slot(st):
arr = [len(list(v)) for _, v in groupby(st)]
match arr:
case[_]: return 1000
case[4, _] | [_, 4]: return 800
case[3, 2] | [2, 3]: return 500
case[3, _, _] | [_, 3, _] | [_, _, 3]: return 300
case[2, 2, _] | [_, 2, 2] | [2, _, 2]: return 200
c... | Exclamation marks series #18: a simple slot machine that only contains exclamation marks and question marks | 57fb4b289610ce39f70000de | [
"Fundamentals"
] | https://www.codewars.com/kata/57fb4b289610ce39f70000de | 7 kyu |
---
# Wrapping a paper net onto a cube
This Kata is about wrapping a net **onto** a cube, not folding one **into** a cube. There is another kata for that task.
Think about how you would fold a net into a cube. You would fold at the creases of the net at a 90 degree angle and make a cube. Wrapping a net onto a cube... | games | # number the cube faces like a dice 1-6
from random import shuffle
WIDTH = 0
HEIGHT = 0
def folding(
grid,
face,
list_on_face,
remain_list,
faces_done
# ,faces_done_on_cube
):
faces = [(list_on_face, face)]
dirs = [1, - 1, WIDTH, - WIDTH]
if list_on_face % WIDTH =... | Wrap a cube with paper nets | 5f4af9c169f1cd0001ae764d | [
"Geometry",
"Puzzles"
] | https://www.codewars.com/kata/5f4af9c169f1cd0001ae764d | 3 kyu |
# Task Overview
Reversi is a game with black and white pieces where you attempt to capture your opponents pieces by trapping them between two of your own.
The purpose of this kata is to take a transcript (list of moves, as a `string`) and determine the state of the game after all those moves have been played. To do t... | algorithms | import re
# A small space to manage the symbols used in the reversi game
class ReversiSymbol:
FREE_SPACE = ' '
WHITE_TILE = 'W'
BLACK_TILE = 'B'
WHITE_PLAYER = WHITE_TILE
BLACK_PLAYER = BLACK_TILE
WHITE_PLAYER_WINS = WHITE_TILE
BLACK_PLAYER_WINS = BLACK_TILE
DRAW_GAME = 'D'
GAME_CO... | Reversi Win Checker | 5b035bb186d0754b5a00008e | [
"Puzzles",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/5b035bb186d0754b5a00008e | 3 kyu |
## Welcome to the world of toroids!
You find yourself in a **toroid maze** with a treasure and **three lives**. This maze is given as an array of strings of the same length:
```python
maze = [
'#### #####',
'# #E#T#',
'###### # #',
' S## H E #',
'#### #####'
]
```
Here you can see that maz... | games | def treasure(m, i, j, n, H=3, s={0}): c = m[i][j]; d = 1 + (c == 'S'); t = (i, j); return H * n * (c != '#') and (c == 'T' or any(treasure(m, a % len(
m), b % len(m[0]), n - 1, H + ((c == 'H') - (c == 'E')) * (t not in s), s | {t}) for a, b in ((i + d, j), (i - d, j), (i, j + d), (i, j - d))))
| The treasure in the Toroid [Code Golf] | 5e5d1e4dd8e2eb002dd73649 | [
"Restricted",
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5e5d1e4dd8e2eb002dd73649 | 3 kyu |
This challenge was inspired by [this kata](https://www.codewars.com/kata/63306fdffa185d004a987b8e). You should solve it before trying this harder version.
# The room
The situation regarding the lights and the switches is exactly is the same as in the original kata. Here is what you should know :
You are in a room wit... | games | class LightController:
def __init__(self, n, switches):
self . n, m = n, len(switches)
if n == 0 or m == 0:
self . dimensional_edge_case = True
return
else:
self . dimensional_edge_case = False
mat = [1 << (m + i) for i in range(n)]
for c, row in enumerate(switches):
... | Can you control the lights? | 633cb47c1ec6ac0064ec242d | [
"Algorithms",
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/633cb47c1ec6ac0064ec242d | 2 kyu |
So I have a few Snafooz puzzles at home (which are basically jigsaw puzzles that are 3d)
https://www.youtube.com/watch?v=ZTuL9O_gQpk
and it's a nice and fun puzzle. The only issue is, well, I'm not very good at it... Or should I say not better than my dad.
As you can see this is a big problem which only has one sen... | games | def solve_snafooz(pieces):
def reverse(xs): return [v[:: - 1] for v in xs]
def rotate(xs): return [[xs[5 - i][j] for i in range(6)] for j in range(6)]
def rotateall(xs): return [xs, rotate(xs), rotate(
rotate(xs)), rotate(rotate(rotate(xs)))]
def combs(xs): return rotateall(xs) + rotateal... | Snafooz solver | 6108f2fa3e38e900070b818c | [
"Games",
"Puzzles",
"Logic",
"Arrays",
"Game Solvers"
] | https://www.codewars.com/kata/6108f2fa3e38e900070b818c | 4 kyu |
<!--Queue Battle-->
<blockquote style="max-width:400px;min-width:200px;border-color:#777;background-color:#111;font-family:Tahoma,Verdana,serif"><strong>“"Forward!", he cried from the rear<br/>
And the front rank died<br/>
The general sat and the lines on the map<br/>
Moved from side to side”</strong><br/><p style="te... | algorithms | from heapq import *
from itertools import starmap
from collections import deque, namedtuple
Army = namedtuple('Army', 'i,q')
Soldier = namedtuple('Soldier', 'i,speed')
def queue_battle(d, * args):
armies = [Army(i, deque(starmap(Soldier, enumerate(q))))
for i, q in enumerate(args)]
# b... | Queue Battle | 5d617c2fa5e6a2001a369da2 | [
"Arrays",
"Puzzles",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/5d617c2fa5e6a2001a369da2 | 4 kyu |
# Overview
Your task is to encode a QR code. You get a string, of at most seven characters and it contains at least one letter. <br>
You should return a QR code as a 2 dimensional array, filled with numbers, 1 is for a black field and 0 for a white field. We are limiting ourself to ```version 1```, always use```byte m... | algorithms | from preloaded import htmlize, alphaTable
byte = "{:08b}" . format
fill = "1110110000010001" * 9
gen = [0, 43, 139, 206, 78, 43, 239, 123, 206,
214, 147, 24, 99, 150, 39, 243, 163, 136]
alphaReverse = {x: i for i, x in enumerate(alphaTable)}
def create_qr_code(text):
code = "0100"
code += byt... | Create the QR-Code | 5fa50a5def5ecf0014debd73 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5fa50a5def5ecf0014debd73 | 4 kyu |
## Strongly connected components
Let `$V$` be the set of vertices of the graph.
A strongly connected component `$S$` of a directed graph is a maximal subset of its vertices `$S ⊆ V$`, so that there is an oriented path from any vertex `$v ∈ S$` to any other vertex `$u \in S$`.
### Example
<center>
<p><img src="https:... | algorithms | # Tarjan's Algorithm
def strongly_connected_components(graph):
def dfs(cur_node, stack, low, disc, in_stack):
nonlocal level
stack . append(cur_node)
checked . add(cur_node)
in_stack[cur_node] = 1
disc[cur_node] = low[cur_node] = (level := level + 1)
for el in graph[cur_node]:
... | Strongly connected components | 5f74a3b1acfbb20033e5b7d9 | [
"Algorithms",
"Data Structures",
"Performance",
"Graph Theory"
] | https://www.codewars.com/kata/5f74a3b1acfbb20033e5b7d9 | 4 kyu |
# Task
IONU Satellite Imaging, Inc. records and stores very large images using run length encoding. You are to write a program that reads a compressed image, finds the edges in the image, as described below, and outputs another compressed image of the detected edges.
A simple edge detection algorithm sets an output... | algorithms | from collections import deque
class Board:
def __init__(self, nums: list, row_length: int, compressed_runs: list = None):
self . row_length = row_length
self . rows = [nums[i: i + row_length]
for i in range(0, len(nums), row_length)]
if len(self . rows[- 1]) < row_length:
... | Challenge Fun #20: Edge Detection | 58bfa40c43fadb4edb0000b5 | [
"Algorithms"
] | https://www.codewars.com/kata/58bfa40c43fadb4edb0000b5 | 4 kyu |
# 'Magic' recursion call depth number
This Kata was designed as a Fork to the one from donaldsebleung Roboscript series with a reference to:
https://www.codewars.com/collections/roboscript
It is not more than an extension of Roboscript infinite "single-" mutual recursion handling to a "multiple-" case.
One can supp... | algorithms | from collections import defaultdict
from itertools import chain
import re
PARSE = re . compile(r'[pP]\d+|q')
def magic_call_depth_number(prog):
def parse(it, p=''):
for m in it:
if m[0]. startswith('p'):
parse(it, m[0])
elif m[0] == 'q':
return
else:
pCmds[p... | 'Magic' recursion call depth number | 5c1b23aa34fb628f2e000043 | [
"Algorithms",
"Recursion"
] | https://www.codewars.com/kata/5c1b23aa34fb628f2e000043 | 4 kyu |
## Description
Beggar Thy Neighbour is a card game taught to me by my parents when I was a small child, and is a game I like to play with my young kids today.
In this kata you will be given two player hands to be played. And must return the **index** of the player who will win.
## Rules of the game
- Special cards... | algorithms | def who_wins_beggar_thy_neighbour(* hands, special_cards='JQKA'):
hands = [list(reversed(hand)) for hand in hands]
player, deck_length = 0, sum(map(len, hands))
deal_start, deal_value, common = None, 0, []
while len(hands[player]) < deck_length:
# Deal ends and current player wins common ... | Beggar Thy Neighbour | 58dbea57d6f8f53fec0000fb | [
"Games",
"Algorithms"
] | https://www.codewars.com/kata/58dbea57d6f8f53fec0000fb | 4 kyu |
# Task
We call letter `x` a counterpart of letter `y`, if `x` is the `i`th letter of the English alphabet, and `y` is the `(27 - i)`th for each valid `i` (1-based). For example, `'z'` is the counterpart of `'a'` and vice versa, `'y'` is the counterpart of `'b'`, and so on.
A properly closed bracket word (`PCBW`) is ... | reference | def closed_bracket_word(st):
return len(st) % 2 == 0 and all(ord(st[i]) + ord(st[- i - 1]) == 219 for i in range(len(st) / / 2))
| Simple Fun #215: Properly Closed Bracket Word | 59000d6c13b00151720000d5 | [
"Fundamentals"
] | https://www.codewars.com/kata/59000d6c13b00151720000d5 | 7 kyu |
> The Wumpus world is a simple world example to illustrate the worth of a knowledge-based agent and to represent knowledge representation.
## Wumpus world rules
The Wumpus world is a cave consisting of 16 rooms (in a 4x4 layout) with passageways between each pair of neighboring rooms. This cave contains:
* `1` agent... | algorithms | from itertools import combinations
def wumpus_world(cave):
n_pits = sum(v == 'P' for r in cave for v in r)
def neighbors(y, x): return {(y + dy, x + dx) for dy, dx in (
(1, 0), (- 1, 0), (0, 1), (0, - 1)) if 0 <= y + dy < 4 and 0 <= x + dx < 4}
smells = {(i, j): [] for i in range(4) for j... | Wumpus world | 625c70f8a071210030c8e22a | [
"Artificial Intelligence",
"Algorithms",
"Game Solvers"
] | https://www.codewars.com/kata/625c70f8a071210030c8e22a | 2 kyu |
For this kata, you have to compute the distance between two points, A and B, in a two-dimensional plane.
We don't want to make this *too* simple though, so there will also be points C[1], C[2], ... C[n] which must be avoided. Each point C[i] is surrounded by a forbidden zone of radius r[i] through which the route from... | algorithms | import numpy as np
from heapq import *
np . seterr(all='ignore')
np . set_printoptions(precision=3)
def shortest_path_length(a, b, cs):
center = np . array([a . x + a . y * 1j] + [c . ctr . x +
c . ctr . y * 1j for c in cs] + [b . x + b . y * 1j])
radius = np . array([0] + [c ... | Tiptoe through the circles | 58b617f15705ae68cc0000a9 | [
"Algorithms",
"Geometry",
"Mathematics",
"Graph Theory"
] | https://www.codewars.com/kata/58b617f15705ae68cc0000a9 | 1 kyu |
<!-- Assorted Rectangular Pieces Puzzle -->
<p>You are given an assortment of rectangular pieces and a square board with holes in it. You need to arrange the pieces on the board so that all the pieces fill up the holes in the board with no overlap.</p>
<h2 style='color:#f88'>Input</h2>
<p>Your function will receive tw... | algorithms | def ck(p, i, j, b, X, Y):
for k1 in range(i, i + p[0]):
for k2 in range(j, j + p[1]):
if not (0 <= k1 < X and 0 <= k2 < Y and b[k1][k2] == "0"):
return frozenset()
return frozenset((k1, k2) for k1 in range(i, i + p[0]) for k2 in range(j, j + p[1]))
from itertools import combinations
... | Assorted Rectangular Pieces Puzzle | 5a8f42da5084d7dca2000255 | [
"Puzzles",
"Performance",
"Algorithms",
"Game Solvers"
] | https://www.codewars.com/kata/5a8f42da5084d7dca2000255 | 2 kyu |
<style>
.game-title-pre{
width: fit-content;
background: black;
color: red;
font-weight: bold;
line-height: 1.25;
margin: auto;
padding-left: 1em;
padding-right: 1em;
}
.game-title-separator{
background: red !important;
}
.reminder-details{
border: 2px sol... | algorithms | from typing import List
DIRS = {'^': (- 1, 0), 'v': (1, 0), '<': (0, - 1), '>': (0, 1)}
def rpg(field: List[List[str]]) - > List[str]:
# print('\n'.join(map(''.join, field)))
nx, ny = len(field), len(field[0])
def next_object(x, y, dir, health):
queue = [(x, y, dir, health, 0, bag['H'], 10, '')]
... | RPG Simulator - Defeat the Demon Lord! [Part 2] | 5ea806698dbd1a001af955f3 | [
"Games",
"Game Solvers",
"Algorithms"
] | https://www.codewars.com/kata/5ea806698dbd1a001af955f3 | 2 kyu |
# Let's play some games!
A new RPG called **_Demon Wars_** just came out! Imagine the surprise when you buy it after work, go home, start you _GameStation X_ and it happens to be too difficult for you. Fortunately, you consider yourself a computer connoisseur, so you want to build an AI that tells you every step you h... | algorithms | def rpg(field, actions):
p = Player(field)
try:
for m in actions:
if m == 'A':
p . attack()
elif m in 'HCK':
p . use(m)
elif m in '<^>v':
p . rotate(m)
p . checkDmgsAndAlive()
if m == 'F':
p . move()
except Exception as e:
return No... | RPG Simulator - Defeat the Demon Lord! [Part 1] | 5e95b6e90663180028f2329d | [
"Games",
"Game Solvers",
"Algorithms"
] | https://www.codewars.com/kata/5e95b6e90663180028f2329d | 4 kyu |
## Knights
In the kingdom of Logres, knights gather around a round table. Each knight is proud of his victories, so he makes scratches on his armor according to the number of defeated opponents. The knight's rank is determined by the number of scratches. Knights are very proud and the one, whose rank is lower, must pa... | algorithms | def knights(A, p, r):
i, j = p - 1, p
g, d = r, 1
while d:
d = 0
while j - i <= len(A) and A[i % len(A)] == g:
i -= 1
d += 1
while j - i <= len(A) and A[j % len(A)] == g:
j += 1
d += 1
g += d
return len(A) - g + r + (g != A[i % len(A)] or g != A[j % len(A)... | Knights | 616ee43a919fae003291d18f | [
"Algorithms",
"Logic",
"Puzzles"
] | https://www.codewars.com/kata/616ee43a919fae003291d18f | 5 kyu |
# Task
Given a binary number, we are about to do some operations on the number. Two types of operations can be here:
* <b>['I', i, j] : Which means invert the bit from i to j (inclusive).</b>
* <b>['Q', i] : Answer whether the i'th bit is 0 or 1.</b>
The MSB (most significant bit) is the first bit (i.e. i = `1`). T... | algorithms | def binary_simulation(s, q):
out, n, s = [], int(s, 2), len(s)
for cmd, * i in q:
if cmd == 'I':
a, b = i
n ^= (1 << b - a + 1) - 1 << s - b
else:
out . append(str(int(0 < 1 << s - i[0] & n)))
return out
| Binary Simulation | 5cb9f138b5c9080019683864 | [
"Performance",
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5cb9f138b5c9080019683864 | 5 kyu |
The professional Russian, Dmitri, from the popular youtube channel <a href="https://www.youtube.com/user/FPSRussia">FPSRussia</a> has hired you to help him move his arms cache between locations without detection by the authorities. Your job is to write a Shortest Path First (SPF) algorithm that will provide a route wi... | algorithms | from heapq import *
def shortest_path(topology, start, end):
q, ans = [(0, 1, 1, start)], []
while q[0][- 1][- 1] != end:
time, _, _, path = heappop(q)
for nextPt, dt in topology[path[- 1]]. items():
heappush(q, (time + dt, len(path) + 1, nextPt != end, path + nextPt))
minTime = q[0... | SPF Russia | 5709aa85fe2d012f1d00169c | [
"Algorithms"
] | https://www.codewars.com/kata/5709aa85fe2d012f1d00169c | 4 kyu |
<p style='font-size:0.9em'><i>This kata is inspired by <a href="https://en.wikipedia.org/wiki/Space_Invaders" style="color:#9f9;text-decoration:none"><b>Space Invaders</b></a> (Japanese: スペースインベーダー), an arcade video game created by Tomohiro Nishikado and released in 1978.</i></p>
<p>Alien invaders are attacking Earth ... | algorithms | def blast_sequence(aliensStart, position):
def moveAliens(aliens, furthest):
lst, shootPath = [], []
for x, y, s in aliens:
y += s
if not (0 <= y < N): # Out of the grid: move down and reverse
x, s = x + 1, - s
y = - y - 1 if y < 0 else 2 * N - y - 1
(shootPath if y == Y else ... | Space Invaders Underdog | 59fabc2406d5b638f200004a | [
"Logic",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/59fabc2406d5b638f200004a | 4 kyu |
<p>Spider-Man ("Spidey") needs to get across town for a date with Mary Jane and his web-shooter is low on web fluid. He travels by slinging his web rope to latch onto a building rooftop, allowing him to swing to the opposite end of the latch point.</p>
<p>Write a function that, when given a list of buildings, returns a... | algorithms | from math import sqrt, ceil
REST_HEIGHT = 50
MIN_HEIGHT = 20
def optimal_one_building(pos, building, building_start):
h, w = building
theoretical = int(pos + sqrt(MIN_HEIGHT * * 2 - REST_HEIGHT * * 2 + 2 * h * (REST_HEIGHT - MIN_HEIGHT)))
if max(pos, building_start) <= theoretical <= building_star... | Spidey Swings Across Town | 59cda1eda25c8c4ffd000081 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/59cda1eda25c8c4ffd000081 | 4 kyu |
<p>This kata is inspired by <a href="https://en.wikipedia.org/wiki/Tower_defense" style="color:#9f9;text-decoration:none"><b>Tower Defense</b></a> (TD), a subgenre of strategy video games where the goal is to defend a player's territories or possessions by obstructing enemy attackers, usually by placing defensive struc... | algorithms | from math import dist
from typing import Dict, List, Tuple
DIRECTIONS = (0, 1, - 1)
def tower_defense(
grid: List[str], turrets: Dict[str, List[int]], aliens: List[int]
) - > int:
def find_start_point() - > Tuple[int, int]:
for index_row, row in enumerate(grid):
if '0' in row:
return ... | Tower Defense: Risk Analysis | 5a57faad880385f3b60000d0 | [
"Logic",
"Games",
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/5a57faad880385f3b60000d0 | 4 kyu |
Your task is to write a **class decorator** named `change_detection` that traces the changes of the attributes of the defined class. When referred on an object, each attribute - defined either on object level or class level - should interpret an additional property called `get_change` which returns one of the followin... | algorithms | def change_detection(cls):
class attr_cls ():
def __init__(self, value, get_change='INIT'):
self . value = value
self . get_change = get_change
def __getattr__(self, name):
return getattr(self . value, name)
def __repr__(self):
return str(self . value)
def __bool__(self)... | Change detection decorator | 56e02d5f2ebcd50083001300 | [
"Decorator",
"Algorithms",
"Metaprogramming"
] | https://www.codewars.com/kata/56e02d5f2ebcd50083001300 | 2 kyu |
If you haven't already done so, you should do the [5x5](https://www.codewars.com/kata/5x5-nonogram-solver/) and [15x15](https://www.codewars.com/kata/15x15-nonogram-solver/) Nonogram solvers first.
In this kata, you have to solve nonograms from any size up to one with an average side length of 50. The nonograms are no... | algorithms | from itertools import repeat, groupby, count, chain
import random
def solve(* args):
return tuple(map(tuple, Nonogram(* args). solve()))
class Memo:
def __init__(self, func):
self . func = func
self . cache = {}
def __call__(self, * args):
if args in self . cache:
retur... | Multisize Nonogram Solver | 5a5519858803853691000069 | [
"Algorithms",
"Logic",
"Games",
"Game Solvers"
] | https://www.codewars.com/kata/5a5519858803853691000069 | 1 kyu |
# Task
Given a string `s` of lowercase letters ('a' - 'z'), get the maximum distance between two same letters, and return this distance along with the letter that formed it.
If there is more than one letter with the same maximum distance, return the one that appears in `s` first.
# Input/Output
- `[input]` strin... | reference | def dist_same_letter(st):
dist_dict = {}
for k, x in enumerate(st):
dist_dict[x] = dist_dict . get(x, []) + [k]
lt = max(dist_dict, key=lambda k: dist_dict[k][- 1] - dist_dict[k][0])
return f' { lt }{ dist_dict [ lt ][ - 1 ] - dist_dict [ lt ][ 0 ] + 1 } '
| Simple Fun #221: Furthest Distance Of Same Letter | 5902bc48378a926538000044 | [
"Fundamentals"
] | https://www.codewars.com/kata/5902bc48378a926538000044 | 6 kyu |
_This kata is a harder version of [A Bubbly Programming Language](https://www.codewars.com/kata/5f7a715f6c1f810017c3eb07). If you haven't done that, I would suggest doing it first._
You are going to make yet another interpreter similar to [A Bubbly Programming Language](https://www.codewars.com/kata/5f7a715f6c1f810017... | games | def get(x): return x if callable(x) else lambda s, c: c(
s, s[x] if isinstance(x, str) else x)
def start(x): return x({}, None)
def return_(s, c): return lambda x: get(x)(s, lambda _s, x: x)
def let(s, c): return lambda x: lambda y: get(y)(s, lambda s, y: lambda z: z({* * s, x: y}, None))
def a... | The Bubbly Interpreter | 5fad08d083d5600032d9edd7 | [
"Functional Programming",
"Puzzles"
] | https://www.codewars.com/kata/5fad08d083d5600032d9edd7 | 4 kyu |
<div style="width:504px;height:262px;background:#ddd;">
<img src="https://i.imgur.com/XbW4CRw.jpg" alt="Super Puzzle Fighter II Turbo screenshot">
</div>
<p>This kata is inspired by the arcade puzzle game <a href="https://en.wikipedia.org/wiki/Super_Puzzle_Fighter_II_Turbo" style="color:#9f9;text-decoration:none"><b>Su... | algorithms | from collections import defaultdict
from itertools import chain, count, cycle
from operator import itemgetter
from heapq import *
def puzzle_fighter(arrMoves):
def getStartPoses(moves, c1, c2):
x,y,iR = start
for m in moves:
y += m in 'RL' and (-1)**(m=='L')
iR = (iR +... | Puzzle Fighter | 5a3cbf29ee1aae06160000c9 | [
"Games",
"Logic",
"Game Solvers",
"Algorithms"
] | https://www.codewars.com/kata/5a3cbf29ee1aae06160000c9 | 1 kyu |
<!--Blobservation-->
<p>Blobs of various sizes are situated in a room. Each blob will move toward the nearest smaller blob until it reaches it and engulfs it. After consumption, the larger blob grows in size.</p>
<p>Your task is to create a class <code>Blobservation</code> (a portmanteau of blob and observation) and me... | algorithms | import math
class Blobservation:
def __init__(self, height, width=None):
self . height = height
self . width = width or height
self . blobs = {} # {(x, y): size}
def populate(self, blobs):
for blob in blobs:
assert type(blob['x']) == type(blob['y']) == type(blob['size']) == in... | Blobservation | 5abab55b20746bc32e000008 | [
"Logic",
"Games",
"Object-oriented Programming",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5abab55b20746bc32e000008 | 3 kyu |
<p>This kata is inspired by <a href="http://plantsvszombies.wikia.com/wiki/Main_Page" style="color:#9f9;text-decoration:none"><b>Plants vs. Zombies</b></a>, a tower defense video game developed and originally published by PopCap Games.</p>
<p>The battlefield is the front lawn and the zombies are coming. Our defenses (... | algorithms | from itertools import chain
def plants_and_zombies(lawn, zProvider):
DEBUG = False
X, Y = len(lawn), len(lawn[0])
class Stuff (object): # Shooters and Zombies instances
def __init__(self, x, y, typ, h=0):
self . x, self . y = x, y
self . isS = typ == 'S'
self . fire = int(typ) if typ no... | Plants and Zombies | 5a5db0f580eba84589000979 | [
"Logic",
"Games",
"Game Solvers",
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/5a5db0f580eba84589000979 | 3 kyu |
<div style="font-size:13px;font-style:italic;color:gray">
This is the performance version of ALowVerus' kata, <a href="https://www.codewars.com/kata/5f5bef3534d5ad00232c0fa8">Topology #0: Converging Coins.</a> You should solve it first, before trying this one.
</div>
## Task
Let `$G$` be an undirected graph. Suppose ... | reference | from itertools import count
from collections import deque, defaultdict
def converge(g, us):
us = set(us)
cnts = (defaultdict(int), defaultdict(int))
floods = [[[u], ({u}, set())] for u in us]
tic, N = 0, len(us)
for u in us:
cnts[tic][u] += 1
if cnts[tic][u] == N:
ret... | Topology #0.1: Converging Coins (Performance edition) | 60d0fd89efbd700055f491c4 | [
"Mathematics",
"Graph Theory"
] | https://www.codewars.com/kata/60d0fd89efbd700055f491c4 | 3 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.