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
<h2>Story:</h2> Alex is a great fan of Snooker and he likes recording the results of his favorite players by recording the balls that fall into the pockets of the table. He asks you to help him with a program that calculates the points a player scored in a given set using his notes. Unfortunatly his notes are quiet a ...
games
import re def frame(balls): if 'W' in balls: return 'Foul' list = re . findall('[A-Z][a-z]*[0-9]*', balls) sum = 0 for ball in list: num = re . findall('[0-9]+', ball) color = ball . rstrip(num[0]) if num else ball n = int(num[0]) if num else 1 sum += n * int(blz[color]...
Alex & snooker: points earned.
58b96d99404be9187c000003
[ "Strings", "Arrays" ]
https://www.codewars.com/kata/58b96d99404be9187c000003
6 kyu
Given a list of lists containing only 1s and 0s, return a new list that differs from list 1 in its first element, list 2 in its second element, list 3 in its 3rd element, and so on. ``` cantor([[0,0,0], [1,1,1], [0,1,0]]) = [1,0,1] cantor([[1,0,0], [0,1,0], [0,0,1]]) = [0,0,0] ``` The...
reference
def cantor(nested_list): return [not (line[i]) for i, line in enumerate(nested_list)]
Cantor's Diagonals
5a5e4f5f118dd1b407000028
[ "Fundamentals" ]
https://www.codewars.com/kata/5a5e4f5f118dd1b407000028
7 kyu
In the world of birding there are four-letter codes for the common names of birds. These codes are created by some simple rules: * If the bird's name has only one word, the code takes the first four letters of that word. * If the name is made up of two words, the code takes the first two letters of each word. * If th...
reference
import re SPLITTER = re . compile(r"[\s-]") def birdify(lst): return '' . join(x[: 4 / / len(lst)] for x in lst) + ('' if len(lst) != 3 else lst[- 1][1]) def bird_code(arr): return [birdify(SPLITTER . split(name)). upper() for name in arr]
Create Four Letter Birding Codes from Bird Names
5a580064e6be38fd34000147
[ "Arrays", "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a580064e6be38fd34000147
6 kyu
# Task: We define the "self reversed power sequence" as one shown below: <img src="http://i.imgur.com/5PwwTaz.jpg"> Implement a function that takes 2 arguments (`ord max` and `num dig`), and finds the smallest term of the sequence whose index is less than or equal to `ord max`, and has exactly `num dig` number of di...
reference
# precalculate results results = {} n, digits = 1, 0 while digits <= 1000: digits = len(str(sum(x * * (n - x + 1) for x in range(1, n)))) if digits not in results: results[digits] = n n += 1 def min_length_num(digits, max_num): n = results . get(digits, 0) return [True, n + 1] if n...
Reversed Self Power
560248d6ba06815d6f000098
[ "Fundamentals", "Mathematics", "Algorithms", "Performance" ]
https://www.codewars.com/kata/560248d6ba06815d6f000098
5 kyu
First order Chebyshew polynomials are defined by: T{0}( v ) = 1 T{1}( v ) = v T{n+1}( v ) = 2 * v * T{n}( v ) - T{n-1}( v ) Calculate `T{n}( v )` for given values of `v` and `n`. You don't have to round your results but you should expect large values.
algorithms
def chebyshev(n, v): t0, t1 = 1, v for _ in range(n): t0, t1 = t1, 2 * v * t1 - t0 return t0
First order Chebyshev polynomials
58a2ff40e7841f82b600010a
[ "Algorithms" ]
https://www.codewars.com/kata/58a2ff40e7841f82b600010a
6 kyu
This is a simple string decoding algorithm. The idea is to take a string of characters and decode it into an array. Each character is a single element in the result unless a backslash followed by a positive number is encountered. When a backslash followed by a positive number is found, the number indicates how many of...
algorithms
from itertools import islice def decode(s): def f(): it = iter(s) for c in it: if c == "\\": digits = next(it) while True: c = next(it) if not c . isdigit(): break digits += c c += "" . join(islice(it, int(digits) - 1)) yield c return list(f())
Decoded String by the Numbers
562c3b54746f50d28d000027
[ "Algorithms" ]
https://www.codewars.com/kata/562c3b54746f50d28d000027
6 kyu
In the wake of the npm's `left-pad` debacle, you decide to write a new super padding method that superceds the functionality of `left-pad`. Your version will provide the same functionality, but will additionally add right, and justified padding of string -- the `super_pad`. Your function `super_pad` should take three ...
algorithms
def super_pad(string, width, fill=" "): if fill . startswith('>'): return (string + width * fill[1:])[: width] elif fill . startswith('^'): pad = (width * fill[1:])[: max(0, width - len(string) + 1) / / 2] return (pad + string + pad)[: width] else: if fill . startswith('<'): ...
Next level string padding
56f3ca069821793533000a3a
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/56f3ca069821793533000a3a
6 kyu
# Task You are given a function that should insert an asterisk (`*`) between every pair of **even digits** in the given input, and return it as a string. If the input is a sequence, concat the elements first as a string. ## Input The input can be an integer, a string of digits or a sequence containing integers onl...
algorithms
import re def asterisc_it(s): if isinstance(s, int): s = str(s) elif isinstance(s, list): s = '' . join(map(str, s)) return re . sub(r'(?<=[02468])(?=[02468])', '*', s)
Asterisk it
5888cba35194f7f5a800008b
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5888cba35194f7f5a800008b
7 kyu
You need to play around with the provided string (s). Move consonants forward 9 places through the alphabet. If they pass 'z', start again at 'a'. Move vowels back 5 places through the alphabet. If they pass 'a', start again at 'z'. For our Polish friends this kata does not count 'y' as a vowel. Exceptions: If the ...
algorithms
def vowel_back(st): return st . translate(str . maketrans("abcdefghijklmnopqrstuvwxyz", "vkbaafpqistuvwnyzabtpvfghi"))
Vowels Back
57cfd92c05c1864df2001563
[ "Fundamentals", "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/57cfd92c05c1864df2001563
6 kyu
John is developing a system to report fuel usage but needs help with the coding. First, he needs you to write a function that, given the actual consumption (in l/100 km) and remaining amount of petrol (in l), will give you how many kilometers you'll be able to drive. Second, he needs you to write a function that, giv...
games
def total_kilometers(cons, petrol): return round(100 * petrol / cons, 2) def check_distance(dist, cons, petrol): return ("You will need to refuel" if dist > total_kilometers(cons, petrol) else [[n * 100, dist - 100 * n, round(petrol - cons * n, 2)] for n in range(dist / / 100 + 1)])
Fuel usage reporting
55cb8b5ddd6a67fef7000070
[ "Fundamentals", "Games", "Puzzles" ]
https://www.codewars.com/kata/55cb8b5ddd6a67fef7000070
6 kyu
Create a decorator ```expected_type()``` that checks if what the decorated function returns is of expected type. An ```UnexpectedTypeException``` should be raised if the type returned by the decorated function doesn't match the ones expected. Requirements: * ```expected_type()``` should accept a tuple of many types t...
reference
class UnexpectedTypeException (Exception): pass def expected_type(return_types): def decor(func): def wrapper(* args, * * kwargs): ans = func(* args, * * kwargs) if not isinstance(ans, return_types): raise UnexpectedTypeException() return ans return wrapper return dec...
Expected Type Decorator
56f411dc9821795fd90011d9
[ "Fundamentals", "Design Patterns", "Object-oriented Programming" ]
https://www.codewars.com/kata/56f411dc9821795fd90011d9
6 kyu
The cat wants to lay down on the table, but the problem is that we don't know where it is in the room! You'll get in input: - the cat coordinates as a list of length 2, with the row on the map and the column on the map. - the map of the room as a list of lists where every element can be 0 if empty or 1 if is the tab...
reference
from itertools import chain def putTheCatOnTheTable(cat, map): lX, lY = len(map), len(map[0]) x, y = cat if not (0 <= x < lX and 0 <= y < lY): return 'NoCat' try: table = divmod(list(chain . from_iterable(map)). index(1), lY) except ValueError: return "NoTable" retu...
Put the cat on the table
560030c3ab9f805455000098
[ "Fundamentals" ]
https://www.codewars.com/kata/560030c3ab9f805455000098
6 kyu
The number 1089 is the smallest one, non palindromic, that has the same prime factors that its reversal. Thus, ```python prime factorization of 1089 with 3, 3, 11, 11 -------> 3, 11 prime factorization of 9801 with 3, 3, 3, 3, 11, 11 -------> 3, 11 ``` The task for this kata is to create a function same_factRev(), t...
reference
from bisect import bisect A110819 = [1089, 2178, 4356, 6534, 8712, 9801, 10989, 21978, 24024, 26208, 42042, 43956, 48048] def same_factRev(nMax): return A110819[: bisect(A110819, nMax)]
Numbers and its Reversal Having Same Prime Factors.
55ea170313b76622b3000014
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/55ea170313b76622b3000014
5 kyu
Write a function that reverses the bits in an integer. For example, the number `417` is `110100001` in binary. Reversing the binary is `100001011` which is `267`. You can assume that the number is not negative.
reference
def reverse_bits(n): return int(bin(n)[: 1: - 1], 2)
Reverse the bits in an integer
5959ec605595565f5c00002b
[ "Bits", "Fundamentals" ]
https://www.codewars.com/kata/5959ec605595565f5c00002b
7 kyu
A group of friends (n >= 2) have reunited for a get-together after a very long time. They agree that they will make presentations on holiday destinations or expeditions they have been to only if it satisfies **one simple rule**: > the holiday/journey being presented must have been visited _only_ by the presenter a...
algorithms
from collections import Counter def presentation_agenda(friend_list): uniqueDest = {d for d, c in Counter( d for p in friend_list for d in p['dest']). items() if c == 1} pFilteredDest = tuple( (p['person'], [d for d in p['dest'] if d in uniqueDest]) for p in friend_list) return [{'...
Exclusive presentations
57dd8c78eb0537722f0006bd
[ "Sets", "Algorithms" ]
https://www.codewars.com/kata/57dd8c78eb0537722f0006bd
6 kyu
Following the trails of your lost master - Λoile - who you inherited your mad programming skills from, you have finally caught a lead and begin your adventure into the dungeon where progress can be made. To pass the first cave, you need to **crack the code** on the podium sitting in front of the gate, blocking you from...
games
# Top portion is adapted from my solution for a different kata about this language # Removing the instructions that aren't used.to not fully spoiler the other kata. from enum import Enum D = Enum('Direction', ['U', 'D', 'L', 'R']) def interpret(code): instructions = tuple(l for l in code . split('\n')) ...
Cryptic Cave: Episode 1
5a5c5a1ab3bfa8728d00008d
[ "Reverse Engineering", "Games", "Esoteric Languages", "Puzzles" ]
https://www.codewars.com/kata/5a5c5a1ab3bfa8728d00008d
5 kyu
All of sudden you and Stripes find yourselves in a sticky situation. Your paper drop business has grown to the point where it's too much for just Stripes and you to handle. Simply, there are just too many houses and not enough of you. Since your job is to make sure the business runs smoothly, it's up to you to find a s...
algorithms
from math import ceil class Route: def __init__(self, soc, h, m, t): c = ceil(h / int((t * 60) * 50 / m)) self . paperboys_needed = lambda: f" { c - 2 } paperboy {[ '' , 's' ][ c > 3 ]} needed for { soc } " if c > 2 else "You and Stripes can handle the work yourselves"
Paperboy 2
56fa467e0ba33b8b1100064a
[ "Algorithms" ]
https://www.codewars.com/kata/56fa467e0ba33b8b1100064a
6 kyu
Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another. Example: ```python unpack([None, [1, ({2, 3}, {'foo':...
reference
from collections import Iterable def unpack(iterable): lst = [] for x in iterable: if isinstance(x, dict): x = unpack(x . items()) elif isinstance(x, str): x = [x] elif isinstance(x, Iterable): x = unpack(x) else: x = [x] lst . extend(x) r...
Unpack
56ee74e7fd6a2c3c7800037e
[ "Fundamentals", "Algorithms", "Lists", "Recursion" ]
https://www.codewars.com/kata/56ee74e7fd6a2c3c7800037e
6 kyu
In logic, an implication (or material conditional) states that > If `p` is true, `q` should be true too. We can express the result of any implication of two statements as a logical table: ``` q T F p T T F F T T ``` In this kata, we will take that further. Given an array, assume that from first to last item ...
algorithms
from functools import reduce def mult_implication(lst): return reduce(lambda p, q: not p or q, lst) if lst else None
Multiple implications
58f671ee5522a9c33800009b
[ "Algorithms" ]
https://www.codewars.com/kata/58f671ee5522a9c33800009b
7 kyu
## Prologue In this kata. We assume that you know what [BrainFuck](http://en.wikipedia.org/wiki/Brainfuck) is. And it would be better if you were able to recite all 8 basic operators to solve this kata. ## Background Have you ever coded BrainFuck by hand ? Have you ever counted the operators again and again to mak...
reference
import re from abc import ABC from collections import ChainMap from collections.abc import Iterable, Iterator, MutableMapping from contextlib import AbstractContextManager from dataclasses import asdict, dataclass, fields, replace from enum import Enum from itertools import islice, tee from typing import Any, Literal, ...
To BrainFuck Transpiler
59f9cad032b8b91e12000035
[ "Esoteric Languages", "Parsing", "Compilers" ]
https://www.codewars.com/kata/59f9cad032b8b91e12000035
1 kyu
You are taking a music class and you need to know what notes are on every fret of the guitar. There are six strings on the guitar and 18 frets. Given the name of the string as a string`"E", "A", "D", "G", "B" or "e"`, as well the fret in integer format (open note is 0), return the note played. We are going to use a mu...
algorithms
notes = "A, A#, B, C, C#, D, D#, E, F, F#, G, G#" . split(', ') def what_note(string, fret): return notes[(notes . index(string . upper()) + fret) % len(notes)]
Figure Out the Notes
5602e85d255e3240c2000024
[ "Algorithms" ]
https://www.codewars.com/kata/5602e85d255e3240c2000024
7 kyu
You are currently in the United States of America. The main currency here is known as the United States Dollar (USD). You are planning to travel to another country for vacation, so you make it today's goal to convert your USD (all bills, no cents) into the appropriate currency. This will help you be more prepared for w...
reference
def convert_my_dollars(usd, currency): if currency[0]. lower() in 'aeiou': rate = CONVERSION_RATES[currency] else: rate = int(str(CONVERSION_RATES[currency]), 2) return f'You now have { usd * rate } of { currency } .'
Currency Conversion
5a5c118380eba8a53d0000ce
[ "Fundamentals", "Mathematics", "Algebra" ]
https://www.codewars.com/kata/5a5c118380eba8a53d0000ce
7 kyu
You are a skier (marked below by the `X`). You have made it to the Olympics! Well done. ``` \_\_\_X\_ \*\*\*\*\*\ \*\*\*\*\*\*\ \*\*\*\*\*\*\*\ \*\*\*\*\*\*\*\*\ \*\*\*\*\*\*\*\*\*\\.\_\_\_\_/ ``` Your job in this kata is to calculate the maximum speed you will achieve during your downhill run. The speed is dictated ...
reference
def ski_jump(mountain): height = len(mountain) speed = height * 1.5 jump_length = height * speed * 9 / 10 return ( f" { jump_length : .2 f } metres: He's crap!" if jump_length < 10 else f" { jump_length : .2 f } metres: He's ok!" if jump_length < 25 else f" { jump_length : .2 f }...
Ski Jump
57ed7214f670e99f7a000c73
[ "Fundamentals", "Strings", "Arrays", "Mathematics" ]
https://www.codewars.com/kata/57ed7214f670e99f7a000c73
7 kyu
In this kata you have a 20x20 preloaded array of oil saturation in some region. Your task is to answer whether it is efficient to place the well at the given point. A well is efficient if its efficiency is bigger or equal to given threshold. Input parameters in that function are: <ul> <li> <b>x</b> and <b>y</b> intege...
reference
def is_efficient(x, y, threshold): o = 0 for i in range(x - 1, x + 2): for j in range(y - 1, y + 2): if 0 <= i <= 19 and 0 <= j <= 19: o += float(FIELD[i][j]) return o >= threshold
Well efficiency calculator
5649b9f069dacef88400005e
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5649b9f069dacef88400005e
6 kyu
You are making your very own boardgame. The game is played by two opposing players, featuring a 6 x 6 tile system, with the players taking turns to move their pieces (similar to chess). The design is finished, now it's time to actually write and implement the features. Being the good programmer you are, you carefully p...
algorithms
def fight_resolve(d, a): return - 1 if d . islower() == a . islower() else d if d . lower() + a . lower() in "ka sp as pk" else a
Boardgame Fight Resolve
58558673b6b0e5a16b000028
[ "Logic", "Algorithms", "Games" ]
https://www.codewars.com/kata/58558673b6b0e5a16b000028
7 kyu
In the board game Talisman, when two players enter combat the outcome is decided by a combat score, equal to the players power plus any modifiers plus the roll of a standard 1-6 dice. The player with the highest combat score wins and the opposing player loses a life. In the case of a tie combat ends with neither player...
algorithms
def get_required(p, e): p, e = sum(p), sum(e) if p - e >= 6: return "Auto-win" if p - e == 0: return "Random" if p - e <= - 6: return "Auto-lose" if p - e <= - 5: return "Pray for a tie!" if p > e: return f"( { e - p + 7 } ..6)" return f"(1.. { p - e +...
Talisman Board Game Combat System Checker
541837036d821665ee0006c2
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/541837036d821665ee0006c2
7 kyu
A crime scene has been discovered, and among the evidence is a list of agents, with no apparent connection. Your job in the records department is to match this list with police records to find an exact match. Your function will receive a list as the first parameter, the stolen record, followed by a list of lists, the...
reference
def agents(list_found, list_records): if list_found: return "Match found" if list_found in list_records else "No matches"
Stolen police records
5a5bef7a5c770d08cd0032fa
[ "Fundamentals" ]
https://www.codewars.com/kata/5a5bef7a5c770d08cd0032fa
7 kyu
Given two integer arrays where the second array is a shuffled duplicate of the first array with one element missing, find the missing element. Please note, there may be duplicates in the arrays, so checking if a numerical value exists in one and not the other is not a valid solution. ``` find_missing([1, 2, 2, 3], [1...
algorithms
def find_missing(arr1, arr2): return sum(arr1) - sum(arr2)
Find the missing element between two arrays
5a5915b8d39ec5aa18000030
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5a5915b8d39ec5aa18000030
7 kyu
# Definition A **number** is called **_Automorphic number_** if and only if *its square ends in the same digits as the number itself*. ___ # Task **_Given_** a **number** *determine if it Automorphic or not* . ___ # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/p...
reference
def automorphic(n): return "Automorphic" if str(n * n). endswith(str(n)) else "Not!!"
Automorphic Number (Special Numbers Series #6)
5a58d889880385c2f40000aa
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a58d889880385c2f40000aa
7 kyu
## Task Given a positive integer `n`, calculate the following sum: ``` n + n/2 + n/4 + n/8 + ... ``` All elements of the sum are the results of integer division. ## Example ``` 25 => 25 + 12 + 6 + 3 + 1 = 47 ```
algorithms
def halving_sum(n): s = 0 while n: s += n n >>= 1 return s
Halving Sum
5a58d46cfd56cb4e8600009d
[ "Algorithms" ]
https://www.codewars.com/kata/5a58d46cfd56cb4e8600009d
7 kyu
Write the following function: ```javascript function areaOfPolygonInsideCircle(circleRadius, numberOfSides) ``` ```haskell areaOfPolygonInsideCircle :: Double -> Int -> Double areaOfPolygonInsideCircle circleRadius numberOfSides = undefined ``` ```php function areaOfPolygonInsideCircle($circleRadius, $numberOfSides) `...
reference
from math import sin, pi def area_of_polygon_inside_circle(r, n): return round(0.5 * n * r * * 2 * sin(2 * pi / n), 3)
Calculate the area of a regular n sides polygon inside a circle of radius r
5a58ca28e626c55ae000018a
[ "Mathematics", "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/5a58ca28e626c55ae000018a
6 kyu
Get the list of integers for Codewars Leaderboard score (aka Honor) in descending order ``` Note: if it was the bad timing, the data could be updated during your test cases. Try several times if you had such experience. ```
reference
import requests from bs4 import BeautifulSoup def get_leaderboard_honor(): soup = BeautifulSoup(requests . get( 'https://www.codewars.com/users/leaderboard'). text) return [ int(tr . find_all('td')[- 1]. text . replace(',', '')) for tr in soup . select('div.leaderboard table t...
Codewars Leaderboard
5a57d101cadebf03d40000b9
[ "Fundamentals" ]
https://www.codewars.com/kata/5a57d101cadebf03d40000b9
6 kyu
# Introduction The ragbaby cipher is a substitution cipher that encodes/decodes a text using a keyed alphabet and their position in the plaintext word they are a part of. To encrypt the text `This is an example.` with the key `cipher`, first construct a keyed alphabet: ``` c i p h e r a b d f g j k l m n o q s t u v...
reference
from string import ascii_lowercase as aLow import re def rotateWord(w, alpha, dct, d): lst = [] for i, c in enumerate(w . lower(), 1): transChar = alpha[(dct[c] + i * d) % 26] if w[i - 1]. isupper(): transChar = transChar . upper() lst . append(transChar) return '' . join(ls...
Ragbaby cipher
5a2166f355519e161a000019
[ "Ciphers", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a2166f355519e161a000019
6 kyu
**Story** On some island lives a chameleon population. Chameleons here can be of only one of three colors - red, green and blue. Whenever two chameleons of different colors meet, they both change their colors to the third one (i.e. when red and blue chameleons meet, they can both become green). There is no other way ...
algorithms
def chameleon(chameleons, color): (_, a), (_, b), (_, c) = sorted((i == color, v) for i, v in enumerate(chameleons)) return - 1 if not a and not c or (b - a) % 3 else b
Chameleon unity
553ba31138239b9bc6000037
[ "Algebra", "Logic", "Algorithms" ]
https://www.codewars.com/kata/553ba31138239b9bc6000037
5 kyu
# Ascii Shift Encryption/Decryption The goal of this kata is to create a very simple ASCII encryption and decryption. The encryption algorithm should shift each character's charcode by the character's current index in the string (0-based). The input strings will never require to go outside of the ASCII range. ### Ex...
algorithms
def ascii_encrypt(plaintext): return '' . join(chr(ord(c) + i) for i, c in enumerate(plaintext)) def ascii_decrypt(plaintext): return '' . join(chr(ord(c) - i) for i, c in enumerate(plaintext))
ASCII Shift Encryption/Decryption
56e9ac87c3e7d512bc001363
[ "Algorithms" ]
https://www.codewars.com/kata/56e9ac87c3e7d512bc001363
7 kyu
The squarefree part of a positive integer is the largest divisor of that integer which itself has no square factors (other than 1). For example, the squareefree part of 12 is 6, since the only larger divisor is 12, and 12 has a square factor (namely, 4). Your challenge, should you choose to accept it, is to implement ...
algorithms
def square_free_part(n): for i in range(2, int(n * * 0.5) + 1): while n % (i * * 2) == 0: n /= i return n
Squarefree Part of a Number
567cd7da4b9255b96b000022
[ "Mathematics", "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/567cd7da4b9255b96b000022
5 kyu
# Definition A number is a **_Special Number_** *if it’s digits only consist 0, 1, 2, 3, 4 or 5* **_Given_** a number *determine if it special number or not* . # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ___ # Notes * **_The numbe...
reference
def special_number(n): return "Special!!" if max(str(n)) <= "5" else "NOT!!"
Special Number (Special Numbers Series #5)
5a55f04be6be383a50000187
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a55f04be6be383a50000187
7 kyu
Define a class called `Lamp`. It will have a string attribute for `color` and boolean attribute, `on`, that will refer to whether the lamp is on or not. Define your class constructor with a parameter for color and assign `on` as `false` on initialize. ```if:javascript,typescript,groovy Give the lamp an instance metho...
reference
class Lamp (object): def __init__(self, color=None, on=False): self . color = color self . on = on def toggle_switch(self): self . on = not self . on def state(self): if self . on: s = 'on' else: s = 'off' return f'The lamp is { s } .'
The Lamp: Revisited
570e6e32de4dc8a8340016dd
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/570e6e32de4dc8a8340016dd
6 kyu
Jurassic Word is full of wonderful prehistoric creatures...eating a lot. In this kata your task is to take in a lunchtime scene of a dinosaur and their food, and decipher exactly what ate what. Now, there isn't much mystery in what a dino might be eating. It can be one of: ```java String dead_dino = "_C C}>"; /...
algorithms
class JurassicWord (object): TREX, VELO, BRAK, TRIS = "A T-Rex", "A velociraptor", "A brachiosaurus", "A triceratops" MEAT, FLOW, LEAF = "a dead dino", "flowers", "leaves" DEF = "Something" DEF_ = DEF . lower() EATEN = [((MEAT, 2, 3), "_C", "C}>"), ((FLOW, 3, 3), "iii", "iii")...
Jurassic Word
55709dc15ebd283cc9000007
[ "Algorithms" ]
https://www.codewars.com/kata/55709dc15ebd283cc9000007
6 kyu
Simple enough this one - you will be given an array. The values in the array will either be numbers or strings, or a mix of both. You will not get an empty array, nor a sparse one. Your job is to return a single array that has first the numbers sorted in ascending order, followed by the strings sorted in alphabetic or...
reference
def db_sort(arr): return sorted(arr, key=lambda x: (isinstance(x, str), x))
Double Sort
57cc79ec484cf991c900018d
[ "Fundamentals", "Strings", "Arrays", "Sorting" ]
https://www.codewars.com/kata/57cc79ec484cf991c900018d
7 kyu
Mash 2 arrays together so that the returning array has alternating elements of the 2 arrays . Both arrays will always be the same length. eg. [1,2,3] + ['a','b','c'] = [1, 'a', 2, 'b', 3, 'c']
reference
def array_mash(xs, ys): return [z for p in zip(xs, ys) for z in p]
Array Mash
582642b1083e12521f0000da
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/582642b1083e12521f0000da
7 kyu
<b>Background</b><br> There is a message that is circulating via public media that claims a reader can easily read a message where the inner letters of each words is scrambled, as long as the first and last letters remain the same and the word contains all the letters. Another example shows that it is quite difficult ...
reference
import re def scramble_words(words): def sort_letters(match): s = match . group() letters = iter(sorted(filter(str . isalpha, s[1: - 1]))) return s[0] + "" . join(next(letters) if c . isalpha() else c for c in s[1: - 1]) + s[- 1] return re . sub(r'[a-z][^\s]*[a-z]', sort_letters, words)
Typoglycemia Generator
55953e906851cf2441000032
[ "Fundamentals" ]
https://www.codewars.com/kata/55953e906851cf2441000032
5 kyu
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```ruby a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same mag...
reference
import math class VectorInputCoordsValidationError (Exception): """Custom exception class for invalid input args given to the Vector instantiation""" class Vector: # https://www.mathsisfun.com/algebra/vectors.html def __init__(self, * args): try: self . x, self . y, self . z = a...
Vector Class
532a69ee484b0e27120000b6
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/532a69ee484b0e27120000b6
5 kyu
## Problem Determine whether a positive integer number is **colorful** or not. `263` is a colorful number because `[2, 6, 3, 2*6, 6*3, 2*6*3]` are all different; whereas `236` is not colorful, because `[2, 3, 6, 2*3, 3*6, 2*3*6]` have `6` twice. So take all consecutive subsets of digits, take their product and ensur...
algorithms
def colorful(number): base_result = [] for x in str(number): base_result . append(int(x)) for y in range(len(base_result) - 1): temp = base_result[y] * base_result[y + 1] base_result . append(temp) # Should you really eval the last value ? :shrug: If so, would use eval return len...
Colorful Number
5441310626bc6a1e61000f2c
[ "Algorithms" ]
https://www.codewars.com/kata/5441310626bc6a1e61000f2c
6 kyu
``` ************************* * Create a frame! * * __ __ * * / \~~~/ \ * * ,----( .. ) * * / \__ __/ * * /| (\ |( * * ^ \ /___\ /\ | * * |__| |__|-.. * ************************* ``` Given an array of strings and a character to be use...
reference
def frame(text, char): n = len(max(text, key=len)) + 4 return "\n" . join([char * n] + ["%s %s %s" % (char, line . ljust(n - 4), char) for line in text] + [char * n])
Create a frame!
5672f4e3404d0609ec00000a
[ "Strings", "Arrays", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5672f4e3404d0609ec00000a
6 kyu
You've been given a list that states the daily revenue for each day of the week. Unfortunately, the list has been corrupted and contains extraneous characters. Rather than fix the source of the problem, your boss has asked you to create a program that removes any unneccessary characters and return the corrected list. ...
reference
import re def fix(value): digits = re . sub('\D', '', value) return '$' + digits[: - 2] + '.' + digits[- 2:] def remove_char(values): return [fix(v) for v in values]
Remove Unnecessary Characters from Items in List
586d12f0aa042830910001d1
[ "Fundamentals", "Regular Expressions", "Lists", "Strings" ]
https://www.codewars.com/kata/586d12f0aa042830910001d1
7 kyu
Find all files in the current directory where you run your code, then make a dictionary in the following manner. ``` { filename : first line of the file , ...} ```
reference
import os def first_line(path): with open(path) as f: return f . readline() def create_file_dict(): return {k: first_line(k) for k in next(os . walk('.'))[2]}
Find the files then read them
5a552ef7e6be3855270000bd
[ "Fundamentals" ]
https://www.codewars.com/kata/5a552ef7e6be3855270000bd
6 kyu
# Definition **_Jumping number_** is the number that *All adjacent digits in it differ by 1*. ____ # Task **_Given_** a number, **_Find if it is Jumping or not_** . ____ # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ___ # Notes * **_N...
reference
def jumping_number(number): arr = list(map(int, str(number))) return ('Not!!', 'Jumping!!')[all(map(lambda a, b: abs(a - b) == 1, arr, arr[1:]))]
Jumping Number (Special Numbers Series #4)
5a54e796b3bfa8932c0000ed
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a54e796b3bfa8932c0000ed
7 kyu
Your friend has invited you to a party, and tells you to meet them in the line to get in. The one problem is it's a masked party. Everyone in line is wearing a colored mask, including your friend. Find which people in line could be your friend. Your friend has told you that he will be wearing a `RED` mask, and has **T...
algorithms
def redWith2Blues(i, line): return any(line[i - 2 + x: i + 1 + x]. count('blue') == 2 for x in range(3)) def friend_find(line): return sum(p == 'red' and redWith2Blues(i, line) for i, p in enumerate(line))
Masquerade Waiting Line
5357edc90d9c5df39a0013bc
[ "Algorithms", "Arrays", "Puzzles" ]
https://www.codewars.com/kata/5357edc90d9c5df39a0013bc
6 kyu
You are back at your newly acquired decrypting job for the secret organization when a new assignment comes in. Apparently the enemy has been communicating using a device they call "The Mirror". It is a rudimentary device with encrypts the message by switching its letter with its mirror opposite (A => Z), (B => Y), (C...
algorithms
def mirror(code, chars="abcdefghijklmnopqrstuvwxyz"): return code . lower(). translate(str . maketrans(chars, chars[:: - 1]))
Mirroring cipher
571af500196bb01cc70014fa
[ "Strings", "Cryptography", "Security", "Algorithms" ]
https://www.codewars.com/kata/571af500196bb01cc70014fa
7 kyu
The magic sum of 3s is calculated on an array by summing up odd numbers which include the digit `3`. Write a function `magic_sum` which accepts an array of integers and returns the sum. *Example:* `[3, 12, 5, 8, 30, 13]` results in `16` (`3` + `13`) If the sum cannot be calculated, `0` should be returned.
reference
def magic_sum(arr): return arr and sum(x for x in arr if x % 2 and '3' in str(x)) or 0
Magic Sum of 3s
57193a349906afdf67000f50
[ "Fundamentals" ]
https://www.codewars.com/kata/57193a349906afdf67000f50
7 kyu
An ATM has banknotes of nominal values 10, 20, 50, 100, 200 and 500 dollars. You can consider that there is a large enough supply of each of these banknotes. You have to write the ATM's function that determines the minimal number of banknotes needed to honor a withdrawal of `n` dollars, with `1 <= n <= 1500`. Return ...
algorithms
def solve(n): if n % 10: return - 1 c, billet = 0, iter((500, 200, 100, 50, 20, 10)) while n: x, r = divmod(n, next(billet)) c, n = c + x, r return c
ATM
5635e7cb49adc7b54500001c
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5635e7cb49adc7b54500001c
7 kyu
**An [isogram](https://en.wikipedia.org/wiki/Isogram)** (also known as a "nonpattern word") is a logological term for a word or phrase without a repeating letter. It is also used by some to mean a word or phrase in which each letter appears the same number of times, not necessarily just once. You task is to write a me...
algorithms
from collections import Counter import re def is_isogram(word): if type(word) is not str or not word: return False return len(set(Counter(re . sub(r'[^a-z]', "", word . lower())). values())) == 1
Is it an isogram?
586d79182e8d9cfaba0000f1
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/586d79182e8d9cfaba0000f1
6 kyu
It might be déjà vu, or it might be a duplicate day. You’re well trained in the arts of cleaning up duplicates. Someone has hacked your database and injected all kinds of duplicate records into your tables. You don’t have access to modify the data in the tables or restore the tables to a previous time because the DBA’s...
algorithms
def find_duplicates(emp): dups, out, uniq = [], [], set() for e in emp: if e in uniq: dups . append(e) else: out . append(e) uniq . add(e) emp . clear() emp . extend(out) return dups
Déjà vu Duplicates
547f601b4a437a2048000981
[ "Algorithms" ]
https://www.codewars.com/kata/547f601b4a437a2048000981
6 kyu
Gematria is an Assyro-Babylonian-Greek system of code and numerology later adopted into Jewish culture. The system assigns numerical value to a word or a phrase in the belief that words or phrases with identical numerical values bear some relation to each other or bear some relation to the number itself. While more com...
reference
TOME = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'k': 10, 'l': 20, 'm': 30, 'n': 40, 'o': 50, 'p': 60, 'q': 70, 'r': 80, 's': 90, 't': 100, 'u': 200, 'x': 300, 'y': 400, 'z': 500, 'j': 600, 'v': 700, 'w': 900} def gematria(s): return sum(TOME . get(c, 0) for c in s . lower()...
Gematria for all
573c91c5eaffa3bd350000b0
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/573c91c5eaffa3bd350000b0
7 kyu
# Union of closed disjoint intervals Write a function `interval_insert` which takes as input - a list `myl` of disjoint closed intervals with integer endpoints, sorted by increasing order of left endpoints - an interval `interval` and returns the union of `interval` with the intervals in `myl`, as an array of disjoi...
reference
from itertools import chain import bisect def merge_intervals(intervals): intervals = iter(intervals) merged = [next(intervals)] for ins in intervals: l, r = merged[- 1] if ins[0] <= r: merged[- 1] = (l, max(r, ins[1])) else: merged . append(ins) return merged ...
Union of Intervals
5495bfa82eced2146100002f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5495bfa82eced2146100002f
6 kyu
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a strin...
reference
from random import sample def actually_really_good(foods): question = "You know what's actually really good? " len_foods = len(foods) if len_foods == 0: return question + "Nothing!" elif len_foods == 1: food = foods[0] return question + f" { food . capitalize ()} and more { food ...
Food combinations
565f448e6e0190b0a40000cc
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/565f448e6e0190b0a40000cc
7 kyu
Given an array of arguments, representing system call arguments keys and values, join it into a single, space-delimited string. You don't need to care about the application name -- your task is only about parameters. Each element of the given array can be: * a single string, * a single string array, * an array of two ...
reference
def args_to_string(args): L = [] for arg in args: if isinstance(arg, str): L . append(arg) elif len(arg) == 1: L . append(arg[0]) elif len(arg[0]) == 1: L . append('-' + ' ' . join(arg)) else: L . append('--' + ' ' . join(arg)) return ' ' . join(L)
Command line parameters
53689951c8a5ca91ac000566
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/53689951c8a5ca91ac000566
6 kyu
An anagram is a word, a phrase, or a sentence formed from another by rearranging its letters. An example of this is "angel", which is an anagram of "glean". Write a function that receives an array of words, and returns the total number of distinct pairs of anagramic words inside it. Some examples: - There are 2 anag...
algorithms
from collections import Counter def anagram_counter(words): return sum(n * (n - 1) / / 2 for n in Counter('' . join(sorted(x)) for x in words). values())
Number of anagrams in an array of words
587e18b97a25e865530000d8
[ "Algorithms" ]
https://www.codewars.com/kata/587e18b97a25e865530000d8
6 kyu
### Definition **_Disarium number_** is the number that *The sum of its digits powered with their respective positions is equal to the number itself*. ____ ### Task **_Given_** a number, **_Find if it is Disarium or not_** . ____ ### Warm-up (Highly recommended) ### [Playing With Numbers Series](https://www.code...
reference
def disarium_number(n): return "Disarium !!" if n == sum(int(d) * * i for i, d in enumerate(str(n), 1)) else "Not !!"
Disarium Number (Special Numbers Series #3)
5a53a17bfd56cb9c14000003
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a53a17bfd56cb9c14000003
7 kyu
### **[Mahjong Series](/collections/mahjong)** **Mahjong** is based on draw-and-discard card games that were popular in 18th and 19th century China and some are still popular today. In each deck, there are three different suits numbered `1` to `9`, which are called **Simple tiles**. To simplify the problem, we talk a...
algorithms
from collections import Counter from copy import * # only works for first case def solution(tiles): valid = "" for i in range(1, 10): x = tiles + str(i) c = Counter(x) if c . most_common(1)[0][1] < 5 and is_valid(Counter(x)): valid += str(i) return valid def is_valid(h...
Mahjong - #1 Pure Hand
56ad7a4978b5162445000056
[ "Games", "Logic", "Algorithms" ]
https://www.codewars.com/kata/56ad7a4978b5162445000056
4 kyu
### **[Mahjong Series](/collections/mahjong)** **Mahjong** is based on draw-and-discard card games that were popular in 18th and 19th century China and some are still popular today. In each deck, there are three different suits numbered 1 to 9, which are called **Simple tiles**. They are *Circles* (denoted by `[1-9]p...
algorithms
ranking = 'psmz' def sorted_tiles(tiles): return sorted(tiles, key=lambda x: (ranking . index(x[1]), int(x[0]))) def check_all_three(tiles): s_tiles = sorted_tiles(tiles) while s_tiles: next = s_tiles[0] if s_tiles . count(next) >= 3: for i in range(3): s_tiles . remove(ne...
Mahjong - #2 Seven-pairs
56a36b618e2548ddb400004d
[ "Games", "Logic", "Algorithms" ]
https://www.codewars.com/kata/56a36b618e2548ddb400004d
3 kyu
## Bezier curves When a shape is described using vector graphics, its outline is often described as a sequence of linear, quadratic, and cubic Bezier curves. You can read about [Bézier curves](https://en.wikipedia.org/wiki/B%C3%A9zier_curve) on Wikipedia. You don't need to know much about Bezier curves to solve this...
reference
class Segment: # Instead of an abstract class, make it the implementation for all three subclasses def __init__(self, * coords): self . control_points = coords # IMHO a getter/setter is overkill here def control_points_at(self, t): # Helper function p = self . control_points result = [] ...
Bezier Curves
5a47391c80eba865ea00003e
[ "Fundamentals" ]
https://www.codewars.com/kata/5a47391c80eba865ea00003e
4 kyu
# Kata Task Given 3 points `a`, `b`, `c` <pre style='color:red'> c b a </pre> Find the shortest distance from point `c` to a straight line that passes through points `a` and `b` **Notes** * all points are of the form `[x,y]` where x >= 0 and y >= 0 * if `a...
algorithms
from math import dist def distance_from_line(a, b, c): ca = dist(c, a) cb = dist(c, b) ab = dist(a, b) s = (ca + cb + ab) / 2 area = (s * (s - ca) * (s - cb) * (s - ab)) * * (1 / 2) if a == b: return ca h = (area * 2) / ab return h
Line Safari : Point distance from a line
59c053f070a3b7d19100007e
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/59c053f070a3b7d19100007e
6 kyu
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an **_array of integers_** , **_Find the minimum sum_** which is obtained *from summing each Two integers product* . ___ # Notes * **_Ar...
reference
def min_sum(arr): arr = sorted(arr) return sum(arr[i] * arr[- i - 1] for i in range(len(arr) / / 2))
Minimize Sum Of Array (Array Series #1)
5a523566b3bfa84c2e00010b
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a523566b3bfa84c2e00010b
7 kyu
You're about to go on a trip around the world! On this trip you're bringing your trusted backpack, that anything fits into. The bad news is that the airline has informed you that your luggage cannot exceed a certain amount of weight. To make sure you're bringing your most valuable items on this journey you've decided ...
algorithms
def pack_bagpack(scores, weights, capacity): load = [0] * (capacity + 1) for score, weight in zip(scores, weights): load = [max(l, weight <= w and load[w - weight] + score) for w, l in enumerate(load)] return load[- 1]
Packing your backpack
5a51717fa7ca4d133f001fdf
[ "Algorithms", "Dynamic Programming" ]
https://www.codewars.com/kata/5a51717fa7ca4d133f001fdf
5 kyu
In this kata, the number 0 is infected. You are given a list. Every turn, any item in the list that is adjacent to a 0 becomes infected and transforms into a 0. How many turns will it take for the whole list to become infected? ``` [0,1,1,0] ==> [0,0,0,0] All infected in 1 turn. [1,1,0,1,1] --> [1,0,0,0,1] --> [0,0,...
reference
def infected_zeroes(s): m = 0 l = 0 for i, n in enumerate(s): if n == 0: m = i if l == 0 else max(m, (i - l + 1) / / 2) l = i + 1 return max(m, len(s) - l)
Infected Zeroes
5a511db1b3bfa8f45b000098
[ "Fundamentals" ]
https://www.codewars.com/kata/5a511db1b3bfa8f45b000098
6 kyu
The number `23` is special in the sense that all of its digits are prime numbers. Furthermore, it's **a prime itself**. There are 4 such numbers between 10 and 100: `23, 37, 53, 73`. Let's call these numbers "total primes". Complete the function that takes a range (`a, b`) and returns the number of total primes within...
algorithms
from itertools import product def isPrime(n): return n == 2 or n % 2 and all(n % p for p in range(3, int(n * * .5) + 1, 2)) def get_total_primes(a, b): low, high = map(len, map(str, (a, b))) return sum(a <= n < b and isPrime(n) for d in range(low, high + 1) for n in map(int, map('' . join, pr...
Total Primes
5a516c2efd56cbd7a8000058
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5a516c2efd56cbd7a8000058
6 kyu
Introduction and warm-up (highly recommended): [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ### Task Given an array/list of integers, find the Nth smallest element in the array. ### Notes * Array/list size is at least 3. * Array/list's numbers could be a...
reference
def nth_smallest(arr, pos): return sorted(arr)[pos - 1]
Nth Smallest Element (Array Series #4)
5a512f6a80eba857280000fc
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a512f6a80eba857280000fc
7 kyu
Suppose I have two vectors: `(a1, a2, a3, ..., aN)` and `(b1, b2, b3, ..., bN)`. The dot product between these two vectors is defined as: ``` a1*b1 + a2*b2 + a3*b3 + ... + aN*bN ``` The vectors are classified as orthogonal if the dot product equals zero. Complete the function that accepts two sequences as inputs an...
algorithms
def is_orthogonal(u, v): return sum(i * j for i, j in zip(u, v)) == 0
Orthogonal Vectors
53670c5867e9f2222f000225
[ "Physics", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/53670c5867e9f2222f000225
7 kyu
The story of the famous Disney-Pixar animated movie "Up" is based on the main character Carl Fredricksen journey in his home equipped with balloons. But can this happen for real? What kind of objects can you lift with helium balloons? How many balloons do you need? In this kata you will create a class ``Journey(ob...
reference
class Journey: def __init__(self, object, crew, balloons): self . base_weight = object['weight'] self . crew_weight = crew * 80 self . balloons_lifts = balloons * 0.0048 def isPossible(self): return self . balloons_lifts >= self . base_weight + self . crew_weight
Can this object fly? Balloons in "Up" and in real life
59ea2a532a7accf2510000ce
[ "Object-oriented Programming", "Fundamentals" ]
https://www.codewars.com/kata/59ea2a532a7accf2510000ce
7 kyu
**How many elephants can the spider web hold?** Imagine a spider web that is defined by two variables: - strength, measured as the weight in kilograms that the web holds. Strength + 1 elephant will break the web - length, measured as the number of elephants that fit one after the other on the web :) Paraphrasing the...
algorithms
def breakTheWeb(strength, width): res = total = 0 for i in range(width): for _ in range(width - i): total += (i + 1) * 1000 if total > strength: return res res += 1 return res
How many elephants can the spider web hold?
5830e55fa317216de000001b
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5830e55fa317216de000001b
6 kyu
The description is rather long but you are given all needed formulas (almost:-) John has bought a bike but before going moutain biking he wants us to do a few simulations. He gathered information: - His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent* - We suppose that:...
reference
from math import sin, atan def temps(v0, slope, d_tot): GRAVITY_ACC = 9.81 * 3.6 * 60.0 # gravity acceleration DRAG = 60.0 * 0.3 / 3.6 # force applied by air on the cyclist DELTA_T = 1.0 / 60.0 # in minutes D_WATTS = 0.5 # power loss in Watts / minute G_THRUST = 60 * 3.6 * 3.6 # acceleration ...
Easy Cyclist's Training
5879f95892074d769f000272
[ "Fundamentals" ]
https://www.codewars.com/kata/5879f95892074d769f000272
5 kyu
# Task **_Given_** *a number* , **_Return_** **_The Maximum number _** *could be formed from the digits of the number given* . ___ # Notes * **_Only Natural numbers_** *passed to the function , numbers Contain digits [0:9] inclusive* * **_Digit Duplications_** *could occur* , So also **_consider it when formin...
reference
def max_number(n): return int('' . join(sorted(str(n), reverse=True)))
Form The Largest
5a4ea304b3bfa89a9900008e
[ "Fundamentals", "Numbers", "Data Types", "Mathematics", "Algorithms", "Logic", "Basic Language Features", "Loops", "Control Flow", "Conditional Statements" ]
https://www.codewars.com/kata/5a4ea304b3bfa89a9900008e
7 kyu
A **balanced number** is a number where the sum of digits to the left of the middle digit(s) and the sum of digits to the right of the middle digit(s) are equal. If the number has an odd number of digits, then there is only one middle digit. (For example, `92645` has one middle digit, `6`.) Otherwise, there are two mi...
reference
def balancedNum(n): s = str(n) l = (len(s) - 1) / / 2 same = len(s) < 3 or sum(map(int, s[: l])) == sum(map(int, s[- l:])) return "Balanced" if same else "Not Balanced" balanced_num = balancedNum
Balanced Number (Special Numbers Series #1 )
5a4e3782880385ba68000018
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a4e3782880385ba68000018
7 kyu
General primality test are often computationally expensive, so in the biggest prime number race the idea is to study special sub-families of prime number and develop more effective tests for them. [Mersenne Primes](https://en.wikipedia.org/wiki/Mersenne_prime) are prime numbers of the form: M<sub>n</sub> = 2<sup>n</s...
algorithms
def lucas_lehmer(n): return n in [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 69725...
Lucas-Lehmer Test for Mersenne Primes
5416fac7932c1dcc4f0006b4
[ "Algorithms" ]
https://www.codewars.com/kata/5416fac7932c1dcc4f0006b4
6 kyu
## Fixed xor Write a function that takes two hex strings as input and XORs them against each other. If the strings are different lengths the output should be the length of the shortest string. Hint: The strings would first need to be converted to binary to be XOR'd. ## Note: If the two strings are of different leng...
algorithms
def fixed_xor(a, b): return "" . join(f" { int ( x , 16 ) ^ int ( y , 16 ): x } " for x, y in zip(a, b))
Fixed xor
580f1220df91273ee90001e7
[ "Algorithms", "Mathematics", "Logic", "Algebra", "Binary", "Cryptography" ]
https://www.codewars.com/kata/580f1220df91273ee90001e7
6 kyu
Removed due to copyright infringement. <!--- &ensp;Iahub got bored, so he invented a game to be played on paper.<br> &ensp;He writes n integers a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub>. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ...
algorithms
def flipping_game(a): current = best = 0 for n in a: current = max(0, current - (n or - 1)) best = max(best, current) return sum(a) + (best or - 1)
Flipping Game
59841e5084533834d6000025
[ "Algorithms", "Games", "Puzzles", "Logic" ]
https://www.codewars.com/kata/59841e5084533834d6000025
6 kyu
## Bocce Description Bocce is a game played by two competing teams, with three types of balls. Each team has its own set of balls (in this kata `red` and `black`) and there is a neutral ball called the `jack`. The jack is thrown at the beginning of each round, followed by the players trying to throw their balls as clo...
algorithms
import math def bocce_score(balls): xy = balls[- 1]['distance'] balls = balls[: - 1] for b in balls: b['distance'] = math . sqrt(((xy[0] - b['distance'][0]) * * 2) + ((xy[1] - b['distance'][1]) * * 2)) reds = [x for x in balls if x['type'] == "red"] blacks = [x for x in balls if x['ty...
Bocce
55332880e679dd9cb3000081
[ "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/55332880e679dd9cb3000081
6 kyu
Cheating a bit... =============== --- ### Introduction So, there is this game where you manage several soldiers, and you're losing against the machine. What can you do? Easy: patch the savegame file to restore your soldier's health! ### Details Each soldier has the following structure: * **name_length**: 16 bit ...
games
def patch_data(s): r, p = '', 0 while p < len(s): ll = ord(s[p]) + 256 * ord(s[p + 1]) r += s[p: p + ll + 2] + chr(244) + chr(1) p += 4 + ll return r
Cheating a bit...
536cce5f49aa8b3648000b52
[ "Strings", "Arrays", "Puzzles" ]
https://www.codewars.com/kata/536cce5f49aa8b3648000b52
5 kyu
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your funct...
algorithms
import heapq import itertools def sort(iterable): heap = list(iterable) heapq . heapify(heap) return (heapq . heappop(heap) for i in range(len(heap)))
Sort a massive list of strings (hard)
5820e17770ca28df760012d7
[ "Data Structures", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/5820e17770ca28df760012d7
5 kyu
*** Nova polynomial from roots*** This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24b...
algorithms
def poly_from_roots(rs): return reduce(poly_multiply, [[- r, 1] for r in rs]) if rs else [1]
nova polynomial 5. from roots
571df7c31f95429529000092
[ "Algorithms" ]
https://www.codewars.com/kata/571df7c31f95429529000092
6 kyu
# Task Let's define a hole of size n as a matrix which is built as follows. ``` Its elements are in range [1..n^2]. The matrix is filled by rings, from the outwards the innermost. Each ring is filled with numbers in the following way: the first number is written in the top left corner; the second number is written in ...
algorithms
def black_hole(n, a, b): cont = min(a, b, n - 1 - a, n - 1 - b) start = 4 * cont * (n - 2 * cont + 1) + 4 * cont * \ (cont - 1) if cont > 0 else 0 n, a, b = n - 2 * cont, a - cont, b - cont fin = (1 + 4 * b if a == 0 and b < n - 1 else 2 + 4 * a if b == n - 1 and a < n - 1 else 3 + 4 ...
Challenge Fun #19: Black Hole
58bd011fd0efbec33400001f
[ "Algorithms" ]
https://www.codewars.com/kata/58bd011fd0efbec33400001f
6 kyu
Imagine a funnel filled with letters. The bottom letter drops out of the funnel and onto a conveyor belt: ``` \b,c/ --> \b,c/ \a/ --> \ / a ------- ------- ``` If there are two letters above a gap, the smaller letter falls into the gap. ``` \b,c/ --> \ c/ \ / --> \b/ ...
reference
def funnel_out(funnel): r = "" h = len(funnel) while funnel[h - 1][0] != "~": r += funnel[h - 1][0] funnel[h - 1][0] = "~" i = h - 1 j = 0 while i > 0: if funnel[i - 1][j] < funnel[i - 1][j + 1]: funnel[i][j] = funnel[i - 1][j] funnel[i - 1][j] = "~" else: ...
Funnel Out A String
5a4b612ee626c5d116000084
[ "Fundamentals" ]
https://www.codewars.com/kata/5a4b612ee626c5d116000084
5 kyu
Many primes can be decomposed as a sum of two perfect squares. For example: ```python 5 = 4 + 1 = 2² + 1² 29 = 4 + 25 = 2² + 5² ``` But we have some primes that does not have this property like 3, 7, 11. Your task is to give the i-th prime in an ordered and increasing sequence of these non partitionable primes in perf...
reference
from gmpy2 import is_prime primes = [n for n in range(3, int(1e6), 4) if is_prime(n)] def ith_nondecomp_prime(i): return primes[i - 1]
Non Decomposable Primes as Sums of Perfect Squares
561c34b31dbb1b11640000de
[ "Fundamentals", "Mathematics", "Algorithms", "Memoization" ]
https://www.codewars.com/kata/561c34b31dbb1b11640000de
6 kyu
Ronald's uncle left him 3 fertile chickens in his will. When life gives you chickens, you start a business selling chicken eggs which is exactly what Ronald decided to do. A chicken lays 300 eggs in its first year. However, each chicken's egg production decreases by 20% every following year (rounded down) until when ...
algorithms
def egged(year, span): total = 0 eggs_per_chicken = 300 for i in range(min(span, year)): total += 3 * eggs_per_chicken eggs_per_chicken = int(eggs_per_chicken * 0.8) return total or "No chickens yet!"
How many eggs?
58c1446b61aefc34620000aa
[ "Algorithms" ]
https://www.codewars.com/kata/58c1446b61aefc34620000aa
6 kyu
Strong number is a number with the sum of the factorial of its digits is equal to the number itself. For example, 145 is strong, because `1! + 4! + 5! = 1 + 24 + 120 = 145`. ### Task Given a positive number, find if it is strong or not, and return either `"STRONG!!!!"` or `"Not Strong !!"`. ### Examples - `1` is a...
reference
import math def strong_num(number): return "STRONG!!!!" if sum(math . factorial(int(i)) for i in str(number)) == number else "Not Strong !!"
Strong Number (Special Numbers Series #2)
5a4d303f880385399b000001
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a4d303f880385399b000001
7 kyu
### Welcome to the Challenge Edition of *Upside-Down Numbers* In the [original kata by @KenKamau](https://www.codewars.com/kata/59f7597716049833200001eb) you were limited to integers below `2^17`. Here, you will be given strings of digits of up to `42` characters in length (upper bound is `10^42 - 1`). Your task is e...
algorithms
def upsidedown(a, b): a, b = str(a), str(int(b) + 1) ans = _solve_len_ge(len(a), a) for i in range(len(a) + 1, len(b) + 1): ans += _solve_len(i) return ans - _solve_len_ge(len(b), b) def _solve_len(n): if n == 1: return 3 if n % 2 == 0: return 4 * 5 * * (n / /...
Upside-Down Numbers - Challenge Edition
59f98052120be4abfa000304
[ "Performance", "Algorithms" ]
https://www.codewars.com/kata/59f98052120be4abfa000304
3 kyu
A natural number is called **k-prime** if it has exactly k prime factors, counted with multiplicity. A natural number is thus prime if and only if it is 1-prime. ``` Examples of k-primes: k = 2 -> 4, 6, 9, 10, 14, 15, 21, 22, … k = 3 -> 8, 12, 18, 20, 27, 28, 30, … k = 5 -> 32, 48, 72, 80, 108, 112, … ``` The k-prime...
reference
def prime_factors_length(n): cnt, i = 0, 2 while (i * i <= n): while (n % i == 0): cnt += 1 n /= i i += 1 if (n > 1): cnt += 1 return cnt def kprimes_step(k, step, start, nd): res = [] for i in range(start, nd - step + 1): if (prime_factors_length(i) ...
Steps in k-primes
5a48948e145c46820b00002f
[ "Mathematics", "Number Theory" ]
https://www.codewars.com/kata/5a48948e145c46820b00002f
6 kyu
Once you complete this kata, there is a [15x15 Version](http://www.codewars.com/kata/15x15-nonogram-solver) that you can try. And once you complete that, you can do the [Multisize Version](https://www.codewars.com/kata/5a5519858803853691000069) which goes up to 50x50. # Description For this kata, you will be making a...
algorithms
import itertools class Nonogram: poss = {(1, 1, 1): set([(1, 0, 1, 0, 1)]), (1, 1): set([(0, 0, 1, 0, 1), (0, 1, 0, 1, 0), (1, 0, 1, 0, 0), (0, 1, 0, 0, 1), (1, 0, 0, 1, 0), (1, 0, 0, 0, 1)]), (1, 2): set([(1, 0, 1, 1, 0), (1, 0, 0, 1, 1), (0, 1, 0, 1, 1)]), (1, 3): set(...
5x5 Nonogram Solver
5a479247e6be385a41000064
[ "Algorithms", "Logic", "Games", "Game Solvers" ]
https://www.codewars.com/kata/5a479247e6be385a41000064
4 kyu
A famous casino is suddenly faced with a sharp decline of their revenues. They decide to offer Texas hold'em also online. Can you help them by writing an algorithm that can rank poker hands? <b style='font-size:16px'>Task:</b> <ul> <li>Create a poker hand that has a constructor that accepts a string containing 5 c...
algorithms
from functools import total_ordering @ total_ordering class PokerHand (object): CARDS = "AKQJT987654321" RANKS = {card: idx for idx, card in enumerate(CARDS)} def score(self, hand): values, suits = zip(* hand . split()) idxs, ordered = zip( * sorted((self . RANKS[card], card) f...
Sortable Poker Hands
586423aa39c5abfcec0001e6
[ "Games", "Fundamentals", "Sorting", "Design Patterns", "Algorithms" ]
https://www.codewars.com/kata/586423aa39c5abfcec0001e6
4 kyu
In traditional [American checkers](https://en.wikipedia.org/wiki/Draughts) (also known as *draughts* outside the U.S.), when one of your pieces becomes a king, it gains the advantage of being able to move diagonally in any direction. This adds more possibilities with regard to capturing multiple enemy pieces in a singl...
algorithms
def king_move_combo(ar): n = len(ar) field = list(map(list, ar)) def max_move(x0, y0): mm = 0 for dx, dy in ((- 1, - 1), (- 1, 1), (1, 1), (1, - 1)): x, y = x0 + 2 * dx, y0 + 2 * dy if x >= 0 and x < n and y >= 0 and y < n: xe, ye = x0 + dx, y0 + dy if field[xe][ye] == 'X': ...
Checkerboard King Combo Move
5a34c8ce55519ecb15000012
[ "Games", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5a34c8ce55519ecb15000012
5 kyu
Let's say you have a bunch of points, and you want to round them all up and calculate the area of the smallest polygon containing all of the points (nevermind why, you just want a challenge). What you're looking for is the area of the *convex hull* of these points. Here is an example, delimited in blue : <a href='http...
algorithms
import numpy as np def slope(p1, p2): dx, dy = vectorize(p1, p2) return dy / dx if dx else float("inf") def vectorize(p1, p2): return [b - a for a, b in zip(p1, p2)] def getArea(p1, p2, p3): return np . cross( vectorize(p1, p2), vectorize(p1, p3)) / 2 def isConcave(p1, pivot, ...
Convex hull area
59c1d64b9f0cbcf5740001ab
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/59c1d64b9f0cbcf5740001ab
4 kyu
### The Problem Consider a flat board with pegs sticking out of one side. If you stretched a rubber band across the outermost pegs what is the set of pegs such that all other pegs are contained within the shape formed by the rubber band? ![alt text](https://upload.wikimedia.org/wikipedia/commons/b/bc/ConvexHull.png) ...
algorithms
def hull_method(points): sorted_points = sorted(points) return half_hull(sorted_points) + half_hull(reversed(sorted_points)) def half_hull(sorted_points): hull = [] for p in sorted_points: while len(hull) > 1 and not is_ccw_turn(hull[- 2], hull[- 1], p): hull . pop() hull . app...
Compute a convex hull
5657d8bdafec0a27c800000f
[ "Algorithms", "Geometry" ]
https://www.codewars.com/kata/5657d8bdafec0a27c800000f
4 kyu
<video controls autoplay='autoplay' loop='loop' width='426'><source src="https://i.imgur.com/XSMoEuK.mp4" type='video/mp4'/></video> <sub><b>Above:</b> <a href="https://i.imgur.com/XSMoEuK.mp4">Game footage from Bloxorz online game</a></sub> This kata is inspired by [**Bloxorz**](http://miniclip.wikia.com/wiki/Bloxor...
algorithms
from collections import deque def blox_solver(arr): def isSame(A, B): return A == B # bloxorz has is pieces superposed # bloxorz is vertical (looking the board from above) def isVert(A, B): return A[0] != B[0] # bloxorz is horizontal (looking the board from above) def isHorz(A, B): retu...
Bloxorz Solver
5a2a597a8882f392020005e5
[ "Games", "Puzzles", "Game Solvers", "Algorithms" ]
https://www.codewars.com/kata/5a2a597a8882f392020005e5
3 kyu
<h1>Task</h1> Create a top-down movement system that would feel highly responsive to the player. In your Update method you have to check for the keys that are currently being pressed, the keys correspond to the enum Direction shown below, based on which key is pressed or released your method should behave this way: 1...
games
class PlayerMovement: def __init__(self, x, y): self . position = Tile(x, y) self . direction = 8 self . a = [] self . q = [] def update(self): a = [Input . get_state(x) for x in (6, 4, 2, 8)] for s, d in zip(a, (6, 4, 2, 8)): if d in self . q and not s: self . q . re...
Top Down Movement System
59315ad28f0ebeebee000159
[ "Games", "Logic", "Puzzles" ]
https://www.codewars.com/kata/59315ad28f0ebeebee000159
4 kyu
You get some nested lists. Keeping the original structures, sort only elements (integers) inside of the lists. In other words, sorting the intergers only by swapping their positions. ``` Example Input : [[[2, 1], [4, 3]], [[6, 5], [8, 7]]] Output : [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] ``` Note: The structures o...
reference
import numpy as np def sort_nested_list(A): return np . sort(A, axis=None). reshape(np . array(A). shape). tolist()
Sort only integers in Nested List
5a4bdd73d8e145f17d000035
[ "Fundamentals", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/5a4bdd73d8e145f17d000035
6 kyu
Mike and Joe are fratboys that love beer and games that involve drinking. They play the following game: Mike chugs one beer, then Joe chugs 2 beers, then Mike chugs 3 beers, then Joe chugs 4 beers, and so on. Once someone can't drink what he is supposed to drink, he loses. Mike can chug at most A beers in total (other...
reference
def game(maxMike, maxJoe): roundsMike = int(maxMike * * .5) roundsJoe = (- 1 + (1 + 4 * maxJoe) * * .5) / / 2 return ("Non-drinkers can't play" if not maxMike or not maxJoe else "Joe" if roundsMike <= roundsJoe else "Mike")
Drinking Game
5a491f0be6be389dbb000117
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a491f0be6be389dbb000117
7 kyu
Similar to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/), but this time you need to operate with shuffled strings to identify if they are composed repeating a subpattern Since there is no deterministic way to tell which pattern was really the original one among all the possible p...
reference
from collections import Counter from functools import reduce from fractions import gcd def has_subpattern(s): c = Counter(s) m = reduce(gcd, c . values()) return '' . join(sorted(k * (v / / m) for k, v in c . items()))
String subpattern recognition III
5a4a2973d8e14586c700000a
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5a4a2973d8e14586c700000a
6 kyu
Print an ordered cross table of a round robin tournament that looks like this: ``` # Player 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Pts SB ========================================================================== 1 Nash King 1 0 = 1 0 = 1 1 0 1 1 1 0 8.0 52.25 2 Karsyn Ma...
reference
def crosstable(players, results): n = len(players) # calculating pts = [sum(s for s in row if s != None) for row in results] sb = [sum(s * pts for (s, pts) in zip(row, pts) if s != None) for row in results] surnames = [p . split(' ')[1] for p in players] # sorting table...
Tournament Cross Table with Sonneborn-Berger Score
5a392890c5e284a7a300003f
[ "Sorting", "Algorithms" ]
https://www.codewars.com/kata/5a392890c5e284a7a300003f
4 kyu