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 |
|---|---|---|---|---|---|---|---|
An architect wants to construct a vaulted building supported by a family of arches C<sub>n</sub>.
f<sub>n</sub>(x) = -nx - xlog(x) is the equation of the arch C<sub>n</sub> where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let f<sub>n</sub>(0) = 0... | reference | weight = lambda n, w, e = __import__('math'). exp(- 2): (1 - 3 * e) / (1 - e) / 4 * (1 - e * * n) * w
| Architect's Dream: drawing curves, observing, thinking | 5db19d503ec3790012690c11 | [
"Fundamentals"
] | https://www.codewars.com/kata/5db19d503ec3790012690c11 | 6 kyu |
Story:
In the realm of numbers, the apocalypse has arrived. Hordes of zombie numbers have infiltrated and are ready to turn everything into undead. The properties of zombies are truly apocalyptic: they reproduce themselves unlimitedly and freely interact with each other. Anyone who equals them is doomed. Out of an infi... | algorithms | def gcd(a, b): # Just a simple Euclidean algorithm to compute gcd
while (b != 0):
a, b = b, a % b
return a
def survivor(zombies):
if (len(zombies) == 0): # First let's deal with lists of length == 0
return - 1
zombies . sort() # Then let's sort the list
if zombies[0] == 1: # If zomb... | Zombie Apocalypse: the Last Number Standing | 5d9b52214a336600216bbd0e | [
"Algorithms"
] | https://www.codewars.com/kata/5d9b52214a336600216bbd0e | 4 kyu |
Positive integers have so many gorgeous features.
Some of them could be expressed as a sum of two or more consecutive positive numbers.
___
### Consider an Example :
* `10` could be expressed as the sum of `1 + 2 + 3 + 4 `.
___
## Task
**_Given_** *Positive integer*, N , return true if it could be expressed as a su... | games | from math import log2
def consecutive_ducks(n):
return not log2(n). is_integer()
| Consecutive Digits To Form Sum | 5dae2599a8f7d90025d2f15f | [
"Fundamentals",
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5dae2599a8f7d90025d2f15f | 7 kyu |
Suppose we know the process by which a string `s` was encoded to a string `r` (see explanation below). The aim of the kata is to decode this string `r` to get back the original string `s`.
#### Explanation of the encoding process:
- input: a string `s` composed of lowercase letters from "a" to "z", and a positive in... | reference | from string import ascii_lowercase as aLow
def decode(r):
i = next(i for i, c in enumerate(r) if c . isalpha())
n, r = int(r[: i]), r[i:]
maps = {chr(97 + n * i % 26): c for i, c in enumerate(aLow)}
return "Impossible to decode" if len(maps) != 26 else '' . join(maps[c] for c in r)
| Reversing a Process | 5dad6e5264e25a001918a1fc | [
"Fundamentals"
] | https://www.codewars.com/kata/5dad6e5264e25a001918a1fc | 6 kyu |
You need count how many valleys you will pass.
Start is always from zero level.
Every time you go down below 0 level counts as an entry of a valley, and as you go up to 0 level from valley counts as an exit of a valley.
One passed valley is equal one entry and one exit of a valley.
```
s='FUFFDDFDUDFUFUF'
U=UP
F=FOR... | algorithms | def counting_valleys(s):
level, valleys = 0, 0
for step in s:
if step == 'U' and level == - 1:
valleys += 1
level += {'U': 1, 'F': 0, 'D': - 1}[step]
return valleys
| Counting Valleys | 5da9973d06119a000e604cb6 | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/5da9973d06119a000e604cb6 | 7 kyu |
<h3>Introduction</h3>
Imagine a function that maps a number from a given range, to another, desired one. If this is too vague - let me explain a little bit further: let's take an arbitrary number - `2` for instance - and map it with this function from range `0-5` to, let's say - `10-20`. Our number lies in `2/5` of th... | algorithms | def map_vector(vector, circle1, circle2):
(vx, vy), (x1, y1, r1), (x2, y2, r2) = vector, circle1, circle2
v = (complex(vx, vy) - complex(x1, y1)) / r1 * r2 + complex(x2, y2)
return v . real, v . imag
| 2D Vector Mapping | 5da995d583326300293ce4cb | [
"Mathematics",
"Algorithms",
"Geometry"
] | https://www.codewars.com/kata/5da995d583326300293ce4cb | 7 kyu |
# A History Lesson
Tetris is a puzzle video game originally designed and programmed by Soviet Russian software engineer Alexey Pajitnov. The first playable version was completed on June 6, 1984. Pajitnov derived its name from combining the Greek numerical prefix tetra- (the falling pieces contain 4 segments) and tenni... | reference | points = [0, 40, 100, 300, 1200]
def get_score(arr) - > int:
cleared = 0
score = 0
for lines in arr:
level = cleared / / 10
score += (level + 1) * points[lines]
cleared += lines
return score
| Tetris Series #1 β Scoring System | 5da9af1142d7910001815d32 | [
"Fundamentals",
"Games",
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/5da9af1142d7910001815d32 | 7 kyu |
Rotate a 2D array by 1 / 8<sup>th</sup> of a full turn
### Example
```haskell
rotateCW,rotateCCW :: [[a]] -> [[a]]
rotateCW [ "ab"
, "cd"
]
-> [ "a"
, "cb"
, "d"
]
rotateCCW [ "ab"
, "cd"
]
-> [ "b"
, "ad"
, "c"
... | algorithms | def rotate_cw(seq, cw=1):
if not seq or not seq[0]:
return []
lst = [[] for i in range(len(seq) + len(seq[0]) - 1)]
for i in range(len(seq)):
for j in range(len(seq[0])):
lst[i + j * cw + int(cw / 2 - 0.5) * (- len(seq[0]) + 1)
]. append(seq[i][j])
return ["" . join... | Rotate 1 / 8th | 5da74bf201735a001180def7 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5da74bf201735a001180def7 | 6 kyu |
You have inherited some Python code related to high school physics. The previous coder is obviously on cracks since the codebase has this kind of pattern all over the place:
```python
LENGTH_UNITS = type('LENGTH_UNITS', (object,), {})
LENGTH_UNITS.pc = 3.08567758149137e16
LENGTH_UNITS.AU = 149597870700
LENGTH_UNITS.km... | bug_fixes | from collections import namedtuple
from unicodedata import normalize
def create_namedtuple_cls(cls_name, fields):
d = {normalize('NFKC', f): f for f in fields}
class Data (namedtuple(cls_name, fields)):
def __getattr__(self, item):
return self . __getattribute__(d[item]) if item in d else No... | The Doppelganger Enigma | 5da558c930187300114d874e | [
"Debugging"
] | https://www.codewars.com/kata/5da558c930187300114d874e | 5 kyu |
_This Kata is a variation of **Histogram - V1**_
**Kata in this series**
* [Histogram - H1](https://www.codewars.com/kata/histogram-h1/)
* [Histogram - H2](https://www.codewars.com/kata/histogram-h2/)
* [Histogram - V1](https://www.codewars.com/kata/histogram-v1/)
* [Histogram - V2](https://www.codewars.com/kata/hist... | reference | def histogram(results):
r = []
m = max(results)
s = sum(results)
if s != 0:
for i in range(m * 15 / / s, - 1, - 1):
l = []
for j in range(6):
c = []
a = results[j] * 15 / / s
b = results[j] * 100 / / s
if a == i:
if b != 0:
c += f' { b } %'
elif b ==... | Histogram - V2 | 5d5f5f25f8bdd3001d6ff70a | [
"Fundamentals"
] | https://www.codewars.com/kata/5d5f5f25f8bdd3001d6ff70a | 5 kyu |
# The Challenge
Write a function that returns the number of significant figures in a given number. You can read about significant figures below.
## Helpful information
* the type of the given number will be string
* you must return the number of significant figures as type int
* no blank strings will be given
## Sign... | algorithms | def number_of_sigfigs(number):
s = number . lstrip("0")
if "." in s:
if s[0] == ".":
return len(s[1:]. lstrip("0")) or 1
return len(s) - 1
return len(s . rstrip("0"))
| Significant Figures | 5d9fe0ace0aad7001290acb7 | [
"Mathematics",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5d9fe0ace0aad7001290acb7 | 7 kyu |
# Description
Given a number `n`, you should find a set of numbers for which the sum equals `n`. This set must consist exclusively of values that are a power of `2` (eg: `2^0 => 1, 2^1 => 2, 2^2 => 4, ...`).
The function `powers` takes a single parameter, the number `n`, and should return an array of unique numbers.
... | algorithms | def powers(n):
return [1 << i for i, x in enumerate(reversed(bin(n))) if x == "1"]
| Sum of powers of 2 | 5d9f95424a336600278a9632 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5d9f95424a336600278a9632 | 7 kyu |
# Background
Different sites have different password requirements.
You have grown tired of having to think up new passwords to meet all the different rules, so you write a small piece of code to do all the thinking for you.
# Kata Task
Return any valid password which matches the requirements.
Input:
```if:pytho... | reference | import re
def make_password(length, flagUpper, flagLower, flagDigit):
password = "1aA2bB3cC4dD5eE6fF7gG8hH9iI0jJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"
if not flagUpper:
password = re . sub('[A-Z]', '', password)
if not flagLower:
password = re . sub('[a-z]', '', password)
if not flagDigit:... | Password Maker | 5b3d5ad43da310743c000056 | [
"Fundamentals"
] | https://www.codewars.com/kata/5b3d5ad43da310743c000056 | 6 kyu |
_This Kata is a variation of **Histogram - H1**_
**Kata in this series**
* [Histogram - H1](https://www.codewars.com/kata/histogram-h1/)
* [Histogram - H2](https://www.codewars.com/kata/histogram-h2/)
* [Histogram - V1](https://www.codewars.com/kata/histogram-v1/)
* [Histogram - V2](https://www.codewars.com/kata/hist... | reference | def histogram(results):
t = sum(results)
return "" . join(f' { i + 1 } | { "β" * ( 50 * results [ i ] / / t )} { 100 * results [ i ] / / t } %\n' if results[i] else f' { i + 1 } |\n' for i in range(len(results) - 1, - 1, - 1))
| Histogram - H2 | 5d5f5ea8e3d37b001dfd630a | [
"Fundamentals"
] | https://www.codewars.com/kata/5d5f5ea8e3d37b001dfd630a | 7 kyu |
Given an integer perimeter, `0 < p <= 1 000 000`, find all right-angled triangles with perimeter `p` that have integral side lengths.
#### Your Task
- Complete the `integerRightTriangles` (or `integer_right_triangles`) function.
- Each element of the solution array should contain the integer side lengths of a valid t... | algorithms | LENGTHS = {12: [3, 4, 5], 30: [5, 12, 13], 70: [20, 21, 29], 40: [8, 15, 17], 56: [7, 24, 25], 176: [48, 55, 73], 126: [28, 45, 53], 208: [39, 80, 89], 408: [119, 120, 169], 198: [36, 77, 85], 154: [33, 56, 65], 234: [65, 72, 97], 84: [12, 35, 37], 90: [9, 40, 41], 330: [88, 105, 137], 260: [60, 91, 109], 546: [105, 20... | Integer Right Triangles | 562c94ed7549014148000069 | [
"Algorithms"
] | https://www.codewars.com/kata/562c94ed7549014148000069 | 5 kyu |
### Story
You just returned from a car trip, and you are curious about your fuel consumption during the trip. Unfortunately, you didn't reset the counter before you started, but you have written down the average consumption of the car and the previous distance travelled at that time. Looking at the dashboard, you note... | algorithms | def solve(before, after):
(avg1, dist1), (avg2, dist2) = before, after
return round((avg2 * dist2 - avg1 * dist1) / (dist2 - dist1), 1)
| Average Fuel Consumption | 5d96030e4a3366001d24b3b7 | [
"Algorithms"
] | https://www.codewars.com/kata/5d96030e4a3366001d24b3b7 | 7 kyu |
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
Fro... | reference | from math import cos, sin, radians
def crusoe(n, d, ang, dist_mult, ang_mult):
x, y, a = 0, 0, radians(ang)
for i in range(n):
x += d * cos(a)
y += d * sin(a)
d *= dist_mult
a *= ang_mult
return x, y
| Robinson Crusoe | 5d95b7644a336600271f52ba | [
"Fundamentals"
] | https://www.codewars.com/kata/5d95b7644a336600271f52ba | 7 kyu |
Imagine an `n x n` grid where each box contains a number. The top left box always contains 1 and each box in a clockwise spiral from there will contain the next natural number. (see below)
```
1 - 2 - 3 - 4
|
12 - 13 - 14 5
| | |
11 16 - 15 6
| |
10 - 9 - 8 - 7
```
**Task**
... | games | # Special cases for first and last column are possible but not needed
# Rule nΒ°1 of those katas, there's ALWAYS a formula
def spiral_column(n, c):
n2, n3, c2, c3 = n * * 2, n * * 3, c * * 2, c * * 3
nc, nc2, n2c = n * c, n * c2, n2 * c
if 2 * c <= n:
return (24 * n2c - 3 * n2 - 48 * nc2 + 6 * nc + 3 * n... | Spiral Column Addition | 5d95118fdb5c3c0001a55c9b | [
"Mathematics",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5d95118fdb5c3c0001a55c9b | 6 kyu |
This kata is a follow-up of **[Domino Tiling - 2 x N Board](https://www.codewars.com/kata/domino-tiling-2-x-n-board)**. If you haven't already done so, you might want to solve that one first.
Did you find a nice solution to that kata using some type of memoization? Well then...
# Memoization won't save you this time!... | games | class Modular (int):
def __new__(cls, n):
return super(). __new__(cls, n % 12345787)
def __add__(self, other):
return Modular(super(). __add__(other))
def __mul__(self, other):
return Modular(super(). __mul__(other))
@ staticmethod
def asmatrix(matrix):
from numpy import mat... | Domino Tiling - 2 x N Board -- Challenge Edition! | 5c1905cc16537c7782000783 | [
"Puzzles",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5c1905cc16537c7782000783 | 4 kyu |
# Kata Task
Connect the dots in order to make a picture!
# Notes
* There are 2-26 dots labelled `a` `b` `c` ...
* Make lines to connect the dots `a` -> `b`, `b` -> `c`, etc
* The line char is `*`
* Use only straight lines - vertical, horizontal, or diagonals of a square
* The paper is rectangular - `\n` terminates... | reference | def connect_the_dots(paper):
Y = paper . find("\n") + 1
lst = list(paper)
pts = {c: i for i, c in enumerate(paper) if c . isalpha()}
chrs = sorted(pts)
for i in range(len(pts) - 1):
a, b = sorted((pts[chrs[i]], pts[chrs[i + 1]]))
(x, y), (u, v) = divmod(a, Y), divmod(b, Y)
dx, ... | Connect the Dots | 5d6a11ab2a1ef8001dd1e817 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d6a11ab2a1ef8001dd1e817 | 6 kyu |
Given a string `s` of uppercase letters, your task is to determine how many strings `t` (also uppercase) with length equal to that of `s` satisfy the followng conditions:
* `t` is lexicographical larger than `s`, and
* when you write both `s` and `t` in reverse order, `t` is still lexicographical larger than `s`.
``... | reference | def solve(s):
r, l = 0, 0
for c in s:
m = ord('Z') - ord(c)
r, l = r + m + l * m, m + l * 26
return r % 1000000007
| String counting | 5cfd36ea4c60c3001884ed42 | [
"Fundamentals"
] | https://www.codewars.com/kata/5cfd36ea4c60c3001884ed42 | 6 kyu |
A system is transmitting messages in binary, however it is not a perfect transmission, and sometimes errors will occur which result in a single bit flipping from 0 to 1, or from 1 to 0.
To resolve this, A 2-dimensional Parity Bit Code is used: https://en.wikipedia.org/wiki/Multidimensional_parity-check_code
In this s... | algorithms | def correct(m, n, bits):
l = m * n
row = next((i for i in range(
m) if f" { bits [ i * n :( i + 1 ) * n ]}{ bits [ l + i ]} " . count("1") % 2), None)
col = next((i for i in range(
n) if f" { bits [ i : l : n ]}{ bits [ l + m + i ]} " . count("1") % 2), None)
if row is col is None:... | Error Correction Codes | 5d870ff1dc2362000ddff90b | [
"Algorithms"
] | https://www.codewars.com/kata/5d870ff1dc2362000ddff90b | 6 kyu |
Your job is to fix the parentheses so that all opening and closing parentheses (brackets) have matching counterparts. You will do this by appending parenthesis to the beginning or end of the string. The result should be of minimum length. Don't add unnecessary parenthesis.
The input will be a string of varying length,... | refactoring | def fix_parentheses(stg):
original, o, c = stg, "(", ")"
while "()" in stg:
stg = stg . replace("()", "")
opening, closing = o * stg . count(c), c * stg . count(o)
return f" { opening }{ original }{ closing } "
| Balance the parentheses | 5d8365b570a6f6001519ecc8 | [
"Refactoring"
] | https://www.codewars.com/kata/5d8365b570a6f6001519ecc8 | 7 kyu |
At the start of each season, every player in a football team is assigned their own unique squad number. Due to superstition or their history certain numbers are more desirable than others.
Write a function generateNumber() that takes two arguments, an array of the current squad numbers (squad) and the new player's des... | algorithms | def generate_number(squad, n):
if n not in squad:
return n
for i in range(1, 10):
for j in range(1, 10):
if i + j == n and i * 10 + j not in squad:
return i * 10 + j
| Squad number generator | 5d62961d18198b000e2f22b3 | [
"Algorithms"
] | https://www.codewars.com/kata/5d62961d18198b000e2f22b3 | 7 kyu |
You are writing a password validator for a website. You want to discourage users from using their username as part of their password, or vice-versa, because it is insecure. Since it is unreasonable to simply not allow them to have any letters in common, you come up with this rule:
**For any password and username pair,... | reference | from difflib import SequenceMatcher
def validate(username, password):
l1, l2 = len(username), len(password)
match = SequenceMatcher(
None, username, password). find_longest_match(0, l1, 0, l2)
return match . size < min(l1, l2) / 2
| Password should not contain any part of your username. | 5c511d8877c0070e2c195faf | [
"Regular Expressions",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5c511d8877c0070e2c195faf | 7 kyu |
If the first day of the month is a Friday, it is likely that the month will have an `Extended Weekend`. That is, it could have five Fridays, five Saturdays and five Sundays.
In this Kata, you will be given a start year and an end year. Your task will be to find months that have extended weekends and return:
```
- The... | reference | from calendar import month_abbr
from datetime import datetime
def solve(a, b):
res = [month_abbr[month]
for year in range(a, b + 1)
for month in [1, 3, 5, 7, 8, 10, 12]
if datetime(year, month, 1). weekday() == 4]
return (res[0], res[- 1], len(res))
| Extended weekends | 5be7f613f59e0355ee00000f | [
"Fundamentals"
] | https://www.codewars.com/kata/5be7f613f59e0355ee00000f | 7 kyu |
# Task
In 10 years of studying, Alex has received a lot of diplomas. He wants to hang them on his wall, but unfortunately it's made of stone and it would be too difficult to hammer so many nails in it.
Alex decided to buy a square desk to hang on the wall, on which he is going to hang his diplomas. Your task is to fin... | games | def diplomas(h, w, n):
x = int((h * w * n) * * .5)
while (x / / h) * (x / / w) < n:
x += 1
return x
| Simple Fun #274: Diplomas | 591592b0f05d9a3019000087 | [
"Puzzles"
] | https://www.codewars.com/kata/591592b0f05d9a3019000087 | 7 kyu |
In this kata you will try to recreate a simple code-breaking game. It is called "Bulls and Cows". The rules are quite simple:
The computer generates a secret number consisting of 4 distinct digits. Then the player, in 8 turns, tries to guess the number. As a result he receives from the computer the number of matches. ... | reference | class BullsAndCows:
def __init__(self, n):
if not self . allowed(n):
raise ValueError()
self . n, self . turns, self . solved = str(n), 0, False
def plural(self, n): return 's' if n != 1 else ''
def allowed(self, n): return 1234 <= n <= 9876 and len(
set(c for c in str(n))) ==... | Bulls and Cows | 5be1a950d2055d589500005b | [
"Games",
"Fundamentals",
"Strings",
"Object-oriented Programming"
] | https://www.codewars.com/kata/5be1a950d2055d589500005b | 7 kyu |
You are the rock paper scissors oracle.
Famed throughout the land, you have the incredible ability to predict which hand gestures your opponent will choose out of rock, paper and scissors.
Unfortunately you're no longer a youngster, and have trouble moving your hands between rounds. For this reason, you can only pick... | reference | from collections import Counter
def oracle(gestures):
res, C = [], Counter(gestures)
if C["scissors"] > C["paper"]:
res . append("rock")
if C["rock"] > C["scissors"]:
res . append("paper")
if C["paper"] > C["rock"]:
res . append("scissors")
return "/" . join(res)... | Rock Paper Scissors Oracle | 580535462e7b330bd300003d | [
"Fundamentals"
] | https://www.codewars.com/kata/580535462e7b330bd300003d | 7 kyu |
# I'm already Tracer
*Note*: this is an easy Kata, but requires a bit of knowledge about the game Overwatch. Feel free to skip the background section if you are familiar with the game!
# Background
Overwatch is a team-based online First Person Shooter. Teams are made up of 6 **unique** heroes. No team can have 2 of th... | reference | ALL_SETS = tuple(map(set, (TANK, DAMAGE, SUPPORT)))
def team_comp(heroes):
s = set(heroes)
if len(heroes) != 6 or len(s) != 6:
raise InvalidTeam()
return [len(s & ss) for ss in ALL_SETS]
| I'm already Tracer | 5c15dd0fb48e91d81b0000c6 | [
"Games",
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5c15dd0fb48e91d81b0000c6 | 7 kyu |
_This kata is based on [Project Euler Problem 546](https://projecteuler.net/problem=546)_
# Objective
Given the recursive sequence
```math
f_k(n) = \sum_{i=1}^n f_k(\text{floor}(i/k)), \text{where} f_k(0)=1
```
Define a function `f` that takes arguments `k` and `n` and returns the nth term in the sequence f<sub>k<... | algorithms | from math import floor
def f(k, n):
num = [1]
if n == 0:
return num[0]
for i in range(1, k):
num . append(i + 1)
for j in range(k, n + 1):
num . append(num[floor(j / k)] + num[j - 1])
if k > n:
return num[n]
return num[- 1]
| Recursive Floor Sequence | 56b85fc4f18876abf0000877 | [
"Algorithms"
] | https://www.codewars.com/kata/56b85fc4f18876abf0000877 | 5 kyu |
# Task
John won the championship of a TV show. He can get some bonuses.
He needs to play a game to determine the amount of his bonus.
Here are some cards in a row. A number is written on each card.
In each turn, John can take a card, but only from the beginning or the end of the row. Then multiply the number on the... | algorithms | def calc(a):
res = [0] * (len(a) + 1)
for k in range(len(a)):
res = [2 * max(a[i] + res[i + 1], a[i + k] + res[i])
for i in range(len(a) - k)]
return res[0]
| Kata 2019: Bonus Game I | 5c2d5de69611562191289041 | [
"Algorithms",
"Dynamic Programming"
] | https://www.codewars.com/kata/5c2d5de69611562191289041 | 5 kyu |
Traditionally, all programming languages implement the 3 most common boolean operations: `and`, `or`, `not`. These three form the complete boolean algebra, i.e. every possible boolean function from `N` arguments can be decomposed into combination of arguments and `and`, `or`, `not`.
In the school we have learned, that... | reference | # sheffer of same thing twice returns opposite
def NOT(a):
return sheffer(a, a)
# return true only if a and b are true, which is NOT sheffer
def AND(a, b):
return NOT(sheffer(a, b))
# sheffer of each variable's NOT flip's sheffer's truth table
def OR(a, b):
return sheffer(NOT(a),... | Sheffer stroke | 5d82344d687f21002c71296e | [
"Fundamentals"
] | https://www.codewars.com/kata/5d82344d687f21002c71296e | 7 kyu |
## What is a Catalan number?
In combinatorial mathematics, the Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively-defined objects. They are named after the Belgian mathematician EugΓ¨ne Charles Catalan (1814β1894).
Using zero-based numbering, the nth... | algorithms | from math import factorial
def nth_catalan_number(n):
return factorial(2 * n) / / factorial(n + 1) / / factorial(n)
| Find the Nth Catalan number | 579637b41ace7f92ae000282 | [
"Big Integers",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/579637b41ace7f92ae000282 | 6 kyu |
# Task
Follow the instructions in each failing test case to write logic that calculates the total price when ringing items up at a cash register.
# Purpose
Practice writing maintainable and extendable code.
# Intent
This kata is meant to emulate the real world where requirements change over time. This kata does not ... | algorithms | import re
class Checkout (object):
def __init__(self, d={}):
self . pricing, self . total, self . fruits, self . free = d, 0, {}, {}
def scan(self, n, qty=1):
item = get_price(n)
for i in range(qty):
if not self . free . get(n, 0):
self . total += item
self . fruit... | Checkout Line Pricing | 57c8d7f8484cf9c1550000ff | [
"Algorithms"
] | https://www.codewars.com/kata/57c8d7f8484cf9c1550000ff | 5 kyu |
We will represent complex numbers in either cartesian or polar form as an array/list, using the first element as a type tag; the **normal** tags are `"cart"` (for cartesian) and `"polar"`. The forms of the tags depend on the language.
- ['cart', 3, 4]`represents the complex n... | reference | def sqr_modulus(z):
if not (z[0] in ('cart', 'polar') and all(isinstance(x, int) for x in z[1:])):
return (False, - 1, 1)
sm = sum(
(re * * 2 + im * * 2 for re, im in zip(z[1:: 2], z[2:: 2]))
if z[0] == 'cart' else
(r * * 2 for r in z[1:: 2]))
return (True, sm, int('' . jo... | Magnitude | 5cc70653658d6f002ab170b5 | [
"Fundamentals"
] | https://www.codewars.com/kata/5cc70653658d6f002ab170b5 | 6 kyu |
## Introduction

Each chemical element in its neutral state has a specific number of electrons associated with it. This is represented by the **atomic number** which is noted by an integer number next to or above each element of th... | reference | EXCEPTIONS = {
'Cr': ['Ar', '4s1 3d5'],
'Cu': ['Ar', '4s1 3d10'],
'Nb': ['Kr', '5s1 4d4'],
'Mo': ['Kr', '5s1 4d5'],
'Ru': ['Kr', '5s1 4d7'],
'Rh': ['Kr', '5s1 4d8'],
'Pd': ['Kr', '5s0 4d10'],
'Ag': ['Kr', '5s1 4d10'],
'La': ['Xe', '6s2 4f0 5d1'],
'Ce': ['Xe', '6s2 4f1 5... | Electron configuration of chemical elements | 597737709e2c45882700009a | [
"Arrays",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/597737709e2c45882700009a | 5 kyu |
In a far away country called AlgoLandia, there are `N` islands numbered `1` to `N`. Each island is denoted by `k[i]`. King Algolas, king of AlgoLandia, built `N - 1` bridges in the country. A bridge is built between islands `k[i]` and `k[i+1]`. Bridges are two-ways and are expensive to build.
The problem is that there... | algorithms | def find_needed_guards(k):
b = '' . join('1' if g else '0' for g in k)
return sum(len(ng) / / 2 for ng in b . split("1"))
| Guarding the AlgoLandia | 5d0d1c14c843440026d7958e | [
"Algorithms",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5d0d1c14c843440026d7958e | 7 kyu |
You will be given an array of non-negative integers and positive integer bin width.
Your task is to create the Histogram method that will return histogram data corresponding to the input array. The histogram data is an array that stores under index i the count of numbers that belong to bin i. The first bin always sta... | algorithms | def histogram(lst, w):
lst = [n / / w for n in lst]
m = max(lst, default=- 1) + 1
return [lst . count(n) for n in range(m)]
| Histogram data | 5704bf9b38428f1446000a9d | [
"Fundamentals",
"Algorithms",
"Arrays",
"Data Science"
] | https://www.codewars.com/kata/5704bf9b38428f1446000a9d | 7 kyu |
This Kata is based on an old riddle.
A group of gnomes have been captured by an evil wizard who plans on transforming them into dolls for his collection.
He presents the gnomes with this challenge:
* At dawn of the next day he will place the gnomes in a straight line.
* He will place on the head of each gnome a red... | games | def my_hat_guess(p, f):
return 'red' if (p . count('blue') + f . count('blue')) % 2 == 0 else 'blue'
| Gnomes and Hats: A Horror Story | 57c4f4ac0fe1438e630007c6 | [
"Puzzles"
] | https://www.codewars.com/kata/57c4f4ac0fe1438e630007c6 | 5 kyu |
Given an array of ones and zero(e)s that represents a positive binary number, convert the number to two's complement value.
Two's complement is the way most computers represent positive or negative integers. The most significant bit is `1` if the number is negative, and `0` otherwise.
Examples:
[1,1,1,1] = -1
[1,0... | reference | def positive_to_negative(arr):
flip = [0 if n == 1 else 1 for n in arr]
for i in range(len(flip)):
if flip[- (i + 1)] == 1:
flip[- (i + 1)] = 0
else:
flip[- (i + 1)] = 1
break
return flip
| Positive to negative binary numbers | 5becace7063291bebf0001d5 | [
"Binary",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5becace7063291bebf0001d5 | 7 kyu |
**Can you compute a cube as a sum?**
In this Kata, you will be given a number `n` (where `n >= 1`) and your task is to find `n` consecutive odd numbers whose sum is exactly the cube of `n`.
Mathematically:
```math
n^3 = a_1 + a_2 + a_3 + \ldots + a_n \\
a_2 = a_1 + 2, \quad a_3 = a_2 + 2, \quad \ldots, \quad a_n =... | games | def find_summands(n):
return list(range(n * n - n + 1, n * n + n + 1, 2))
| compute cube as sums | 58af1bb7ac7e31b192000020 | [
"Puzzles"
] | https://www.codewars.com/kata/58af1bb7ac7e31b192000020 | 6 kyu |
Create methods to convert between Bijective Binary strings and integers and back.
A bijective binary number is represented by a string composed only of the characters 1 and 2. Positions have the same value as in binary numbers, a string of repeated 1's has the same value in binary and bijective binary.
As there is no ... | algorithms | def bijective_to_int(b):
return sum(2 * * i * int(d) for i, d in enumerate(b[:: - 1]))
def int_to_bijective(n):
b = ""
while n:
b += "21" [n % 2]
n = (n - 1) / / 2
return b[:: - 1]
| Bijective Binary | 58f5e53e663082f9aa000060 | [
"Algorithms"
] | https://www.codewars.com/kata/58f5e53e663082f9aa000060 | 6 kyu |
The objective is to disambiguate two given names: the original with another
This kata is slightly more evolved than the previous one: [Author Disambiguation: to the point!](https://www.codewars.com/kata/580a429e1cb4028481000019).
The function ```could_be``` is still given the original name and another one to test
aga... | algorithms | import re
def could_be(original, another):
a, b = [re . findall('[^ !.,;:?]+', x . lower(). strip())
for x in (original, another)]
return a != [] and b != [] and all(c in a for c in b)
| Author Disambiguation: a name is a Name! | 580a8f039a90a3654b000032 | [
"Puzzles",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/580a8f039a90a3654b000032 | 6 kyu |
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> rand... | algorithms | class Random:
def __init__(self, seed: int = 0) - > None:
self . seed = seed
def randint(self, start: int, stop: int) - > int:
return start + int(self . random() * (stop - start + 1))
def random(self) - > float:
x = self . seed & 0xFFFFFFFF
x ^= x << 13 & 0xFFFFFFFF
x ^= x >> 1... | Write your own pseudorandom number generator! | 5872a121056584c25400011d | [
"Algorithms"
] | https://www.codewars.com/kata/5872a121056584c25400011d | 6 kyu |
Everyone Knows AdFly and their Sister Sites.
If we see the Page Source of an ad.fly site we can see this perticular line:
```javascript
var ysmm = 'M=z=dQoPdZH5RWwTc0zIolvaLj2hFmkRZUi95ksMeFSR9VnWbuyF5zwVajHlAX/Od6Tx1EhdS5FIITwWY10VRVvbdjkBwnzWZXDlNFkceSTdVl0W';
```
Believe it or not This is actually the Encoded url w... | algorithms | from base64 import b64decode, b64encode
from random import randint
def adFly_decoder(sc):
return b64decode(b64decode(sc[:: 2] + sc[:: - 2])[26:]) or "Invalid"
def adFly_encoder(url):
temp = b64encode(
"{:02d}https://adf.ly/go.php?u={}" . format(randint(0, 99), b64encode(url)))
return '' . join... | AdFly Encoder and Decoder | 56896d1d6ba4e91b8c00000d | [
"Ciphers",
"Algorithms"
] | https://www.codewars.com/kata/56896d1d6ba4e91b8c00000d | 5 kyu |
A `bouncy number` is a positive integer whose digits neither increase nor decrease. For example, 1235 is an increasing number, 5321 is a decreasing number, and 2351 is a bouncy number. By definition, all numbers under 100 are non-bouncy, and 101 is the first bouncy number.
Determining if a number is bouncy is easy, bu... | reference | def bouncy_count(m):
num = den = 1
for i in range(1, 11):
num *= m + i + i * (i == 10)
den *= i
return 10 * * m - num / / den + 10 * m + 1
| Bouncy Numbers with N Digits | 5769ac186f2dea6304000172 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5769ac186f2dea6304000172 | 5 kyu |
<h1>Castle of Cubes:</h1>
You've been hired by a castle building company.<br>
Their procedure is very simple : In their castles, all the rooms are the same cube.<br>
They build thousands of the same square stone panels, and assemble them (ground,walls,ceiling).<br>
Neighboring rooms share one same panel between them.<b... | algorithms | def panel_count(n, dim=3):
res = n * dim
for k in range(dim, 0, - 1):
if n:
p, d, l = 1, n, []
for r in range(dim, 0, - 1):
s = k < r or round(d * * (1 / r))
l . append(s)
d / /= s
p *= s
for r, s in zip(range(dim, 0, - 1), l):
res += k >= r and p / / s
n -= p... | Castle of Cubes | 5cbcf4d4a0dcd2001e28fc79 | [
"Algorithms"
] | https://www.codewars.com/kata/5cbcf4d4a0dcd2001e28fc79 | 5 kyu |
Help prepare for the entrance exams to art school.
It is known in advance that this year, the school chose the symmetric letter βWβ as the object for the image, and the only condition for its image is only the size that is not known in advance, so as training, you need to come up with a way that accurately depicts the... | reference | def get_w(h):
return [(' ' * w + '*' + ' ' * (2 * (h - w) - 3) + '*' + ' ' * (2 * w - 1) + '*' + ' ' * (2 * (h - w) - 3) + '*' + ' ' * w). replace('**', '*') for w in range(h)] if h > 1 else []
| IntroToArt | 5d7d05d070a6f60015c436d1 | [
"Arrays",
"Strings",
"ASCII Art",
"Fundamentals"
] | https://www.codewars.com/kata/5d7d05d070a6f60015c436d1 | 6 kyu |
Time to build a crontab parser... https://en.wikipedia.org/wiki/Cron
A crontab command is made up of 5 fields in a space separated string:
```
minute: 0-59
hour: 0-23
day of month: 1-31
month: 1-12
day of week: 0-6 (0 == Sunday)
```
Each field can be a combination of the following values:
* a wildcard `*` which equ... | reference | RANGES = {
'minute': (0, 59),
'hour': (0, 23),
'day of month': (1, 31),
'month': (1, 12),
'day of week': (0, 6),
}
ALIASES = {
'month': ' JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC' . split(' '),
'day of week': 'SUN MON TUE WED THU FRI SAT' . split(),
}
def get_alias(fi... | Crontab Parser | 5d7b9ed14cd01b000e7ebb41 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d7b9ed14cd01b000e7ebb41 | 5 kyu |
Fibonacci sequence is defined as follows: `F(n+1) = F(n) + F(n-1)`, where `F(0) = 0, F(1) = 1`.
There are many generalizations, including Tribonacci numbers, Padovan numbers, Lucas numbers, etc. Many of there have their respective katas in codewars, including:
- Fibonacci: https://www.codewars.com/kata/fibonacci-numb... | algorithms | import numpy as np
def generalized_fibonacchi(a, b, n):
return np . dot(np . matrix(np . vstack((np . eye(len(b) - 1, len(b), 1), b[:: - 1])). astype(int), dtype=object) * * n, a)[0, 0]
| Big Generalized Fibonacci numbers | 5d7bb3eda58b36000fcc0bbb | [
"Performance",
"Algorithms",
"Mathematics",
"Big Integers"
] | https://www.codewars.com/kata/5d7bb3eda58b36000fcc0bbb | 4 kyu |
Speedcubing is the hobby involving solving a variety of twisty puzzles, the most famous being the 3x3x3 puzzle or Rubik's Cube, as quickly as possible.
In the majority of Speedcubing competitions, a Cuber solves a scrambled cube 5 times, and their result is found by taking the average of the middle 3 solves (ie. the s... | reference | def cube_times(times):
return (round((sum(times) - (min(times) + max(times))) / 3, 2), min(times))
| Find the Speedcuber's times! | 5d7c7697e8ad48001e642964 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d7c7697e8ad48001e642964 | 7 kyu |
I don't like writing classes like this:
```javascript
function Animal(name,species,age,health,weight,color) {
this.name = name;
this.species = species;
this.age = age;
this.health = health;
this.weight = weight;
this.color = color;
}
```
```coffeescript
Animal = (@name, @species, @age, @health, @weight, @c... | algorithms | def make_class(* args):
class MyClass:
def __init__(self, * vals):
self . __dict__ = {x: y for x, y in zip(args, vals)}
return MyClass
| Make Class | 5d774cfde98179002a7cb3c8 | [
"Object-oriented Programming",
"Algorithms"
] | https://www.codewars.com/kata/5d774cfde98179002a7cb3c8 | 7 kyu |
Some integral numbers are odd. All are more odd, or less odd, than others.
Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`.
Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Re... | algorithms | def more_odd(a, b):
if a % 2 == b % 2:
return more_odd(a / / 2, b / / 2)
return - 1 if a % 2 else 1
def oddest(a):
return sorted(a, cmp=more_odd)[0]
| Odder than the rest - 2 | 5d72704499ee62001a7068c7 | [
"Puzzles",
"Algorithms",
"Recursion"
] | https://www.codewars.com/kata/5d72704499ee62001a7068c7 | 7 kyu |
Integral numbers can be even or odd.
Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`.
Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Recursively. :]
Even numbers are just ... | algorithms | def oddest(numbers):
most_odd = 0 # The current most odd number in the list
max_oddity = - 1 # The current greatest oddity rate, starts at -1 so that even an even number can be the unique most odd
is_unique = True # If the current most odd number is really the most, so if there is no unique oddest number... | Odder than the rest | 5d6ee508aa004c0019723c1c | [
"Puzzles",
"Algorithms",
"Recursion"
] | https://www.codewars.com/kata/5d6ee508aa004c0019723c1c | 6 kyu |
A **Seven Segment Display** is an electronic display device, used to display decimal or hexadecimal numerals. It involves seven led segments that are lit in specific combinations to represent a specific numeral. An example of each combination is shown below:
 for r in '''\
### | | ### | ### | | ### | ### | ### | ### | ### |
# # | # | # | # | # # | # | # | # | # # | # # |
# # | # | # | # | # # | # | # | # | # # | # # |
# # | # | # | # | # # | # | # | # | # # | # # |
| | ### | ### | ### | ### | ### | | ### | ### |
# # | # | # | # | # | # | #... | Seven Segment Display | 5d7091aa7bf8d0001200c133 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5d7091aa7bf8d0001200c133 | 6 kyu |
~~~if-not:ruby,python
Return `1` when *any* odd bit of `x` equals 1; `0` otherwise.
~~~
~~~if:ruby,python
Return `true` when *any* odd bit of `x` equals 1; `false` otherwise.
~~~
Assume that:
* `x` is an unsigned, 32-bit integer;
* the bits are zero-indexed (the least significant bit is position 0)
## Examples
```
... | reference | def any_odd(n):
return 1 if '1' in bin(n)[2:][- 2:: - 2] else 0
| Is There an Odd Bit? | 5d6f49d85e45290016bf4718 | [
"Bits",
"Fundamentals"
] | https://www.codewars.com/kata/5d6f49d85e45290016bf4718 | 7 kyu |
John wants to give a total bonus of `$851` to his three employees taking *fairly as possible* into account their number of days of absence during the period under consideration.
Employee A was absent `18` days, B `15` days, and C `12` days.
**The more absences, the lower the bonus** ...
How much should each employee... | reference | def bonus(arr, s):
# ΠΠΠ―Π’Π¬, Π½ΠΈΡ
ΡΡ Π½Π΅ Π½Π°ΠΏΠΈΡΠ°Π½ΠΎ ΠΊΠ°ΠΊ ΠΏΠΎΠ»ΡΡΠΈΡΡ ΡΡΠΎΡ ΡΠ±Π°Π½ΡΠΉ Π±ΠΎΠ½ΡΡ!!!!!!
# Π― Π±Π»ΡΡΡ Π½Π° ΡΠ°ΠΉΡ ΠΏΠΎ ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΠΈΡΠΎΠ²Π°Π½ΠΈΡ Π·Π°ΡΡΠ» ΠΈΠ»ΠΈ Π½Π° ΡΠ°ΠΉΡ ΡΠΊΡΡΡΠ°ΡΠ΅Π½ΠΎΡΠΎΠ² ΠΠΠ₯Π£Π?!?!?!?!
print("ΠΠΈΡ
ΡΡ Π½Π΅ ΠΏΠΎΠ½ΡΠ», Π½ΠΎ ΠΎΡΠ΅Π½Ρ ΠΈΠ½ΡΠ΅ΡΠ΅ΡΠ½ΠΎ!!!!")
s = s / (sum(1 / n for n in arr))
return [round(s / n) for n in arr]
| Bonuses | 5d68d05e7a60ba002b0053f6 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d68d05e7a60ba002b0053f6 | 6 kyu |
It's your best friend's birthday! You already bought a box for the present. Now you want to pack the present in the box. You want to decorate the box with a ribbon and a bow.
But how much cm of ribbon do you need?
Write the method ```wrap``` that calculates that!
A box has a ```height```, a ```width``` and a ```leng... | reference | def wrap(height, width, length):
a, b, c = sorted([height, width, length])
return 4 * a + 2 * c + 2 * b + 20
| Happy Birthday | 5d65fbdfb96e1800282b5ee0 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d65fbdfb96e1800282b5ee0 | 7 kyu |
Given an array `A` and an integer `x`, map each element in the array to `F(A[i],x)` then return the xor sum of the resulting array.
where F(n,x) is defined as follows:
F(n, x) = <sup>x</sup>C<sub>x</sub> **+** <sup>x+1</sup>C<sub>x</sub> **+** <sup>x+2</sup>C<sub>x</sub> **+** ... **+** <sup>n</sup>C<sub>x</sub>
and... | algorithms | from functools import reduce
from gmpy2 import comb
from operator import xor
def transform(a, x):
return reduce(xor, (comb(n + 1, x + 1) for n in a))
| Combinations xor sum | 5bb9053a528b29a970000113 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5bb9053a528b29a970000113 | 6 kyu |
In this kata, you are given a list containing the times that employees have clocked in and clocked out of work.
Your job is to convert that list into a list of the hours that employee has worked for each sublist
e.g.:
clock = [ ["2:00pm", "8:00pm"], ["8:00am", "4:30pm"] ] == [6.0, 8.5]
Convert the time into a f... | reference | def get_hours(shifts):
return [clockToDelta(s) for s in shifts]
def clockToDelta(shift):
start, end = map(convert, shift)
return round(4 * (end - start)) / 4 % 24
def convert(clock):
h, m = map(int, clock[: - 2]. split(':'))
return h % 12 + 12 * (clock[- 2] == 'p') + m / 60
| On the clock | 5d629a6c65c7010022e3b226 | [
"Date Time",
"Fundamentals"
] | https://www.codewars.com/kata/5d629a6c65c7010022e3b226 | 6 kyu |
Given a 2D ( nested ) list ( array, vector, .. ) of size `m * n`, your task is to find the sum of the minimum values in each row.
For Example:
```text
[ [ 1, 2, 3, 4, 5 ] # minimum value of row is 1
, [ 5, 6, 7, 8, 9 ] # minimum value of row is 5
, [ 20, 21, 34, 56, 100 ] # minimum value of row is 2... | reference | def sum_of_minimums(numbers):
return sum(map(min, numbers))
| Sum of Minimums! | 5d5ee4c35162d9001af7d699 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5d5ee4c35162d9001af7d699 | 7 kyu |
## Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they play simple word games for fun. This is one of those days!
## Today's Game
Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word (made up... | algorithms | def mutations(alice, bob, word, first):
seen = {word}
mapping = {0: alice, 1: bob}
prev_state, state = - 1, - 1
def foo(word, first):
nonlocal state, prev_state
foo . counter += 1
if foo . counter > 2 and state < 0 or foo . counter > 2 and prev_state < 0:
return
for a_word i... | Four Letter Words ~ Mutations | 5cb5eb1f03c3ff4778402099 | [
"Strings",
"Arrays",
"Games",
"Parsing",
"Algorithms"
] | https://www.codewars.com/kata/5cb5eb1f03c3ff4778402099 | 5 kyu |
Given a triangle of consecutive odd numbers:
```
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
```
find the triangle's row knowing its index (the rows are 1-indexed), e.g.:
```
odd_row(1) == [1]
odd_row(2) == [3, 5]
odd_row(3) == [7, 9, 11]
```
**... | algorithms | def odd_row(n): return list(range(n * (n - 1) + 1, n * (n + 1), 2))
| Row of the odd triangle | 5d5a7525207a674b71aa25b5 | [
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/5d5a7525207a674b71aa25b5 | 6 kyu |
In this Kata you are expected to find the coefficients of quadratic equation of the given two roots (`x1` and `x2`).
Equation will be the form of ```ax^2 + bx + c = 0```
<b>Return type</b> is a Vector (tuple in Rust, Array in Ruby) containing coefficients of the equations in the order `(a, b, c)`.
Since there are in... | reference | def quadratic(x1, x2):
return (1, - x1 - x2, x1 * x2)
| Quadratic Coefficients Solver | 5d59576768ba810001f1f8d6 | [
"Fundamentals",
"Mathematics",
"Algebra"
] | https://www.codewars.com/kata/5d59576768ba810001f1f8d6 | 8 kyu |
You are an aerial firefighter (someone who drops water on fires from above in order to extinguish them) and your goal is to work out the minimum amount of bombs you need to drop in order to fully extinguish the fire (the fire department has budgeting concerns and you can't just be dropping tons of bombs, they need that... | algorithms | from math import ceil
def waterbombs(fire, w):
return sum(ceil(len(l) / w) for l in fire . split('Y'))
| Aerial Firefighting | 5d10d53a4b67bb00211ca8af | [
"Strings",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5d10d53a4b67bb00211ca8af | 7 kyu |
## Intro:
Imagine that you are given a task to hang a curtain of known length `(length)` on a window using curtain hooks. _**It is required**_ of you that the spacing (distance) between each hook is _**uniform**_ throughout the whole curtain and is lower than or equal to provided distance `(max_hook_dist)`. _**However... | games | from math import *
def number_of_hooks(length, maxHook):
return length and 2 * * ceil(max(0, log2(length / maxHook))) + 1
| Hanging the curtains | 5d532b1893309000125cc43d | [
"Puzzles",
"Mathematics",
"Algorithms",
"Logic"
] | https://www.codewars.com/kata/5d532b1893309000125cc43d | 7 kyu |
Your task is to add up letters to one letter.
```if-not:haskell,crystal,cpp,dart,elixir,reason,c,r,factor,java,swift,racket,bf,go,clojure,csharp,elm,lua,nim,kotlin,groovy,scala,sql,fortran,rust,fsharp,objc,powershell,vb,erlang,cfml,prolog,shell,haxe
The function will be given a variable amount of arguments, each one be... | algorithms | def add_letters(* letters):
return chr((sum(ord(c) - 96 for c in letters) - 1) % 26 + 97)
| Alphabetical Addition | 5d50e3914861a500121e1958 | [
"Algorithms"
] | https://www.codewars.com/kata/5d50e3914861a500121e1958 | 7 kyu |
Your task is to determine how much time will take to download all the files in your Torrent and the order of completion. All downloads are started and done in parallel like in real life. In the event of a tie you should list alphabeticaly.
### Help:
* GB: Giga Byte
* Mbps: Mega bits per second
* G = 1000 M
* Byte =... | reference | def torrent(files):
files = sorted(files, key=lambda f: (
f['size_GB'] / f['speed_Mbps'], f['name']))
last = files[- 1]
return [f['name'] for f in files], 8000 * last['size_GB'] / last['speed_Mbps']
| Computer problem series #2: Torrent download | 5d4c6809089c6e5031f189ed | [
"Fundamentals"
] | https://www.codewars.com/kata/5d4c6809089c6e5031f189ed | 7 kyu |
Two fishing vessels are sailing the open ocean, both on a joint ops fishing mission.
On a high stakes, high reward expidition - the ships have adopted the strategy of hanging a net between the two ships.
The net is **40 miles long**. Once the straight-line distance between the ships is greater than 40 miles, the net ... | algorithms | from math import sin, radians
def find_time_to_break(bearing_A, bearing_B):
a = radians(abs(bearing_A - bearing_B) / 2)
return 40 / (3 * sin(a)) if a else float("inf")
| Time until distance between moving ships | 5d4dd5c9af0c4c0019247110 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5d4dd5c9af0c4c0019247110 | 7 kyu |
# Task
Given the birthdates of two people, find the date when the younger one is exactly half the age of the other.
# Notes
* The dates are given in the format YYYY-MM-DD and are not sorted in any particular order
* Round **down** to the nearest day
* Return the result as a string, like the input dates | reference | from dateutil . parser import parse
def half_life(* persons):
p1, p2 = sorted(map(parse, persons))
return str(p2 + (p2 - p1))[: 10]
| Half Life | 5d472159d4f8c3001d81b1f8 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5d472159d4f8c3001d81b1f8 | 7 kyu |
Inside of the city there are many gangs, each with differing numbers of members wielding different weapons and possessing different strength levels. The gangs do not really want to fight one another, and so the "If you can't beat 'em, join 'em" rule applies. The gangs start combining with the most powerful gangs being ... | algorithms | from itertools import chain
def cant_beat_so_join(lsts):
return list(chain . from_iterable(sorted(lsts, key=sum, reverse=True)))
| If you can't beat 'em, join 'em! | 5d37899a3b34c6002df273ee | [
"Fundamentals",
"Arrays",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5d37899a3b34c6002df273ee | 7 kyu |
Create a __moreZeros__ function which will __receive a string__ for input, and __return an array__ (or null terminated string in C) containing only the characters from that string whose __binary representation of its ASCII value__ consists of _more zeros than ones_.
You should __remove any duplicate characters__, kee... | reference | def more_zeros(s):
results = []
for letter in s:
dec_repr = bin(ord(letter))[2:]
if (dec_repr . count("0") > dec_repr . count("1")) and (letter not in results):
results . append(letter)
return results
| More Zeros than Ones | 5d41e16d8bad42002208fe1a | [
"Fundamentals"
] | https://www.codewars.com/kata/5d41e16d8bad42002208fe1a | 6 kyu |
The town sheriff dislikes odd numbers and wants all odd numbered families out of town! In town crowds can form and individuals are often mixed with other people and families. However you can distinguish the family they belong to by the number on the shirts they wear. As the sheriff's assistant it's your job to find all... | reference | def odd_ones_out(numbers):
return [i for i in numbers if numbers . count(i) % 2 == 0]
| Odd Ones Out! | 5d376cdc9bcee7001fcb84c0 | [
"Fundamentals",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5d376cdc9bcee7001fcb84c0 | 7 kyu |
This kata is the part two version of the [Find X](https://www.codewars.com/kata/find-x) kata, if you haven't solved it you should try solving it, it's pretty easy.
In this version you're given the following function
```python
def find_x(n):
if n == 0: return 0
x = 0
for i in range(1, n+1):
x += find_x(... | reference | M = 10 * * 9 + 7
def find_x(n):
return 3 * (pow(2, n + 1, M) - n - 2) % M
| Find X β
‘ | 5d339b01496f8d001054887f | [
"Fundamentals"
] | https://www.codewars.com/kata/5d339b01496f8d001054887f | 6 kyu |
The goal of this Kata is to write a function that will receive an array of strings as its single argument, then the strings are each processed and sorted (in desending order) based on the length of the single longest sub-string of contiguous vowels ( `aeiouAEIOU` ) that may be contained within the string. The strings m... | reference | import re
def sort_strings_by_vowels(seq):
return sorted(seq, reverse=True, key=lambda x: max((len(i) for i in re . findall(r'[aeiouAEIOU]+', x)), default=0))
| Sort Strings by Most Contiguous Vowels | 5d2d0d34bceae80027bffddb | [
"Fundamentals",
"Strings",
"Sorting"
] | https://www.codewars.com/kata/5d2d0d34bceae80027bffddb | 6 kyu |
## An Invitation
Most of us played with toy blocks growing up. It was fun and you learned stuff. So what else can you do but rise to the challenge when a 3-year old exclaims, "Look, I made a square!", then pointing to a pile of blocks, "Can _you_ do it?"
## Our Blocks
Just to play along, of course we'll be viewing t... | algorithms | def build_square(blocks):
for x in range(4):
if 4 in blocks:
blocks . remove(4)
elif 3 in blocks and 1 in blocks:
blocks . remove(3)
blocks . remove(1)
elif blocks . count(2) >= 2:
blocks . remove(2)
blocks . remove(2)
elif 2 in blocks and blocks . count(1) >= 2:
b... | Playing With Toy Blocks ~ Can you build a 4x4 square? | 5cab471da732b30018968071 | [
"Logic",
"Arrays",
"Games",
"Puzzles",
"Geometry",
"Algorithms"
] | https://www.codewars.com/kata/5cab471da732b30018968071 | 6 kyu |
# Inner join
In SQL, an inner join query joins two tables by selecting records which satisfy the join predicates and combining column values of the two tables.
# Task
Write a function to mimic an SQL inner join. The function should take two 2D arrays and two index values, which specifies the column to perform the j... | reference | def inner_join(arrA, arrB, indA, indB):
return [[* x, * y]
for x in arrA if x[indA] is not None
for y in arrB if y[indB] == x[indA]]
| 2D array inner join | 56b7a75cbd06e6237000138b | [
"Fundamentals",
"Matrix",
"Algorithms"
] | https://www.codewars.com/kata/56b7a75cbd06e6237000138b | 6 kyu |
[Wikipedia](https://en.wikipedia.org/wiki/Baum%E2%80%93Sweet_sequence): The BaumβSweet sequence is an infinite automatic sequence of `0`s and `1`s defined by the rule:
b<sub>n</sub> = `1` if the binary representation of `n` contains no block of consecutive `0`s of odd length;
b<sub>n</sub> = `0` otherwise;
for `n β₯... | algorithms | from itertools import count
def baum_sweet():
yield 1
for i in count(1):
yield not any(map(lambda x: len(x) % 2, bin(i). split('1')))
| The Baum-Sweet sequence | 5d2659626c7aec0022cb8006 | [
"Algorithms"
] | https://www.codewars.com/kata/5d2659626c7aec0022cb8006 | 7 kyu |
[Wikipedia](https://en.wikipedia.org/wiki/Regular_paperfolding_sequence): The **regular paperfolding sequence**, also known as the **dragon curve sequence**, is an infinite automatic sequence of `0`s and `1`s defined as the **limit** of inserting an alternating sequence of `1`s and `0`s around and between the terms of ... | algorithms | def paper_fold():
gen = paper_fold()
while True:
yield 1
yield next(gen)
yield 0
yield next(gen)
| The PaperFold sequence | 5d26721d48430e0016914faa | [
"Algorithms"
] | https://www.codewars.com/kata/5d26721d48430e0016914faa | 6 kyu |
The Takeuchi function is defined as:
```python
def T(x,y,z):
if x β€ y:
return y
else:
return T(T(x-1,y,z),T(y-1,z,x),T(z-1,x,y))
```
```javascript
function T(x,y,z){
if (x β€ y)
return y;
else
return T(T(x-1,y,z),T(y-1,z,x),T(z-1,x,y));
}
```
```haskell
t :: Int -> Int -> Int -> Int
t x y z = if... | reference | from functools import lru_cache
@ lru_cache(maxsize=None)
def T(x, y, z):
if x <= y:
return y, 0
else:
(a, ac), (b, bc), (c, cc) = T(x - 1, y, z), T(y - 1, z, x), T(z - 1, x, y)
d, dc = T(a, b, c)
return d, 1 + ac + bc + cc + dc
def solve(n):
count = T(n, 0, n + 1)[1]
... | The Takeuchi function | 5d2477487c046b0011b45254 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d2477487c046b0011b45254 | 6 kyu |
Some new cashiers started to work at your restaurant.
They are good at taking orders, but they don't know how to capitalize words, or use a space bar!
All the orders they create look something like this:
`"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"`
The kitchen staff are threatening to quit,... | reference | def get_order(order):
menu = ['burger', 'fries', 'chicken', 'pizza',
'sandwich', 'onionrings', 'milkshake', 'coke']
clean_order = ''
for i in menu:
clean_order += (i . capitalize() + ' ') * order . count(i)
return clean_order[: - 1]
| New Cashier Does Not Know About Space or Shift | 5d23d89906f92a00267bb83d | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5d23d89906f92a00267bb83d | 6 kyu |
In an infinite array with two rows, the numbers in the top row are denoted
`. . . , A[β2], A[β1], A[0], A[1], A[2], . . .`
and the numbers in the bottom row are denoted
`. . . , B[β2], B[β1], B[0], B[1], B[2], . . .`
For each integer `k`, the entry `A[k]` is directly above
the entry `B[k]` in the array, as shown:
... | algorithms | def find_a(lst, n):
if n < 0:
return find_a(lst[:: - 1], 3 - n)
if n < 4:
return lst[n]
a, b, c, d = lst
for _ in range(n - 3):
a, b, c, d = b, c, d, 6 * d - 10 * c + 6 * b - a
return d
| Averaging in an Infinite Array | 5d1eb2db874bdf9bf6a4b2aa | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5d1eb2db874bdf9bf6a4b2aa | 6 kyu |
Given an array of integers `a` and integers `t` and `x`, count how many elements in the array you can make equal to `t` by **increasing** / **decreasing** it by `x` (or doing nothing).
*EASY!*
```python
# ex 1
a = [11, 5, 3]
t = 7
x = 2
count(a, t, x) # => 3
```
- you can make 11 equal to 7 by subtracting 2 twice
- ... | reference | def count(a, t, x):
return sum(not (t - v) % x if x else t == v for v in a)
| Make Equal | 5d1e1560c193ae0015b601a2 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d1e1560c193ae0015b601a2 | 7 kyu |
A strongness of an even number is the number of times we can successively divide by 2 until we reach an odd number starting with an even number n.
For example, if n = 12, then
* 12 / 2 = 6
* 6 / 2 = 3
So we divided successively 2 times and we reached 3, so the strongness of 12 is `2`.
If n = 16 then
* 16 / 2 = 8
* 8... | algorithms | """Strongest even number in an interval kata
Defines strongest_even(n, m) which returns the strongest even number in the set
of integers on the interval [n, m].
Constraints:
1. 1 <= n < m < MAX_INT
Note:
1. The evenness of zero is need not be defined given the constraints.
2. In Python 3, the int type is ... | Strongest even number in an interval | 5d16af632cf48200254a6244 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5d16af632cf48200254a6244 | 6 kyu |
In this Kata, you will be given a multi-dimensional array containing `2 or more` sub-arrays of integers. Your task is to find the maximum product that can be formed by taking any one element from each sub-array.
```
Examples:
solve( [[1, 2],[3, 4]] ) = 8. The max product is given by 2 * 4
solve( [[10,-15],[-1,-3]] ) =... | reference | def solve(arr):
p, q = 1, 1
for k in arr:
x, y = max(k), min(k)
a = p * x
b = q * x
c = p * y
d = q * y
p = max(a, b, c, d)
q = min(a, b, c, d)
return max(p, q)
| Simple array product | 5d0365accfd09600130a00c9 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d0365accfd09600130a00c9 | 7 kyu |
## Baby Shark Lyrics

Create a function, as short as possible, that returns this lyrics.
Your code should be less than `300` characters.
Watch out for the three points at... | reference | def baby_shark_lyrics(): return "\n" . join(f" { y } , { ' doo' * 6 } \n" * 3 + y + "!" for y in [
x + " shark" for x in "Baby Mommy Daddy Grandma Grandpa" . split()] + ["Let's go hunt"]) + "\nRun away,β¦"
| Baby shark lyrics generator | 5d076515e102162ac0dc514e | [
"Strings",
"Lists",
"Fundamentals",
"Restricted"
] | https://www.codewars.com/kata/5d076515e102162ac0dc514e | 7 kyu |
`Lithium_3` has the electron configuration: `2)1)`, meaning it has 2 electrons in the first shell, 1 in the second shell.
Electrons are always torn from the last shell when an ionization occurs. In the `Li` atom above, if we tear one electron apart from it, it becomes `2)`.
This ionization as a cost in energy, which... | reference | def electron_ionization(electrons, rc, arad):
res, el, rd, prot = 0, electrons[:], arad / len(electrons), sum(electrons)
while rc and el:
res += min(rc, el[- 1]) * prot / (rd * len(el)) * * 2
rc -= min(rc, el[- 1])
el . pop()
return res
| Extract the Electrons | 5d023b69ac68b82dd2cdf70b | [
"Fundamentals"
] | https://www.codewars.com/kata/5d023b69ac68b82dd2cdf70b | 6 kyu |
Let us consider this example (array written in general format):
`ls = [0, 1, 3, 6, 10]`
Its following parts:
```
ls = [0, 1, 3, 6, 10]
ls = [1, 3, 6, 10]
ls = [3, 6, 10]
ls = [6, 10]
ls = [10]
ls = []
```
The corresponding sums are (put together in a list):
`[20, 20, 19, 16, 10, 0]`
The function `parts_sums` (or its... | algorithms | def parts_sums(ls):
result = [sum(ls)]
for item in ls:
result . append(result[- 1] - item)
return result
| Sums of Parts | 5ce399e0047a45001c853c2b | [
"Fundamentals",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5ce399e0047a45001c853c2b | 6 kyu |
The principle of spiral permutation consists in concatenating the different characters of a string in a spiral manner starting with the last character (last character, first character, character before last character, second character, etc.).
This principle is illustrated by the example below, which for a starting str... | games | def sp(s):
ln = len(s)
res = [''] * ln
res[:: 2] = s[ln / / 2:][:: - 1]
res[1:: 2] = s[: ln / / 2]
return '' . join(res)
def spiral_permutations(s):
seen, cur, res = {s}, s, [s]
while True:
cur = sp(cur)
if cur in seen:
return res
else:
seen . add(cur... | Word Spiral Permutations Generator | 5cfca6670310c20001286bc8 | [
"Puzzles"
] | https://www.codewars.com/kata/5cfca6670310c20001286bc8 | 6 kyu |
In this Kata, you will be given a string and your task will be to return the length of the longest prefix that is also a suffix. A prefix is the start of a string while the suffix is the end of a string. For instance, the prefixes of the string `"abcd"` are `["a","ab","abc"]`. The suffixes are `["bcd", "cd", "d"]`. Yo... | reference | def solve(st):
return next((n for n in range(len(st) / / 2, 0, - 1) if st[: n] == st[- n:]), 0)
| String prefix and suffix | 5ce969ab07d4b7002dcaa7a1 | [
"Fundamentals"
] | https://www.codewars.com/kata/5ce969ab07d4b7002dcaa7a1 | 7 kyu |
# Summary
In this kata, you have to make a function named `uglify_word` (`uglifyWord` in Java and Javascript). It accepts a string parameter.
# What does the uglify_word do?
It checks the char in the given string from the front with an iteration, in the iteration it does these steps:
1. There is a flag and it will be ... | algorithms | def uglify_word(s):
flag = 1
ugly = []
for c in s:
ugly . append(c . upper() if flag else c . lower())
flag = not flag or not c . isalpha()
return '' . join(ugly)
| Uglify Word | 5ce6cf94cb83dc0020da1929 | [
"Algorithms"
] | https://www.codewars.com/kata/5ce6cf94cb83dc0020da1929 | 7 kyu |
In this Kata, we will check if a string contains consecutive letters as they appear in the English alphabet and if each letter occurs only once.
```haskell
Rules are: (1) the letters are adjacent in the English alphabet, and (2) each letter occurs only once.
For example:
solve("abc") = True, because it contains a,b... | reference | import string
def solve(st):
return '' . join(sorted(st)) in string . ascii_letters
| Consecutive letters | 5ce6728c939bf80029988b57 | [
"Fundamentals"
] | https://www.codewars.com/kata/5ce6728c939bf80029988b57 | 7 kyu |
Your job is to list all of the numbers up to 2 ** `n` - 1 that contain a 1 at the same places/bits as the binary representation of b.`b` will be 1,2,4,8,etc.</br>
For example:
`solution(4,2)` would return [2,3,6,7,10,11,14,15].</br>
The binary numbers from 1 to 16 are:</br>
8 4 2 1 (place)</br>
0 0 0 1</br>
0 0 1 0</br... | reference | def solution(n, b):
return [x for x in range(1 << n) if x & b]
| Fun with binary numbers | 5ce04eadd103f4001edd8986 | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/5ce04eadd103f4001edd8986 | 7 kyu |
Most football fans love it for the goals and excitement. Well, this Kata doesn't.
You are to handle the referee's little notebook and count the players who were sent off for fouls and misbehavior.
The rules:
Two teams, named "A" and "B" have 11 players each; players on each team are numbered from 1 to 11.
Any player m... | reference | def men_still_standing(cards):
# generate teams
A = {k: 0 for k in range(1, 12)}
B = A . copy()
for card in cards:
# parse card
team = A if card[0] == "A" else B
player = int(card[1: - 1])
color = card[- 1]
if player not in team:
continue
# record penalty
... | Football - Yellow and Red Cards | 5cde4e3f52910d00130dc92c | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/5cde4e3f52910d00130dc92c | 6 kyu |
In this Kata you are a game developer and have programmed the #1 MMORPG(Massively Multiplayer Online Role Playing Game) worldwide!!! Many suggestions came across you to make the game better, one of which you are interested in and will start working on at once.
Players in the game have levels from 1 to 170, XP(short fo... | algorithms | def xp_to_target_lvl(* args):
if len(args) < 2:
return 'Input is invalid.'
current_xp, target_lvl = args
if not isinstance(target_lvl, int):
return 'Input is invalid.'
if not (0 < target_lvl < 171):
return 'Input is invalid.'
if current_xp < 0:
return 'Input is invalid.'
level = ... | Level Up! | 593dbaccdf1adef94100006c | [
"Iterators",
"Algorithms"
] | https://www.codewars.com/kata/593dbaccdf1adef94100006c | 6 kyu |
We want to define the location `x`, `y` of a `point` on a two-dimensional plane where `x` and `y` are positive integers.
Our definition of such a `point` will return a function (procedure). There are several possible functions to do that.
Possible form of `point`:
```if:racket
~~~
(define (point a b)
(lambda ...))... | reference | def point(a, b):
def f(): return (a, b)
f . x = a
f . y = b
return f
def fst(pt):
return pt . x
def snd(pt):
return pt . y
def sqr_dist(pt1, pt2):
return (pt2 . x - pt1 . x) * * 2 + (pt2 . y - pt1 . y) * * 2
def line(pt1, pt2):
a = pt1 . y - pt2 . y
b = pt2 . x - pt1 ... | Change your Points of View | 5ca3ae9bb7de3a0025c5c740 | [
"Fundamentals"
] | https://www.codewars.com/kata/5ca3ae9bb7de3a0025c5c740 | 6 kyu |
Your job is to implement a function which returns the last `D` digits of an integer `N` as a list.
### Special cases:
* If `D > (the number of digits of N)`, return all the digits.
* If `D <= 0`, return an empty list.
## Examples:
```
N = 1
D = 1
result = [1]
N = 1234
D = 2
result = [3, 4]
N = 637547
D = 6
result... | reference | def solution(n, d):
return [int(c) for c in str(n)[- d:]] if d > 0 else []
| last digits of a number | 5cd5ba1ce4471a00256930c0 | [
"Fundamentals"
] | https://www.codewars.com/kata/5cd5ba1ce4471a00256930c0 | 7 kyu |
# Summary:
Given a number, `num`, return the shortest amount of `steps` it would take from 1, to land exactly on that number.
# Description:
A `step` is defined as either:
- Adding 1 to the number: `num += 1`
- Doubling the number: `num *= 2`
You will always start from the number `1` and you will have to return th... | games | def shortest_steps_to_num(num):
steps = 0
while num != 1:
if num % 2:
num -= 1
else:
num / /= 2
steps += 1
return steps
| Shortest steps to a number | 5cd4aec6abc7260028dcd942 | [
"Puzzles",
"Mathematics",
"Fundamentals",
"Games"
] | https://www.codewars.com/kata/5cd4aec6abc7260028dcd942 | 6 kyu |
Everybody loves **pi**, but what if **pi** were a square? Given a number of digits ```digits```, find the smallest integer whose square is greater or equal to the sum of the squares of the first ```digits``` digits of pi, including the ```3``` before the decimal point.
**Note:** Test cases will not extend beyond 100 d... | algorithms | from math import ceil
PI_DIGITS_SQUARED = [int(d) * * 2 for d in "31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"]
def square_pi(n):
return ceil(sum(PI_DIGITS_SQUARED[: n]) * * 0.5)
| Square Pi's | 5cd12646cf44af0020c727dd | [
"Algorithms"
] | https://www.codewars.com/kata/5cd12646cf44af0020c727dd | 7 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.