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
## Task You are watching a volleyball tournament, but you missed the beginning of the very first game of your favorite team. Now you're curious about how the coach arranged the players on the field at the start of the game. The team you favor plays in the following formation: ``` 0 3 0 4 0 2 0 6 0 5 0 1 ``` where po...
games
from collections import deque POS = [(3, 2), (1, 2), (0, 1), (1, 0), (3, 0), (2, 1)] def volleyball_positions(formation, k): players = deque([formation[x][y] for x, y in POS]) players . rotate(k % 6) baseForm = [l[:] for l in formation] for i, (x, y) in enumerate(POS): baseForm[x][y] ...
Simple Fun #58: Volleyball Positions
5889f08eb71a7dcee600006c
[ "Puzzles" ]
https://www.codewars.com/kata/5889f08eb71a7dcee600006c
6 kyu
# Task Define crossover operation over two equal-length strings A and B as follows: the result of that operation is a string of the same length as the input strings result[i] is chosen at random between A[i] and B[i]. Given array of strings `arr` and a string result, find for how many pairs of strings from `arr`...
games
from itertools import combinations def strings_crossover(arr, result): return sum(1 for s1, s2 in combinations(arr, 2) if all(r in (x, y) for x, y, r in zip(s1, s2, result)))
Simple Fun #54: Strings Crossover
5889902f53ad4a227100003f
[ "Puzzles" ]
https://www.codewars.com/kata/5889902f53ad4a227100003f
6 kyu
Each exclamation mark's weight is 2; each question mark's weight is 3. Putting two strings `left` and `right` on the balance - are they balanced? If the left side is more heavy, return `"Left"`; if the right side is more heavy, return `"Right"`; if they are balanced, return `"Balance"`. ## Examples ```python "!!", ...
reference
def balance(left, right): left_count = left . count("!") * 2 + left . count("?") * 3 right_count = right . count("!") * 2 + right . count("?") * 3 if (left_count > right_count): return "Left" elif (right_count > left_count): return "Right" else: return "Balance"
Exclamation marks series #17: Put the exclamation marks and question marks on the balance - are they balanced?
57fb44a12b53146fe1000136
[ "Fundamentals" ]
https://www.codewars.com/kata/57fb44a12b53146fe1000136
6 kyu
# Task `EvilCode` is a game similar to `Codewars`. You have to solve programming tasks as quickly as possible. However, unlike `Codewars`, `EvilCode` awards you with a medal, depending on the time you took to solve the task. To get a medal, your time must be (strictly) inferior to the time corresponding to the medal. ...
games
def evil_code_medal(user_time, gold, silver, bronze): for medal, time in [["Gold", gold], ["Silver", silver], ["Bronze", bronze]]: if user_time < time: return medal return "None"
Simple Fun #270: Evil Code Medal
5915686ed2563aa6650000ab
[ "Puzzles" ]
https://www.codewars.com/kata/5915686ed2563aa6650000ab
7 kyu
# Description: Remove the minimum number of exclamation marks from the start/end of each word in the sentence to make their amount equal on both sides. ### Notes: * Words are separated with spaces * Each word will include at least 1 letter * There will be no exclamation marks in the middle of a word ___ ## Examples...
reference
def remove(s): return ' ' . join( r for r, _ in __import__('re'). findall(r'((!*)\w+\2)', s))
Exclamation marks series #10: Remove some exclamation marks to keep the same number of exclamation marks at the beginning and end of each word
57fb04649610ce369a0006b8
[ "Fundamentals" ]
https://www.codewars.com/kata/57fb04649610ce369a0006b8
6 kyu
# Task You are given `N` ropes, where the length of each rope is a positive integer. At each step, you have to reduce all the ropes by the length of the smallest rope. The step will be repeated until no ropes are left. Given the length of N ropes, print the number of ropes that are left before each step. # Example...
algorithms
def cut_the_ropes(a): if not a: return [] m = min(a) return [len(a)] + cut_the_ropes([x - m for x in a if x > m])
Simple Fun #160: Cut The Ropes
58ad388555bf4c80e800001e
[ "Algorithms" ]
https://www.codewars.com/kata/58ad388555bf4c80e800001e
6 kyu
Mr. Odd is my friend. Some of his common dialogues are: _"Am I looking odd?", "It’s looking very odd",_ etc. Actually, "odd" is his favorite word. This Valentine's Day he went to meet his girlfriend, but he forgot to take a gift. So he told her that he did an _odd_ thing. His girlfriend became angry and gave him a puzz...
games
import re pattern = re . compile('o(.*?)d(.*?)d') def odd(s): n = 0 while pattern . search(s): n += 1 s = pattern . sub(r'\1\2', s, count=1) return n
Simple Fun #121: Mr. Odd
589d74722cae97a7260000d9
[ "Puzzles" ]
https://www.codewars.com/kata/589d74722cae97a7260000d9
6 kyu
### Longest Palindrome Find the length of the longest substring in the given string `s` that is the same in reverse. As an example, if the input was “I like racecars that go fast”, the substring (`racecar`) length would be `7`. If the length of the input string is `0`, the return value must be `0`. ### Ex...
reference
def longest_palindrome(s): """Manacher algorithm - Complexity O(n)""" # Transform S into T. # For example, S = "abba", T = "^#a#b#b#a#$". # ^ and $ signs are sentinels appended to each end to avoid bounds checking T = '#' . join('^{}$' . format(s)) n = len(T) P = [0] * n C = R = 0 fo...
longest_palindrome
54bb6f887e5a80180900046b
[ "Fundamentals" ]
https://www.codewars.com/kata/54bb6f887e5a80180900046b
6 kyu
# Task The sequence of `Chando` is an infinite sequence of all Chando's numbers in ascending order. A number is called `Chando's` if it is an integer that can be represented as a sum of different positive integer powers of 5. The first Chando's numbers is 5 (5^1). And the following n<sup>th</sup> Chando's numbers ...
algorithms
def nth_chandos_number(n): return int((bin(n) + "0")[2:], 5)
Simple Fun #146: Chandos Number
58aa8368ae929ea2e00000d9
[ "Algorithms", "Number Theory" ]
https://www.codewars.com/kata/58aa8368ae929ea2e00000d9
6 kyu
Removed due to copyright infringement. <!--- # Task Given the positions of a white `bishop` and a black `pawn` on the standard chess board, determine whether the bishop can capture the pawn in one move. The `bishop` has no restrictions in distance for each move, but is limited to diagonal movement. Check out the e...
games
def bishop_and_pawn(bishop, pawn): return abs(ord(bishop[0]) - ord(pawn[0])) == abs(int(bishop[1]) - int(pawn[1]))
Chess Fun #2: Bishop And Pawn
589425c2561a35dd1a0000a2
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/589425c2561a35dd1a0000a2
6 kyu
Removed due to copyright infringement. <!--- # Task In the Land Of Chess, bishops don't really like each other. In fact, when two bishops happen to stand on the same diagonal, they immediately rush towards the opposite ends of that same diagonal. Given the initial positions (in chess notation) of two bishops, `bis...
games
def bishop_diagonal(a, b): a, b = sorted([['abcdefgh' . index(f), '12345678' . index(r)] for f, r in [a, b]]) m = int((b[1] - a[1]) / (b[0] - a[0])) if abs(a[1] - b[1] ) == abs(a[0] - b[0]) and abs(a[1] - b[1]) else 0 if m: while ...
Chess Fun #4: Bishop Diagonal
5897e394fcc4b9c310000051
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5897e394fcc4b9c310000051
5 kyu
Among the ruins of an ancient city a group of archaeologists found a mysterious function with lots of HOLES in it called ```getNum(n)``` (or `get_num(n)` in ruby, python, or r). They tried to call it with some arguments. And finally they got this journal: ```javascript getNum(300) #-> returns 2 getNum(90783) #-> return...
games
def get_num(n): return sum({'0': 1, '6': 1, '9': 1, '8': 2}. get(d, 0) for d in str(n))
Mysterious function
55217af7ecb43366f8000f76
[ "Puzzles" ]
https://www.codewars.com/kata/55217af7ecb43366f8000f76
6 kyu
# Task You are given a square that has a height of `n`. Each `1 × 1` square has two diagonals as shown below: ![](https://cdn2.scratch.mit.edu/get_image/project/103759149_100x80.png) Count the number of triangles formed by the squares sides and diagonals. # Input/Output `[input]` integer `n` `1 ≤ n ≤ 100` `[out...
games
def count_triangles(n): return [8, 44, 124, 268, 492, 816, 1256, 1832, 2560, 3460, 4548, 5844, 7364, 9128, 11152, 13456, 16056, 18972, 22220, 25820, 29788, 34144, 38904, 44088, 49712, 55796, 62356, 69412, 76980, 85080, 93728, 102944, 112744, 123148, 134172, 145836, 158156, 171152, 184840, 199240, 214368, 230244, 2...
Simple Fun #267: Count Triangles
5913ffb2cb1475215c000039
[ "Puzzles" ]
https://www.codewars.com/kata/5913ffb2cb1475215c000039
6 kyu
# Task `Triangular numbers` are defined by the formula `n * (n + 1) / 2` with `n` starting from 1. They count the number of objects that can form an equilateral triangle as shown in the picture below: ![](https://i.gyazo.com/eec11cc9e17a31324338edc4eb7bb746.png) So the sequence of triangular numbers begins as follows...
games
from math import sqrt def triangular_sum(n): return sqrt(2 * (sqrt(8 * n + 1) - 1)) % 2 == 0
Simple Fun #268: Triangular Sum
591404294ef3051cbe000035
[ "Puzzles" ]
https://www.codewars.com/kata/591404294ef3051cbe000035
6 kyu
# Task For the given set `S` its powerset is the set of all possible subsets of `S`. Given an array of integers nums, your task is to return the powerset of its elements. Implement an algorithm that does it in a depth-first search fashion. That is, for every integer in the set, we can either choose to take or not tak...
algorithms
def powerset(nums): if not nums: return [[]] l = powerset(nums[1:]) a = nums[0] return l + [[a] + q for q in l]
Simple Fun #273: Powerset
59157809f05d9a8ad7000096
[ "Algorithms" ]
https://www.codewars.com/kata/59157809f05d9a8ad7000096
5 kyu
### Task Given a fair dice that you can throw an unlimited number of times and a number `n`, find the number of ways to throw the dice so that the sum of the dots on its upper surface equals `n`. ### Input/Output `[input]` integer `n` The sum of dots, `1 ≤ n ≤ 50`. `[output]` an integer The number of ways to thr...
reference
from functools import cache # Basically fibonacci with the previous 6 @ cache def throwing_dice(n): return n == 0 or sum(map(throwing_dice, range(max(0, n - 6), n)))
Simple Fun #272: Throwing Dice
591575f6d64db0431c000009
[ "Fundamentals" ]
https://www.codewars.com/kata/591575f6d64db0431c000009
5 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! # #Series:<br> <a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br> <a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br> <a href="http://www.c...
games
time_units = {'ms': 1, 's': 1000, 'm': 60000, 'h': 3600000, 'd': 86400000} dist_units = {'mm': 1, 'cm': 10, 'dm': 100, 'm': 1000, 'km': 1000000} def testit(a): if all(unit(x) in time_units for x in a): return sorted(a, key=lambda x: val(x) * time_units[unit(x)]) if all(unit(x) in dist_units for x i...
Thinking & Testing : Spatiotemporal index
56d98b555492513acf00077d
[ "Puzzles", "Arrays" ]
https://www.codewars.com/kata/56d98b555492513acf00077d
6 kyu
## Task Complete function `splitOddAndEven`, accept a number `n`(n>0), return an array that contains the continuous parts of odd or even digits. Please don't worry about digit `0`, it won't appear ;-) ## Examples ```javascript splitOddAndEven(123) === [1,2,3] splitOddAndEven(223) === [22,3] splitOddAndEven(11...
games
from itertools import groupby def split_odd_and_even(n): return [int("" . join(g)) for i, g in groupby(str(n), key=lambda x: int(x) % 2)]
T.T.T.17: Split odd and even
57a2ab1abb994466910003af
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57a2ab1abb994466910003af
6 kyu
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: * 232 * 110011 * 54322345 Complete the function to test if the given number (`num`) **can be <u>rearranged</u>** to form a numerical palindrome or not. Return a boo...
reference
def palindrome(num): s = str(num) if not isinstance(num, int) or num < 0: return "Not valid" return num > 9 and sum(s . count(x) % 2 for x in set(s)) < 2
Numerical Palindrome #5
58e26b5d92d04c7a4f00020a
[ "Fundamentals" ]
https://www.codewars.com/kata/58e26b5d92d04c7a4f00020a
6 kyu
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: `2332, 110011, 54322345` For a given number ```num```, write a function which returns an array of all the numerical palindromes contained within each number. The arra...
reference
def palindrome(num): if not isinstance(num, int) or num < 0: return "Not valid" n = str(num) l = len(n) result = {int(n[i: j]) for i in range(l - 1) for j in range(i + 2, l + 1) if int(n[i]) and n[i: j] == n[i: j][:: - 1]} re...
Numerical Palindrome #3.5
58e2708f9bd67fee17000080
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/58e2708f9bd67fee17000080
6 kyu
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 <br>110011 <br>54322345 For a given number ```num```, write a function which returns the number of numerical palindromes within each number. For this kata, sin...
reference
def palindrome(num): if not isinstance(num, int) or num < 0: return 'Not valid' s = str(num) return sum(sum(s[i: i + n] == s[i: i + n][:: - 1] for i in range(len(s) - n + 1)) for n in range(2, len(s) + 1))
Numerical Palindrome #3
58df62fe95923f7a7f0000cc
[ "Fundamentals" ]
https://www.codewars.com/kata/58df62fe95923f7a7f0000cc
6 kyu
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: <p>2332 <br>110011 <br>54322345 For this kata, single digit numbers will <u>not</u> be considered numerical palindromes. For a given number ```num```, write a fun...
reference
def palindrome(num): if type(num) != int or num < 0: return "Not valid" s = str(num) for i in range(len(s) - 2): if s[i] == s[i + 1] or s[i] == s[i + 2]: return True return len(s) != 1 and s[- 1] == s[- 2]
Numerical Palindrome #2
58de819eb76cf778fe00005c
[ "Fundamentals" ]
https://www.codewars.com/kata/58de819eb76cf778fe00005c
6 kyu
When we have a 2x2 square matrix we may have up to 24 different ones changing the positions of the elements. We show some of them ``` a b a b a c a c a d a d b a b a c d d c d b b d b c c b c d d c ``` You may think to generate the remaining ones until completing t...
reference
from collections import Counter from functools import reduce from math import factorial from operator import mul def count_perms(matrix): return factorial(len(matrix) * len(matrix[0])) / / reduce(mul, map(factorial, Counter(sum(matrix, [])). values()))
#6 Matrices: How Many Matrices Do These Elements Produce?
59040fdae1bfd334ca00007a
[ "Permutations", "Matrix", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/59040fdae1bfd334ca00007a
6 kyu
# Task A ciphertext alphabet is obtained from the plaintext alphabet by means of rearranging some characters. For example "bacdef...xyz" will be a simple ciphertext alphabet where a and b are rearranged. A substitution cipher is a method of encoding where each letter of the plaintext alphabet is replaced with the co...
games
def is_substitution_cipher(s1, s2): return len(set(s1)) == len(set(s2)) == len(set(zip(s1, s2)))
Simple Fun #31: Is Substitution Cipher?
58870742c815166a960000af
[ "Puzzles" ]
https://www.codewars.com/kata/58870742c815166a960000af
6 kyu
# Story Old MacDingle had a farm. To be more precise, he had a free-range chicken farm. But Old MacDingle also had a fox problem. Foxes ```F``` eat chickens ```C``` At night the only guaranteed "safe" chickens are in their cages ```[]``` (unless a fox has got into the cage with them!) # Kata Task Given the ini...
reference
import re CHICKEN, FOX, DIRT = 'CF.' CAGE = '[{}]' def hungry_foxes(farm): parts = re . split(r'[[\]]', farm) inside, outside = slice(1, None, 2), slice(None, None, 2) fox_outside = any(FOX in part for part in parts[outside]) parts[outside] = [fox_outside and part . replace( CHIC...
The Hunger Games - Foxes and Chickens
591144f42e6009675300001f
[ "Fundamentals" ]
https://www.codewars.com/kata/591144f42e6009675300001f
6 kyu
Given a rational number n ``` n >= 0, with denominator strictly positive``` - as a string (example: "2/3" in Ruby, Python, Clojure, JS, CS, Go) - or as two strings (example: "2" "3" in Haskell, Java, CSharp, C++, Swift, Dart) - or as a rational or decimal number (example: 3/4, 0.67 in R) - or two integers (Fortr...
reference
from math import ceil from fractions import Fraction as F def decompose(n): f = F(n) ff = int(f) result = [str(ff)] if ff else [] f -= ff while f > 0: x = F(1, int(ceil(f * * - 1))) f -= x result . append(str(x)) return result
Some Egyptian fractions
54f8693ea58bce689100065f
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/54f8693ea58bce689100065f
5 kyu
My name is State Trooper Mark (_"skidmark"_ ) McDingle. My job is maintaining 117 miles of the Interstate, keeping it clean and clear of dead varmints. It is a serious job and I take my job seriously. I am the <span style='color:red;font-size:1.5em;'><b>Road-Kill Detective</b></span> ![](https://i.imgur.com/LYuQtsO...
algorithms
from re import match def road_kill(photo): remains = photo . replace('=', '') for animal in ANIMALS: parts = '^' + '+' . join(c for c in animal) + '+$' if match(parts, remains) or match(parts, remains[:: - 1]): return animal return '??'
The Road-Kill Detective
58e18c5434a3022d270000f2
[ "Algorithms" ]
https://www.codewars.com/kata/58e18c5434a3022d270000f2
5 kyu
# Task In one city it is allowed to write words on the buildings walls. The local janitor, however, doesn't approve of it at all. Every night he vandalizes the writings by erasing all occurrences of some letter. Since the janitor is quite lazy, he wants to do this with just one swipe of his mop. Given a `word`, find t...
games
from string import ascii_lowercase as alphabet def the_janitor(word): return [word . rindex(c) - word . index(c) + 1 if c in word else 0 for c in alphabet]
Simple Fun #265: The Janitor And His Mop
59128363e5bc24091a00006f
[ "Puzzles" ]
https://www.codewars.com/kata/59128363e5bc24091a00006f
6 kyu
## Task Let's call `product(x)` the product of x's digits. Given an array of integers a, calculate `product(x)` for each x in a, and return the number of distinct results you get. ## Example For `a = [2, 8, 121, 42, 222, 23]`, the output should be `3`. Here are the products of the array's elements: ``` 2: product...
games
from functools import reduce from operator import mul def unique_digit_products(a): return len({reduce(mul, map(int, str(x))) for x in a})
Simple Fun #91: Unique Digit Products
5897d94dd07028546c00009d
[ "Puzzles" ]
https://www.codewars.com/kata/5897d94dd07028546c00009d
6 kyu
# Description: Find the longest successive exclamation marks and question marks combination in the string. A successive exclamation marks and question marks combination must contains two part: a substring of "!" and a substring "?", they are adjacent. If more than one result are found, return the one which at lef...
reference
import re def find(s): return max(re . findall(r'(?=(!+\?+|\?+!+))', s), key=len, default='')
Exclamation marks series #16: Find the longest successive exclamation marks and question marks combination in the string
57fb3c839610ce39f7000023
[ "Fundamentals" ]
https://www.codewars.com/kata/57fb3c839610ce39f7000023
6 kyu
### Task Yesterday you found some shoes in your room. Each shoe is described by two values: ``` type indicates if it's a left or a right shoe; size is the size of the shoe. ``` Your task is to check whether it is possible to pair the shoes you found in such a way that each pair consists of a right and a left shoe of ...
games
def pair_of_shoes(a): return sorted(s for lr, s in a if lr == 1) == sorted(s for lr, s in a if lr == 0)
Simple Fun #52: Pair Of Shoes
58885a7bf06a3d466e0000e3
[ "Puzzles" ]
https://www.codewars.com/kata/58885a7bf06a3d466e0000e3
6 kyu
# Description: Remove odd number continuous exclamation marks and question marks(from the left to the right), until no continuous exclamation marks and question marks exist. Please note: One exclamation mark or question mark is not a continuous exclamation marks or question marks. The string only contains `!` and `?`...
reference
import re def remove(inp): while True: next = re . sub(r'!{3,}|\?{3,}', lambda m: "" if len( m . group(0)) % 2 == 1 else m . group(0), inp) if next == inp: break inp = next return next
Exclamation marks series #12: Remove odd number continuous exclamation marks and question marks
57fb0f3f9610ced69000023c
[ "Fundamentals" ]
https://www.codewars.com/kata/57fb0f3f9610ced69000023c
6 kyu
# Task Given array of integers `sequence` and some integer `fixedElement`, output the number of `even` values in sequence before the first occurrence of `fixedElement` or `-1` if and only if `fixedElement` is not contained in sequence. # Input/Output `[input]` integer array `sequence` A non-empty array of positiv...
reference
def even_numbers_before_fixed(s, f): return len([x for x in s[: s . index(f)] if x % 2 == 0]) if f in s else - 1
Simple Fun #263: Even Numbers Before Fixed
5912701a89fc3d0a6a000169
[ "Fundamentals" ]
https://www.codewars.com/kata/5912701a89fc3d0a6a000169
7 kyu
# Task Given an initial string `s`, switch case of the minimal possible number of letters to make the whole string written in the upper case or in the lower case. # Input/Output `[input]` string `s` String of odd length consisting of English letters. 3 ≤ inputString.length ≤ 99. `[output]` a string The resulting...
reference
def case_unification(s): return s . upper() if sum(c . islower() for c in s) < len(s) / 2 else s . lower()
Simple Fun #262: Case Unification
59126cd3379de6ca5f00019c
[ "Fundamentals" ]
https://www.codewars.com/kata/59126cd3379de6ca5f00019c
7 kyu
Businesses use keypad letters in creative ways to spell out a phone number and make it more memorable. Example: http://en.wikipedia.org/wiki/File:Telephone-keypad2.svg Create a mapping for your dialer as given in the above link. Constraints: 1. letters are all uppercase 2. digits 0, 1 are mapped to 0, 1 respectivel...
algorithms
from itertools import product mapping = { '0': '0', '1': '1', '2': 'ABC', '3': 'DEF', '4': 'GHI', '5': 'JKL', '6': 'MNO', '7': 'PQRS', '8': 'TUV', '9': 'WXYZ', } def telephoneWords(digits): digits = map(lambda x: mapping[x], digits) return map('' . join...
telephone words
5653d33e78e3d9dfe600004e
[ "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5653d33e78e3d9dfe600004e
6 kyu
You are playing euchre and you want to know the new score after finishing a hand. There are two teams and each hand consists of 5 tricks. The team who wins the majority of the tricks will win points but the number of points varies. To determine the number of points, you must know which team called trump, how many trick...
algorithms
def update_score(sc, trmp, alone, trks): tot = trks . count(trmp) if tot <= 2: sc[trmp % 2] += 2 elif 3 <= tot <= 4: sc[trmp - 1] += 1 elif tot >= 5 and not alone: sc[trmp - 1] += 2 elif tot >= 5 and alone: sc[trmp - 1] += 4 else: print("what ha...
Get Euchre Score
586eca3b35396db82e000481
[ "Games", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/586eca3b35396db82e000481
6 kyu
# Task Two players - `"black"` and `"white"` are playing a game. The game consists of several rounds. If a player wins in a round, he is to move again during the next round. If a player loses a round, it's the other player who moves on the next round. Given whose turn it was on the previous round and whether he won, de...
games
def whoseMove(lastPlayer, win): return lastPlayer if win else 'white' if lastPlayer == 'black' else 'black'
Simple Fun #261: Whose Move
59126992f9f87fd31600009b
[ "Puzzles" ]
https://www.codewars.com/kata/59126992f9f87fd31600009b
8 kyu
## Story Jumbo Juice makes a fresh juice out of fruits of your choice.Jumbo Juice charges $5 for regular fruits and $7 for special ones. Regular fruits are Banana, Orange, Apple, Lemon and Grapes. Special ones are Avocado, Strawberry and Mango. Others fruits that are not listed are also available upon request. Those e...
reference
def mix_fruit(arr): regular = ["banana", "orange", "apple", "lemon", "grapes"] special = ["avocado", "strawberry", "mango"] return round(sum(5 if fruit . lower() in regular else (7 if fruit . lower() in special else 9) for fruit in arr) / len(arr))
Mix Fruit Juice
5905871c00881d0e85000015
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5905871c00881d0e85000015
6 kyu
> When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description You are given a number sequence (an array) that contains some positive integer and zero. ``` [3,2,1,0,5,6,4,0,1,5,3,0,4,2,8,0] ``` It can be split to som...
games
from itertools import groupby def sort_sequence(sequence): return sum(sorted([sorted(y) + [0] for x, y in groupby(sequence, lambda x: x == 0) if not x], key=sum), [])
Sort the number sequence
5816b76988ca9613cc00024f
[ "Puzzles", "Sorting", "Algorithms" ]
https://www.codewars.com/kata/5816b76988ca9613cc00024f
6 kyu
# Description: Give you a sentence `s`. It contains some words and separated by spaces. Another arguments is `n`, its a number(1,2 or 3). You should convert `s` to camelCase n. There are three kinds of camelCase: ``` camelCase 1: The first letter of each word should be capitalized. Except for ...
games
def toCamelCase(s, n): if n == 1: return s[0]. lower() + s . title(). replace(' ', '')[1:] elif n == 2: return '' . join(map(lambda x: x[: - 1]. lower() + x[- 1]. upper(), s . split()))[: - 1] + s[- 1]. lower() else: return '' . join(map(lambda x: x[: - 1] + x[- 1]. upper(), (s[0]. lower()...
From..To..Series #7: from sentence to camelCase. Can you convert it?
58097ae96037b88f57000105
[ "Puzzles" ]
https://www.codewars.com/kata/58097ae96037b88f57000105
6 kyu
Our friendly friend Pete is really a nice person, but he tends to be rather... Inappropriate. And possibly loud, if given enough ethanol and free rein, so we ask you to write a function that should take its not always "clean" speech and cover as much as possible of it, in order not to offend some more sensible spirits...
algorithms
import re PATTERN = re . compile(r'(?P<first>(?:(?<=[.!?] )|^)\w+)|(?P<other>\w+)') def pete_talk(speech, ok=[]): def watchYourMouth(m): w = (m . group("first") or m . group("other")). lower() if w not in ok and len(w) > 1: w = w[0] + '*' * (len(w) - 2) + w[- 1] if m . group("first"...
Pete's inappropriate speech
571d0c80eed4a1c850000ef2
[ "Regular Expressions", "Strings", "Algorithms" ]
https://www.codewars.com/kata/571d0c80eed4a1c850000ef2
6 kyu
You have an 8x8 grid with coordinates ranging from `1` to `8`. The origin `(1, 1)` is in the top left corner. The bottom right corner is `(8, 8)`. You are given a string as an input which will contain the 2 coordinates in this format: `"(x1 y1)(x2 y2)"`, where `(x1 y1)` represents point `A` and `(x2 y2)` represents po...
algorithms
from math import comb def travel_chessboard(s): x1, y1, x2, y2 = (int(e) for e in s . replace(')(', ' ')[1: - 1]. split(' ')) return comb(x2 - x1 + y2 - y1, x2 - x1)
Travelling on a Grid
5845b080a87f768aaa00027c
[ "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5845b080a87f768aaa00027c
6 kyu
All Unix user know the command line `history`. This one comes with a set of useful commands know as the `bang` command. For more information about the history command line you can take a look at: - The man page -> simply type `man history` in your terminal. - The online man page [here](https://linux.die.net/man/3/h...
algorithms
def bang_contain_string(stg, history): for line in history . splitlines()[:: - 1]: if stg in line: return line . lstrip(" 0123456789") return f"! { stg } : event not found"
Linux history and `!` command. Series#5 The `!?string` command
581b29b549b2c0daeb001454
[ "Strings", "Parsing", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/581b29b549b2c0daeb001454
6 kyu
All Unix user know the command line `history`. This one comes with a set of useful commands know as the `bang` command. For more information about the history command line you can take a look at: - The man page -> simply type `man history` in your terminal. - The online man page [here](https://linux.die.net/man/3/h...
algorithms
import re _PATTERN = re . compile(r'\A\s*(\d+)\s+(.*)\Z') def bang_start_string(n, history): cmds = (_PATTERN . match(line). group(2) for line in history . splitlines()[:: - 1]) return next((cmd for cmd in cmds if cmd . startswith(n)), '!{}: event not found' . format(n))
Linux history and `!` command. Series#4 The `!string` command
5818236ae7f457017b00022b
[ "Strings", "Parsing", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5818236ae7f457017b00022b
6 kyu
All Unix user know the command line `history`. This one comes with a set of useful commands know as the `bang` command. For more information about the history command line you can take a look at: - The man page -> simply type `man history` in your terminal. - The online man page [here](https://linux.die.net/man/3/h...
algorithms
def bang_minus_n(n, history): try: return history . split('\n')[- n]. split(' ')[- 1] except: return "!-{}: event not found" . format(n)
Linux history and `!` command. Series#3 The `!-n` command
5815fd7441e062463d0000f8
[ "Strings", "Parsing", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5815fd7441e062463d0000f8
6 kyu
All Unix user know the command line `history`. This one comes with a set of useful commands know as the `bang` command. For more information about the history command line you can take a look at: - The man page -> simply type `man history` in your terminal. - The online man page [here](https://linux.die.net/man/3/h...
algorithms
def bang_n(n, history): try: return history . split('\n')[n - 1]. split(' ')[- 1] except: return "!{}: event not found" . format(n)
Linux history and `!` command. Series#2 The `!n` command
5814bf3f3db1ffc0180000d3
[ "Strings", "Parsing", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5814bf3f3db1ffc0180000d3
6 kyu
Earlier this year I was in a <a href="https://www.hackerrank.com/contests/regular-expresso/challenges">contest on HackerRank</a> which included a <a href="https://en.wikipedia.org/wiki/Code_golf">code golf</a>-style <a href="https://www.hackerrank.com/contests/regular-expresso/challenges/winning-tic-tac-toe">challenge<...
reference
import re def regex_tic_tac_toe_win_checker(board): regex = r'(\w)(\1\1(...)*$|..\1..\1|.\1.\1..$|...\1...\1)' return bool(re . search(regex, board))
Regex Tic Tac Toe Win Checker
582e0450fe38013dbc0002d3
[ "Games", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/582e0450fe38013dbc0002d3
6 kyu
You are given string "elements" and an int "n". Your task is to return a string that is a palindrom using elements from the string "elements" with the length "n". The format of the palindromization: - Your palindrome begins with the first element of "elements". - After obtaining a pair, you insert the next element in...
algorithms
def palindromization(elements, n): if not elements or n < 2: return "Error!" left = ((n / / len(elements) + 1) * elements)[:(n + 1) / / 2] return left + left[- 1 - n % 2:: - 1]
Palindromization
5840107b6fcbf56d2000010b
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5840107b6fcbf56d2000010b
6 kyu
## Pair of gloves Winter is coming, you must prepare your ski holidays. The objective of this kata is to determine the number of pair of gloves you can constitute from the gloves you have in your drawer. Given an array describing the color of each glove, return the number of pairs you can constitute, assuming that on...
games
def number_of_pairs(gloves): return sum(gloves . count(color) / / 2 for color in set(gloves))
Pair of gloves
58235a167a8cb37e1a0000db
[ "Arrays", "Puzzles" ]
https://www.codewars.com/kata/58235a167a8cb37e1a0000db
6 kyu
All Unix user know the command line `history`. This one comes with a set of useful commands know as the `bang` command. For more information about the history command line you can take a look at: - The man page -> simply type `man history` in your terminal. - The online man page [here](https://linux.die.net/man/3/h...
algorithms
def bang_bang(history): return history . split(' ')[- 1]
Linux history and `!` command. Series#1 The `!!` command
58143221f9588e340e00009f
[ "Strings", "Parsing", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/58143221f9588e340e00009f
6 kyu
In case you might be unlucky enough not to know the best dark fantasy franchise ever, Berserk tells the story of a man that, hating gratuitous violence, decided to become a mercenary (thus one who sells violence, no gratuity anymore!) and starts an epic struggle against apparently unsormountable odds, unsure if he real...
algorithms
def berserk_rater(synopsis): n = sum([score(s . upper()) for s in synopsis]) return 'worstest episode ever' if n < 0 else 'bestest episode ever' if n > 10 else str(n) def score(s): return 5 if 'CLANG' in s else - 2 if 'CG' in s else - 1
Berserk rater: CG Vs. Clang
57fa3a33e8c829780a0001d2
[ "Algorithms" ]
https://www.codewars.com/kata/57fa3a33e8c829780a0001d2
6 kyu
The [Padovan sequence](https://en.wikipedia.org/wiki/Padovan_sequence) is the sequence of integers defined by the initial values ``` P(0) = P(1) = P(2) = 1 ``` and the recurrence relation ``` P(n) = P(n-2) + P(n-3) ``` The first few values of `P(n)` are: ``` 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 8...
algorithms
def padovan(n): p0 = p1 = p2 = 1 for i in range(n): p0, p1, p2 = p1, p2, p0 + p1 return p0
Padovan numbers
5803ee0ed5438edcc9000087
[ "Algorithms" ]
https://www.codewars.com/kata/5803ee0ed5438edcc9000087
6 kyu
## Task Given a positive integer as input, return the output as a string in the following format: Each element, corresponding to a digit of the number, multiplied by a power of 10 in such a way that with the sum of these elements you can obtain the original number. ## Examples Input | Output --- | --- 0 | ""...
reference
def simplify(n): output = [] exp = 0 while n: n, r = divmod(n, 10) if r: output . append(f" { r } * { 10 * * exp } " if exp else f" { r } ") exp += 1 return "+" . join(output[:: - 1])
Simplify the number!
5800b6568f7ddad2c10000ae
[ "Fundamentals" ]
https://www.codewars.com/kata/5800b6568f7ddad2c10000ae
6 kyu
You are given a string of words (x), for each word within the string you need to turn the word 'inside out'. By this I mean the internal letters will move out, and the external letters move toward the centre. If the word is even length, all letters will move. If the length is odd, you are expected to leave the 'middl...
reference
import re def inside_out(s): return re . sub(r'\S+', lambda m: inside_out_word(m . group()), s) def inside_out_word(s): i, j = len(s) / / 2, (len(s) + 1) / / 2 return s[: i][:: - 1] + s[i: j] + s[j:][:: - 1]
Inside Out Strings
57ebdf1c2d45a0ecd7002cd5
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57ebdf1c2d45a0ecd7002cd5
6 kyu
Write a function that takes a number or a string and gives back the number of **permutations without repetitions** that can generated using all of its element.; more on permutations [here](https://en.wikipedia.org/wiki/Permutation). For example, starting with: ``` 1 45 115 "abc" ``` You could respectively generate: `...
algorithms
from operator import mul from math import factorial from functools import reduce from collections import Counter def perms(inp): return factorial(len(str(inp))) / / reduce(mul, map(factorial, Counter(str(inp)). values()), 1)
Number of permutations without repetitions
571bff6082661c8a11000823
[ "Permutations", "Combinatorics", "Algorithms" ]
https://www.codewars.com/kata/571bff6082661c8a11000823
6 kyu
[Vowel harmony](https://en.wikipedia.org/wiki/Vowel_harmony) is a phenomenon in some languages. It means that "A vowel or vowels in a word are changed to sound the same (thus "in harmony.")" ([wikipedia](https://en.wikipedia.org/wiki/Vowel_harmony#Hungarian)). This kata is based on [vowel harmony in Hungarian](https://...
reference
mod = {"e": u"é", "i": u"í", u"ö": u"ő", u"ü": u"ű", "a": u"á", "o": u"ó", "u": u"ú"} def instrumental(word): # find the last vowel for c in word[:: - 1]: if c in u"aáoóuú": suf = "val" break elif c in u"eéiíöőüű": suf = "vel" break # word ends with a vowel ...
Hungarian Vowel Harmony (harder)
57fe5b7108d102fede00137a
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57fe5b7108d102fede00137a
6 kyu
# Task There are `n` houses in a village on a circular road numbered `from 1 to n` starting from some house in clockwise order. It takes one minute to get from one house to any of two adjacent houses and there are no other roads in this village besides the circular one. Find the minimal time required to make all visits...
algorithms
def visits_on_circular_road(n, order): return sum(min((d := abs(b - a)), n - d) for a, b in zip([1, * order], order))
Simple Fun #255: Visits On Circular Road
591074c7ea12ad515500007e
[ "Algorithms" ]
https://www.codewars.com/kata/591074c7ea12ad515500007e
6 kyu
# Task A masked number is a string that consists of digits and one asterisk (`*`) that should be replaced by exactly one digit. Given a masked number `s`, find all the possible options to replace the asterisk with a digit to produce an integer divisible by 6. # Input/Output `[input]` string `s` A masked number. `1...
games
import sys sys . set_int_max_str_digits(0) def is_divisible_by_6(s: str) - > list[str]: res = [] for i in range(10): num = int(s . replace("*", str(i))) if num % 6 == 0: res . append(str(num)) return res
Simple Fun #258: Is Divisible By 6
5911385598dcd432ae000004
[ "Puzzles" ]
https://www.codewars.com/kata/5911385598dcd432ae000004
6 kyu
## Description Give you a 2D array(n * n, n is an odd number more than 1), rotate it, remove elements, return the last surviving number. ``` arr=[ [3,5,8,4,2], [1,9,2,3,8], [4,6,7,2,2], [7,5,5,5,5], [6,5,3,8,1] ] ``` Rotate it in a counter clockwise direction: ``` 2,8,2,5,1 4,3,2,5,8 8,2,7,5,3 5,9,6,5,5 3,1,4,7,6 ```...
games
def rotate_and_remove(arr): while len(arr) > 1: arr = [popMinMax([* r]) for r in zip(* arr)][:: - 1] return arr[0][0] def popMinMax(r): for f in min, max: r . remove(f(r)) return r
myjinxin katas #001 : Rotate, Remove, Return
57dab71714e53f4bc9000310
[ "Puzzles", "Algorithms", "Arrays" ]
https://www.codewars.com/kata/57dab71714e53f4bc9000310
5 kyu
Create a function hollow_triangle(height) that returns a hollow triangle of the correct height. The height is passed through to the function and the function should return a list containing each line of the hollow triangle. ``` hollow_triangle(6) should return : ['_____#_____', '____#_#____', '___#___#___', '__#_____#...
reference
def hollow_triangle(n): return [(f'# { "_" * ( 2 * i - 1 )} #' if i else '#'). center(2 * n - 1, '_') for i in range(n - 1)] + ['#' * (2 * n - 1)]
Hollow Triangle
57819b700a8eb2d6b00002ab
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/57819b700a8eb2d6b00002ab
6 kyu
Given an array (ints) of n integers, find three integers in arr such that the sum is closest to a given number (num), target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: ```ruby closest_sum([-1, 2, 1, -4], 1) # 2 (-1 + 2 + 1 = 2) ``` Note: your solu...
reference
from itertools import combinations def closest_sum(ints, num): return sum(min(combinations(ints, 3), key=lambda a: abs(num - sum(a))))
Closest Sum
577e694af5db624cf30002d0
[ "Fundamentals" ]
https://www.codewars.com/kata/577e694af5db624cf30002d0
6 kyu
If n is the numerator and d the denominator of a fraction, that fraction is defined a (reduced) proper fraction if and only if GCD(n,d)==1. For example `5/16` is a proper fraction, while `6/16` is not, as both 6 and 16 are divisible by 2, thus the fraction can be reduced to `3/8`. Now, if you consider a given number ...
algorithms
def proper_fractions(n): phi = n > 1 and n for p in range(2, int(n * * .5) + 1): if not n % p: phi -= phi / / p while not n % p: n / /= p if n > 1: phi -= phi / / n return phi
Number of Proper Fractions with Denominator d
55b7bb74a0256d4467000070
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/55b7bb74a0256d4467000070
4 kyu
Removed due to copyright infringement. <!--- # Task In ChessLand there is a small but proud chess bishop with a recurring dream. In the dream the bishop finds itself on an `n × m` chessboard with mirrors along each edge, and it is not a bishop but a ray of light. This ray of light moves only along diagonals (the...
games
def chess_bishop_dream(b, p, d, k): yq, yr = divmod(p[0] + k * d[0], 2 * b[0]) xq, xr = divmod(p[1] + k * d[1], 2 * b[1]) return [min(yr, 2 * b[0] - yr - 1), min(xr, 2 * b[1] - xr - 1)]
Chess Fun #6: Chess Bishop Dream
5897ea323387497f460001a0
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5897ea323387497f460001a0
5 kyu
An array of size N x M represents pixels of an image. Each cell of this array contains an array of size 3 with the pixel's color information: `[R,G,B]` Convert the color image, into an *average* greyscale image. The `[R,G,B]` array contains integers between 0 and 255 for each color. To transform a color pixel into...
algorithms
from statistics import mean def grey(rgb): return [int(round(mean(rgb)))] * 3 def color_2_grey(colors): return [[grey(pixel) for pixel in row] for row in colors]
Convert Color image to greyscale
590ee3c979ae8923bf00095b
[ "Image Processing", "Algorithms" ]
https://www.codewars.com/kata/590ee3c979ae8923bf00095b
7 kyu
This is the rightful continuation to this easier Kata [**here**](https://www.codewars.com/kata/5853213063adbd1b9b0000be) and some rules are the same with few substantial alterations. This time we have to deal with a situation like Super Street Fighter 2 Selection Screen: ![alt text](https://images.duckduckgo.com/iu/?...
reference
MOVES = {"up": (- 1, 0), "down": (1, 0), "right": (0, 1), "left": (0, - 1)} def super_street_fighter_selection(fighters, initial_position, moves): y, x = initial_position hovered_fighters = [] for move in moves: dy, dx = MOVES[move] y += dy if not 0 <= y < len(fighters) or not fighter...
Street Fighter 2 - Character Selection - Part 2
58583922c1d5b415b00000ff
[ "Arrays", "Lists", "Fundamentals", "Graph Theory" ]
https://www.codewars.com/kata/58583922c1d5b415b00000ff
5 kyu
In this kata, you must write a function that expects a two-dimensional list `matrix` (minimum size: 2 x 2) as the only argument. The return value will be a two-dimensional list (size: 2 x 2) showing only the corners after `n` clockwise rotations. Examples of corner values, rotation and corners-only return value: `inva...
reference
def rotate_corners(matrix): def score(m): return sum(sum(ord(c) if isinstance(c, str) else int(c) for c in r) for r in m) corners = [[matrix[i][j] for j in (0, - 1)] for i in (0, - 1)] n = (score(matrix) - score(corners)) * score(corners) % 4 for _ in range(n): ...
Rotate Corners
5717fbf85122b8f757001b3f
[ "Fundamentals" ]
https://www.codewars.com/kata/5717fbf85122b8f757001b3f
6 kyu
Consider the sequence `a(1) = 7, a(n) = a(n-1) + gcd(n, a(n-1)) for n >= 2`: `7, 8, 9, 10, 15, 18, 19, 20, 21, 22, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 69, 72, 73...`. Let us take the differences between successive elements of the sequence and get a second sequence `g: 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1,...
reference
from fractions import gcd def seq(): i, a, g = 1, 7, 1 while 1: yield i, a, g i += 1 g = gcd(i, a) a += g def count_ones(n): return sum(g == 1 for _, (i, a, g) in zip(range(n), seq())) def p(n): seen = set() for i, a, g in seq(): if not n: brea...
Weird prime generator
562b384167350ac93b00010c
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/562b384167350ac93b00010c
5 kyu
You will be given two inputs: a string of words and a letter. For each string, return the alphabetic character after every instance of letter(case insensitive). If there is a number, punctuation or underscore following the letter, it should not be returned. ``` If letter = 'r': comes_after("are you really learning ...
reference
def comes_after(st, letter): letter = letter . lower() return '' . join(b for a, b in zip(st . lower(), st[1:]) if a == letter and b . isalpha())
What comes after?
590f5b4a7bbb3e246000007d
[ "Fundamentals" ]
https://www.codewars.com/kata/590f5b4a7bbb3e246000007d
7 kyu
``` ------------------------------------------------------------------ we are programmed just to do anything you want us to w e a r e t h e r o b o t s -----------------------------------------------------------[ d[(0)(0)]b] ``` Task..... You will receieve an array of strings su...
games
import re LEGS = r'[a-z]' BODY = r'[|};&#\[\]/><()*]' def counRobots(strng, typeRobot): return str(sum(len(re . findall(LEGS + BODY + "{2}0" + BODY + "{2}0" + BODY + "{2}" + LEGS, substr)) for substr in map(str . lower, strng) if typeRobot in substr)) def count...
We are the Robots d[(0)(0)]b
587ae98e2ab0ef32ef00004c
[ "Algorithms", "Data Structures", "Regular Expressions", "Puzzles", "Strings" ]
https://www.codewars.com/kata/587ae98e2ab0ef32ef00004c
6 kyu
In this Kata, you need to simulate an old mobile display, similar to this one: ``` *************************** * * * * * CodeWars * * * * * * Menu Contacts * *************************** ``` **Input P...
reference
def mobile_display(width, height_ratio): width, height_ratio = max(width, 20), max(height_ratio, 30) height = width * height_ratio / / 100 def center(string, width, filler, prefix, suffix): width -= len(string) + len(prefix) + len(suffix) left, right = width / / 2, (width + 1) / / 2 return...
Old Mobile Display
584e8bba044a15d3ed00016c
[ "Strings", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/584e8bba044a15d3ed00016c
6 kyu
Alan's child can be annoying at times. When Alan comes home and tells his kid what he has accomplished today, his kid never believes him. Be that kid. Your function 'AlanAnnoyingKid' takes as input a sentence spoken by Alan (a string). The sentence contains the following structure: "Today I " + [action_verb] +...
reference
OUTPUT = "I don't think you {} today, I think you {} {} {}!" . format def alan_annoying_kid(phrase): words = phrase . split() action = ' ' . join(words[2:]). rstrip('.') if "didn't" in phrase: return OUTPUT(action, 'did', words[3], 'it') return OUTPUT(action, "didn't", words[2][: - 2], 'at...
The Sceptical Kid Generator
570957fc20a35bd2df0004f9
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/570957fc20a35bd2df0004f9
6 kyu
A traveling salesman has to visit clients. He got each client's address e.g. `"432 Main Long Road St. Louisville OH 43071"` as a list. The basic zipcode format usually consists of two capital letters followed by a white space and five digits. The list of clients to visit was given as a string of all addresses, each se...
reference
def travel(r, zipcode): streets = [] nums = [] addresses = r . split(',') for address in addresses: if ' ' . join(address . split()[- 2:]) == zipcode: streets . append(' ' . join(address . split()[1: - 2])) nums += address . split()[: 1] return '{}:{}/{}' . format(zipcode, ',' . ...
Salesman's Travel
56af1a20509ce5b9b000001e
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/56af1a20509ce5b9b000001e
6 kyu
<h4>DevOps legacy roasting!</h4> Save the business from technological purgatory. Convert IT to DevOps, modernize application workloads, take it all to the Cloud……. You will receive a string of workloads represented by words….some legacy and some modern mixed in with complaints from the business….your job is to burn ...
reference
import re complaints = ["slow!", "expensive!", "manual!", "down!", "hostage!", "security!"] legacy = { "cobol": 1000, "nonobject": 500, "monolithic": 500, "fax": 100, "modem": 100, "thickclient": 50, "tape": 50, "floppy": 50, "oldschoolit": 50 } def ...
DevOps legacy roasting -> disco inferno -> burn baby burn
58ade79f3c97367977000274
[ "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/58ade79f3c97367977000274
6 kyu
In this Kata, we will calculate running pace. To do that, we have to know the distance and the time. Create the following function: ```if:python `running_pace(distance, time)` ``` ```if:javascript, typescript `runningPace(distance, time)` ``` Where: `distance` - A float with the number of kilometres `time` - A str...
algorithms
def running_pace(distance, time): m, s = map(int, time . split(':')) second = m * 60 + s pace = second / distance return f' { int ( pace / / 60 )} : { int ( pace % 60 ):0 2 } '
What's your running pace?
578b8c0e84ac69a4d20004c8
[ "Mathematics", "Strings", "Algorithms", "Date Time" ]
https://www.codewars.com/kata/578b8c0e84ac69a4d20004c8
6 kyu
# Task Let's call a string cool if it is formed only by Latin letters and no two lowercase and no two uppercase letters are in adjacent positions. Given a string, check if it is cool. # Input/Output `[input]` string `s` A string that contains uppercase letters, lowercase letters numbers and spaces. `1 ≤ s.length ≤...
reference
def cool_string(s): return s . isalpha() and all(x . islower() != y . islower() for x, y in zip(s, s[1:]))
Simple Fun #253: Cool String
590fd3220f05b4f1ad00007c
[ "Fundamentals" ]
https://www.codewars.com/kata/590fd3220f05b4f1ad00007c
7 kyu
You will be given an array which lists the current inventory of stock in your store and another array which lists the new inventory being delivered to your store today. Your task is to write a function that returns the updated list of your current inventory **in alphabetical order**. ## Example ```javascript current...
algorithms
from collections import defaultdict def update_inventory(cur_stock, new_stock): answer = defaultdict(int) for stock, item in cur_stock + new_stock: answer[item] += stock return [(answer[item], item) for item in sorted(answer)]
Update inventory in your smartphone store
57a31ce7cf1fa5a1e1000227
[ "Algorithms", "Data Structures", "Arrays" ]
https://www.codewars.com/kata/57a31ce7cf1fa5a1e1000227
6 kyu
We all love the future president (or Führer or duce or sōtō as he could find them more fitting) donald trump, but we might fear that some of his many fans like <a href="https://www.washingtonpost.com/politics/donald-trump-alter-ego-barron/2016/05/12/02ac99ec-16fe-11e6-aa55-670cabef46e0_story.html" target="_blank" title...
algorithms
import re def trump_detector(ts): x = re . findall(r'([aeiou])(\1*)', ts, re . I) y = [len(i[1]) for i in x] return round(sum(y) / len(y), 2)
Trumpness detector
57829376a1b8d576640000d6
[ "Regular Expressions", "Strings", "Algorithms" ]
https://www.codewars.com/kata/57829376a1b8d576640000d6
6 kyu
Write a function that takes a single array as an argument (containing multiple strings and/or positive numbers and/or arrays), and returns one of four possible string values, depending on the ordering of the lengths of the elements in the input array: Your function should return... - “Increasing” - if the lengths of ...
reference
def order_type(arr): if not arr: return 'Constant' arr = list( map(len, [str(elt) if type(elt) == int else elt for elt in arr])) cmp = sorted(arr) if arr == [arr[0]] * len(arr): s = 'Constant' elif arr == cmp: s = 'Increasing' elif arr == cmp[:: - 1]: s = ...
Identify the array's ordering
57f669477c9a2b1b9700022d
[ "Arrays", "Strings", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/57f669477c9a2b1b9700022d
6 kyu
You've just finished writing the last chapter for your novel when a virus suddenly infects your document. It has swapped the 'i's and 'e's in 'ei' words and capitalised random letters. Write a function which will: a) remove the spelling errors in 'ei' words. (Example of 'ei' words: their, caffeine, deceive, weight) ...
reference
def proofread(s): return '. ' . join(i . lower(). replace('ie', 'ei'). capitalize() for i in s . split('. '))
Proof Read
583710f6b468c07ba1000017
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/583710f6b468c07ba1000017
6 kyu
The principal of a school likes to put challenges to the students related with finding words of certain features. One day she said: "Dear students, the challenge for today is to find a word that has only one vowel and seven consonants but cannot have the letters "y" and "m". I'll give a special award for the first stud...
reference
def wanted_words(vowels, consonants, forbidden): return [w for w in WORD_LIST if len(w) == vowels + consonants and sum(map(w . count, 'aeiou')) == vowels and not any(c in w for c in forbidden)]
Word Challenges at School
580be55ca671827cfd000043
[ "Fundamentals", "Logic", "Strings", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/580be55ca671827cfd000043
6 kyu
A bar of a certain metal of length ```l``` is subjected to the application of different perpendicular forces (that may have up or down direction). The bar has a foothold at its midpoint ``` S``` . Each point of application of the force is at a distance that has an integer value, respect to the point ``` S```. <a href...
reference
def rot_pred(arr): pivot = len(arr) / / 2 if not len(arr) % 2 or arr[pivot] != 'S': return 'Not a Valid Entry' moment = sum(i * x for i, x in enumerate(arr, - pivot) if i) return 'steady' if not moment else 'anti ' * (moment < 0) + 'clockwise'
Resultant Moment I
57a125e772292dadcb0005f5
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/57a125e772292dadcb0005f5
6 kyu
The aim of this Kata is to write a function which will reverse the case of all consecutive duplicate letters in a string. That is, any letters that occur one after the other and are identical. If the duplicate letters are lowercase then they must be set to uppercase, and if they are uppercase then they need to be cha...
reference
import re def reverse(s): return re . sub(r'(.)\1+', lambda m: m . group(). swapcase(), s)
Case Reversal of Consecutive Duplicates
577c2d68311a24132a0002a5
[ "Fundamentals" ]
https://www.codewars.com/kata/577c2d68311a24132a0002a5
6 kyu
# Description: Convert the continuous exclamation marks or question marks to a digit, Use all the digits to form a number. If this number is a prime number, return it. If not, divide this number by the smallest factor that it is greater than 1, until it becomes a prime number. You can assume that all test results ...
reference
from gmpy2 import is_prime, next_prime from itertools import groupby def convert(s): x = int('' . join(str(sum(1 for _ in l)) for _, l in groupby(s))) p = 2 while not is_prime(x): while x > p and x % p == 0: x / /= p p = next_prime(p) return x
Exclamation marks series #14: Convert the exclamation marks and question marks to a prime number
57fb1705f815ebd49e00024c
[ "Fundamentals" ]
https://www.codewars.com/kata/57fb1705f815ebd49e00024c
6 kyu
Time to win the lottery! Given a lottery ticket (ticket), represented by an array of 2-value arrays, you must find out if you've won the jackpot. Example ticket: ```javascript [ [ 'ABC', 65 ], [ 'HGR', 74 ], [ 'BYHT', 74 ] ] ``` ```cpp { { "ABC", 65 }, { "HGR", 74 }, { "BYHT", 74 } } ``` ```c { { "ABC", 65 }, { "HG...
reference
def bingo(ticket, win): return 'Winner!' if sum(chr(n) in s for s, n in ticket) >= win else 'Loser!'
Lottery Ticket
57f625992f4d53c24200070e
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57f625992f4d53c24200070e
6 kyu
Consider having a cow that gives a child every year from her fourth year of life on and all her subsequent children do the same. After n years how many cows will you have? | After n years | Cow count | | - | - | | 0 | 1 | | 1 | 1 | | 3 | 2 | | 4 | 3 | | 10 | 28 | Return null if n is not an integer. Note: Assume all...
games
def count_cows(n): if not isinstance(n, int): return None return 1 if n < 3 else count_cows(n - 1) + count_cows(n - 3)
How many cows do you have?
58311536e77f7d08de000085
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/58311536e77f7d08de000085
6 kyu
This Kata is like the game of <span style="font-weight:bold;color:red">Snakes & Ladders</span> There is an array representing the squares on the game board. The `starting` square is at array element 0. The `final` square is the last array element. At each "turn" you move forward a number of places (according to the ...
reference
def snakes_and_ladders(board, dice): pos = 0 for d in dice: if pos + d < len(board): pos += d + board[pos + d] return pos
Snakes & Ladders
5821cd4770ca285b1f0001d5
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5821cd4770ca285b1f0001d5
6 kyu
Laura really hates people using acronyms in her office and wants to force her colleagues to remove all acronyms before emailing her. She wants you to build a system that will edit out all known acronyms or else will notify the sender if unknown acronyms are present. Any combination of <b>three or more letters in upper...
algorithms
import re from functools import reduce _ACRONYMS = { 'KPI': 'key performance indicators', 'EOD': 'the end of the day', 'EOP': 'the end of the day', # snafu in the tests? 'TBD': 'to be decided', 'WAH': 'work at home', 'IAM': 'in a meeting', 'OOO': 'out of office', 'NRN': 'no re...
Acronym Buster
58397ee871df657929000209
[ "Regular Expressions", "Parsing", "Strings", "Algorithms" ]
https://www.codewars.com/kata/58397ee871df657929000209
6 kyu
1) Given some text, count each alphabetic character's occurrence in it, regardless of the case. 2) Let's suppose you have to use an old terminal window to represent the occurrencies of each character in a text-based horizontal bar graph. The terminal has a maximum width, provided as parameter (`max_units_on_screen`...
reference
from collections import Counter import re def count_and_print_graph(text, max_units_on_screen): counts = Counter(re . sub("[^a-z]", "", text . lower())) adjust = counts . most_common(1)[0][1] / max_units_on_screen return "\n" . join([x[0] + ":" + "#" * int(x[1] / adjust) for x in sorted(counts . items(), ...
Character Counter and Bars Graph
5826773bfad36332bf0002f9
[ "ASCII Art", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5826773bfad36332bf0002f9
6 kyu
## The Story Green Lantern's long hours of study and practice with his ring have really paid off -- his skills, focus, and control have improved so much that now he can even use his ring to update and redesign his web site. Earlier today he was focusing his will and a beam from his ring upon the Justice League web serv...
reference
def yellow_be_gone(s): d = {'gold': 'ForestGreen', 'khaki': 'LimeGreen', 'lemonchiffon': 'PaleGreen', 'lightgoldenrodyellow': 'SpringGreen', 'lightyellow': 'MintCream', 'palegoldenrod': 'LightGreen', 'yellow': 'Lime'} if s[0] == '#': R, G, B = s[1: 3], s[3: 5], s[5:] if B < G and B < R: ...
Help Green Lantern with his web site
57e6bcbd684e570c6700021c
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57e6bcbd684e570c6700021c
6 kyu
Build a function `sumNestedNumbers`/`sum_nested_numbers` that finds the sum of all numbers in a series of nested arrays raised to the power of their respective nesting levels. Numbers in the outer most array should be raised to the power of 1. For example, ```javascript sumNestedNumbers([1, [2], 3, [4, [5]]]) ``` ``...
reference
def sum_nested_numbers(a, depth=1): return sum(sum_nested_numbers(e, depth + 1) if type(e) == list else e * * depth for e in a)
Sum of nested numbers
5845e6a7ae92e294f4000315
[ "Fundamentals" ]
https://www.codewars.com/kata/5845e6a7ae92e294f4000315
6 kyu
Have you finished [this one](https://www.codewars.com/kata/590938089ff3d186cb00004c)? Now there is a complex version: ### Task Given the prefix sums of some array `A`, return suffix sums for the same array. Array of prefix sums is defined as: ``` B[0] = A[0] B[1] = A[0] + A[1] B[2] = A[0] + A[1] + A[2] ... B[n - 1] =...
algorithms
def prefix_sums_to_suffix_sums(prefix_sums): return [prefix_sums[- 1] - (i and prefix_sums[i - 1]) for i, s in enumerate(prefix_sums)]
Simple Fun #250: Prefix Sums To Suffix Sums
590c4c342ad5cd6a8700005c
[ "Algorithms" ]
https://www.codewars.com/kata/590c4c342ad5cd6a8700005c
6 kyu
# Task A person is moving along a straight line. Initially he is at point `A`. He goes to point `B` from `A` with speed equal to `1 meter per second`. Immediately after reaching `B` he turns around and heads to `A` from `B` with the same speed. After reaching point `A` he turns around once again and heads to `B`. etc. ...
reference
def to_and_from(a, b, t): times, rem = divmod(t, b - a) if not times % 2: return a + rem return b - rem
Simple Fun #247: To And From
590c3173cd3b99c467000a26
[ "Fundamentals" ]
https://www.codewars.com/kata/590c3173cd3b99c467000a26
6 kyu
# Task Your friend has invited you to watch a tennis match at a local sports club. Since tennis isn't your favorite sport, you get bored right at the start of the first game and start looking for something to keep yourself entertained. Noticing the scoreboard, you realize you don't even know how many points have been w...
reference
def tennis_game_points(score): arr = ["love", "15", "30", "40"] [a, b] = score . split("-") return arr . index(a) + (arr . index(a) if b == "all" else arr . index(b))
Simple Fun #238: Tennis Game Points
590942d4efde93886900185a
[ "Fundamentals" ]
https://www.codewars.com/kata/590942d4efde93886900185a
7 kyu
Given an input of an array of digits, return the array with each digit incremented by its position in the array: the first digit will be incremented by 1, the second digit by 2, etc. Make sure to **start counting your positions from 1** ( and not 0 ). Your result can only contain single digit numbers, so if adding a d...
reference
def incrementer(nums): return [(v + i) % 10 for i, v in enumerate(nums, 1)]
Incrementer
590e03aef55cab099a0002e8
[ "Fundamentals" ]
https://www.codewars.com/kata/590e03aef55cab099a0002e8
7 kyu
#Permutation position In this kata you will have to permutate through a string of lowercase letters, each permutation will start at ```a``` and you must calculate how many iterations it takes to reach the current permutation. ##examples ``` input: 'a' result: 1 input: 'c' result: 3 input: 'z' result: 26 input: 'fo...
reference
trans_table = str . maketrans('abcdefghijklmnopqrstuvwxyz', '0123456789abcdefghijklmnop') def permutation_position(perm): return int(perm . translate(trans_table), 26) + 1
Permutation position
57630df805fea67b290009a3
[ "Fundamentals" ]
https://www.codewars.com/kata/57630df805fea67b290009a3
6 kyu
Create a function that calculates all possible diagonals of a given (square) matrix. Diagonals must be laid out from top to bottom > Matrix = array of `n` length whose elements are `n` length arrays of integers. 2x2 example: ```javascript diagonals( [ [ 1, 2 ], [ 3, 4 ] ] ); returns -> [ [ 1 ], [ 2, 3 ], [ 4 ...
algorithms
def diagonals(matrix): def skewed(left, right): tilted = [[None] * l + row + [None] * r for l, row, r in zip(left, matrix, right)] return [[x for x in row if x is not None] for row in zip(* tilted)] left, right = range(len(matrix)), range(len(matrix) - 1, - 1, - 1) return matri...
Diagonals
5592dd43a9cd0e43a800019e
[ "Matrix", "Algorithms" ]
https://www.codewars.com/kata/5592dd43a9cd0e43a800019e
5 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" /> # A History Lesson <b>Soundex</b> is an interesting phonetic algorithm developed nearly 100 years ago for indexing names as they are pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be ...
algorithms
import re REPLACMENTS = ["BFPV", "CGJKQSXZ", "DT", "L", "MN", "R"] ER1, ER2 = "HW", "AEIOUY" TABLE_ERASE1 = str . maketrans("", "", ER1) TABLE_NUMS = str . maketrans('' . join(REPLACMENTS), '' . join( str(n) * len(elt) for n, elt in enumerate(REPLACMENTS, 1))) TABLE_ERASE2 = str . maketrans("", "", ER2) ...
Soundex
587319230e9cf305bb000098
[ "Algorithms" ]
https://www.codewars.com/kata/587319230e9cf305bb000098
5 kyu
# Introduction <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">Slot machine (American English), informally fruit machine (British English), puggy (Scottish English slang), the slots (Canadian and American English), poker machine (or p...
reference
def fruit(reels, spins): fruits = {"Wild": 10, "Star": 9, "Bell": 8, "Shell": 7, "Seven": 6, "Cherry": 5, "Bar": 4, "King": 3, "Queen": 2, "Jack": 1} spin = sorted(reels[i][spins[i]] for i in range(3)) matches = len(set(spin)) if matches == 1: return fruits[spin[0]] * 10 i...
Fruit Machine
590adadea658017d90000039
[ "Arrays", "Games", "Fundamentals" ]
https://www.codewars.com/kata/590adadea658017d90000039
6 kyu
# Task Consider an array of integers `a`. Let `min(a)` be its minimal element, and let `avg(a)` be its mean. Define the center of the array `a` as array `b` such that: ``` - b is formed from a by erasing some of its elements. - For each i, |b[i] - avg(a)| < min(a). - b has the maximum number of elements among all the...
algorithms
def array_center(lst): return [i for i in lst if abs(i - sum(lst) * 1.0 / len(lst)) < min(lst)]
Simple Fun #246: Array Center
590bdaa251ab8267b800005b
[ "Algorithms" ]
https://www.codewars.com/kata/590bdaa251ab8267b800005b
7 kyu
A family of <a href="https://en.wikipedia.org/wiki/Laughing_kookaburra">kookaburras</a> are in my backyard. I can't see them all, but I can hear them! # How many kookaburras are there? <img src="https://i.imgur.com/JyeBAJH.png" style='width:60%'/> ## Hint The trick to counting kookaburras is to listen carefully ...
algorithms
import re def kooka_counter(laughing): return len(re . findall(r'(ha)+|(Ha)+', laughing))
Kooka-Counter
58e8cad9fd89ea0c6c000258
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/58e8cad9fd89ea0c6c000258
7 kyu