description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
In the previous <a title="Kata" href="https://www.codewars.com/kata/575eac1f484486d4600000b2">Kata</a> we discussed the OR case. We will now discuss the AND case, where rather than calculating the probablility for either of two (or more) possible results, we will calculate the probability of receiving <i>all</i> of th...
reference
def ball_probability(balls): colors, (first, second), replaced = balls first_choice = colors . count(first) / len(colors) second_choice = colors . count(second) / len(colors) if replaced else ( colors . count(second) - 1 * (first == second)) / (len(colors) - 1) return round(first_choice * s...
Statistics in Kata 2: AND case - Ball bags
576a527ea25aae70b7000c77
[ "Statistics", "Probability", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/576a527ea25aae70b7000c77
6 kyu
The year is 2070 and intelligent connected machines have replaced humans in most things. There are still a few critical jobs for mankind including machine software developer, for writing and maintaining the AI software, and machine forward deployed engineer for controlling the intelligent machines in the field. Lorima...
algorithms
from numpy import mean, std def sensor_analysis(sensor_data): data = [data[1] for data in sensor_data] return (round(mean(data), 4), round(std(data, ddof=1), 4))
AD2070: Help Lorimar troubleshoot his robots- ultrasonic distance analysis
57102bbfd860a3369300089c
[ "Mathematics", "Statistics", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/57102bbfd860a3369300089c
7 kyu
The purpose of this series is developing understanding of stastical problems in AS and A level maths. Let's get started with a simple concept in statistics: Mutually exclusive events. The probability of an OR event is calculated by the following rule: `P(A || B) = P(A) + P(B) - P(A && B)` The probability of event A ...
games
def mutually_exclusive(dice, call1, call2): dice = dict(dice) if abs(sum(dice . values()) - 1) < 1e-12: return '%0.2f' % (dice[call1] + dice[call2])
Statistics in Kata 1: OR case - Unfair dice
575eac1f484486d4600000b2
[ "Probability", "Statistics" ]
https://www.codewars.com/kata/575eac1f484486d4600000b2
6 kyu
We have a distribution of probability of a discrete variable (it may have only integer values) ``` x P(x) 0 0.125 1 0.375 2 0.375 3 0.125 Total = 1.000 # The sum of the probabilities for all the possible values should be one (=1) ``` The mean, ```μ```, of the values of x is: <a href="h...
reference
def stats_disc_distr(distrib): err = check_errors(distrib) if not err: mean = sum(x[0] * x[1] for x in distrib) var = sum((x[0] - mean) * * 2 * x[1] for x in distrib) std_dev = var * * 0.5 return [mean, var, std_dev] if not err else err def check_errors(distrib): errors = 0 ...
Mean, Variance and Standard Deviation of a Probability Distribution for Discrete Variables.
5708ccb0fe2d01677c000565
[ "Algorithms", "Mathematics", "Statistics", "Probability" ]
https://www.codewars.com/kata/5708ccb0fe2d01677c000565
6 kyu
# Convert Improper Fraction to Mixed Number You will need to convert an [improper fraction](https://www.mathplacementreview.com/arithmetic/fractions.php#improper-fractions) to a [mixed number](https://www.mathplacementreview.com/arithmetic/fractions.php#mixed-number). For example: ```javascript getMixedNum('18/11'); ...
reference
def get_mixed_num(fraction): n, d = [int(i) for i in fraction . split('/')] return '{} {}/{}' . format(n / / d, n % d, d)
Convert Improper Fraction to Mixed Number
584acbee7d22f84dc80000e2
[ "Fundamentals", "Strings", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/584acbee7d22f84dc80000e2
7 kyu
Having two standards for a keypad layout is inconvenient! Computer keypad's layout: <img src="http://upload.wikimedia.org/wikipedia/commons/9/99/Numpad.svg" style="width:250px;height:250px" alt="7 8 9 \n 4 5 6 \n 1 2 3 \n 0 \n" /> Cell phone keypad's layout: <img src="http://upload.wikimedia.org/wikipedia...
games
def computer_to_phone(numbers): return numbers . translate(str . maketrans('123789', '789123'))
Keypad horror
5572392fee5b0180480001ae
[ "Strings" ]
https://www.codewars.com/kata/5572392fee5b0180480001ae
7 kyu
Your colleagues have been good enough(?) to buy you a birthday gift. Even though it is your birthday and not theirs, they have decided to play pass the parcel with it so that everyone has an even chance of winning. There are multiple presents, and you will receive one, but not all are nice... One even explodes and cove...
reference
_RESULTS = { 'goodpresent': lambda y: '' . join(chr(ord(c) + y) for c in 'goodpresent'), 'crap': lambda y: 'acpr', 'empty': lambda y: 'empty', 'bang': lambda y: str(sum(ord(c) - y for c in 'bang')), 'badpresent': lambda y: 'Take this back!', 'dog': lambda y: 'pass out from excitement {} ti...
Birthday II - Presents
5805f0663f1f9c49be00011f
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5805f0663f1f9c49be00011f
7 kyu
Mars rover is on an important mission to take pictures of Mars. In order to take pictures of all directions it needs an algorithm to help it turn to face the correct position. Mars rover can face 4 different directions, that would be `N`, `S`, `E`, `W`. Every time it needs to turn it will call a command `turn` passin...
algorithms
def turn(frm, to): return "right" if f" { frm }{ to } " in "NESWN" else "left"
Turn the Mars rover to take pictures
588e68aed4cff457d300002e
[ "Algorithms" ]
https://www.codewars.com/kata/588e68aed4cff457d300002e
7 kyu
Once upon a time, more precisely upon BASIC time, there were 2 functions named LEFT$ and RIGHT$ (I wrote them uppercase because it was the custom in those early years). These functions let you read left(/right)-most characters of a string. * use: `LEFT$ (str, i)` -> returns `i` left-most characters of `str`. ``` -...
reference
def left(string, i=1): i = string . index(i) if type(i) == str else i return string[: i] def right(string, i=1): i = string[:: - 1]. index(i[:: - 1]) if type(i) == str else i return string[- i:] if i != 0 else ""
Left$ and Right$
53f211b159c3fcec3d000efa
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/53f211b159c3fcec3d000efa
7 kyu
You've been collecting change all day, and it's starting to pile up in your pocket, but you're too lazy to see how much you've found. Good thing you can code! Create ```change_count()``` to return a dollar amount of how much change you have! Valid types of change include: ``` penny: 0.01 nickel: 0.05 dime: 0.10 quar...
reference
def change_count(change): return "$%.2f" % sum(CHANGE[coin] for coin in change . split())
Loose Change!
57e1857d333d8e0f76002169
[ "Fundamentals" ]
https://www.codewars.com/kata/57e1857d333d8e0f76002169
7 kyu
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.<br/> <span style='font-size:20px'><b>Task:</b></span><br/> Write ``` smallest(n) ``` that will find the smallest positive number that is evenly divisible by all of the numbers from 1 to n (n <= 40). <br/> E.g<br/>...
algorithms
from functools import reduce from math import gcd def smallest(n): return reduce(lambda a, b: a * b / / gcd(a, b), range(1, n + 1))
Satisfying numbers
55e7d9d63bdc3caa2500007d
[ "Algorithms" ]
https://www.codewars.com/kata/55e7d9d63bdc3caa2500007d
7 kyu
Create a function that takes index [0, 8] and a character. It returns a string with columns. Put character in column marked with index. Ex.: index = 2, character = 'B' ``` | | |B| | | | | | | 0 1 2 3 4 5 6 7 8 ``` Assume that argument index is integer [0, 8]. Assume that argument character is string with one chara...
reference
def build_row_text(index, character): a = list('|||||||||') a[index] = "|" + character + "|" return " " . join(a)
Put a Letter in a Column
563d54a7329a7af8f4000059
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/563d54a7329a7af8f4000059
7 kyu
To celebrate the start of the Rio Olympics (and the return of 'the Last Leg' on C4 tonight) this is an Olympic inspired kata. Given a string of random letters, you need to examine each. Some letters naturally have 'rings' in them. 'O' is an obvious example, but 'b', 'p', 'e', 'A', etc are all just as applicable. 'B' e...
reference
def olympic_ring(string): rings = string . translate(str . maketrans( 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', '1201000000000011110000000011011010000000111000000000')) score = sum(map(int, rings)) / / 2 return ['Not even a medal!', 'Bronze!', 'Silver!', 'Gold!'][(score > ...
Olympic Rings
57d06663eca260fe630001cc
[ "Fundamentals", "Arrays", "Strings" ]
https://www.codewars.com/kata/57d06663eca260fe630001cc
7 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: John learns to play poker with his uncle. His uncle told him: Poker to be in accordance with the order of "2 3 4 5 6 7 8 9 10 J Q K A". The same suit sho...
games
def order(arr): return {card[0]: i for i, card in enumerate(arr)} ranks = order("2 3 4 5 6 7 8 9 10 J Q K A" . split()) suit_table = {ord(suit): ' ' + suit for suit in 'SDHC'} def split_hand(hand): return hand . translate(suit_table). split() def sort_poker(john, uncle): suits = order(split_hand(un...
Sorting Poker
580ed88494291dd28c000019
[ "Puzzles", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/580ed88494291dd28c000019
5 kyu
You've just discovered a square (NxN) field and you notice a warning sign. The sign states that there's a single bomb in the 2D grid-like field in front of you. Write a function `mineLocation`/`MineLocation` that accepts a 2D array, and returns the location of the mine. The mine is represented as the integer `1` in t...
algorithms
def mineLocation(field): for subfield in field: if 1 in subfield: return [field . index(subfield), subfield . index(1)]
Find the Mine!
528d9adf0e03778b9e00067e
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/528d9adf0e03778b9e00067e
6 kyu
# Task Given an array `arr`, find the rank of the element at the ith position. The `rank` of the arr[i] is a value equal to the number of elements `less than or equal to` arr[i] standing before arr[i], plus the number of elements `less than` arr[i] standing after arr[i]. # Example For `arr = [2,1,2,1,2], i = 2`, ...
games
def rank_of_element(arr, i): return sum(x <= arr[i] if n < i else x < arr[i] for n, x in enumerate(arr))
Simple Fun #177: Rank Of Element
58b8cc7e8e7121740700002d
[ "Puzzles" ]
https://www.codewars.com/kata/58b8cc7e8e7121740700002d
7 kyu
# Task Imagine `n` horizontal lines and `m` vertical lines. Some of these lines intersect, creating rectangles. How many rectangles are there? # Examples For `n=2, m=2,` the result should be `1`. there is only one 1x1 rectangle. For `n=2, m=3`, the result should be `3`. there are two 1x1 rectangles a...
games
def rectangles(n, m): return m * n * (m - 1) * (n - 1) / 4
Simple Fun #105: Rectangles
589a8d9b729e7abd9a0000ed
[ "Puzzles" ]
https://www.codewars.com/kata/589a8d9b729e7abd9a0000ed
7 kyu
A Cartesian coordinate system is a coordinate system that specifies each point uniquely in a plane by a pair of numerical coordinates, which are the signed distances to the point from two fixed perpendicular directed lines, measured in the same unit of length. The сoordinates of a point in the grid are written as (x,y...
reference
from itertools import product def cartesian_neighbor(x, y): return [z for z in product(range(x - 1, x + 2), range(y - 1, y + 2)) if z != (x, y)]
Cartesian neighbors
58989a079c70093f3e00008d
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/58989a079c70093f3e00008d
7 kyu
# Task One night you go for a ride on your motorcycle. At 00:00 you start your engine, and the built-in timer automatically begins counting the length of your ride, in minutes. Off you go to explore the neighborhood. When you finally decide to head back, you realize there's a chance the bridges on your route home are...
games
def late_ride(n): return sum([int(x) for x in (str(n % 60) + str(int(n / 60)))])
Simple Fun #3: Late Ride
588422ba4e8efb583d00007d
[ "Puzzles" ]
https://www.codewars.com/kata/588422ba4e8efb583d00007d
7 kyu
# Background While mpg (miles per gallon) is a common unit of measurement for fuel economy in North America, for Europe the standard unit of measurement is generally liter per 100 km. Conversion between these units is somewhat hard to calculate in your head, so your task here is to implement a simple convertor in both ...
algorithms
mpg2lp100km = lp100km2mpg = lambda x: round(235.214583 / x, 2)
Fuel economy converter (mpg <-> L/100 km)
558aa460dcfb4a94c40001d7
[ "Algorithms" ]
https://www.codewars.com/kata/558aa460dcfb4a94c40001d7
7 kyu
Given a time in AM/PM format as a string, convert it to 24-hour [military time](https://en.wikipedia.org/wiki/24-hour_clock#Military_time) time as a string. Midnight is `12:00:00AM` on a 12-hour clock, and `00:00:00` on a 24-hour clock. Noon is `12:00:00PM` on a 12-hour clock, and `12:00:00` on a 24-hour clock Try no...
reference
def get_military_time(time): if time[- 2:] == 'AM': hour = '00' if time[0: 2] == '12' else time[0: 2] else: hour = '12' if time[0: 2] == '12' else str(int(time[0: 2]) + 12) return hour + time[2: - 2]
What time is it?
57729a09914da60e17000329
[ "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/57729a09914da60e17000329
7 kyu
Brief ===== Sometimes we need information about the list/arrays we're dealing with. You'll have to write such a function in this kata. Your function must provide the following informations: * Length of the array * Number of integer items in the array * Number of float items in the array * Number of string character ...
reference
def array_info(x): if not x: return 'Nothing in the array!' return [ [len(x)], [sum(isinstance(i, int) for i in x) or None], [sum(isinstance(i, float) for i in x) or None], [sum(isinstance(i, str) and not i . isspace() for i in x) or None], [sum(isinstance(i, ...
Array Info
57f12b4d5f2f22651c00256d
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/57f12b4d5f2f22651c00256d
7 kyu
# Task You're given a substring s of some cyclic string. What's the length of the smallest possible string that can be concatenated to itself many times to obtain this cyclic string? # Example For` s = "cabca"`, the output should be `3` `"cabca"` is a substring of a cycle string "ab<b><font color='red'>cabca</fon...
games
def cyclic_string(s): return next((i for i, _ in enumerate(s[1:], 1) if s . startswith(s[i:])), len(s))
Simple Fun #55: Cyclic String
58899594b832f80348000122
[ "Puzzles" ]
https://www.codewars.com/kata/58899594b832f80348000122
7 kyu
#### Input - a string `strng` of n positive numbers (n = 0 or n >= 2) Let us call weight of a number the sum of its digits. For example `99` will have "weight" `18`, `100` will have "weight" `1`. Two numbers are "close" if the difference of their weights is small. #### Task: For each number in `strng` calculate it...
reference
def closest(s): wght = sorted([[sum(int(c) for c in n), i, int(n)] for i, n in enumerate(s . split())], key=lambda k: (k[0], k[1])) diff = [abs(a[0] - b[0]) for a, b in zip(wght, wght[1:])] return [wght[diff . index(min(diff))], wght[diff . index(min(diff)) + 1]] if wght else []
Closest and Smallest
5868b2de442e3fb2bb000119
[ "Fundamentals", "Sorting" ]
https://www.codewars.com/kata/5868b2de442e3fb2bb000119
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;"> Drink driving is an issue all around the world!  On average 3,000 people are killed or seriously injured each year in drink drive collisions, nearly one in six of all de...
reference
def drive(drinks, finished, drive_time): f, d = (list(map(int, x . split(':'))) for x in [finished, drive_time]) delta = d[0] - f[0] + (d[1] - f[1]) / 60 + (24 * (f >= d)) units = sum(strength * volume for strength, volume in drinks) / 1000 return [round(units, 2), delta > units]
Am I safe to drive?
58ce88427e6c3f41c2000087
[ "Fundamentals" ]
https://www.codewars.com/kata/58ce88427e6c3f41c2000087
6 kyu
This should be fairly simple. It is more of a puzzle than a programming problem. There will be a string input in this format: ```'a+b'``` 2 lower case letters (a-z) seperated by a '+' Return the sum of the two variables. There is one correct answer for a pair of variables. I know the answers, it is your task to fin...
games
def the_var(vars): return sum(ord(c) - 96 for c in vars . split("+"))
The unknown but known variables: Addition
5716955a794d3013d00013f9
[ "Puzzles" ]
https://www.codewars.com/kata/5716955a794d3013d00013f9
7 kyu
# Task Four men, `a`, `b`, `c` and `d` are standing in a line, one behind another. There's a wall between the first three people (`a`, `b` and `c`) and the last one (`d`). The men `a`, `b` and `c` are lined up in order of height, so that: * person `a` can see the backs of `b` and `c` * person `b` can see the bac...
games
def guess_hat_color(a, b, c, d): return 1 if b == c else 2
Simple Fun #195: Guess Hat Color
58c21c4ff130b7cab400009e
[ "Puzzles" ]
https://www.codewars.com/kata/58c21c4ff130b7cab400009e
7 kyu
## Euler's Method We want to calculate the shape of an unknown curve which starts at a given point with a given slope. This curve satisfies an ordinary differential equation (ODE): ```math \frac{dy}{dx} = f(x, y);\\ y(x_0) = y_0 ``` The starting point `$ A_0 (x_0, y_0) $` is known as well as the slope to the curve ...
algorithms
from math import floor, exp def ex_euler(n): # fct to study def F(t, y): return 2 - exp(- 4 * t) - 2 * y # initial conditions t0 = 0 y0 = 1 # pt A0 T = 1 # variables h = T / float(n) X = [t0] Y = [y0] Z = [] R = [] # points A1 ... An for k in range(0, n): X...
Euler's method for a first-order ODE
56347fcfd086de8f11000014
[ "Algorithms" ]
https://www.codewars.com/kata/56347fcfd086de8f11000014
5 kyu
Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome. Examples: ```ruby ["bat", "tab", "cat"] # [[0, 1], [1, 0]] ["dog", "cow", "tap", "god", "pat"] # [[0, 3], [2, 4], [3, 0], [4, 2]] ["abcd", "dcb...
reference
def palindrome_pairs(words): indices = [] for i in range(len(words)): for j in range(len(words)): if i != j: concatenation = str(words[i]) + str(words[j]) if concatenation == concatenation[:: - 1]: indices . append([i, j]) return indices
Palindrome Pairs
5772ded6914da62b4b0000f8
[ "Lists", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5772ded6914da62b4b0000f8
7 kyu
Complete the code which should return `true` if the given object is a single ASCII letter (lower or upper case), `false` otherwise.
reference
def is_letter(s): return len(s) == 1 and s . isalpha()
Regexp Basics - is it a letter?
567de72e8b3621b3c300000b
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/567de72e8b3621b3c300000b
7 kyu
A [happy number](https://en.wikipedia.org/wiki/Happy_number) is one where if you repeatedly square its digits and add them together, you eventually end up at 1. For example: ```7 -> 49 -> 97 -> 130 -> 10 -> 1``` so ```7``` is a happy number. ```42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42``` so ```42``` is **...
algorithms
def isHappy(n, pow): nums = [] while True: nums . append(n) n = sum([d * * pow for d in map(int, str(n))]) if n == 1: return [1] if n in nums: return nums[nums . index(n):] + [n]
Happy numbers to the n power
578597a122542a7d24000018
[ "Algorithms" ]
https://www.codewars.com/kata/578597a122542a7d24000018
6 kyu
Write a function that checks if all the letters in the second string are present in the first one at least once, regardless of how many times they appear: ``` ["ab", "aaa"] => true ["trances", "nectar"] => true ["compadres", "DRAPES"] => true ["parses", "parsecs"] => false ``` Function should not be cas...
algorithms
def letter_check(arr): return set(arr[1]. lower()) <= set(arr[0]. lower())
noobCode 03: CHECK THESE LETTERS... see if letters in "String 2" are present in "String 1"
57470efebf81fea166001627
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/57470efebf81fea166001627
7 kyu
Extend the Math object (JS) or module (Ruby and Python) to convert degrees to radians and viceversa. The result should be rounded to two decimal points. Note that all methods of Math object are static. Example: ```javascript Math.degrees(Math.PI) //180deg Math.radians(180) //3.14rad ``` ```python math.degrees(math.pi)...
reference
def degrees(rad): return '%gdeg' % round(180 * rad / math . pi, 2) def radians(deg): return '%grad' % round(math . pi * deg / 180, 2) math . degrees = degrees math . radians = radians
Convert between radians and degrees
544e2c60908f2da03600022a
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/544e2c60908f2da03600022a
7 kyu
Egg Talk. Insert an "egg" after each consonant. If there are no consonants, there will be no eggs. Argument will consist of a string with only alphabetic characters and possibly some spaces. eg: hello => heggeleggleggo eggs => egegggeggsegg FUN KATA => FeggUNegg KeggATeggA //// This Kata is designed for begin...
reference
import re def heggeleggleggo(word): return re . sub(r'(?i)([^aeiou\W])', r'\1egg', word)
heggeleggleggo
55ea5304685da2fb40000018
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/55ea5304685da2fb40000018
7 kyu
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/56f928b19982cc7a14000c9d) ## Task: Every uppercase letter is Father, The corresponding lowercase letters is the Son. Give you a string ```s```, If the father and s...
games
def sc(strng): seen = set(strng) return '' . join(a for a in strng if a . swapcase() in seen)
Coding 3min: Father and Son
56fe9a0c11086cd842000008
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56fe9a0c11086cd842000008
7 kyu
Make me slow! Calling makeMeSlow() should take at least 7 seconds.
reference
def make_me_slow(): import time time . sleep(7)
Make Me Slow
57f59da8d3978bb31f000152
[ "Fundamentals" ]
https://www.codewars.com/kata/57f59da8d3978bb31f000152
7 kyu
Given - a semi-inclusive interval `I = [l, u)` (l is in interval I but u is not) `l` and `u` being floating numbers `(0 <= l < u)`, - an integer `n (n > 0)` - a function `f: x (float number) -> f(x) (float number)` we want to return as a list the `n` values: `f(l), f(l + 1 * d), ..., f(u -d)` where `d = (u - l) ...
reference
from math import floor def interp(f, l, u, n): d = (u - l) / n return [floor(f(l + d * i) * 100.) / 100. for i in range(n)]
Floating-point Approximation (II)
581ee0db1bbdd04e010002fd
[ "Fundamentals" ]
https://www.codewars.com/kata/581ee0db1bbdd04e010002fd
6 kyu
Removed due to copyright infringement. <!--- Vasya is a lazy student. He has certain amount of clean bowls and plates (lets call it `b` and `p`). Vasya has made an eating plan for the next several days. ----- ### Vasya's eating Plan As Vasya is lazy, he will eat exactly *1* dish per day. In order to eat a dish, ...
games
def count_clean(b, p, dishes): dirty = max(len(dishes) - b - p, dishes . count(1) - b) return 0 if dirty < 0 else dirty
Vasya and Plates
55807d36933247feff00002f
[ "Puzzles", "Algorithms", "Logic", "Mathematics", "Numbers", "Fundamentals" ]
https://www.codewars.com/kata/55807d36933247feff00002f
7 kyu
``isMatching`` checks if a string can be created by combining and rearranging the letters of two other strings (**not case sensitive**). !**Spaces** will be ignored but **special characters** and **numbers** won't match the string and return false. For example: ``isMatching("email box", "b aIl", "Mo x e") return...
algorithms
def clean(s): return sorted(s . replace(' ', ''). lower()) def is_matching(st, st1, st2): return clean(st) == clean(st1 + st2)
String Matcher
565ce4ab24ef4aee6a000074
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/565ce4ab24ef4aee6a000074
7 kyu
You're looking through different hex codes, and having trouble telling the difference between <a href='http://www.colorhexa.com/000001'> #000001 </a> and <a href='http://www.colorhexa.com/100000'> #100000 </a> We need a way to tell which is red, and which is blue! That's where you create __hex color__ !!! It shoul...
reference
colors = { (1, 0, 0): 'red', (0, 1, 0): 'green', (0, 0, 1): 'blue', (1, 0, 1): 'magenta', (1, 1, 0): 'yellow', (0, 1, 1): 'cyan', (1, 1, 1): 'white', } def hex_color(codes): codes = codes or '0 0 0' items = [int(c) for c in codes . split()] m = max(items) ret...
Colored Hexes!
57e17750621bca9e6f00006f
[ "Fundamentals" ]
https://www.codewars.com/kata/57e17750621bca9e6f00006f
7 kyu
Multiplication can be thought of as repeated addition. Exponentiation can be thought of as repeated multiplication. [Tetration](https://en.wikipedia.org/wiki/Tetration) is repeated exponentiation. Just as the 4th power of 3 is `3*3*3*3`, the 4th tetration of 3 is `3^3^3^3`. By convention, we insert parentheses from rig...
reference
from functools import reduce from itertools import repeat def tetration(x, y): return reduce(int . __rpow__, repeat(x, y), 1)
Tetration
5797bbb34be9127074000132
[ "Fundamentals" ]
https://www.codewars.com/kata/5797bbb34be9127074000132
7 kyu
## Description John's each hand has five fingers(If you are surprised, please tell me how many fingers you have ;-) Even more amazing is that when he was a child, he already had 5 fingers(one hand). At that time, he often to count the number by using his fingers. He is counting this way: ``` a - Thumb b - Index finge...
games
a = ("Index finger", "Thumb", "Index finger", "Middle finger", "Ring finger", "Little finger", "Ring finger", "Middle finger") def which_finger(n): return a[n % 8]
T.T.T.32: Count with your fingers
57add740e298a7a6d500000d
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57add740e298a7a6d500000d
7 kyu
You have an amount of money `a0 > 0` and you deposit it with an interest rate of `p percent divided by 360` *per day* on the `1st of January 2016`. You want to have an amount `a >= a0`. #### Task: The function `date_nb_days` (or dateNbDays...) with parameters `a0, a, p` will return, as a string, the date on which you ...
reference
from math import log, ceil from datetime import date, timedelta as td def date_nb_days(a0, a, p): n = log(a, 1 + p / 36000.0) - log(a0, 1 + p / 36000.0) return str(date(2016, 1, 1) + td(ceil(n)))
Target Date
569218bc919ccba77000000b
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/569218bc919ccba77000000b
7 kyu
## Task Given a square `matrix`, your task is to reverse the order of elements on both of its longest diagonals. The longest diagonals of a square matrix are defined as follows: * the first longest diagonal goes from the top left corner to the bottom right one; * the second longest diagonal goes from the top right co...
games
def reverse_on_diagonals(matrix): copy = [line[:] for line in matrix] for i in range(len(matrix)): copy[i][i] = matrix[- 1 - i][- 1 - i] copy[i][- 1 - i] = matrix[- 1 - i][i] return copy
Simple Fun #59: Reverse On Diagonals
5889a6b653ad4a22710000d0
[ "Puzzles" ]
https://www.codewars.com/kata/5889a6b653ad4a22710000d0
7 kyu
# Task You are implementing a command-line version of the Paint app. Since the command line doesn't support colors, you are using different characters to represent pixels. Your current goal is to support rectangle x1 y1 x2 y2 operation, which draws a rectangle that has an upper left corner at (x1, y1) and a lower righ...
games
def draw_rectangle(canvas, rectangle): x0, y0, x1, y1 = rectangle for x in range(x0, x1): canvas[y0][x] = canvas[y1][x] = '-' for y in range(y0, y1): canvas[y][x0] = canvas[y][x1] = '|' canvas[y0][x0] = canvas[y0][x1] = \ canvas[y1][x0] = canvas[y1][x1] = '*' return canvas
Simple Fun #62: Draw Rectangle
5889ae4f7af7f99a9a000019
[ "Puzzles" ]
https://www.codewars.com/kata/5889ae4f7af7f99a9a000019
7 kyu
<img src=https://cdn.meme.am/instances/21245401.jpg> Chuck Norris is the world's toughest man - he once kicked a horse in the chin. Its descendants today are known as giraffes. Like his punches, Chuck NEVER needs more than one line of code. Your task, to please Chuck, is to create a function that chains 4 methods o...
algorithms
import re def one_punch(s): return re . sub("[eaEA]", "", " " . join( sorted(s . split()))) if isinstance(s, str) and s else "Broken!"
Chuck Norris II - One Punch
57057a035eef1f7e790009ef
[ "Fundamentals", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/57057a035eef1f7e790009ef
7 kyu
I'm creating a scoreboard on my game website, but I want the score to be displayed as tally marks instead of Roman numerals. Write a function that translates the numeric score into tally marks. My tally mark font uses the letters a, b, c, d, e to represent tally marks for 1, 2, 3, 4, 5, respectively. I want a space an...
algorithms
def score_to_tally(s): return 'e <br>' * (s / / 5) + 'abcd' [s % 5 - 1: s % 5]
Tally it up
5630d1747935943168000013
[ "Algorithms" ]
https://www.codewars.com/kata/5630d1747935943168000013
7 kyu
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/570dff30e6e9284ba3000a8f) ## Task: Give you a positive integer ```n```, find out the special factor. What is the special factor? An example: if n has a factor x, we ...
games
def sc(n): s = f" { n : b } " return sorted(y for x in range(1, int(n * * .5) + 1) for y in (x, n / / x) if n % x == 0 and f" { y : b } " in s)
Coding 3min : Special factor
570e5d0b93214b1a950015b1
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/570e5d0b93214b1a950015b1
7 kyu
The hamming distance of two equal-length strings is the number of positions, in which the two string differ. In other words, the number of character substitutions required to transform one string into the other. For this first Kata, you will write a function ```hamming_distance(a, b)``` with two equal-length strings ...
reference
def hamming_distance(a, b): return sum(c != d for c, d in zip(a, b))
Hamming Distance - Part 1: Binary codes
5624e574ec6034c3a20000e6
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5624e574ec6034c3a20000e6
7 kyu
The [Hamming Distance](http://en.wikipedia.org/wiki/Hamming_distance) is a measure of similarity between two strings of equal length. Complete the function so that it returns the number of positions where the input strings do not match. ### Examples: ``` a = "I like turtles" b = "I like turkeys" Result: 3 a = "Hell...
algorithms
def hamming(a, b): return sum(ch1 != ch2 for ch1, ch2 in zip(a, b))
Hamming Distance
5410c0e6a0e736cf5b000e69
[ "Algorithms" ]
https://www.codewars.com/kata/5410c0e6a0e736cf5b000e69
6 kyu
# Task The `hamming distance` between a pair of numbers is the number of binary bits that differ in their binary notation. # Example For `a = 25, b = 87`, the result should be `4` ``` 25: 00011001 87: 01010111 ``` The `hamming distance` between these two would be `4` ( the `2nd, 5th, 6th, 7th` bit ). # Input/Outp...
games
def hamming_distance(a, b): return bin(a ^ b). count('1')
Simple Fun #141: Hamming Distance
58a6af7e8c08b1e9c40001c1
[ "Puzzles" ]
https://www.codewars.com/kata/58a6af7e8c08b1e9c40001c1
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: Give you an array `arr` that contains some numbers(arr.length>=2), and give you a positive integer `k`. Find such two numbers m,n: m and n at least a dif...
reference
def furthest_distance(arr, k): # Sort the array and keep track of original indexes srt, idx = zip(* sorted((n, i) for i, n in enumerate(arr))) # For each index l, find the minimum index r such as arr[r] - arr[l] >= k # Extrema are computed on the run # As the data are sorted, r does at most 2...
The furthest distance of index
581963edc929ba19e7000148
[ "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/581963edc929ba19e7000148
6 kyu
Given a starting list/array of data, it could make some statistical sense to know how much each value differs from the average. If for example during a week of work you have collected 55,95,62,36,48 contacts for your business, it might be interesting to know the total (296), the average (59.2), but also how much you m...
reference
from numpy import mean def distances_from_average(test_list): avg = mean(test_list) return [round(avg - x, 2) for x in test_list]
Distance from the average
568ff914fc7a40a18500005c
[ "Arrays", "Lists", "Statistics", "Fundamentals", "Data Science" ]
https://www.codewars.com/kata/568ff914fc7a40a18500005c
7 kyu
## Task You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input. ## Example For `arr = [1, 1, 1]`, the output should be `3`. ## Input/Output - `[input]` integ...
games
from functools import reduce def array_change(arr): return reduce(lambda a, u: ( max(a[0] + 1, u), a[1] + max(0, a[0] - u + 1)), arr, (- 10001, 0))[1]
Simple Fun #67: Array Change
5893f43b779ce54da4000124
[ "Puzzles" ]
https://www.codewars.com/kata/5893f43b779ce54da4000124
7 kyu
# Task Given a string `s`, find out if its characters can be rearranged to form a palindrome. # Example For `s = "aabb"`, the output should be `true`. We can rearrange `"aabb"` to make `"abba"`, which is a palindrome. # Input/Output - `[input]` string `s` A string consisting of lowercase English letters....
games
def palindrome_rearranging(s): return sum(s . count(c) % 2 for c in set(s)) < 2
Simple Fun #68: Palindrome Rearranging
5893fa478a8a23ef82000031
[ "Puzzles" ]
https://www.codewars.com/kata/5893fa478a8a23ef82000031
7 kyu
Removed due to copyright infringement. <!--- # Task Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform. The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically and one square horizontally a...
games
def chess_knight(cell): x, y = (ord(c) - ord(origin) for c, origin in zip(cell, 'a1')) return sum(0 <= x + dx < 8 and 0 <= y + dy < 8 for dx, dy in ( (- 2, - 1), (- 2, 1), (- 1, - 2), (- 1, 2), (1, - 2), (1, 2), (2, - 1), (2, 1)))
Chess Fun #3: Chess Knight
589433358420bf25950000b6
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/589433358420bf25950000b6
7 kyu
## Task Court is in session. We got a group of witnesses who have all taken an oath to tell the truth. The prosecutor is pointing at the defendants one by one and asking each witnesses a simple question - "guilty or not?". The witnesses are allowed to respond in one of the following three ways: ``` I am sure he/she is...
games
def is_information_consistent(evidences): return all(max(l) - min(l) <= 1 for l in zip(* evidences))
Simple Fun #86: is Information Consistent?
58956f5ff780edf4a70000a2
[ "Puzzles" ]
https://www.codewars.com/kata/58956f5ff780edf4a70000a2
7 kyu
# Task Given a sequence of 0s and 1s, determine if it is a prefix of Thue-Morse sequence. The infinite Thue-Morse sequence is obtained by first taking a sequence containing a single 0 and then repeatedly concatenating the current sequence with its binary complement. A binary complement of a sequence X is a sequence ...
games
def is_thue_morse(seq): init_seq = [0] while len(init_seq) < len(seq): init_seq += [1 if n == 0 else 0 for n in init_seq] return init_seq[: len(seq)] == seq
Simple Fun #106: Is Thue Morse?
589a9792ea93aae1bf00001c
[ "Puzzles" ]
https://www.codewars.com/kata/589a9792ea93aae1bf00001c
7 kyu
# Task You have set an alarm for some of the week days. Days of the week are encoded in binary representation like this: ``` 0000001 - Sunday 0000010 - Monday 0000100 - Tuesday 0001000 - Wednesday 0010000 - Thursday 0100000 - Friday 1000000 - Saturday``` For example, if your alarm is set only for Sunday and Friday...
games
def next_day_of_week(current_day, available_week_days): x = 2 * * current_day while not x & available_week_days: x = max(1, (x * 2) % 2 * * 7) return x . bit_length()
Simple Fun #149: Next Day Of Week
58aa9662c55ffbdceb000101
[ "Puzzles" ]
https://www.codewars.com/kata/58aa9662c55ffbdceb000101
7 kyu
## Task Consider the following algorithm for constructing 26 strings S(1) .. S(26): ``` S(1) = "a"; For i in [2, 3, ..., 26]: S(i) = S(i - 1) + character(i) + S(i - 1). ``` For example: ``` S(1) = "a" S(2) = S(1) + "b" + S(1) = "a" + "b" + "a" = "aba" S(3) = S(2) + "c" + S(2) = "aba" + "c" +"aba" = "abacaba" ....
games
def abacaba(k): n = 26 if k % 2: return 'a' while k % pow(2, n) != 0: n -= 1 return chr(97 + n)
Simple Fun #114: "abacaba"
589d237fdfdef0239a00002e
[ "Puzzles" ]
https://www.codewars.com/kata/589d237fdfdef0239a00002e
7 kyu
# Task N lamps are placed in a line, some are switched on and some are off. What is the smallest number of lamps that need to be switched so that on and off lamps will alternate with each other? You are given an array `a` of zeros and ones - `1` mean switched-on lamp and `0` means switched-off. Your task is to ...
games
def lamps(a): n = sum(1 for i, x in enumerate(a) if x != i % 2) return min(n, len(a) - n)
Simple Fun #124: Lamps
58a3c1f12f949e21b300005c
[ "Puzzles" ]
https://www.codewars.com/kata/58a3c1f12f949e21b300005c
7 kyu
# Task After a long night (work, play, study) you find yourself sleeping on a bench in a park. As you wake up and try to figure out what happened you start counting trees. You notice there are different tree sizes but there's always one size which is unbalanced. For example there are 2 size 2, 2 size 1 and 1 size 3. ...
algorithms
def find_the_missing_tree(trees): return sorted(trees, key=trees . count)[0]
Simple Fun #147: Find The Missing Tree
58aa8698ae929e1c830001c7
[ "Algorithms" ]
https://www.codewars.com/kata/58aa8698ae929e1c830001c7
7 kyu
# Task Round the given number `n` to the nearest multiple of `m`. If `n` is exactly in the middle of 2 multiples of m, return `n` instead. # Example For `n = 20, m = 3`, the output should be `21`. For `n = 19, m = 3`, the output should be `18`. For `n = 50, m = 100`, the output should be `50`. # Input/Output...
reference
def rounding(n, m): return n if n % m == m / 2 else m * round(n / m)
Simple Fun #181: Rounding
58bccdf56f25ff6b6d00002f
[ "Fundamentals" ]
https://www.codewars.com/kata/58bccdf56f25ff6b6d00002f
7 kyu
# Task Your task is to find the smallest number which is evenly divided by all numbers between `m` and `n` (both inclusive). # Example For `m = 1, n = 2`, the output should be `2`. For `m = 2, n = 3`, the output should be `6`. For `m = 3, n = 2`, the output should be `6` too. For `m = 1, n = 10`, the outpu...
reference
from numpy import lcm from functools import reduce def mn_lcm(* args): a, b = sorted(args) return reduce(lcm, range(a, b + 1))
Simple Fun #184: LCM from m to n
58bcdc65f6d3b11fce000045
[ "Fundamentals" ]
https://www.codewars.com/kata/58bcdc65f6d3b11fce000045
7 kyu
# Task Lonerz got some crazy growing plants and he wants to grow them nice and well. Initially, the garden is completely barren. Each morning, Lonerz can put any number of plants into the garden to grow. And at night, each plant mutates into two plants. Lonerz really hopes to see `n` plants in his garde...
games
def plant_doubling(n): return bin(n). count("1")
Simple Fun #189: Plant Doubling
58bf97cde4a5edfd4f00008d
[ "Puzzles" ]
https://www.codewars.com/kata/58bf97cde4a5edfd4f00008d
7 kyu
# Task Consider integer numbers from 0 to n - 1 written down along the circle in such a way that the distance between any two neighbouring numbers is equal (note that 0 and n - 1 are neighbouring, too). Given `n` and `firstNumber`/`first_number`/`first-number`, find the number which is written in the radially opposit...
games
def circle_of_numbers(n, fst): return (fst + (n / 2)) % n
Simple Fun #2: Circle of Numbers
58841cb52a077503c4000015
[ "Puzzles" ]
https://www.codewars.com/kata/58841cb52a077503c4000015
7 kyu
Create a function that returns the average of an array of numbers ("scores"), rounded to the nearest whole number. You are not allowed to use any loops (including for, for/in, while, and do/while loops). The array will never be empty.
reference
def average(array): return round(sum(array) / len(array))
Average Scores
57b68bc7b69bfc8209000307
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/57b68bc7b69bfc8209000307
7 kyu
In telecomunications we use information coding to detect and prevent errors while sending data. A parity bit is a bit added to a string of binary code that indicates whether the number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code, and can detect a 1 bit err...
reference
def parity_bit(binary): return ' ' . join(byte[: - 1] if byte . count('1') % 2 == 0 else 'error' for byte in binary . split())
Parity bit - Error detecting code
58409435258e102ae900030f
[ "Algorithms", "Binary", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/58409435258e102ae900030f
6 kyu
It's time to create an autocomplete function! Yay! The autocomplete function will take in an input string and a dictionary array and return the values from the dictionary that start with the input string. If there are more than 5 matches, restrict your output to the first 5 results. If there are no matches, return a...
reference
def autocomplete(input_, dictionary): input_ = '' . join([c for c in list(input_) if c . isalpha()]) return [x for x in dictionary if x . lower(). startswith(input_ . lower())][: 5]
Autocomplete! Yay!
5389864ec72ce03383000484
[ "Strings", "Regular Expressions", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5389864ec72ce03383000484
6 kyu
Your task is to write a higher order function for chaining together a list of unary functions. In other words, it should return a function that does a left fold on the given functions. ```python chained([a,b,c,d])(input) ``` Should yield the same result as ```python d(c(b(a(input)))) ```
reference
def chained(functions): def f(x): for function in functions: x = function(x) return x return f
Unary function chainer
54ca3e777120b56cb6000710
[ "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/54ca3e777120b56cb6000710
6 kyu
The idea for this kata came from 9gag today: [![The lyrics to "Never gonna give you up" by Rick Astley encoded in the NATO phonetic alphabet](https://9gag.com/photo/amrb4r9_700b.jpg)](http://9gag.com/gag/amrb4r9) ## Task You'll have to translate a string to Pilot's alphabet ([NATO phonetic alphabet](https://en.wiki...
reference
def to_nato(words): return ' ' . join(NATO . get(char, char) for char in words . upper() if char != ' ')
If you can read this...
586538146b56991861000293
[ "Fundamentals" ]
https://www.codewars.com/kata/586538146b56991861000293
6 kyu
**Kata in this series** * [Histogram - H1](https://www.codewars.com/kata/histogram-h1/) * [Histogram - H2](https://www.codewars.com/kata/histogram-h2/) * [Histogram - V1](https://www.codewars.com/kata/histogram-v1/) * [Histogram - V2](https://www.codewars.com/kata/histogram-v2/) <h2>Background</h2> A 6-sided die is r...
algorithms
def histogram(rolls): hist = "-----------\n1 2 3 4 5 6\n" for i in range(max(rolls) + 1): hist = '' . join(['# ' if i < v else '{:<2d}' . format( i) if i == v and v != 0 else ' ' for v in rolls]). rstrip() + '\n' + hist return hist
Histogram - V1
57c6c2e1f8392d982a0000f2
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/57c6c2e1f8392d982a0000f2
5 kyu
## MTV Cribs is back! ![](https://s-media-cache-ak0.pinimg.com/236x/1b/cf/f4/1bcff4f4621644461103576e40bde4ed.jpg) _If you haven't solved it already I recommend trying [this kata](https://www.codewars.com/kata/5834a44e44ff289b5a000075) first._ ## Task Given `n` representing the number of floors build a penthouse li...
reference
def my_crib(n): wide = 4 + 3 + 6 * (n - 1) door = 2 + n - 1 roof = 3 + 2 * (n - 1) r = '{0}{1}{0}\n' . format(' ' * (wide / / 2 - n), '_' * (3 + 2 * (n - 1))) for i in range(1, roof): r += '{0}/{1}\\{0}\n' . format(' ' * (wide / / 2 - n - i), '_' * (3 + 2 * (n - 1) + 2 * (i - 1))) for...
Now that's a crib!
58360d112fb0ba255300008b
[ "Fundamentals", "ASCII Art" ]
https://www.codewars.com/kata/58360d112fb0ba255300008b
5 kyu
## Task Given `n` representing the number of floors build a beautiful multi-million dollar mansions like the ones in the example below: ``` /\ / \ / \ /______\ number of floors 3 | | | | |______| /\ / \ /____\ | | 2 floors |____| /\ /__\ 1 floor...
reference
def my_crib(n): roof = "\n" . join("%s/%s\\%s" % (" " * (n - i), " " * i * 2, " " * (n - i)) for i in range(n)) ceiling = "\n/%s\\\n" % ("_" * (n * 2)) walls = ("|%s|\n" % (" " * (n * 2))) * (n - 1) floor = "|%s|" % ("_" * (n * 2)) return roof + ceiling + walls + floor...
MTV Cribs
5834a44e44ff289b5a000075
[ "Fundamentals", "ASCII Art" ]
https://www.codewars.com/kata/5834a44e44ff289b5a000075
6 kyu
Your aged grandfather is tragically optimistic about Team GB's chances in the upcoming World Cup, and has enlisted you to help him make [Union Jack](https://en.wikipedia.org/wiki/Union_Jack) flags to decorate his house with. ## Instructions * Write a function which takes as a parameter a number which represents the d...
reference
from math import ceil X = 'X' # X' for the red/white lines B = '-' # '-' for the blue background def union_jack(n): try: n = max(7, ceil(n)) except TypeError: return False half, odd = divmod(n - 1, 2) result = [] for i in range(half): half_row = B * i + X + B * (half - i...
The Union Jack
5620281f0eeee479cd000020
[ "Strings", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5620281f0eeee479cd000020
6 kyu
## Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows. * Note:```Returning``` the pattern is not the same as ```Printing``` the pattern. ### Parameters: pattern( n , x , y ); ...
reference
def pattern(n: int, x: int = 1, y: int = 1, * _) - > str: lines = [] for i in range(1, n + 1): line = ' ' * (i - 1) + str(i % 10) + ' ' * (n - i) line += line[- 2:: - 1] lines . append(line + line[1:] * (x - 1)) cross = lines + lines[- 2:: - 1] return '\n' . join(cross + (cross[1:...
Complete The Pattern #15
558db3ca718883bd17000031
[ "Arrays", "Strings", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/558db3ca718883bd17000031
6 kyu
## Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows. * Note:`Returning` the pattern is not the same as `Printing` the pattern. ### Parameters: pattern( n , x ); ^ ^ ...
reference
def pattern(n: int, x: int = 1, * _) - > str: lines = [] for i in range(1, n + 1): line = ' ' * (i - 1) + str(i % 10) + ' ' * (n - i) line += line[- 2:: - 1] lines . append(line + line[1:] * (x - 1)) return '\n' . join(lines + lines[- 2:: - 1])
Complete The Pattern #13
5592e5d3ede9542ff0000057
[ "Strings", "Arrays", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5592e5d3ede9542ff0000057
6 kyu
<p style="text-align:left;"><font face="Impact" size="5"><A HREF="http://www.codewars.com/kata/5592e5d3ede9542ff0000057">< PREVIOUS KATA</A></font> <span style="float:right;"><font face="Impact" size="5" ><A HREF="http://www.codewars.com/kata/558db3ca718883bd17000031">NEXT KATA ></A></font></span></p> ## Task: You h...
reference
def pattern(n: int, x: int = 1, * _) - > str: lines = [] for i in range(1, n + 1): line = ' ' * (i - 1) + str(i % 10) + ' ' * (n - i) lines . append(line + line[- 2:: - 1]) cross = lines + lines[- 2:: - 1] return '\n' . join(cross + (cross[1:] * (x - 1)))
Complete The Pattern #14
559379505c859be5a9000034
[ "Strings", "Arrays", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/559379505c859be5a9000034
6 kyu
### Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto (2n-1) rows, where n is parameter. * Note:`Returning` the pattern is not the same as `Printing` the pattern. #### Parameters: pattern( n ); ^ ...
reference
def pattern(n): res = [] for i in range(1, n + 1): line = ' ' * (i - 1) + str(i % 10) + ' ' * (n - i) res . append(line + line[:: - 1][1:]) return '\n' . join(res + res[:: - 1][1:])
Complete The Pattern #12
558ac25e552b51dbc60000c3
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/558ac25e552b51dbc60000c3
6 kyu
Given an array `arr` of strings, complete the function by calculating the total perimeter of all the islands. Each piece of land will be marked with `'X'` while the water fields are represented as `'O'`. Consider each tile being a perfect `1 x 1` piece of land. Some examples for better visualization: ```text ['XOOXO',...
reference
def land_perimeter(arr): I, J = len(arr), len(arr[0]) P = 0 for i in range(I): for j in range(J): if arr[i][j] == 'X': if i == 0 or arr[i - 1][j] == 'O': P += 1 if i == I - 1 or arr[i + 1][j] == 'O': P += 1 if j == 0 or arr[i][j - 1] == 'O': P += 1 ...
Land perimeter
5839c48f0cf94640a20001d3
[ "Fundamentals" ]
https://www.codewars.com/kata/5839c48f0cf94640a20001d3
5 kyu
### Task: You have to write a function **pattern** which creates the following Pattern(See Examples) upto n(parameter) number of rows. #### Rules/Note: * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * All the lines in the pattern have same length i.e equal to the number of ch...
reference
def pattern(n): output = [] for i in range(1, n + 1): wing = ' ' * (n - i) + '' . join(str(d % 10) for d in range(1, i)) output . append(wing + str(i % 10) + wing[:: - 1]) return '\n' . join(output)
Complete The Pattern #8 - Number Pyramid
5575ff8c4d9c98bc96000042
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5575ff8c4d9c98bc96000042
6 kyu
Write a function which takes one parameter representing the dimensions of a checkered board. The board will always be square, so 5 means you will need a 5x5 board. The dark squares will be represented by a unicode white square, while the light squares will be represented by a unicode black square (the opposite colours...
reference
def checkered_board(n): return isinstance(n, int) and n > 1 and \ '\n' . join(' ' . join("■" if (x + y) % 2 ^ n % 2 else "□" for y in range(n)) for x in range(n))
Checkered Board
5650f1a6075b3284120000c0
[ "Strings", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5650f1a6075b3284120000c0
6 kyu
# How much is the fish! (- Scooter ) The ocean is full of colorful fishes. We as programmers want to know the hexadecimal value of these fishes. ## Task Take all hexadecimal valid characters (a,b,c,d,e,f) of the given name and XOR them. Return the result as an integer. ## Input The input is always a string, which can...
reference
from functools import reduce from operator import xor def fisHex(name): return reduce(xor, (int(x, 16) for x in name . lower() if 'a' <= x <= 'f'), 0)
How much hex is the fish
5714eb80e1bf814e53000c06
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5714eb80e1bf814e53000c06
6 kyu
## Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto n number of rows. * Note:```Returning``` the pattern is not the same as ```Printing``` the pattern. ### Rules/Note: * The pattern should be created using only unit digits. * If `n < 1` then it should return "" i....
reference
def pattern(n): return "\n" . join( "" . join( str((n - min(j, i)) % 10) for j in range(n) ) for i in range(max(n, 0)) )
Complete The Pattern #16
55ae997d1c40a199e6000018
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/55ae997d1c40a199e6000018
6 kyu
### Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto (3n-2) rows, where n is parameter. * Note:`Returning` the pattern is not the same as `Printing` the pattern. #### Rules/Note: * The pattern should be created using only unit digits. * If `n < 1` then it should re...
reference
def pattern(n): h = '' . join(str(i % 10) for i in range(1, n)) h = h + str(n % 10) * n + h[:: - 1] v = [(str(i % 10) * n). center(len(h)) for i in range(1, n)] return '\n' . join(v + [h] * n + v[:: - 1])
Complete The Pattern #11 - Plus
5589ad588ee1db3f5e00005a
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5589ad588ee1db3f5e00005a
6 kyu
## Task: You have to write a function **pattern** which returns the following Pattern(See Examples) upto (2n-1) rows, where n is parameter. ### Rules/Note: * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * All the lines in the pattern have same length i.e equal to the number o...
reference
def pattern(n): lines = [] for c in range(1, n + 1): s = (' ' * (n - c)) + '' . join([str(s)[- 1] for s in range(1, c + 1)]) lines += [s + s[:: - 1][1:]] lines += lines[:: - 1][1:] return '\n' . join(str(x) for x in lines)
Complete The Pattern #9 - Diamond
5579e6a5256bac65e4000060
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5579e6a5256bac65e4000060
6 kyu
The objective is to return all pairs of integers from a given array of integers that have a difference of 2. The result array should be sorted in ascending order of values. Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter. ## Examples ~~~if-not:pyth...
algorithms
def twos_difference(a): s = set(a) return sorted((x, x + 2) for x in a if x + 2 in s)
Difference of 2
5340298112fa30e786000688
[ "Arrays", "Sorting", "Algorithms" ]
https://www.codewars.com/kata/5340298112fa30e786000688
6 kyu
Three candidates take part in a TV show. In order to decide who will take part in the final game and probably become rich, they have to roll the Wheel of Fortune! The Wheel of Fortune is divided into 20 sections, each with a number from 5 to 100 (only mulitples of 5). Each candidate can roll the wheel once or twice ...
algorithms
def winner(candidates): try: assert len(candidates) == 3 max_total = 0 for c in candidates: name, scores = c['name'], c['scores'] assert 1 <= len(scores) <= 2 assert all(not s % 5 and 0 < s <= 100 for s in scores) total = sum(scores) if max_total < total <= 100: selecte...
Wheel of Fortune
55191f78cd82ff246f000784
[ "Games", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/55191f78cd82ff246f000784
6 kyu
#Task# Raj once wanted to code a program to make a plus sign using the numbers but he didn't have any idea to do so. Using `n` as a parameter in the function `pattern` complete the code and solve the pattern so that Raj fells happy. ###Rules/Note:### * You are assured that n>1 * There are white spaces on top a...
reference
def pattern(n): s1 = '\n' . join(' ' * (n - 1) + str(i % 10) for i in range(1, n)) s2 = '' . join(str(i % 10) for i in range(1, n)) s2 = s2 + str(n % 10) + s2[:: - 1] s3 = '\n' . join(' ' * (n - 1) + str(i % 10) for i in range(n - 1, 0, - 1)) return s1 + '\n' + s2 + '\n' + s3 + '\n'
Numbers' Plus Pattern
563cb92e0996a4ac0b000042
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/563cb92e0996a4ac0b000042
6 kyu
Complete the function to find the count of the most frequent item of an array. You can assume that input is an array of integers. For an empty array return `0` ## Example ```python input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3] ouptut: 5 ``` The most frequent number in the array is `-1` and it occurs `5` ...
reference
def most_frequent_item_count(collection): if collection: return max([collection . count(item) for item in collection]) return 0
Find Count of Most Frequent Item in an Array
56582133c932d8239900002e
[ "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/56582133c932d8239900002e
7 kyu
## Task: You have to write a function **pattern** which returns the following Pattern(See Examples) upto n rows, where n is parameter. ### Rules/Note: * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * The length of each line = (2n-1). * Range of n is (-∞,100] ## Examples: pa...
reference
def pattern(n): nums = '1234567890' str_nums = nums * (n / / 10) + nums[: n % 10] return '\n' . join(' ' * (n - i - 1) + str_nums + ' ' * i for i in range(n))
Complete The Pattern #10 - Parallelogram
5581a7651185fe13190000ee
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5581a7651185fe13190000ee
7 kyu
###Task: You have to write a function `pattern` which creates the following pattern (see examples) up to the desired number of rows. * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * If any even number is passed as argument then the pattern should last upto the largest odd nu...
reference
def pattern(n): return '\n' . join(str(i) * i for i in range(1, n + 1, 2))
Complete The Pattern #6 - Odd Ladder
5574940eae1cf7d520000076
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5574940eae1cf7d520000076
7 kyu
Create a function which checks a number for three different properties. - is the number prime? - is the number even? - is the number a multiple of 10? Each should return either true or false, which should be given as an array. Remark: The Haskell variant uses `data Property`. ### Examples ```javascript numberPropert...
algorithms
import math def number_property(n): return [isPrime(n), isEven(n), isMultipleOf10(n)] # Return isPrime? isEven? isMultipleOf10? # your code here def isPrime(n): if n <= 3: return n >= 2 if n % 2 == 0 or n % 3 == 0: return False for i in range(5, int(n * * 0.5) + 1, 6): ...
Simple Maths Test
5507309481b8bd3b7e001638
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5507309481b8bd3b7e001638
7 kyu
### Task: You have to write a function `pattern` which creates the following pattern (See Examples) upto desired number of rows. If the Argument is `0` or a Negative Integer then it should return `""` i.e. empty string. ### Examples: `pattern(9)`: 123456789 234567891 345678912 456789123 5678912...
reference
def pattern(n): return '\n' . join('' . join(str((x + y) % n + 1) for y in range(n)) for x in range(n))
Complete The Pattern #7 - Cyclical Permutation
557592fcdfc2220bed000042
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/557592fcdfc2220bed000042
7 kyu
### Task: You have to write a function **pattern** which creates the following pattern up to `n/2` number of lines. * If `n <= 1` then it should return `""` (i.e. empty string). * If any odd number is passed as argument then the pattern should last up to the largest even number which is smaller than the passed odd nu...
reference
def pattern(n): return "\n" . join(str(i) * i for i in range(2, n + 1, 2))
Complete The Pattern #5 - Even Ladder
55749101ae1cf7673800003e
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/55749101ae1cf7673800003e
7 kyu
Johnny is a boy who likes to open and close lockers. He loves it so much that one day, when school was out, he snuck in just to play with the lockers. Each locker can either be open or closed. If a locker is closed when Johnny gets to it, he opens it, and vice versa. The lockers are numbered sequentially, starting at...
games
from math import floor # Pretty sure this is the fastest implementation; only one square root, and sqrt(n) multiplications. # Plus, no booleans, because they're super slow. def locker_run(l): return [i * i for i in range(1, int(floor(l * * .5)) + 1)]
Slamming Lockers
55a5085c1a3d379fbb000062
[ "Algorithms", "Fundamentals", "Puzzles" ]
https://www.codewars.com/kata/55a5085c1a3d379fbb000062
7 kyu
### Instructions Complete the function that returns the lyrics for the song [99 Bottles of Beer](http://en.wikipedia.org/wiki/99_Bottles_of_Beer) as **an array of strings**: each line should be a separate element - see the example at the bottom. ***Note:*** *in order to avoid hardcoded solutions, the size of your cod...
algorithms
def sing(): lst = [] for i in range(97): lst . append( f' { 99 - i } bottles of beer on the wall, { 99 - i } bottles of beer.') lst . append( f'Take one down and pass it around, { 98 - i } bottles of beer on the wall.') return lst + ['2 bottles of beer on the wall, 2 bottles o...
99 Bottles of Beer
52a723508a4d96c6c90005ba
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/52a723508a4d96c6c90005ba
7 kyu
## Oh no! Some really funny web dev gave you a _sequence of numbers_ from his API response as an _sequence of strings_! You need to cast the whole array to the correct type. Create the function that takes as a parameter a sequence of numbers represented as strings and outputs a sequence of numbers. ie:``` ["1", "2",...
reference
def to_float_array(arr): return list(map(float, arr))
Convert an array of strings to array of numbers
5783d8f3202c0e486c001d23
[ "Arrays", "Parsing", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5783d8f3202c0e486c001d23
7 kyu
# Esolang Interpreters #4 - Boolfuck Interpreter ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were all somewh...
algorithms
from collections import defaultdict def boolfuck(code, input=""): input = [int(c) for c in '' . join( [bin(ord(c))[2:]. rjust(8, '0') for c in input][:: - 1])] cp, p, out, bits, starts, brackets = 0, 0, [], defaultdict(int), [], {} for i, c in enumerate(code): if c == '[': s...
Esolang Interpreters #4 - Boolfuck Interpreter
5861487fdb20cff3ab000030
[ "Esoteric Languages", "Interpreters", "Algorithms", "Tutorials" ]
https://www.codewars.com/kata/5861487fdb20cff3ab000030
3 kyu
A number m of the form 10x + y is divisible by 7 if and only if x − 2y is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. Continue to do this until a number known to be divisible by 7 is obtained; you can stop when this number has *at most* 2 digits becaus...
reference
def seven(m, step=0): if m < 100: return (m, step) x, y, step = m / / 10, m % 10, step + 1 res = x - 2 * y return seven(res, step)
A Rule of Divisibility by 7
55e6f5e58f7817808e00002e
[ "Fundamentals" ]
https://www.codewars.com/kata/55e6f5e58f7817808e00002e
7 kyu