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
Flash has invited his nemesis The Turtle (He actually was a real villain! ) to play his favourite card game, SNAP. In this game a 52 card deck is dealt out so both Flash and the Turtle get 26 random cards. Each players cards will be represented by an array like below Flash’s pile: ```[ 'A', '5', 'Q', 'Q', '6', '2', ...
reference
def round(flash_pile, turtle_pile): faceup_pile = [] while turtle_pile: for pile in flash_pile, turtle_pile: faceup_pile . append(pile . pop(0)) if len(faceup_pile) >= 2 and faceup_pile[- 1] == faceup_pile[- 2]: flash_pile . extend(faceup_pile) return True def snap(flash_pile, tu...
SNAP
5b49cc5a578c6ab6b200004c
[ "Recursion", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5b49cc5a578c6ab6b200004c
6 kyu
A friend of mine told me privately: "I don't like palindromes". "why not?" - I replied. "Because when I want to do some programming challenges, I encounter 2 or 3 ones first related with palindromes. I'm fed up" - he confess me with anger. I said to myself:"Thankfully, that doesn't happen in Codewars". Talking seriousl...
reference
def count_pal(n): # No recursion; direct calculation: return [9 * 10 * * ((n - 1) / / 2), 10 * * (n / / 2) * (13 - 9 * (- 1) * * n) / / 2 - 2]
Allergy to Palindromes.
5b33452ab6989d2407000100
[ "Fundamentals", "Algorithms", "Mathematics", "Performance", "Permutations" ]
https://www.codewars.com/kata/5b33452ab6989d2407000100
6 kyu
In this kata, we will check is an array is (hyper)rectangular. A rectangular array is an N-dimensional array with fixed sized within one dimension. Its sizes can be repsented like A1xA2xA3...xAN. That means a N-dimensional array has N sizes. The 'As' are the hyperrectangular properties of an array. You should implem...
algorithms
import numpy as np def hyperrectangularity_properties(arr): try: return np . array(arr, np . int32). shape except: return None
Array Hyperrectangularity
5b33e9c291c746b102000290
[ "Mathematics", "Arrays", "Recursion", "Algorithms", "Data Structures", "Lists" ]
https://www.codewars.com/kata/5b33e9c291c746b102000290
6 kyu
This kata is the third part of a series: [Neighbourhood kata collection](https://www.codewars.com/collections/5b2f4db591c746349d0000ce). You may want to do the first two before trying this version. ___ # Now we are ready for higher dimensions We add one dimension. You should have good spatial thinking to solve this k...
reference
NEIGHBOURHOOD = {"von_neumann": sum, "moore": max} def closer_cells(n_type, distance, x, y, z): return ((x + u, y + v, z + w) for u in range(- distance, distance + 1) for v in range(- distance, distance + 1) for w in range(- distance, distance + 1) if 0 < NEIGHBOURHOOD[n_type](map(ab...
3D Cellular Neighbourhood
5b33fee525c2bb5753000168
[ "Algorithms", "Data Structures", "Arrays", "Lists", "Matrix" ]
https://www.codewars.com/kata/5b33fee525c2bb5753000168
6 kyu
This kata is the second part of a series: [Neighbourhood kata collection](https://www.codewars.com/collections/5b2f4db591c746349d0000ce). You may want to do the first one before trying this version. ___ # Now we will implement the distance The distance extends the reach of the neighbourhood - instead of returning on...
algorithms
def get_neighbourhood(t, a, c, d=1): r, t = [], t == "von_neumann" x, y = c if x < len(a) and y < len(a[0]): for i in range(- d, d + 1): for j in range(- d + abs(i) * t, d - abs(i) * t + 1): try: if x + i >= 0 and y + j >= 0 and (i or j): r . append(a[x + i][y + j]) exce...
2D Cellular Neighbourhood - Part 2
5b315b8ca454c8c5b40003a2
[ "Algorithms", "Data Structures", "Arrays", "Matrix" ]
https://www.codewars.com/kata/5b315b8ca454c8c5b40003a2
6 kyu
Related to [MrZizoScream's Product Array](https://www.codewars.com/kata/product-array-array-series-number-5) kata. You might want to solve that one first :) This is an adaptation of a problem I came across on LeetCode. Given an array of numbers, your task is to return a new array where each index (`new_array[i]`) is...
reference
from functools import reduce def product_sans_n(nums): z = nums . count(0) if z > 1: return [0] * len(nums) p = reduce(int . __mul__, (v for v in nums if v)) return [not v and p for v in nums] if z else [p / / v for v in nums]
Array Product (Sans n)
5b3e609cd58499284100007a
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5b3e609cd58499284100007a
6 kyu
Roma is programmer and he likes memes about IT, Maxim is chemist and he likes memes about chemistry, Danik is designer and he likes memes about design, and Vlad likes all other memes. ___ You will be given a meme (string), and your task is to identify its category, and send it to the right receiver: `IT - 'Roma...
reference
import re from itertools import accumulate patterns = [ (re . compile('.*' . join('bug'), flags=re . I), 'Roma'), (re . compile('.*' . join('boom'), flags=re . I), 'Maxim'), (re . compile('.*' . join('edits'), flags=re . I), 'Danik'), ] def memesorting(meme): return next((who for m in accumu...
Memesorting
5b6183066d0db7bfac0000bb
[ "Strings", "Regular Expressions", "Fundamentals", "Sorting" ]
https://www.codewars.com/kata/5b6183066d0db7bfac0000bb
6 kyu
We have a big list having values fom 1 to n, occurring only once but unordered with an unknown amount of missing values. The number `n` will be considered the maximum value of the array. We have to output the missing numbers sorted by value. Example: ``` [8, 10, 11, 7, 3, 15, 6, 1, 14, 5, 12] ---> [2, 4, 9, 13] ``` T...
reference
def miss_nums_finder(arr): mx = max(arr) s = set(arr) return [x for x in range(1, mx) if x not in s]
Unknown Amount of Missing Numbers in an Unordered Array. (Hardcore version)
5b559899f7e38620ef000803
[ "Algorithms", "Performance", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5b559899f7e38620ef000803
6 kyu
Given the molecular mass of two molecules `$M_1$` and `$M_2$`, their masses present `$m_1$` and `$m_2$` in a vessel of volume `$V$` at a specific temperature `$T$`, find the total pressure `$P_{total}$` exerted by the molecules. Formula to calculate the pressure is: ```math \LARGE P_{total} = {{({{m_1} \over {M_1}} +...
reference
def solution(M1, M2, m1, m2, V, T): return (m1 / M1 + m2 / M2) * 0.082 * (T + 273.15) / V
Total pressure calculation
5b7ea71db90cc0f17c000a5a
[ "Fundamentals" ]
https://www.codewars.com/kata/5b7ea71db90cc0f17c000a5a
8 kyu
```if:python Given a sorted array of distinct integers, write a function `index_equals_value` that returns the lowest index for which `array[index] == index`. Return `-1` if there is no such index. ``` ```if:haskell,javascript Given a sorted array of distinct integers, write a function `indexEqualsValue` that returns...
algorithms
def index_equals_value(arr): lo, hi = 0, len(arr) while lo < hi: mid = lo + hi >> 1 if arr[mid] >= mid: hi = mid else: lo = mid + 1 return lo if lo < len(arr) and arr[lo] == lo else - 1
Element equals its index
5b7176768adeae9bc9000056
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5b7176768adeae9bc9000056
6 kyu
In this Kata, we define an arithmetic progression as a series of integers in which the differences between adjacent numbers are the same. You will be given an array of ints of `length > 2` and your task will be to convert it into an arithmetic progression by the following rule: ```Haskell For each element there are exa...
reference
def solve(arr): res = [] for first in (arr[0] - 1, arr[0], arr[0] + 1): for second in (arr[1] - 1, arr[1], arr[1] + 1): val, step, count = second, second - \ first, abs(arr[0] - first) + abs(arr[1] - second) for current in arr[2:]: val += step if abs(val - current) > 1: ...
Fix arithmetic progression
5b77b030f0aa5c9114000024
[ "Fundamentals" ]
https://www.codewars.com/kata/5b77b030f0aa5c9114000024
5 kyu
Consider the string `"adfa"` and the following rules: ``` a) each character MUST be changed either to the one before or the one after in alphabet. b) "a" can only be changed to "b" and "z" to "y". ``` From our string, we get: ``` "adfa" -> ["begb","beeb","bcgb","bceb"] Here is another example: "bd" -> ["ae","ac","...
algorithms
def solve(st): return all(True if ord(x) - ord(y) in [- 2, 0, 2] else False for x, y in zip(st, st[:: - 1]))
Create palindrome
5b7bd90ef643c4df7400015d
[ "Algorithms" ]
https://www.codewars.com/kata/5b7bd90ef643c4df7400015d
7 kyu
Assume we take a number `x` and perform any one of the following operations: ```Pearl a) Divide x by 3 (if it is divisible by 3), or b) Multiply x by 2 ``` After each operation, we write down the result. If we start with `9`, we can get a sequence such as: ``` [9,3,6,12,4,8] -- 9/3=3 -> 3*2=6 -> 6*2=12 -> 12/3=4 -> 4*2...
reference
def solve(a): for i in a: li = [i] while 1: if li[- 1] % 3 == 0 and li[- 1] / / 3 in a: li . append(li[- 1] / / 3) elif li[- 1] * 2 in a: li . append(li[- 1] * 2) else: break if len(li) == len(a): return li
Fix array sequence
5b7bae02402fb702ce000159
[ "Fundamentals" ]
https://www.codewars.com/kata/5b7bae02402fb702ce000159
6 kyu
## Given two words, how many letters do you have to remove from them to make them anagrams? # Example * First word : <span style="color: green">c</span> <span style="color: red">od</span> <span style="color: green">e</span> <span style="color: red">w</span> <span style="color: green">ar</span> <span style="color: red...
reference
from collections import Counter def anagram_difference(* words): c1, c2 = map(Counter, words) c1 . subtract(c2) return sum(map(abs, c1 . values()))
Anagram difference
5b1b27c8f60e99a467000041
[ "Strings", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5b1b27c8f60e99a467000041
6 kyu
You have the `radius` of a circle with the center in point `(0,0)`. Write a function that calculates the number of points in the circle where `(x,y)` - the cartesian coordinates of the points - are `integers`. Example: for `radius = 2` the result should be `13`. `0 <= radius <= 1000` ![](http://i.imgur.com/1SMov3s....
reference
def points(R): from math import sqrt point = sum(int(sqrt(R * R - x * x)) for x in range(0, R + 1)) * 4 + 1 return point
Points in the circle
5b55c49d4a317adff500015f
[ "Geometry", "Algorithms", "Logic", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5b55c49d4a317adff500015f
6 kyu
You are given 4 spheres, one of them lies on 3 others; all the spheres are in contact - see the image below: <img src='https://i.imgur.com/LJCiIya.png' alt='figure'> *(The front sphere was made transparent for clear view)* All spheres have the same radius `r` ## Task Your task is to write a function that accepts...
reference
def calculate_distance(r): return round(r * (8 / 3) * * .5, 4) * (r > 0)
[Code Golf] One Line Task: Pyramid of Spheres
5b74532131ef05150d000109
[ "Mathematics", "Geometry", "Restricted", "Fundamentals" ]
https://www.codewars.com/kata/5b74532131ef05150d000109
7 kyu
Your task is to remove all **consecutive duplicate** words from a string, leaving only first words entries. For example: ``` "alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta" --> "alpha beta gamma delta alpha beta gamma delta" ``` Words will be separated by a single space. There will...
algorithms
from itertools import groupby def remove_consecutive_duplicates(s): return ' ' . join(k for k, _ in groupby(s . split()))
Remove consecutive duplicate words
5b39e91ee7a2c103300018b3
[ "Strings", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5b39e91ee7a2c103300018b3
7 kyu
You are the best freelancer in the city. Everybody knows you, but what they don't know, is that you are actually offloading your work to other freelancers and and you rarely need to do any work. You're living the life! To make this process easier you need to write a method called workNeeded to figure out how much time...
reference
def work_needed(project_minutes, freelancers): available_minutes = sum( hours * 60 + minutes for hours, minutes in freelancers) workload_minutes = project_minutes - available_minutes if workload_minutes <= 0: return 'Easy Money!' else: hours, minutes = divmod(workload_minutes, 60)...
Offload your work!
5b3e1dca3da310a4390000f3
[ "Fundamentals" ]
https://www.codewars.com/kata/5b3e1dca3da310a4390000f3
7 kyu
Given a logarithm base X and two values A and B, return a sum of logratihms with the base X: `$ \log_XA + \log_XB $`.
algorithms
from math import log def logs(x, a, b): # Your code here return log(a * b, x)
easy logs
5b68c7029756802aa2000176
[ "Algorithms" ]
https://www.codewars.com/kata/5b68c7029756802aa2000176
8 kyu
We need you to implement a method of receiving commands over a network, processing the information and responding. Our device will send a single packet to you containing data and an instruction which you must perform before returning your reply. To keep things simple, we will be passing a single "packet" as a string....
reference
INSTRUCTIONS = {"0F12": int . __add__, "B7A2": int . __sub__, "C3D9": int . __mul__} def communication_module(packet): header, inst, d1, d2, footer = (packet[i: i + 4] for i in range(0, 20, 4)) res = max(0, min(9999, INSTRUCTIONS[inst](int(d1), int(d2)))) return f" { header } FFFF...
String Packet Based Communications
5b2be37991c7460d17000009
[ "Networks", "Strings", "Fundamentals", "Logic" ]
https://www.codewars.com/kata/5b2be37991c7460d17000009
7 kyu
Your job is to find the gravitational force between two spherical objects (obj1 , obj2). input ==== Two arrays are given : - arr_val (value array), consists of 3 elements - 1st element : mass of obj 1 - 2nd element : mass of obj 2 - 3rd element : distance between their centers - arr_unit (unit array), c...
algorithms
units = {"kg": 1, "g": 1e-3, "mg": 1e-6, "μg": 1e-9, "lb": 0.453592, "m": 1, "cm": 1e-2, "mm": 1e-3, "μm": 1e-6, "ft": 0.3048, "G": 6.67e-11} def solution(v, u): m1, m2, r = (v[i] * units[u[i]] for i in range(3)) return units["G"] * m1 * m2 / r * * 2
Find the force of gravity between two objects
5b609ebc8f47bd595e000627
[ "Algorithms" ]
https://www.codewars.com/kata/5b609ebc8f47bd595e000627
8 kyu
Your company is working with an old, proprietary piece of software. This software has a python API that, for no good reason, supplies you with 32-bit big-endian signed integers as *a list of byte arrays*... You have been tasked with writing a function that receives a list of byte strings and interprets them as integer...
algorithms
def interpret_as_int32(a): s = b"" . join(a) return [int . from_bytes(s[i: i + 4], "big", signed=True) for i in range(0, len(s) / / 4 * 4, 4)]
Receiving integers as bytes
56df605f2ebcd54c4d000335
[ "Algorithms" ]
https://www.codewars.com/kata/56df605f2ebcd54c4d000335
6 kyu
You are working at a lower league football stadium and you've been tasked with automating the scoreboard. The referee will shout out the score, you have already set up the voice recognition module which turns the ref's voice into a string, but the spoken score needs to be converted into a pair for the scoreboard! e.g...
reference
def scoreboard(string): scores = {'nil': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9} return [scores[x] for x in string . split() if x in scores]
Convert the score
5b6c220fa0a661fbf200005d
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5b6c220fa0a661fbf200005d
7 kyu
This kata is the first part of a series: [Neighbourhood kata collection](https://www.codewars.com/collections/5b2f4db591c746349d0000ce). If this one is too easy you can try out the harder katas. ;) ___ The neighbourhood of a cell (in a matrix) are cells that are near to it. There are two popular types: - The [Moore ne...
algorithms
def get_neighbourhood(typ, arr, coordinates): def isInside(x, y): return 0 <= x < len(arr) and 0 <= y < len(arr[0]) x, y = coordinates if not isInside(x, y): return [] neigh = ([(dx, dy) for dx in range(- 1, 2) for dy in range(- 1, 2) if (dx, dy) != (0, 0)] if typ == 'mo...
2D Cellular Neighbourhood
5b2e5a02a454c82fb9000048
[ "Algorithms", "Data Structures", "Arrays", "Matrix" ]
https://www.codewars.com/kata/5b2e5a02a454c82fb9000048
7 kyu
Create a Circular List A circular list is of finite size, but can infititely be asked for its previous and next elements. This is because it acts like it is joined at the ends and loops around. For example, imagine a CircularList of `[1, 2, 3, 4]`. Five invocations of `next()` in a row should return 1, 2, 3, 4 and th...
reference
class CircularList (): def __init__(self, * args): if not args: raise Exception("missing required args") self . n = len(args) self . lst = args self . i = None def next(self): if self . i is None: self . i = - 1 self . i = (self . i + 1) % self . n return self . ls...
Circular List
5b2e60742ae7543f9d00005d
[ "Lists", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/5b2e60742ae7543f9d00005d
7 kyu
The concept of "[smooth number](https://en.wikipedia.org/wiki/Smooth_number)" is applied to all those numbers whose prime factors are lesser than or equal to `7`: `60` is a smooth number (`2 * 2 * 3 * 5`), `111` is not (`3 * 37`). More specifically, smooth numbers are classified by their highest prime factor and your ...
games
def is_smooth(n): smooth = { 2: "power of 2", 3: "3-smooth", 5: "Hamming number", 7: "humble number" } for k in smooth: while n % k == 0: n / /= k if n == 1: return smooth[k] return "non-smooth"
Smooth numbers
5b2f6ad842b27ea689000082
[ "Number Theory" ]
https://www.codewars.com/kata/5b2f6ad842b27ea689000082
7 kyu
A forest fire has been spotted at *fire*, a simple 2 element array with x, y coordinates. The forest service has decided to send smoke jumpers in by plane and drop them in the forest. The terrain is dangerous and surveyors have determined that there are three possible safe *dropzones*, an array of three simple arrays...
reference
from math import hypot def dropzone(fire, dropzones): return min(dropzones, key=lambda p: hypot(p[0] - fire[0], p[1] - fire[1]))
Dropzone
5b6d065a1db5ce9b4c00003c
[ "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/5b6d065a1db5ce9b4c00003c
7 kyu
You receive the name of a city as a string, and you need to return a string that shows how many times each letter shows up in the string by using asterisks (`*`). For example: ``` "Chicago" --> "c:**,h:*,i:*,a:*,g:*,o:*" ``` As you can see, the letter `c` is shown only once, but with 2 asterisks. The return strin...
reference
from collections import Counter def get_strings(city): return "," . join(f" { char } : { '*' * count } " for char, count in Counter(city . replace(" ", ""). lower()). items())
Interview Question (easy)
5b358a1e228d316283001892
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5b358a1e228d316283001892
7 kyu
# Meanwhile... somewhere in a Pentagon basement Your job is to compare two confidential documents that have come into your possession. The first document has parts <a href=https://www.merriam-webster.com/dictionary/redacted>redacted</a>, and the other one doesn't. <img src="https://i.imgur.com/8BSbFEy.png" sty...
reference
def redacted(doc1, doc2): return len(doc1) == len(doc2) and all((c1 == 'X' and c2 != '\n') or c1 == c2 for c1, c2 in zip(doc1, doc2))
Redacted!
5b662d286d0db722bd000013
[ "Fundamentals" ]
https://www.codewars.com/kata/5b662d286d0db722bd000013
7 kyu
# First Things First ## Description Well the purpose of this kata to find a way to do some operations after the return statement. ## Your task You are required to call two functions `first` and `last`. You must call them in that order inside your function. The catch is that your function must return what the fi...
bug_fixes
def solution(first, last): try: return first() finally: last()
First thing first.
5b64334ab1788374fb0000c8
[ "Debugging" ]
https://www.codewars.com/kata/5b64334ab1788374fb0000c8
7 kyu
Given a long number, return all the possible sum of two digits of it. For example, `12345`: all possible sum of two digits from that number are: [ 1 + 2, 1 + 3, 1 + 4, 1 + 5, 2 + 3, 2 + 4, 2 + 5, 3 + 4, 3 + 5, 4 + 5 ] Therefore the result must be: [ 3, 4, 5, 6, 5, 6, 7, 7, 8, 9 ]
algorithms
from itertools import combinations def digits(num): return list(map(sum, combinations(map(int, str(num)), 2)))
Every possible sum of two digits
5b4e474305f04bea11000148
[ "Algorithms" ]
https://www.codewars.com/kata/5b4e474305f04bea11000148
7 kyu
Given an array (or list or vector) of arrays (or, guess what, lists or vectors) of integers, your goal is to return the sum of a specific set of numbers, starting with elements whose position is equal to the main array length and going down by one at each step. Say for example the parent array (etc, etc) has 3 sub-arr...
algorithms
def elements_sum(arr, d=0): return sum(r[i] if i < len(r) else d for i, r in enumerate(reversed(arr)))
Sub-array elements sum
5b5e0ef007a26632c400002a
[ "Arrays", "Lists", "Algorithms" ]
https://www.codewars.com/kata/5b5e0ef007a26632c400002a
7 kyu
You are given a array which contains sub-arrays. Each sub-array represents a point in a (2d) cartesian coordinate system. Create a function which returns the distance of the two points which are farthest apart. All distances are to be rounded to 2 decimal places. If the array contains two points return the distance ...
reference
from itertools import combinations def furthestDistance(arr): return round(max(sum((y - x) * * 2 for x, y in zip(* comb)) * * .5 for comb in combinations(arr, 2)), 2)
Farthest Distance
5b56e42805f04b1780000073
[ "Arrays", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5b56e42805f04b1780000073
7 kyu
Beaches are filled with sand, water, fish, and sun. Given a string, calculate how many times the words `"Sand"`, `"Water"`, `"Fish"`, and `"Sun"` appear without overlapping (regardless of the case). ## Examples ```csharp SumOfABeach("WAtErSlIde") ==> 1 SumOfABeach("GolDeNSanDyWateRyBeaChSuNN") ...
algorithms
import re def sum_of_a_beach(beach): return len(re . findall('Sand|Water|Fish|Sun', beach, re . IGNORECASE))
Sum of a Beach
5b37a50642b27ebf2e000010
[ "Fundamentals", "Algorithms", "Strings", "Regular Expressions" ]
https://www.codewars.com/kata/5b37a50642b27ebf2e000010
7 kyu
# Summary Given a `Hash` made up of _keys_ and _values_, invert the hash by swapping them. # Examples ```ruby Given: { 'a' => 1, 'b' => 2, 'c' => 3 } Return: { 1 => 'a', 2 => 'b', 3 => 'c' } Given: { 'foo' => 'bar', 'hello' => 'world' } Return: { 'bar' => 'foo', 'world' =...
reference
def invert_hash(dictionary): return {v: k for k, v in dictionary . items()}
Inverting a Hash
5b5604e26dc79e6832000101
[ "Fundamentals" ]
https://www.codewars.com/kata/5b5604e26dc79e6832000101
7 kyu
You managed to send your friend to queue for tickets in your stead, but there is a catch: he will get there only if you tell him how much that is going to take. And everybody can only take one ticket at a time, then they go back in the last position of the queue if they need more (or go home if they are fine). Each ti...
algorithms
def queue(queuers, pos): return sum(min(queuer, queuers[pos] - (place > pos)) for place, queuer in enumerate(queuers))
Queue time counter
5b538734beb8654d6b00016d
[ "Queues", "Lists", "Algorithms" ]
https://www.codewars.com/kata/5b538734beb8654d6b00016d
7 kyu
Given a number `n`, draw stairs using the letter `"I"`, `n` tall and `n` wide, with the tallest in the top left. For example `n = 3` result in: ``` "I\n I\n I" ``` or printed: ``` I I I ``` Another example, a 7-step stairs should be drawn like this: ``` I I I I I I I ```
algorithms
def draw_stairs(n): return '\n' . join(' ' * i + 'I' for i in range(n))
Draw stairs
5b4e779c578c6a898e0005c5
[ "ASCII Art", "Algorithms" ]
https://www.codewars.com/kata/5b4e779c578c6a898e0005c5
8 kyu
Given a non-empty array of non-empty integer arrays, multiply the contents of each nested array and return the smallest total. ### Example ``` input = [ [1, 5], [2], [-1, -3] ] result = 2 ```
reference
from math import prod def smallest_product(a): return min(map(prod, a))
Smallest Product
5b6b128783d648c4c4000129
[ "Fundamentals" ]
https://www.codewars.com/kata/5b6b128783d648c4c4000129
7 kyu
You have a group chat application, but who is online!? You want to show your users which of their friends are online and available to chat! Given an input of an array of objects containing usernames, status and time since last activity (in mins), create a function to work out who is ```online```, ```offline``` and ``...
reference
from collections import defaultdict def who_is_online(friends): d = defaultdict(list) for user in friends: status = 'away' if user['status'] == 'online' and user['last_activity'] > 10 else user['status'] d[status]. append(user['username']) return d
Who's Online?
5b6375f707a2664ada00002a
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5b6375f707a2664ada00002a
7 kyu
A number is a Kaprekar number if its square can be split up into two parts which sum up to the original number. (https://en.wikipedia.org/wiki/Kaprekar_number ) For example, the following are Kaprekar numbers: - 9: 9^2=81 and 8+1=9. - 45: 45^2=2025 and 20+25=45 - 2223: 2223^2=4941729 and 494+1729=2223 Create a fu...
reference
def kaprekar_split(n): s = str(n * * 2) for i in range(len(s)): if int(s[: i] or 0) + int(s[i:] or 0) == n: return i return - 1
Kaprekar Split
5b6ee22ac5cc71833f0010d7
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5b6ee22ac5cc71833f0010d7
7 kyu
DNA sequencing data can be stored in many different formats. In this Kata, we will be looking at SAM formatting. It is a plain text file where every line (excluding the first header lines) contains data about a "read" from whatever sample the file comes from. Rather than focusing on the whole read, we will take two pie...
reference
import re def is_matched(read): total = sum([int(num) for num in re . findall(r'\d+', read[0])]) if read[0] == str(len(read[1])) + 'M': return True elif len(read[1]) != total: return 'Invalid cigar' else: return False
Cigar Strings (Easy)
5b64d2cd83d64828ce000039
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5b64d2cd83d64828ce000039
7 kyu
Given two forces (_F<sub>1</sub>_ and _F<sub>2</sub>_ ) and the angle _F<sub>2</sub>_ makes with _F<sub>1</sub>_ find the resultant force _R_ and the angle it makes with _F<sub>1</sub>_. input ==== Three values : - _F<sub>1</sub>_ - _F<sub>2</sub>_ making an angle _θ_ with _F<sub>1</sub>_ - angle _θ_ output ==== ...
algorithms
from math import cos, radians, sin, atan2, degrees, hypot def solution(f1, f2, theta): r = radians(theta) x = f1 + f2 * cos(r) y = f2 * sin(r) return hypot(x, y), degrees(atan2(y, x))
Calculate the resultant force
5b707fbc8adeaee7ac00000c
[ "Physics", "Geometry", "Algorithms" ]
https://www.codewars.com/kata/5b707fbc8adeaee7ac00000c
7 kyu
Ronny the robot is watching someone perform the Cups and Balls magic trick. The magician has one ball and three cups, he shows Ronny which cup he hides the ball under (b), he then mixes all the cups around by performing multiple two-cup switches (arr). Ronny can record the switches but can't work out where the ball is....
reference
from functools import reduce def cup_and_balls(b, arr): return reduce(lambda x, y: y[1] if x == y[0] else y[0] if x == y[1] else x, arr, b)
Ball and Cups
5b715fd11db5ce5912000019
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5b715fd11db5ce5912000019
7 kyu
A bug lives in a world which is a cuboid and has to walk from one corner of the cuboid to the opposite corner (see the picture below). <img src="https://www.technologyuk.net/mathematics/geometry/images/geometry_0161.gif" alt="Google 'Cuboid Space Diagonal' " style="float: right; margin-right: 10px;" /> ###...
reference
def shortest_distance(a, b, c): a, b, c = sorted([a, b, c]) return ((a + b) * * 2 + c * * 2) * * 0.5
Bugs Life
5b71af678adeae41df00008c
[ "Fundamentals", "Geometry" ]
https://www.codewars.com/kata/5b71af678adeae41df00008c
7 kyu
Your task is to sum the differences between consecutive pairs in the array in descending order. ## Example ``` [2, 1, 10] --> 9 ``` In descending order: `[10, 2, 1]` Sum: `(10 - 2) + (2 - 1) = 8 + 1 = 9` If the array is empty or the array has only one element the result should be `0` (`Nothing` in Haskell, `None...
reference
def sum_of_differences(arr): return max(arr) - min(arr) if arr else 0
Sum of differences in array
5b73fe9fb3d9776fbf00009e
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5b73fe9fb3d9776fbf00009e
8 kyu
In this Kata, you will be given a lower case string and your task will be to remove `k` characters from that string using the following rule: ```Python - first remove all letter 'a', followed by letter 'b', then 'c', etc... - remove the leftmost character first. ``` ```Python For example: solve('abracadabra', 1) = 'b...
reference
def solve(st, k): for l in sorted(st)[: k]: st = st . replace(l, '', 1) return st
Simple letter removal
5b728f801db5cec7320000c7
[ "Fundamentals" ]
https://www.codewars.com/kata/5b728f801db5cec7320000c7
7 kyu
In this Kata, you will be given two positive integers `a` and `b` and your task will be to apply the following operations: ``` i) If a = 0 or b = 0, return [a,b]. Otherwise, go to step (ii); ii) If a ≥ 2*b, set a = a - 2*b, and repeat step (i). Otherwise, go to step (iii); iii) If b ≥ 2*a, set b = b - 2*a, and repeat ...
reference
def solve(a, b): ''' Used the % operator instead of repeated subtraction of a - 2*b or b - 2*a Because as long as a > 2*b, the repeated subtraction has to be done and it will eventually give a % 2*b. Repeated subtration in recursion has the problem of exceeding the recursion depth, so this ...
Recursion 101
5b752a42b11814b09c00005d
[ "Fundamentals" ]
https://www.codewars.com/kata/5b752a42b11814b09c00005d
7 kyu
You start with a value in dollar form, e.g. $5.00. You must convert this value to a string in which the value is said, like '5 dollars' for example. This should account for ones, cents, zeroes, and negative values. Here are some examples: ```python dollar_to_speech('$0.00') == '0 dollars.' dollar_to_speech('$1.00') == ...
algorithms
def dollar_to_speech(value): if "-" in value: return "No negative numbers are allowed!" d, c = (int(n) for n in value . replace("$", ""). split(".")) dollars = "{} dollar{}" . format( str(d), "s" if d != 1 else "") if d or not c else "" link = " and " if (d and c) else "" cents = "{} cen...
Dollar Value to Speech Conversion
5b23d98da97f02a5f4000a4c
[ "Algorithms" ]
https://www.codewars.com/kata/5b23d98da97f02a5f4000a4c
7 kyu
You will be given a matrix of ```m``` rows and ```n``` columns like: <a href="http://imgur.com/0w2EWQb"><img src="http://i.imgur.com/0w2EWQb.png?2" title="source: imgur.com" /></a> The matrix has some ```aij``` equals to ```0``` at different locations ```i, j``` and the others, all positive. Your task will be to fin...
reference
from itertools import groupby from functools import reduce def highest_prod(matrix, isH=1): return max([reduce(int . __mul__, g) for row in matrix for k, g in map(lambda t: (t[0], list(t[1])), groupby(row, key=bool)) if k and len(g) > 1] + [highest_prod(zip(* matrix)...
Has the Largest Product Horizontal or Vertical Direction? Find it!!
5b216555a454c8eaa2000019
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Algebra", "Performance" ]
https://www.codewars.com/kata/5b216555a454c8eaa2000019
6 kyu
# Leonardo numbers The **Leonardo numbers** are a sequence of numbers defined by: L(0) = 1 || 0 L(1) = 1 || 0 L(x) = L(x - 1) + L(x - 2) + 1 Generalizing the above a bit more: L(x) = L(x - 1) + L(x - 2) + a Assume `a` to be the __add number__. --- # Task Return the first `n` **Leonardo num...
algorithms
def L(n, a, b, inc): lst = [] for _ in range(n): lst . append(a) a, b = b, a + b + inc return lst
Leonardo numbers
5b2117eea454c89d4400005f
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/5b2117eea454c89d4400005f
7 kyu
You are the Dungeon Master for a public DnD game at your local comic shop and recently you've had some trouble keeping your players' info neat and organized so you've decided to write a bit of code to help keep them sorted! The goal of this code is to create an array of objects that stores a player's name and contact ...
games
import re def player_manager(players): return players and [{'player': who, 'contact': int(num)} for who, num in re . findall(r'(.+?), (\d+)(?:, )?', players)] or []
Player Contact Manager
5b203de891c7469b520000b4
[ "Arrays" ]
https://www.codewars.com/kata/5b203de891c7469b520000b4
7 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" /> # A History Lesson The <a href=https://en.wikipedia.org/wiki/Pony_Express>Pony Express</a> was a mail service operating in the US in 1859-60. <img src="https://i.imgur.com/oEqUjpP.png" title="Pony Express" /> It reduced the time for messages...
reference
def riders(stations): riders, travelled = 1, 0 for dist in stations: if travelled + dist > 100: riders += 1 travelled = dist else: travelled += dist return riders
The Pony Express
5b18e9e06aefb52e1d0001e9
[ "Fundamentals" ]
https://www.codewars.com/kata/5b18e9e06aefb52e1d0001e9
7 kyu
## Given a set of words, how many letters do you have to remove from them to make them anagrams? # Example You are given the set of words ```{'hello', 'hola', 'allo'}```. To obtain anagrams, you have to remove 3 letters from 'hello' (the letters 'hel'), 2 letters from 'hola' (the letters 'ha'), and 2 letters from 'al...
algorithms
from collections import Counter from functools import reduce from operator import and_ def anagram_difference(words): cWords = list(map(Counter, words)) required = reduce(and_, cWords) return sum(sum((c - required). values()) for c in cWords)
Hardcore anagram difference
5b1b48cc647c7e7c56000083
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5b1b48cc647c7e7c56000083
6 kyu
Comparing two numbers written in index form like `2^11` and `3^7` is not difficult, as any calculator would confirm that `2^11 = 2048 < 3^7 = 2187`. However, confirming that `632382^518061 > 519432^525806` would be much more difficult, as both numbers contain over three million digits. Your task is to write a functio...
algorithms
from math import log def compare(* numbers): return max(numbers, key=lambda n: n[1] * log(n[0]))
Exponential Comparison
5b1cce03777ab73442000134
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5b1cce03777ab73442000134
6 kyu
```if:python <strong>Note: Python may currently have some performance issues. If you find them, please let me know and provide suggestions to improve the Python version! It's my weakest language... any help is much appreciated :)</strong> ``` Artlessly stolen and adapted from <a href="https://www.hackerrank.com/chall...
reference
def leaderboard_climb(arr, kara): scores = sorted(set(arr), reverse=True) position = len(scores) ranks = [] for checkpoint in kara: while position >= 1 and checkpoint >= scores[position - 1]: position -= 1 ranks . append(position + 1) return ranks
Climbing the Leaderboard
5b19f34c7664aacf020000ec
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5b19f34c7664aacf020000ec
6 kyu
# Description You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1. # Example ```python string = "This is ...
reference
def find_nth_occurrence(substring, string, occurrence=1): idx = - 1 for i in range(occurrence): idx = string . find(substring, idx + 1) if idx == - 1: return - 1 return idx
Find the nth occurrence of a word in a string!
5b1d1812b6989d61bd00004f
[ "Fundamentals" ]
https://www.codewars.com/kata/5b1d1812b6989d61bd00004f
7 kyu
# Story: Everybody is going crazy about the new cool battle-royale gamemode, but **you are not**, you are crazy about **math**! After seeing how people are rushing towards a safe-zone every couple of minutes to not get killed by some force, you, on the other hand, rushed to see what distance does one have to travel to...
reference
import numpy as np def distance(player, relocation, quotients, radius): y_movement = player[1] - relocation[1] / quotients[1] x_movement = player[0] - relocation[0] / quotients[0] distance_p_center = np . sqrt(y_movement * * 2 + x_movement * * 2) distance_to_cross = distance_p_center * radius...
Distance to the safe-zone moving towards its center
5b1d0685da48c294e3001b31
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5b1d0685da48c294e3001b31
6 kyu
Consider the sequence `U(n, x) = x + 2x**2 + 3x**3 + .. + nx**n` where x is a real number and n a positive integer. When `n` goes to infinity and `x` has a correct value (ie `x` is in its domain of convergence `D`), `U(n, x)` goes to a finite limit `m` depending on `x`. Usually given `x` we try to find `m`. Here we w...
reference
def solve(m): '''U = x + 2*x^2 + 3*x^3 + ... + n*x^n x*U = x^2 + 2*x^3 + 3*x^4 + ... + (n-1)*x^n + n*x^(n+1) (1-x)*U = x + x^2 + x^3 + ... + x^n - n*x^(n+1) x*(1-x^n) (1-x)*U = --------- - n*x^(n+1) 1-x x*(1-x^n) n*x^(n+1) x - x^(n+1) - n*x^(n+1) + n*x^(n+2) U = --------- - ------...
Which x for that sum?
5b1cd19fcd206af728000056
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5b1cd19fcd206af728000056
5 kyu
Linear Kingdom has exactly one tram line. It has `n` stops, numbered from 1 to n in the order of tram's movement. At the i-th stop a<sub>i</sub> passengers exit the tram, while b<sub>i</sub> passengers enter it. The tram is empty before it arrives at the first stop. ## Your task Calculate the tram's minimum capacity ...
algorithms
from itertools import accumulate def tram(stops, descending, onboarding): return max(accumulate(o - d for d, o in zip(descending[: stops], onboarding)))
Tram Capacity
5b190aa7803388ec97000054
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5b190aa7803388ec97000054
7 kyu
You wrote all your unit test names in camelCase. But some of your colleagues have troubles reading these long test names. So you make a compromise to switch to underscore separation. To make these changes fast you wrote a class to translate a camelCase name into an underscore separated name. Implement the ToUnderscor...
algorithms
import re def toUnderScore(name): return re . sub("(?<=[^_-])_?(?=[A-Z])|(?<=[^\\d_])_?(?=\\d)", "_", name)
CamelCase to underscore
5b1956a7803388baae00003a
[ "Fundamentals", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5b1956a7803388baae00003a
6 kyu
In this Kata, you will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on: * make as few changes as possible. * if the string contains equal number of uppercase and lowercase letters, convert the string to ...
reference
def solve(s): upper = 0 lower = 0 for char in s: if char . islower(): lower += 1 else: upper += 1 if upper == lower or lower > upper: return s . lower() else: return s . upper()
Fix string case
5b180e9fedaa564a7000009a
[ "Fundamentals" ]
https://www.codewars.com/kata/5b180e9fedaa564a7000009a
7 kyu
### Task You are given a dictionary/hash/object containing some languages and your test results in the given languages. Return the list of languages where your test score is at least `60`, in descending order of the scores. Note: the scores will always be unique (so no duplicate values) ### Examples ```ruby {"Java...
algorithms
def my_languages(results): return sorted((l for l, r in results . items() if r >= 60), reverse=True, key=results . get)
My Language Skills
5b16490986b6d336c900007d
[ "Sorting", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5b16490986b6d336c900007d
7 kyu
We need a function (for commercial purposes) that may perform integer partitions with some constraints. The function should select how many elements each partition should have. The function should discard some "forbidden" values in each partition. So, create ```part_const()```, that receives three arguments. ```part_co...
reference
def part_const(n, k, num): return part(n, k) - part(n - (num or n), k - 1) def part(n, k): return 1 if k in (1, n) else sum(part(n - k, i) for i in range(1, min(n - k, k) + 1))
Cut me in Pieces but in The Way I Like
55fbb7063097cf0b6b000032
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/55fbb7063097cf0b6b000032
6 kyu
This kata is inspired on the problem #50 of the Project Euler. The prime ``` 41``` is the result of the sum of many consecutive primes. In fact, ``` 2 + 3 + 5 + 7 + 11 + 13 = 41 , (6 addens) ``` Furthermore, the prime ``` 41``` is the prime below ``` 100 (val_max)``` that has the longest chain of consecutive ...
reference
PRIME_SUMS = [(0, 0), (2, 2), (3, 5), (5, 10), (7, 17), (11, 28), (13, 41), (17, 58), (19, 77), (23, 100)] def is_prime(n: int) - > bool: sqrt = int(n * * .5) for i in range(1, len(PRIME_SUMS)): p = PRIME_SUMS[i][0] if p > sqrt: return n > 1 if n % p == 0: return F...
The Primes as a Result of the Longest Consecutive Sum I
56e93159f6c72164b700062b
[ "Performance", "Algorithms", "Mathematics", "Data Structures", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/56e93159f6c72164b700062b
5 kyu
A product-sum number is a natural number N which can be expressed as both the product and the sum of the same set of numbers. N = a1 × a2 × ... × ak = a1 + a2 + ... + ak For example, 6 = 1 × 2 × 3 = 1 + 2 + 3. For a given set of size, k, we shall call the smallest N with this property a minimal product-sum number. T...
algorithms
""" code to generate arr (takes ~18s so is precomputed): from math import log2, ceil from bisect import bisect_right def find_terms(lower_bound, length, curr_sum, curr_prod, curr_min): # searches for terms that are >= lower_bound such that sum(terms) + curr_sum = prod(terms) * curr_prod. the number of terms i...
Product-Sum Numbers
5b16bbd2c8c47ec58300016e
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5b16bbd2c8c47ec58300016e
4 kyu
In this Kata, you will be given an integer `n` and your task will be to return `the largest integer that is <= n and has the highest digit sum`. For example: ``` solve(100) = 99. Digit Sum for 99 = 9 + 9 = 18. No other number <= 100 has a higher digit sum. solve(10) = 9 solve(48) = 48. Note that 39 is also an option, ...
algorithms
def solve(n): x = str(n) res = [x] + [str(int(x[: i]) - 1) + '9' * (len(x) - i) for i in range(1, len(x))] return int(max(res, key=lambda x: (sum(map(int, x)), int(x))))
Simple max digit sum
5b162ed4c8c47ea2f5000023
[ "Algorithms" ]
https://www.codewars.com/kata/5b162ed4c8c47ea2f5000023
6 kyu
We have a set of consecutive numbers from ```1``` to ```n```. We want to count all the subsets that do not contain consecutive numbers. E.g. If our set ```S1``` is equal to ```[1,2,3,4,5]``` The subsets that fulfill these property are: ``` [1],[2],[3],[4],[5],[1,3],[1,4],[1,5],[2,4],[2,5],[3,5],[1,3,5] ``` A total of ...
reference
def f(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b + 1 return a
# Counting 1: I Want Some Subsets, Not All!
591392af88a4994caa0000e0
[ "Number Theory", "Fundamentals" ]
https://www.codewars.com/kata/591392af88a4994caa0000e0
6 kyu
### Task: Your job is to take a pair of parametric equations, passed in as strings, and convert them into a single rectangular equation by eliminating the parameter. Both parametric halves will represent linear equations of x as a function of time and y as a function of time respectively. The format of the final equ...
reference
from math import gcd def para_to_rect(eqn1, eqn2): a, b = eqn1 . split('= ')[1]. split('t ') c, d = eqn2 . split('= ')[1]. split('t ') if a in ("", "-"): a += '1' if c in ("", "-"): c += '1' a, b, c, d = map(eval, (a, b, c, d)) x = gcd(a, c) e, f = c / / x, - a / / x if...
Parametric to Rectangular Equation
5b13530f828fab68820000c4
[ "Fundamentals" ]
https://www.codewars.com/kata/5b13530f828fab68820000c4
6 kyu
# Challenge : Write a function that takes a single argument `n` that is a string representation of a simple mathematical expression and evaluates it as a floating point value. # Commands : - positive or negative decimal numbers - `+, -, *, /, ( / ).` --- Expressions use [infix notation](https://en.wikipedia.org/...
games
def e(s, i=0): l, o, r, i = 0, 0, '', i or iter(s + ' ') for x in i: if '(' == x: r = e(s, i) elif '/' < x or not r: r += x else: r = float(r) l, o, r = {'+': l + r, '-': l - r, '*': l * r, '/': l / r, 0: r}[o], x, '' if ')' == x: ...
Math expression [HARD][CODE-GOLF]
5b05a8dd91cc5739df0000aa
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/5b05a8dd91cc5739df0000aa
5 kyu
A group of students of Computer Science were studying the performance of the following generator in Python 2 and Python 3. ``` python def permut(iterable): if len(iterable) <=1: yield iterable else: for perm in permut(iterable[1:]): for i in range(len(iterable)): yield perm[:...
reference
from itertools import accumulate from operator import mul def fa(iterable): return sum(accumulate(range(2, sum(1 for _ in iterable) + 1), mul))
Avoid trillion years of calculations !!
5b1027fe5b07a105f4000092
[ "Performance", "Algorithms", "Mathematics", "Machine Learning" ]
https://www.codewars.com/kata/5b1027fe5b07a105f4000092
6 kyu
I assume most of you are familiar with the ancient legend of the rice (but I see wikipedia suggests [wheat](https://en.wikipedia.org/wiki/Wheat_and_chessboard_problem), for some reason) problem, but a quick recap for you: a young man asks as a compensation only `1` grain of rice for the first square, `2` grains for the...
games
squares_needed = int . bit_length
The wheat/rice and chessboard problem
5b0d67c1cb35dfa10b0022c7
[ "Mathematics", "Recursion", "Puzzles" ]
https://www.codewars.com/kata/5b0d67c1cb35dfa10b0022c7
7 kyu
Professor Chambouliard has just completed an experiment on gravitational waves. He measures their effects on small magnetic particles. This effect is very small and negative. In his first experiment the effect satisfies the equation: `x**2 + 1e9 * x + 1 = 0`. Professor C. knows how to solve equations of the form: `...
reference
def quadratic(a, b, c): return - c / b
Floating-point Approximation (III)
5b0c0ec907756ffcff00006e
[ "Fundamentals" ]
https://www.codewars.com/kata/5b0c0ec907756ffcff00006e
7 kyu
The code provided has a method `hello` which is supposed to show only those attributes which have been *explicitly* set. Furthermore, it is supposed to say them in the *same order* they were set. But it's not working properly. # Notes There are 3 attributes * name * age * sex ('M' or 'F') When the same attribute i...
bug_fixes
class Dinglemouse (object): def __init__(self): self . name = None self . sex = None self . age = None self . hell = 'Hello.' def setAge(self, age): if self . age == None: self . hell = self . hell + ' I am {age}.' self . age = age return self def setSex(self, sex): if s...
FIXME: Hello
5b0a80ce84a30f4762000069
[ "Debugging" ]
https://www.codewars.com/kata/5b0a80ce84a30f4762000069
6 kyu
Alice and Bob have participated to a Rock Off with their bands. A jury of true metalheads rates the two challenges, awarding points to the bands on a scale from 1 to 50 for three categories: Song Heaviness, Originality, and Members' outfits. For each one of these 3 categories they are going to be awarded one point, sh...
reference
def solve(a, b): alice = sum(i > j for i, j in zip(a, b)) bob = sum(j > i for i, j in zip(a, b)) if alice == bob: words = 'that looks like a "draw"! Rock on!' elif alice > bob: words = 'Alice made "Kurt" proud!' else: words = 'Bob made "Jeff" proud!' return '{}, {}: {}' . ...
Rock Off!
5b097da6c3323ac067000036
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5b097da6c3323ac067000036
7 kyu
The [Floyd's triangle](https://en.wikipedia.org/wiki/Floyd%27s_triangle) is a right-angled triangular array of natural numbers listing them in order, in lines of increasing length, so a Floyds triangle of size 6 looks like: ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ... ``` In this kata you'r...
reference
def nth_floyd(n): return ((1 + 8 * (n - 1)) * * 0.5 + 1) / / 2
nth Floyd line
5b096efeaf15bef812000010
[ "Mathematics", "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/5b096efeaf15bef812000010
7 kyu
The T9 typing predictor helps with suggestions for possible word combinations on an old-style numeric keypad phone. Each digit in the keypad (2-9) represents a group of 3-4 letters. To type a letter, press once the key which corresponds to the letter group that contains the required letter. Typing words is done by typi...
games
FROM = "abc def ghi jkl mno pqrs tuv wxyz" . split() TO_NUM = "222 333 444 555 666 7777 888 9999" . split() TABLE_TO_NUM = str . maketrans(* map('' . join, (FROM, TO_NUM))) TABLE_TO_CHAR = str . maketrans( * map(lambda lst: '' . join(x[0] for x in lst), (TO_NUM, FROM))) def T9(words, seq): return ([...
T9 Predictor
5b085335abe956c1ef000266
[ "Puzzles" ]
https://www.codewars.com/kata/5b085335abe956c1ef000266
6 kyu
Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number and `n` a positive integer (n > 0). When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit `lim` depending on `z`. Experiment with `S(n,...
reference
import math def f(z, eps): if (abs(z) >= 1.0): return - 1 return int(math . log(eps) / math . log(abs(z)))
Experimenting with a sequence of complex numbers
5b06c990908b7eea73000069
[ "Fundamentals", "Puzzles" ]
https://www.codewars.com/kata/5b06c990908b7eea73000069
6 kyu
*This is the advanced version of the [Minimum and Maximum Product of k Elements](https://www.codewars.com/kata/minimum-and-maximum-product-of-k-elements/) kata.* --- Given a list of **integers** and a positive integer `k` (> 0), find the minimum and maximum possible product of `k` elements taken from the list. If y...
algorithms
from functools import reduce from operator import mul def find_min_max_product(arr, k): if k > len(arr): return None if k == 1: return min(arr), max(arr) if k == len(arr): prod = reduce(mul, arr) return prod, prod arr = sorted(arr) prods = [] for i in ra...
Minimum and Maximum Product of k Elements - Advanced
5b05867c87566a947a00001c
[ "Arrays", "Lists", "Performance", "Algorithms" ]
https://www.codewars.com/kata/5b05867c87566a947a00001c
5 kyu
# Background: In Japan, a game called Shiritori is played. The rules are simple, a group of people take turns calling out a word whose beginning syllable is the same as the previous player's ending syllable. For example, the first person would say the word ねこ, and the second player must make a word that starts with こ, ...
reference
def game(words): if not words or not words[0]: return [] for i in range(1, len(words)): if not words[i] or words[i - 1][- 1] != words[i][0]: return words[: i] return words
An English Twist on a Japanese Classic
5b04be641839f1a0ab000151
[ "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/5b04be641839f1a0ab000151
7 kyu
For every string, after every occurrence of `'and'` and/or `'but'`, insert the substring `'apparently'` directly after the occurrence(s). If input does not contain 'and' or 'but', return the same string. If a blank string, return `''`. If substring `'apparently'` is already directly after an `'and'` and/or `'but'`, d...
reference
import re def apparently(string): return re . sub(r'(?<=\b(and|but)\b(?! apparently\b))', ' apparently', string)
Apparently-Modifying Strings
5b049d57de4c7f6a6c0001d7
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5b049d57de4c7f6a6c0001d7
7 kyu
Kate and Michael want to buy a pizza and share it. Depending on the price of the pizza, they are going to divide the costs: * If the pizza is less than €5,- Michael invites Kate, so Michael pays the full price. * Otherwise Kate will contribute 1/3 of the price, but no more than €10 (she's broke :-) and Michael pays th...
reference
def michael_pays(cost): return round(cost if cost < 5 else max(cost * 2 / 3, cost - 10), 2)
Pizza Payments
5b043e3886d0752685000009
[ "Fundamentals" ]
https://www.codewars.com/kata/5b043e3886d0752685000009
7 kyu
The input will be an array of dictionaries. Return the values as a string-seperated sentence in the order of their keys' integer equivalent (increasing order). The keys are not reoccurring and their range is `-999 < key < 999`. The dictionaries' keys & values will always be strings and will always not be empty. ## E...
reference
def sentence(ds): return ' ' . join(v for _, v in sorted((int(k), v) for d in ds for k, v in d . items()))
String Reordering
5b047875de4c7f9af800011b
[ "Fundamentals", "Strings", "Lists" ]
https://www.codewars.com/kata/5b047875de4c7f9af800011b
7 kyu
In a secret Mars base, the NASA uses an omni wheel robot. It is a repair robot wich can fix their reactor. Currently there are no astronauts on the Mars because of the low budget, only this robot can save the secret Mars base. But there is a problem. The the robot's motor controller is a little bit buggy since the las...
reference
def controller(Q): return [[east, west, north, south][V]() for V in [ [0], [1], [2], [3], [2, 0], [3, 1], [2, 1], [3, 0]][Q]]
Fix the robot and save the secret Mars base
5b029d9dde4c7f01600001ad
[ "Algorithms", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5b029d9dde4c7f01600001ad
6 kyu
## Description Peter enjoys taking risks, and this time he has decided to take it up a notch! Peter asks his local barman to pour him **n** shots, after which Peter then puts laxatives in **x** of them. He then turns around and lets the barman shuffle the shots. Peter approaches the shots and drinks **a** of them one...
games
from functools import reduce def get_chance(n, x, a): return round(reduce(lambda m, b: m * (1 - x / (n - b)), range(a), 1), 2)
Laxative Shot Roulette
5b02ae6aa2afd8f1b4001ba4
[ "Probability", "Puzzles", "Data Science", "Statistics" ]
https://www.codewars.com/kata/5b02ae6aa2afd8f1b4001ba4
7 kyu
My grandfather always predicted how old people would get, and right before he passed away he revealed his secret! In honor of my grandfather's memory we will write a function using his formula! * Take a list of ages when each of your great-grandparent died. * Multiply each number by itself. * Add them all togethe...
reference
def predict_age(* ages): return sum(a * a for a in ages) * * .5 / / 2
Predict your age!
5aff237c578a14752d0035ae
[ "Fundamentals" ]
https://www.codewars.com/kata/5aff237c578a14752d0035ae
7 kyu
Did you watch the famous "Life of Brian" moovie? Pilate could not say letter "r". Try to call callme() in a try block without "r" letter. It means you cannot write the "try" keyword in your source because that contains letter "r". And remember, Pilate was not equal with others, so you cannot use "=" symbol. Good Luck!...
reference
exec("t\x72y:callme()\nexcept:0")
Try without letter "r"! - Pontius Pilate will tly it :)
5b01e9f73e971587e70001ab
[ "Security", "Fundamentals" ]
https://www.codewars.com/kata/5b01e9f73e971587e70001ab
6 kyu
You are given a length of string and two thumbtacks. On thumbtack goes into the focus point *F₀* with coordinates *x₀* and *y₀*, and the other does into point *F₁* with points *x₁* and *y₁*. The string is then tied at the ends to the thumbtacks and has length *l* excluding the knots at the ends. If you pull the string ...
algorithms
def dis(p1, p2): return ((p1['x'] - p2['x']) * * 2 + (p1['y'] - p2['y']) * * 2) * * 0.5 def ellipse_contains_point(f0, f1, l, p): return dis(f0, p) + dis(f1, p) <= l
Ellipse contains point?
5b01abb9de4c7f3c22000012
[ "Geometry", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5b01abb9de4c7f3c22000012
7 kyu
Create the hi_all() function without using strings, numbers and booleans. The return value is "Hello World". No, it is not impossible, use the builtin functions. Good luck :)
reference
def hi_all(): one = - ~ len([]) two = one + one three = one + two four = two * two five = three + two seven = four + three eight = four * two ten = pow(three, two) + one hundred = ten * ten H = chr((seven * ten) + two) e = chr(hundred + one) l = chr(hundred ...
Hello World without strings, numbers and booleans
5b0148133e9715bf6f000154
[ "Strings", "Restricted", "Fundamentals" ]
https://www.codewars.com/kata/5b0148133e9715bf6f000154
6 kyu
A population of bears consists of black bears, brown bears, and white bears. The input is an array of two elements. Determine whether the offspring of the two bears will return `'black'`, `'brown'`, `'white'`, `'dark brown'`, `'grey'`, `'light brown'`, or `'unknown'`. Elements in the the array will always be a stri...
reference
DEFAULT = 'unknown' COLORS = {'black' + 'brown': 'dark brown', 'black' + 'white': 'grey', 'brown' + 'white': 'light brown'} def bear_fur(bears): b1, b2 = sorted(bears) return b1 if b1 == b2 else COLORS . get(b1 + b2, DEFAULT)
Offspring Traits
5b011461de4c7f8d78000052
[ "Fundamentals", "Lists", "Strings" ]
https://www.codewars.com/kata/5b011461de4c7f8d78000052
7 kyu
### Description Given a list of **integers** (possibly including duplicates) and a positive integer `k` (> 0), find the minimum and maximum possible product of `k` elements taken from the list. If you cannot take enough elements from the list (`k` > list size), return `None`/`nil`. ### Examples ```python numbers =...
algorithms
from functools import reduce from itertools import combinations from operator import mul def find_min_max_product(arr, k): if k <= len(arr): prods = [reduce(mul, nums) for nums in combinations(arr, k)] return min(prods), max(prods)
Minimum and Maximum Product of k Elements
5afd81d0de4c7f45f4000239
[ "Arrays", "Lists", "Algorithms" ]
https://www.codewars.com/kata/5afd81d0de4c7f45f4000239
7 kyu
## Task You must create a class, `Projectile`, which takes in 3 arguments when initialized: * starting height (`0 ≤ h0 < 200`) * starting velocity (`0 < v0 < 200`) * angle of the projectile when it is released (`0° < a < 90°`, measured in degrees). **All units for distance are feet, and units for time are seconds.**...
reference
from math import sin, cos, radians, sqrt class Projectile: def __init__(self, h0, v0, a): self . h = float(h0) self . x = v0 * cos(radians(a)) self . y = v0 * sin(radians(a)) def height_eq(self): return f'h(t) = -16.0t^2 + { round ( self . y , 3 )} t' + (self . h > 0) * f' + { round...
Projectile Motion
5af96cea3e9715ec670001dd
[ "Fundamentals" ]
https://www.codewars.com/kata/5af96cea3e9715ec670001dd
6 kyu
Some numbers can be expressed as a difference of two squares, for example, <code>20 = 6<sup>2</sup>-4<sup>2</sup></code> and <code>21 = 5<sup>2</sup>-2<sup>2</sup></code>. Many numbers can be written this way, but not all. ## Your Task Complete the function that takes a positive integer `n` and returns the amount of n...
algorithms
def count_squareable(n): return n / / 4 + (n + 1) / / 2
How Many Differences of Squares?
5afa08f23e971553170001e0
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5afa08f23e971553170001e0
6 kyu
### Goal Given a list of elements [a1, a2, ..., an], with each <i>ai</i> being a string, write a function **majority** that returns the value that appears the most in the list. If there's no winner, the function should return None, NULL, nil, etc, based on the programming language. ### Example ```python majority(["A...
reference
from collections import Counter def majority(arr): mc = Counter(arr). most_common(2) if arr and (len(mc) == 1 or mc[0][1] != mc[1][1]): return mc[0][0]
Find the majority
5af974846bf32304a2000e98
[ "Fundamentals" ]
https://www.codewars.com/kata/5af974846bf32304a2000e98
7 kyu
How many times we create a python class and in the __init__ method we just write: ```python self.name1 = name1 self.name2 = name2 ..... ``` for all arguments..... How boring!!!! Your task here is to implement a metaclass that let this instantiation be done automatically. But let's see an example: ```python class Per...
reference
class LazyInit (type): def __call__(self, * args, * * kwargs): varnames = list(self . __init__ . __code__ . co_varnames)[1:] for i, name in enumerate(varnames): setattr(self, name, args[i]) return self
Lazy Init
59b7b43b4f98a81b2d00000a
[ "Metaprogramming" ]
https://www.codewars.com/kata/59b7b43b4f98a81b2d00000a
4 kyu
Write a function that returns the `degree` of a polynomial function: ```javascript degree(x => 42); // 0 degree(x => x); // 1 degree(x => x * x); // 2 degree(x => x * x * x); // 3 degree(x => 2 * x + 3 * x * x + 5); // 2 ``` * Assume that the polynomi...
algorithms
def degree(p): r, d = [p(i) for i in list(range(12))], 0 while r . count(r[0]) != len(r): r, d = list(map(lambda i: r[i + 1] - r[i], list(range(11 - d)))), d + 1 return d
What’s the degree?
55fde83eeccc08d87d0000af
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/55fde83eeccc08d87d0000af
5 kyu
You are given an array of documents (strings), a term (string), and two booleans finetuning your indexing operation. Return an array containing the document IDs (`1`-based indices of documents in the array), where the term occurs, sorted in ascending order. Booleans: 1. CaseSensitive: `test` matches `test`, but not ...
reference
import re def build_inverted_index(coll, term, cS, eM): return [i + 1 for i, x in enumerate(coll) if re . search(r"{0}{1}{0}" . format('\\b' if eM else '', term), x, flags=not cS and re . I)]
NLP-Series #1 - Inverted Index
5af823451839f1768f00009d
[ "Fundamentals", "Parsing", "Regular Expressions" ]
https://www.codewars.com/kata/5af823451839f1768f00009d
7 kyu
# Problem Since table has four corners, there are eight ways to iterate over its' elements ((by rows then by columns | by columns then by rows) * (top left to bottom right | top right to bottom left | bottom left to top right | bottom right to top left)). Implement forward iterator that can be constucted with two dir...
algorithms
DIRECTION_UP, DIRECTION_LEFT, DIRECTION_DOWN, DIRECTION_RIGHT = range(1, 5) class Table: def __init__(self, data): self . data = data def walk(self, dir0, dir1): horizontal = range(len(self . data[0]))[ :: - 1 if DIRECTION_LEFT in (dir0, dir1) else 1] vertical = range(len(self . d...
Eight ways to iterate over table
5af5c18786d075cd5e00008b
[ "Iterators", "Algorithms" ]
https://www.codewars.com/kata/5af5c18786d075cd5e00008b
5 kyu
<!--Amidakuji--> <p><span style='color:#8df'><a href='https://en.wikipedia.org/wiki/Ghost_Leg' style='color:#9f9;text-decoration:none'>Amidakuji</a></span> is a method of lottery designed to create random pairings between two sets comprised of an equal number of elements.</p> <p>Your task is to write a function <code>a...
reference
def amidakuji(ar): numbers = list(range(len(ar[0]) + 1)) for line in ar: for i, swap in enumerate(line): if swap == '1': numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i] return numbers
Amidakuji
5af4119888214326b4000019
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5af4119888214326b4000019
6 kyu
Our spaceship has crashed on an unknown planet many light years away from earth. Thankfully we were able to send out a distress signal right before the crash. Help will be here shortly but we need to gather as much information about this planet as we can before we're rescued. Before our control panels were destroyed, ...
games
def is_leap_year(d, y): return (d * y). is_integer()
We've crashed on a distance planet in our galaxy! When do leap years occur here?
5af43416882143534300142c
[ "Puzzles" ]
https://www.codewars.com/kata/5af43416882143534300142c
7 kyu
Hello, I am Jomo Pipi and today we will be evaluating an expression like this: (there are an infinite number of radicals) <!-- Just incase <img src="https://latex.codecogs.com/gif.latex?\bg_black&space;\LARGE&space;\sqrt{x+\sqrt{x+\sqrt{x+\sqrt{x...}}}}" title="\LARGE \sqrt{x+\sqrt{x+\sqrt{x+\sqrt{x...}}}}" /> -->...
algorithms
def fn(x): return (1 + (1 + 4 * x) * * 0.5) / 2
Infinitely Nested Radicals
5af2b240d2ee2764420000a2
[ "Mathematics", "Algorithms", "Logic" ]
https://www.codewars.com/kata/5af2b240d2ee2764420000a2
7 kyu