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
Fortunately last weekend, I met an utterly drunk old man. He was too drunk to be aggressive towards me. He was letting everything what he held out, from both his mind and his stomach. Although i was a bit uncomfortable, the old man's broken wisdom words caught my attention. However, his talk was not continuous as it w...
reference
def wdm(talk): return ' ' . join(talk . replace('puke', ''). replace('hiccup', ''). split())
Wise drunk man
58e953ace87e856a97000046
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/58e953ace87e856a97000046
7 kyu
Compute the [complex logarithm](https://en.wikipedia.org/wiki/Complex_logarithm) at any given **complex number**, accurate to at least `1 in 10^-12`. The imaginary part should be inside the interval `(−π, π]` (i.e if the imaginary part is exactly `π`, keep it as is). Note: You shouldn't try to compute the value of thi...
algorithms
from cmath import log as clog def log(real, imag): try: lg = clog(complex(real, imag)) return lg . real, lg . imag except ValueError: pass
Computing the complex logarithm function
590ba2baf06c49595f0000a0
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/590ba2baf06c49595f0000a0
6 kyu
In this Kata you must convert integers numbers from and to a negative-base binary system. Negative-base systems can accommodate all the same numbers as standard place-value systems, but both positive and negative numbers are represented without the use of a minus sign (or, in computer representation, a sign bit); this...
algorithms
def int_to_negabinary(i): ds = [] while i != 0: ds . append(i & 1) i = - (i >> 1) return '' . join(str(d) for d in reversed(ds)) if ds else '0' def negabinary_to_int(s): i = 0 for c in s: i = - (i << 1) + int(c) return i
Base -2
54c14c1b86b33df1ff000026
[ "Algorithms", "Binary" ]
https://www.codewars.com/kata/54c14c1b86b33df1ff000026
5 kyu
Given a set of elements (integers or string characters, characters only in RISC-V), where any element may occur more than once, return the number of subsets that do not contain a repeated element. Let's see with an example: ``` set numbers = {1, 2, 3, 4} ``` The subsets are: ``` {{1}, {2}, {3}, {4}, {1,2}, {1,3}, {...
reference
def est_subsets(arr): return 2 * * len(set(arr)) - 1
Estimating Amounts of Subsets
584703d76f6cf6ffc6000275
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/584703d76f6cf6ffc6000275
6 kyu
**This Kata is intended as a small challenge for my students** Your family runs a shop and have just brought a Scrolling Text Machine (http://3.imimg.com/data3/RP/IP/MY-2369478/l-e-d-multicolour-text-board-250x250.jpg) to help get some more business. The scroller works by replacing the current text string with a si...
reference
def rotate(str_): return [str_[i + 1:] + str_[: i + 1] for i in range(len(str_))]
All Star Code Challenge #15
586560a639c5ab3a260000f3
[ "Fundamentals" ]
https://www.codewars.com/kata/586560a639c5ab3a260000f3
6 kyu
# Task You have found a machine which, when fed with two numbers `s` and `e`, produces a strange code consisting of the letters `"a"` and `"b"`. The machine seems to be using the following algorithm: ``` step1: Check if s is less than e - 1. If so, continue to step 2. If not, exit. step2: Increment s by 1, Decrement e ...
games
def strange_code(s, e): if s >= e - 1: return '' n = (e - s) / / 2 return 'ab' * (n / / 2) + 'a' * (n % 2)
Simple Fun #241: Strange Code
590a7f2be8e86e1240000068
[ "Puzzles" ]
https://www.codewars.com/kata/590a7f2be8e86e1240000068
7 kyu
Lot of junior developer can be stuck when they need to change the access permission to a file or a directory in an Unix-like operating systems. To do that they can use the `chmod` command and with some magic trick they can change the permissionof a file or a directory. For more information about the `chmod` command yo...
reference
def chmod_calculator(perm): perms = {"r": 4, "w": 2, "x": 1} value = "" for permission in ["user", "group", "other"]: value += str(sum(perms . get(x, 0) for x in perm . get(permission, ""))) return value
chmod calculator in octal.
57f4ccf0ab9a91c3d5000054
[ "Fundamentals" ]
https://www.codewars.com/kata/57f4ccf0ab9a91c3d5000054
6 kyu
### Corner circle A circle with radius `r` is placed in a right angled corner, where `r` is an integer and `≥ 1`. <center><img src="https://i.imgur.com/9HWl86o.png" alt="circles" style="max-height:20em"></center> What is the radius of the smaller circle, rounded to two decimal places?
games
def corner_circle(r): return round(r * 0.171572875, 2)
Corner circle
5898761a9c700939ee000011
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/5898761a9c700939ee000011
6 kyu
You are given a certain integer, ```n, n > 0```. You have to search the partition or partitions, of n, with maximum product value. Let'see the case for ```n = 8```. ``` Partition Product [8] 8 [7, 1] 7 [6, 2] 12 [6, 1, 1] ...
reference
def find_part_max_prod(n): if n == 1: return [[1], 1] q, r = divmod(n, 3) if r == 0: return [[3] * q, 3 * * q] if r == 1: return [[4] + [3] * (q - 1), [3] * (q - 1) + [2, 2], 3 * * (q - 1) * 2 * * 2] return [[3] * q + [2], 3 * * q * 2]
Find the Partition with Maximum Product Value
5716a4c2794d305f4900156b
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/5716a4c2794d305f4900156b
5 kyu
In this kata, your goal is to write a function which will reverse the vowels in a string. Any characters which are not vowels should remain in their original position. Here are some examples: ``` "Hello!" => "Holle!" "Tomatoes" => "Temotaos" "Reverse Vowels In A String" => "RivArsI Vewols en e Streng" ``` For simplic...
reference
def reverse_vowels(s): v = [c for c in s if c . lower() in 'aeiou'] return '' . join(v . pop(- 1) if c . lower() in 'aeiou' else c for c in s)
Reverse Vowels In A String
585db3e8eec141ce9a00008f
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/585db3e8eec141ce9a00008f
6 kyu
The sports centre needs repair. Vandals have been kicking balls so hard into the roof that some of the tiles have started sticking up. The roof is represented by r. As a quick fix, the committee have decided to place another old roof over the top, if they can find one that fits. This is your job. A 'new' roof (f) wil...
reference
def roof_fix(new, old): return all(patch == ' ' for patch, tile in zip(new, old) if tile in '\/')
Roof Replacement
57d15a03264276aaf000007f
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57d15a03264276aaf000007f
6 kyu
Given a string, return a new string that has transformed based on the input: * Change case of every character, ie. lower case to upper case, upper case to lower case. * Reverse the order of words from the input. **Note:** You will have to handle multiple spaces, and leading/trailing spaces. For example: ``` "Exampl...
reference
def string_transformer(s): return ' ' . join(s . swapcase(). split(' ')[:: - 1])
String transformer
5878520d52628a092f0002d0
[ "Fundamentals" ]
https://www.codewars.com/kata/5878520d52628a092f0002d0
6 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
class Phone (object): def __init__(self): self . ring = "" self . screen = "" self . microphone = "" def incomingcall(self, number): self . name, self . ring = next( ((c["name"], c["ring"]) for c in contacts if c["number"] == number), ("stranger", "Di Da Di")) self . screen...
Thinking & Testing : Mobile phone simulator
56de82fb9905a1c3e6000b52
[ "Puzzles", "Games", "Object-oriented Programming" ]
https://www.codewars.com/kata/56de82fb9905a1c3e6000b52
6 kyu
~~~if-not:factor A nested list (or *array* in JavaScript) is a list that appears as a value inside another list, ```python [item, item, [item, item], item] ``` in the above list, [item, item] is a nested list. Your goal is to write a function that determines the depth of the deepest nested list within a given li...
algorithms
def list_depth(l): depths = [1] for x in l: if isinstance(x, list): depths . append(list_depth(x) + 1) return max(depths)
Nested List Depth
56b3b9c7a6df24cf8c00000e
[ "Lists", "Algorithms" ]
https://www.codewars.com/kata/56b3b9c7a6df24cf8c00000e
6 kyu
You're playing to scrabble. But counting points is hard. You decide to create a little script to calculate the best possible value. The function takes two arguments :<br/> <ol> <li>`points` : an array of integer representing for each letters from A to Z the points that it pays</li> <li>`words` : an array of stri...
algorithms
from string import ascii_uppercase as uppercase def get_best_word(points, words): points = dict(zip(uppercase, points)) def score(word): return sum(points[c] for c in word) return words . index(sorted(sorted(words, key=len), key=score, reverse=True)[0])
Scrabble best word
563f960e3c73813942000015
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/563f960e3c73813942000015
6 kyu
### Background: At work I need to keep a timesheet, by noting which project I was working on every 15 minutes. I have an timer that beeps every 15 minutes to prompt me to note down what I was working on at that point, but sometimes when I'm away from my desk or working continuously on one project, I don't note anyth...
algorithms
def fill_gaps(timesheet): result = timesheet[:] v, i = None, None for j, w in enumerate(timesheet): if w is not None: if w == v: for k in range(i + 1, j): result[k] = v else: v = w i = j return result
Fill in the gaps in my timesheet.
564871e795df155582000013
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/564871e795df155582000013
6 kyu
*This kata is based on [Project Euler Problem 539](https://projecteuler.net/problem=539)* ## Object Find the last number between 1 and `n` (inclusive) that survives the elimination process #### How It Works Start with the first number on the left then remove every other number moving right until you reach the the e...
algorithms
def last_man_standing(n): a = list(range(1, n + 1)) while len(a) > 1: a = a[1:: 2][:: - 1] return a[0]
Last man standing
567c26df18e9b1083a000049
[ "Lists", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/567c26df18e9b1083a000049
7 kyu
For a given two numbers your mission is to derive a function that evaluates whether two given numbers are **abundant**, **deficient** or **perfect** and whether together they are **amicable**. ### Abundant Numbers An abundant number or excessive number is a number for which the sum of its proper divisors is greater ...
reference
def deficiently_abundant_amicable_numbers(a, b): c, d = map(sumOfDivs, (a, b)) return f' { kind ( a , c )} { kind ( b , d ) } { "not " * ( a != d or b != c or a == b ) } amicable' def kind( n, sD): return 'abundant' if sD > n else 'perfect' if sD == n else 'deficient' def sumOfDivs(n): ...
Deficiently Abundant Perfect Amicable Numbers
56bc7687e8936faed5000c09
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/56bc7687e8936faed5000c09
6 kyu
You're fed up about changing the version of your software manually. Instead, you will create a little script that will make it for you. ## Exercice Create a function `nextVersion`, that will take a string in parameter, and will return a string containing the next version number. For example: ``` Current -...
algorithms
def next_version(version): ns = version . split('.') i = len(ns) - 1 while i > 0 and ns[i] == '9': ns[i] = '0' i -= 1 ns[i] = str(int(ns[i]) + 1) return '.' . join(ns)
Next Version
56c0ca8c6d88fdb61b000f06
[ "Arrays", "Strings", "Algorithms" ]
https://www.codewars.com/kata/56c0ca8c6d88fdb61b000f06
6 kyu
Hi there! You have to implement the `String get_column_title(int num) // syntax depends on programming language` function that takes an integer number (index of the Excel column) and returns the string represents the title of this column. # Intro In the MS Excel lines are numbered by decimals, columns - by sets of...
algorithms
from string import ascii_uppercase as u def get_column_title(n): assert isinstance(n, int) and n > 0 col = [] while n: n, r = divmod(n - 1, 26) col . append(u[r]) return '' . join(reversed(col))
Get the Excel column title!
56d082c24f60457198000e77
[ "Algorithms" ]
https://www.codewars.com/kata/56d082c24f60457198000e77
6 kyu
What is your favourite day of the week? Check if it's the most frequent day of the week in the year. You are given a year as integer (e. g. 2001). You should return the most frequent day(s) of the week in that year. The result has to be a list of days sorted by the order of days in week (e. g. `['Monday', 'Tuesday']`,...
reference
from calendar import weekday week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] def most_frequent_days(year): beg = weekday(year, 1, 1) end = weekday(year, 12, 31) if beg == end: return [week[beg]] else: if beg < end: return [week[beg]...
Most Frequent Weekdays
56eb16655250549e4b0013f4
[ "Fundamentals" ]
https://www.codewars.com/kata/56eb16655250549e4b0013f4
6 kyu
# Intro Hi there! You have to implement the `get_reversed_color(hex_color)` (Python, Ruby, Haskell) or `getReversedColor(hexColor)` (JavaScript, Java) <img src="http://www.w3schools.com/colors/img_colormap.gif" align=right></img> function that takes a hex-color string and returns the string represents the compl...
reference
def get_reversed_color(hex_color): if hex_color . startswith('#') or len(hex_color) > 6: raise ValueError return "#%06X" % (16777215 - int('0' + hex_color, 16))
HTML Complementary Color
56be4affc5dc03b84b001d2d
[ "Fundamentals" ]
https://www.codewars.com/kata/56be4affc5dc03b84b001d2d
6 kyu
You have a grid with `$m$` rows and `$n$` columns. Return the number of unique ways that start from the top-left corner and go to the bottom-right corner. You are only allowed to move right and down. For example, in the below grid of `$2$` rows and `$3$` columns, there are `$10$` unique paths: ``` o----o----o----o | ...
reference
from scipy . misc import comb def number_of_routes(m, n): return comb(m + n, min(m, n), exact=True)
Paths in the Grid
56a127b14d9687bba200004d
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/56a127b14d9687bba200004d
6 kyu
Vicky is quite the small wonder. Most people don't even realize she's not a real girl, but a robot living amongst us. Sure, if you stick around her home for a while you might see her creator open up her back and make a few tweaks and even see her recharge in the closet instead of sleeping in a bed. In this kata, we're...
reference
BAD_INPUT = 'I do not understand the input' KNOWN_WORD = 'I already know the word %s' NEW_WORD = 'Thank you for teaching me %s' class Robot (object): def __init__(self): self . vocabulary = set( word . lower() for message in (BAD_INPUT, KNOWN_WORD, NEW_WORD) for word in mes...
80's Kids #7: She's a Small Wonder
56743fd3a12043ffbb000049
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/56743fd3a12043ffbb000049
6 kyu
You've made it through the moat and up the steps of knowledge. You've won the temples games and now you're hunting for treasure in the final temple run. There's good news and bad news. You've found the treasure but you've triggered a nasty trap. You'll surely perish in the temple chamber. With your last movements, you...
algorithms
def mark_spot(n): if isinstance(n, int) and n % 2 != 0 and n > 0: top = [' ' * i * 2 + 'X' + ' ' * (n * 2 - 3 - 4 * i) + 'X' for i in range(n / 2)] middle = [' ' * (n - 1) + 'X'] bottom = top[:: - 1] return '\n' . join(top + middle + bottom) + '\n' else: return '?'
80's Kids #4: Legends of the Hidden Temple
56648a2e2c464b8c030000bf
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/56648a2e2c464b8c030000bf
6 kyu
Well, those numbers were right and we're going to feed their ego. Write a function, isNarcissistic, that takes in any amount of numbers and returns true if all the numbers are narcissistic. Return false for invalid arguments (numbers passed in as strings are ok). For more information about narcissistic numbers (and b...
algorithms
def is_narcissistic(* l): try: return all(sum(int(i) * * len(str(n)) for i in str(n)) == n for n in map(int, l)) except: return False
Numbers so vain, they probably think this Kata is about them.
565225029bcf176687000022
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/565225029bcf176687000022
6 kyu
<div style="border:1pt solid; background-color:#030; padding:1ex;margin:0 0 1ex;"> <span style="border:1px solid;display:inline-block;padding:0 1ex; margin-right:1em; background-color:#ccc;color:#000;">Stuck?</span> [Try this one](http://www.codewars.com/kata/remove-the-minimum).</div> # A Storm at Sea Jill the adven...
reference
from heapq import nsmallest def remove_smallest(n, arr): if n <= 0: return arr a = arr[:] for i in nsmallest(n, a): a . remove(i) return a
Another one down—the Survival of the Fittest!
563ce9b8b91d25a5750000b6
[ "Lists", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/563ce9b8b91d25a5750000b6
6 kyu
Every positive integer number, that is not prime, may be decomposed in prime factors. For example the prime factors of 20, are: ``` 2, 2, and 5, because: 20 = 2 . 2 . 5 ``` The first prime factor (the smallest one) of ```20``` is ```2``` and the last one (the largest one) is ```5```. The sum of the first and the last ...
reference
def sflpf_data(val, nMax): r = [] for i in range(2, nMax): fac = primef(i) if len(fac) > 1 and fac[0] + fac . pop() == val: r . append(i) return r def primef(n): i = 2 f = [] while i * i <= n: if n % i: i += 1 else: n / /= i f . ...
The Sum of The First and The Last Prime Factor Make Chains of Numbers
5629b94e34e04f8fb200008e
[ "Mathematics", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/5629b94e34e04f8fb200008e
6 kyu
Your function ```given_nth_value()``` (Javascript: ```givenNthValue()```)will receive an array or list of integers, positive or negative, then, it will receive an integer k, to search a certain term and finally the mode string ```"min"``` or ```"max"```. We may understand better graphically ```python given_nth_value(ar...
reference
def given_nth_value(lst, k, mode): s = set(lst) if not isinstance(k, int) or k < 0: return "Incorrect value for k" if not isinstance(mode, str) or mode . lower() not in ("max", "min"): return "Valid entries: 'max' or 'min'" if not s or any(not isinstance(e, int) for e in s): return "I...
Required Data II (Easy One)
560985a07add63e1a1000019
[ "Fundamentals", "Algorithms", "Data Structures", "Sorting" ]
https://www.codewars.com/kata/560985a07add63e1a1000019
6 kyu
We want to find the numbers higher or equal than 1000 that the sum of every four consecutives digits cannot be higher than a certain given value. If the number is ``` num = d1d2d3d4d5d6 ```, and the maximum sum of 4 contiguous digits is ```maxSum```, then: ```python d1 + d2 + d3 + d4 <= maxSum d2 + d3 + d4 + d5 <= maxS...
reference
def check(num, max_sum): l = [int(i) for i in str(num)] for i in range(0, len(l) - 3): if sum(l[i: i + 4]) > max_sum: return False return True def max_sumDig(nMax, maxSum): found = [i for i in range(1000, nMax + 1) if check(i, maxSum)] mean = sum(found) / float(len(found)) ...
How Many Numbers? II
55f5efd21ad2b48895000040
[ "Algorithms", "Data Structures", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/55f5efd21ad2b48895000040
5 kyu
We have the first value of a certain sequence, we will name it ```init_val```. We define pattern list, ```pattern_l```, an array that has the differences between contiguous terms of the sequence. ``` E.g: pattern_l = [k1, k2, k3, k4]``` The terms of the sequence will be such values that: ```python term1 = init_val t...
reference
def sumDig_nthTerm(initVal, patternL, nthTerm): cycles, position = divmod(nthTerm - 1, len(patternL)) result = initVal + sum(patternL) * cycles + sum(patternL[: position]) return sum(map(int, str(result)))
Reach Me and Sum my Digits
55ffb44050558fdb200000a4
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/55ffb44050558fdb200000a4
6 kyu
Every number may be factored in prime factors. For example, the number 18 may be factored by its prime factors ``` 2 ``` and ```3``` ``` 18 = 2 . 3 . 3 = 2 . 3² ``` The sum of the prime factors of 18 is ```2 + 3 + 3 = 8``` But some numbers like 70 are divisible by the sum of its prime factors: ``` 70 = 2 . 5 . 7 # s...
algorithms
def mult_primefactor_sum(a, b): s = [] for i in range(a, b + 1): r = factorize_add(i) if r != i and i % r == 0: s . append(i) return s def factorize_add(num): if num < 4: return num d = 2 p = 0 while d < num * * .5 + 1: while not num % d: ...
The Sum Of The Prime Factors Of a Number... What For?
5626ec066d35051d4500009e
[ "Algorithms" ]
https://www.codewars.com/kata/5626ec066d35051d4500009e
6 kyu
<h1>Most Improvd - Puzzles #4</h1> <p> When being graded in a subject or a course high marks are focused on the most but what about most improved? As a computer science teacher you would like to create a function which calculates the most improved students and rank them in a list. </p> <h2>Task</h2> <p> Your task is t...
games
def calculate_improved(students): students = ({ "name": s["name"], "improvement": round( 100.0 * (s["marks"][- 1] or 0) / (s["marks"][0] or 0) - 100.0) if s["marks"][0] else 0 } for s in students) return sorted(students, key=lambda s: (- s["improvement"], s["name"]...
Most improved - Puzzles #4
55da2a419f8361df45000025
[ "Arrays", "Puzzles" ]
https://www.codewars.com/kata/55da2a419f8361df45000025
6 kyu
Decompose a number into an array *(tuple in Haskell, array of arrays `long[][]` in C# or Java)* in the form `[ [k1, k2, k3, ...], r ]` such that: ### num = 2<sup>k1</sup> + 3<sup>k2</sup> + 4<sup>k3</sup> + ... + n<sup>kn-1</sup> + r Where every k<sub>i</sub> > 1 and every k<sub>i</sub> is maximized (first maximizi...
algorithms
from math import log def decompose(n): i = 2 result = [] while n >= i * i: k = int(log(n, i)) result . append(k) n -= i * * k i += 1 return [result, n]
Decompose a number
55ec80d40d5de30631000025
[ "Algorithms" ]
https://www.codewars.com/kata/55ec80d40d5de30631000025
6 kyu
Spin-off of <a href="http://www.codewars.com/kata/558dd9a1b3f79dc88e000001" target="_blank" title="Duplicated Number in a Consecutive Unsorted List">this kata</a>, here you will have to figure out an efficient strategy to solve the problem of finding the sole duplicate number among an unsorted array/list of numbers sta...
algorithms
def find_dup(arr): seen = set() for a in arr: if a in seen: return a seen . add(a)
Find The Duplicated Number in a Consecutive Unsorted List - Tougher Version
558f0553803bc3c4720000af
[ "Lists", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/558f0553803bc3c4720000af
6 kyu
Some numbers have the property to be divisible by 2 and 3. Other smaller subset of numbers have the property to be divisible by 2, 3 and 5. Another subset with less abundant numbers may be divisible by 2, 3, 5 and 7. These numbers have something in common: their prime factors are contiguous primes. Implement a functio...
reference
from gmpy2 import next_prime as np from math import prod def count_specMult(n, t): a, b = 2, [] while n > 0: b, a, n = b + [a], np(a), n - 1 return t / / prod(b)
Special Multiples
55e785dfcb59864f200000d9
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/55e785dfcb59864f200000d9
6 kyu
The integers 14 and 15, are contiguous (1 the difference between them, obvious) and have the same number of divisors. ```python 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` ```javascript 14 ----> 1, 2, 7, 14 (4 divisors) 15 ----> 1, 3, 5, 15 (4 divisors) ``` ```coffeescript 14 ----> 1, 2, 7, ...
reference
def count_pairs_int(d, m): return sum(1 for i in range(1, m - d) if divisors(i) == divisors(i + d)) def divisors(n): return sum(1 + (n / / k != k) for k in range(1, int(n * * 0.5) + 1) if n % k == 0)
Find Numbers with Same Amount of Divisors
55f1614853ddee8bd4000014
[ "Algorithms", "Mathematics", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55f1614853ddee8bd4000014
6 kyu
Create a function ```javascript hasTwoCubeSums(n) ``` ```java boolean hasTwoCubeSums(int n) ``` ```python has_two_cube_sums(n) ``` ```ruby has_two_cube_sums(n) ``` ```csharp bool HasTwoCubeSums(int n) ``` ```haskell hasTwoCubeSums :: Integer -> Bool ``` which checks if a given number `n` can be written as the sum of...
reference
def has_two_cube_sums(n): sum = [] power = int(n * * (1 / 3.0)) + 1 for i in xrange(1, power): for x in xrange(1, power): if i == x: continue tmp = i * * 3 + x * * 3 if tmp > n: break if tmp == n: if len(sum) == 2: return True sum . append([i, x]) re...
Two cube sums
55fd4919ce2a1d7c0d0000f3
[ "Fundamentals" ]
https://www.codewars.com/kata/55fd4919ce2a1d7c0d0000f3
6 kyu
We need a function that receives an array or list of integers (positive and negative) and may give us the following information in the order and structure presented below: `[(1), (2), (3), [[(4)], 5]]` (1) - Total amount of received integers. (2) - Total amount of different values the array has. (3) - Total amount...
reference
from collections import defaultdict, Counter def count_sel(nums): cnt = Counter(nums) d = defaultdict(list) total = 0 unique = 0 for k, v in cnt . iteritems(): d[v]. append(k) total += v unique += 1 maximum = max(d) return [total, unique, len(d[1]), [sorted(d[maxim...
Required Data I
55f95dbb350b7b1239000030
[ "Algorithms", "Data Structures", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/55f95dbb350b7b1239000030
6 kyu
Create a function ```sel_number()```, that will select numbers that fulfill the following constraints: 1) The numbers should have 2 digits at least. 2) They should have their respective digits in increasing order from left to right. Examples: 789, 479, 12678, have these feature. But 617, 89927 are not of this type. ...
reference
from itertools import pairwise def sel_number(n: int, d: int) - > int: return sum(all(0 < b - a <= d for a, b in pairwise(map(int, str(i)))) for i in range(12, n + 1))
How Many Numbers?
55d8aa568dec9fb9e200004a
[ "Fundamentals", "Algorithms", "Mathematics", "Data Structures" ]
https://www.codewars.com/kata/55d8aa568dec9fb9e200004a
6 kyu
- Input: Integer `n` - Output: String Example: `a(4)` prints as ``` A A A A A A A A ``` `a(8)` prints as ``` A A A A A A A A A A A A A A A A A A ``` `a(12)` prints as ``` A A A...
reference
def a(n): """ """ if n % 2 != 0: n = n - 1 if n < 4: return '' side = " " * (n - 1) li = [side + "A" + side] for i in range(1, n): side = side[1:] middle = "A " * (i - 1) if i == (n / 2) else " " * (i - 1) li . append(side + "A " + middle + "A" + side) r...
A for Apple
55de3f83e92c3e521a00002a
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/55de3f83e92c3e521a00002a
6 kyu
Let's say take 2 strings, A and B, and define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings `abc` and `abd` is 2, while the similarity of strings `aaa` and `aaab` is 3. write a function that calculates the sum of similarities of a st...
algorithms
from os . path import commonprefix def string_suffix(s): return sum(len(commonprefix([s, s[i:]])) for i in range(len(s)))
String Suffixes
559d34cb2e65e765b90000f0
[ "Strings", "Logic", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/559d34cb2e65e765b90000f0
6 kyu
Find the closest prime number under a certain integer ```n``` that has the maximum possible amount of even digits. For ```n = 1000```, the highest prime under ```1000``` is ```887```, having two even digits (8 twice) Naming ```f()```, the function that gives that prime, the above case and others will be like the foll...
reference
from gmpy2 import next_prime def f(n): first = 2 result = count = 1 while first < n: temp = sum(i in '02468' for i in str(first)) if temp >= count: count = temp result = first first = next_prime(first) return result
Primes with Even Digits
582dcda401f9ccb4f0000025
[ "Strings", "Data Structures", "Algorithms", "Mathematics", "Number Theory" ]
https://www.codewars.com/kata/582dcda401f9ccb4f0000025
5 kyu
We have the following sequence: ```python f(0) = 0 f(1) = 1 f(2) = 1 f(3) = 2 f(4) = 4; f(n) = f(n-1) + f(n-2) + f(n-3) + f(n-4) + f(n-5); ``` Your task is to give the number of total values for the odd terms of the sequence up to the n-th term (included). (The number n (of n-th term) will be given as a positive inte...
reference
def count_odd_pentaFib(n): return 2 * (n / / 6) + [0, 1, 2, 2, 2, 2][n % 6] - (n >= 2)
Pentabonacci
55c9172ee4bb15af9000005d
[ "Fundamentals", "Mathematics", "Algorithms", "Performance", "Dynamic Programming" ]
https://www.codewars.com/kata/55c9172ee4bb15af9000005d
6 kyu
Define two functions: `hex_to_bin` and `bin_to_hex` (or `hexToBin` and `binToHex`) # hex_to_bin Takes a hexadecimal string as an argument . **Note:** This string can contain upper or lower case characters and start with any amount of zeros. Returns the binary representation (without leading zeros) of the numerical...
games
bin2hex = {"0000": "0", "0001": "1", "0010": "2", "0011": "3", "0100": "4", "0101": "5", "0110": "6", "0111": "7", "1000": "8", "1001": "9", "1010": "a", "1011": "b", "1100": "c", "1101": "d", "1110": "e", "1111": "f"} hex2bin = {v: k for k, v in bin2hex . items()} def bin_to_h...
Bin to Hex and back
55d1b0782aa1152115000037
[ "Puzzles", "Binary", "Strings", "Data Types" ]
https://www.codewars.com/kata/55d1b0782aa1152115000037
6 kyu
##Task: You have to write a function `add` which takes two binary numbers as strings and returns their sum as a string. ##Note: * You are `not allowed to convert binary to decimal & vice versa`. * The sum should contain `No leading zeroes`. ##Examples: ``` add('111','10'); => '1001' add('1101','101'); => '10010' add(...
reference
def binary_string_to_int(string): return sum((d == '1') * 2 * * i for i, d in enumerate(string[:: - 1])) def add(a, b): return '{:b}' . format(binary_string_to_int(a) + binary_string_to_int(b))
Adding Binary Numbers
55c11989e13716e35f000013
[ "Binary", "Bits", "Fundamentals" ]
https://www.codewars.com/kata/55c11989e13716e35f000013
6 kyu
**Ore Numbers** (also called Harmonic Divisor Numbers) are numbers for which the [harmonic mean](https://en.wikipedia.org/wiki/Harmonic_mean) of all their divisors (including the number itself) equals an integer. For example, 6 is an Ore Number because its harmonic mean is exactly 2: ``` H(6) = 4 / (1/1 + 1/2 + 1/3 +...
algorithms
# Harmonic mean = count/sum(1/divisors) # can be simplified to # Harmonic Mean = count*n/sum(divisors) # this avoids the many division operations in the sum def is_ore(n): sum = 0 count = 0 for divisor in range(1, n + 1): if n % divisor == 0: count += 1 sum += divisor if n * count % sum == 0...
Ore Numbers
55ba95a17970ff3e80000064
[ "Mathematics", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/55ba95a17970ff3e80000064
6 kyu
Backwards Read Primes are primes that when read backwards in base 10 (from right to left) are a different prime. (This rules out primes which are palindromes.) ``` Examples: 13 17 31 37 71 73 are Backwards Read Primes ``` 13 is such because it's prime and read from right to left writes 31 which is prime too. Same for ...
algorithms
def backwardsPrime(start, stop): primes = [] for n in range(start, stop + 1): if n not in primes and is_prime(n) and is_prime(reverse(n)) and n != reverse(n): primes . append(n) if start <= reverse(n) <= stop: primes . append(reverse(n)) return sorted(primes) def is_prime(n): ...
Backwards Read Primes
5539fecef69c483c5a000015
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5539fecef69c483c5a000015
6 kyu
Scheduling is how the processor decides which jobs (processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Round-Robin, which today you will be implementing. Round-Robin works by queu...
algorithms
def roundRobin(jobs, slice, index): total_cc = 0 while True: for idx in range(len(jobs)): cc = min(jobs[idx], slice) jobs[idx] -= cc total_cc += cc if idx == index and jobs[idx] == 0: return total_cc
Scheduling (Round-Robin)
550cb646b9e7b565d600048a
[ "Algorithms" ]
https://www.codewars.com/kata/550cb646b9e7b565d600048a
6 kyu
<h3>Introduction to Disjunctions</h3> <p>In logic and mathematics, a disjunction is an operation on 2 or more propositions. A disjunction is true if and only if 1 or more of its operands is true. In programming, we typically denote a disjunction using "||", but in logic we typically use "v".</p> <p>Example of disju...
algorithms
from operator import or_, xor from functools import reduce def disjunction(operands, is_exclusive): return reduce([or_, xor][is_exclusive], operands)
Logical Disjunctions
55b019265ff4eeef8c000039
[ "Logic", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/55b019265ff4eeef8c000039
6 kyu
You certainly can tell which is the larger number between 2<sup>10</sup> and 2<sup>15</sup>. But what about, say, 2<sup>10</sup> and 3<sup>10</sup>? You know this one too. Things tend to get a bit more complicated with **both** different bases and exponents: which is larger between 3<sup>9</sup> and 5<sup>6</sup>? W...
algorithms
from math import log def compare_powers(* numbers): a, b = map(lambda n: n[1] * log(n[0]), numbers) return (a < b) - (a > b)
Compare powers
55b2549a781b5336c0000103
[ "Algorithms" ]
https://www.codewars.com/kata/55b2549a781b5336c0000103
6 kyu
You may be familiar with the concept of combinations: for example, if you take 5 cards from a 52 cards deck as you would playing poker, you can have a certain number (2,598,960, would you say?) of different combinations. In mathematics the number of *k* combinations you can have taking from a set of *n* elements is ca...
algorithms
from math import comb as choose
Quick (n choose k) calculator
55b22ef242ad87345c0000b2
[ "Combinatorics", "Algorithms" ]
https://www.codewars.com/kata/55b22ef242ad87345c0000b2
6 kyu
Lucas numbers are numbers in a sequence defined like this: ``` L(0) = 2 L(1) = 1 L(n) = L(n-1) + L(n-2) ``` Your mission is to complete the function that returns the `n`th term of this sequence. **Note:** It should work for negative numbers as well; how you do this is you flip the equation around, so for negative num...
algorithms
def lucasnum(n): a = 2 b = 1 flip = n < 0 and n % 2 != 0 for _ in range(abs(n)): a, b = b, a + b return - a if flip else a
Lucas numbers
55a7de09273f6652b200002e
[ "Algorithms" ]
https://www.codewars.com/kata/55a7de09273f6652b200002e
6 kyu
Create an English to Enigeliisohe Translator, which after each consonant or semivowel inserts in lower case form the last vowel which precedes it in the alphabet. Trivia: Enigeliisohe is a language based on written English, and Esper' phonetics, in which each letter in written English is converted to the Esperanto n...
algorithms
def toexuto(text): output = '' for char in text: output += char for item in 'abcd efgh ijklmn opqrst uvwxyz' . split(): if char . lower() in item[1:]: output += item[0] return output
Enigeliisohe too Eniigeeliiisoohee Toroanisoliatooro
55a5d97d81a010881800004a
[ "Regular Expressions", "Strings", "Algorithms" ]
https://www.codewars.com/kata/55a5d97d81a010881800004a
6 kyu
Write a function that takes an `array / list` of numbers and returns a number. See the examples and try to guess the pattern: ```python (1, 2, 6, 1, 6, 3, 1, 9, 6) => 393 (1, 2, 3) => 5 (0, 2, 3) => 3 (1, 0, 3) => 3 (3, 2) => 6 ```
games
from functools import reduce from operator import add, mul from itertools import cycle def even_odd(arr): ops = cycle((mul, add)) return reduce(lambda x, y: next(ops)(x, y), arr)
Even Odd Pattern #1
559e708e72d342b0c900007b
[ "Logic", "Arrays", "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/559e708e72d342b0c900007b
6 kyu
You're hanging out with your friends in a bar, when suddenly one of them is so drunk, that he can't speak, and when he wants to say something, he writes it down on a paper. However, none of the words he writes make sense to you. He wants to help you, so he points at a beer and writes "yvvi". You start to understand wha...
games
def parse_character(char): if 65 <= ord(char) <= 90: return chr(155 - ord(char)) elif 97 <= ord(char) <= 122: return chr(219 - ord(char)) else: return char def decode(string_): if not isinstance(string_, str): return "Input is not a string" return "" . join(map(parse_ch...
Drunk friend
558ffec0f0584f24250000a0
[ "Strings", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/558ffec0f0584f24250000a0
6 kyu
Given a side length `n`, traveling only right and down how many ways are there to get from the top left corner to the bottom right corner of an `n by n` grid? Your mission is to write a program to do just that! Add code to `route(n)` that returns the number of routes for a grid `n by n` (if n is less than 1 return 0)...
games
from math import factorial def routes(n): return n > 0 and factorial(2 * n) / / factorial(n) * * 2
Routes in a square grid
559aa1295f5c38fd7b0000ac
[ "Fundamentals", "Puzzles" ]
https://www.codewars.com/kata/559aa1295f5c38fd7b0000ac
6 kyu
**Getting Familiar:** <a href="http://simple.wikipedia.org/wiki/Leet" title="example">LEET:</a> (sometimes written as "1337" or "l33t"), also known as eleet or leetspeak, is another alphabet for the English language that is used mostly on the internet. It uses various combinations of ASCII characters to replace Latinat...
reference
trans = str . maketrans("abdeiknoprtuvwxy", "αβδεικηθρπτμυωχγ") def gr33k_l33t(string): return string . lower(). translate(trans)
(L33T + Grεεκ) Case
556025c8710009fc2d000011
[ "Strings", "Algorithms", "Unicode" ]
https://www.codewars.com/kata/556025c8710009fc2d000011
6 kyu
In this kata you have to correctly return who is the "survivor", ie: the last element of a <a href="http://www.codewars.com/kata/josephus-permutation/" target="_blank" title="Josephus sequence">Josephus permutation</a>. Basically you have to assume that n people are put into a circle and that they are eliminated in st...
algorithms
def josephus_survivor(n, k): v = 0 for i in range(1, n + 1): v = (v + k) % i return v + 1
Josephus Survivor
555624b601231dc7a400017a
[ "Mathematics", "Combinatorics", "Algorithms", "Lists", "Arrays" ]
https://www.codewars.com/kata/555624b601231dc7a400017a
5 kyu
This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege. Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: **they formed a circl...
algorithms
def josephus(xs, k): i, ys = 0, [] while len(xs) > 0: i = (i + k - 1) % len(xs) ys . append(xs . pop(i)) return ys
Josephus Permutation
5550d638a99ddb113e0000a2
[ "Mathematics", "Permutations", "Algorithms", "Combinatorics" ]
https://www.codewars.com/kata/5550d638a99ddb113e0000a2
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;">Hungry Hungry Hippos is a tabletop game made for 2–4 players, produced by Hasbro, under the brand of its subsidiary, Milton Bradley. The idea for the game was published in...
reference
class Game (): AROUND = {(- 1, 0), (1, 0), (0, - 1), (0, 1)} def __init__(self, board): self . toCheck = {(x, y) for x in range(len(board)) for y in range(len(board)) if board[x][y] == 1} def play(self): c = 0 while self . toCheck: newInLeap = {self . toCh...
Hungry Hippos
590300eb378a9282ba000095
[ "Games", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/590300eb378a9282ba000095
5 kyu
## Task Given a `matrix`, find its submatrix obtained by deleting the specified rows and emptying the specified columns. ## Input/Output `[input]` 2D integer array `matrix` 2-dimensional array of integers. `1 ≤ matrix.length ≤ 10,` `1 ≤ matrix[0].length ≤ 10,` `0 ≤ matrix[i][j] ≤ 9.` `[input]` integer array `ro...
reference
import numpy as np def construct_submatrix(m, rs, cs): return np . delete(np . delete(m, rs, 0), cs, 1). tolist()
Simple Fun #235: Construct Submatrix
590818ddffa0da26ad00009b
[ "Fundamentals", "Matrix" ]
https://www.codewars.com/kata/590818ddffa0da26ad00009b
7 kyu
You will get an odd integer `n` (`n >= 3`) and your task is to draw an X. The lines are separated by newlines (`\n`). Use the following characters: `'■'` and `'□'` (Ruby, Crystal and PHP: `'o'` and `' '`). ## Examples ``` ■□□□■ ■□■ □■□■□ x(3) =>...
algorithms
def x(n): ret = [['□' for _ in range(n)] for _ in range(n)] for i in range(len(ret)): ret[i][i] = '■' ret[i][- 1 - i] = '■' return '\n' . join('' . join(row) for row in ret)
ASCII Fun #1: X- Shape
5906436806d25f846400009b
[ "ASCII Art" ]
https://www.codewars.com/kata/5906436806d25f846400009b
6 kyu
See the "contour" of a matrix in the following example: ``` M = [[ 1, 3, -4, 5, -2, 5, 1], [2, 0, -7, 6, 8, 8, 15], [4, 4, -2,-10, 7, -1, 7], [-1, 3, 1, 0, 11, 4, 21], [-7, 6, -4, 10, 5, 7, 6], [-5, 4, 3, -5, 7, 8, 17], [-11,3, 4, -8, 6, 16, 4]] ``` It's...
reference
from collections import Counter def countour_mode(m, a, b): v = m[0] + [r[- 1] for r in m[1:]] + m[- 1][: - 1] + [r[0] for r in m[1: - 1]] c = Counter([e for e in v if a <= e <= b]) mx = max(c . values()) return [mx, sorted([k for k in ...
#7 Matrices: Focused on the Contour
590572de63bfadf5d4000027
[ "Matrix", "Algorithms", "Searching", "Fundamentals" ]
https://www.codewars.com/kata/590572de63bfadf5d4000027
6 kyu
*Note: to get straight to the kata you may skip the first two paragraphs* ## Introduction - JoJo's World You may have heard about one of the most popular and influencial Japanese franchises, hailing from the 80s and still running with very good sale figures: <a href="http://en.wikipedia.org/wiki/JoJo's_Bizarre_Advent...
reference
regex = "^(jo[a-zA-Z]* (jo[a-zA-Z]*|[a-zA-Z]*jo))|(gio[a-zA-Z]* gio[a-zA-Z]*)" def is_jojo(name): spl = name . split() return len(spl) > 1 and (spl[0][0: 2] == 'Jo' and (spl[1][- 2:] == 'jo' or spl[1][0: 2] == 'Jo')) or (spl[0][0: 3] == 'Gio' and spl[1][0: 3] == 'Gio')
JoJo's Bizarre Kata
55327e12f5363713200000e4
[ "Fundamentals", "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/55327e12f5363713200000e4
6 kyu
You're a support engineer and you have to write a regex that captures the following information from our log files: - the date - the log level (ERROR, INFO or DEBUG), - the user - the main function - the sub function - the logged message You asked your supervisor about the rules defining all the logs. He told you th...
reference
# Date parsing logparser = ("(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d{3})\s+" # Error level "(ERROR|INFO|DEBUG)\s+" # User, Function, Subfunction "\[(\w+):(\w+)(?::(\w+))?\]\s+" # Error message "(.+)")
Parse the log
558ecd6398ae4ed3350000c2
[ "Regular Expressions", "Parsing", "Fundamentals" ]
https://www.codewars.com/kata/558ecd6398ae4ed3350000c2
6 kyu
Given an integer `n` return `"odd"` if the number of its divisors is odd. Otherwise return `"even"`. **Note**: big inputs will be tested. ## Examples: All prime numbers have exactly two divisors (hence `"even"`). For `n = 12` the divisors are `[1, 2, 3, 4, 6, 12]` – `"even"`. For `n = 4` the divisors are `[1, 2, 4...
algorithms
def oddity(n): # your code here return 'odd' if n * * 0.5 == int(n * * 0.5) else 'even'
Odd/Even number of divisors
55830eec3e6b6c44ff000040
[ "Mathematics", "Performance", "Algorithms" ]
https://www.codewars.com/kata/55830eec3e6b6c44ff000040
6 kyu
Description: ------------ A [triangle number](https://en.wikipedia.org/wiki/Triangular_number) is a number where *n* objects form an equilateral triangle (it's a bit hard to explain). For example, 6 is a triangle number because you can arrange 6 objects into an equilateral triangle: ``` 1 2 3 4 5 6 ``` 8 is not a t...
algorithms
# solution based on the fact that triangle numbers are defined by forumla n(n+1)/2 # so if we have integer n which can fit into formula for our number, then number is triangle # We simply need to solve equation like ax^2+bx+c = 0 and check if answer is integer # 25 ms for 34 tests from math import sqrt def is_triangl...
Triangle number check
557e8a141ca1f4caa70000a6
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/557e8a141ca1f4caa70000a6
6 kyu
### Background We **all** know about "balancing parentheses" (plus brackets, braces and chevrons) and even balancing characters that are identical. Read that last sentence again, I balanced different characters and identical characters twice and you didn't even notice... :) ### Kata Your challenge in this kata is ...
algorithms
def is_balanced(source, caps): source = filter(lambda x: x in caps, source) caps = dict(zip(caps[:: 2], caps[1:: 2])) stack = [] for cap in source: if stack and cap == caps . get(stack[- 1], ''): stack . pop() else: stack . append(cap) return not stack
All that is open must be closed...
55679d644c58e2df2a00009c
[ "Stacks", "Parsing", "Algorithms" ]
https://www.codewars.com/kata/55679d644c58e2df2a00009c
5 kyu
Removed due to copyright infringement. <!--- Vasya isn't really good at math. However, he wants to get a good mark for the class. So he made a deal with his teacher. "I wil study very hard and will be able to solve any given problem!" - Vasya said. Finally, today is the time to show what Vasya achieved. He solved th...
reference
def solution(n, m): return sum(a + max(n - a * a, 0) * * 2 == m for a in range(0, m))
Vasya and System of Equations
556eed2836b302917b0000a3
[ "Fundamentals", "Mathematics", "Algorithms", "Logic", "Numbers", "Algebra", "Puzzles", "Games" ]
https://www.codewars.com/kata/556eed2836b302917b0000a3
6 kyu
### Preface You are currently working together with a local community to build a school teaching children how to code. First plans have been made and the community wants to decide on the best location for the coding school. In order to make this decision data about the location of students and potential locations is co...
algorithms
def optimum_location(students, locations): m = min(locations, key=lambda loc: sum( abs(loc['x'] - s[0]) + abs(loc['y'] - s[1]) for s in students)) return "The best location is number %d with the coordinates x = %d and y = %d" % (m['id'], m['x'], m['y'])
Optimum coding school location
55738b0cffd95756c3000056
[ "Algorithms" ]
https://www.codewars.com/kata/55738b0cffd95756c3000056
6 kyu
# Problem Statement Write a function that takes two string parameters, an IP (v4) address and a subnet mask, and returns two strings: the network block, and the host identifier. The function does not need to support CIDR notation. # Description A single IP address with subnet mask actually specifies several addresses...
algorithms
def ipv4__parser(addr, mask): return tuple("." . join(str(n) for n in a) for a in zip(* (((a & m), (a & ~ m)) for a, m in zip((int(n) for n in addr . split(".")), (int(n) for n in mask . split("."))))))
IPv4 Parser
556d120c7c58dacb9100008b
[ "Networks", "Binary", "Bits", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/556d120c7c58dacb9100008b
6 kyu
It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever ...
algorithms
def ride(group, comet): n1 = 1 n2 = 1 for x in group: n1 *= ord(x . lower()) - 96 for x in comet: n2 *= ord(x . lower()) - 96 if n1 % 47 == n2 % 47: return "GO" else: return "STAY"
Your Ride Is Here
55491e9e50f2fc92f3000074
[ "Algorithms" ]
https://www.codewars.com/kata/55491e9e50f2fc92f3000074
6 kyu
Removed due to copyright infringement. <!--- Vasya wants to climb up a stair of certain amount of steps (Input parameter 1). There are 2 simple rules that he has to stick to. 1. Vasya can climb 1 or 2 steps at each move. 2. Vasya wants the number of moves to be a multiple of a certain integer. (Input parameter 2). ...
algorithms
def numberOfSteps(steps, m): if (steps < m): return - 1 if (steps % 2 == 0 and (steps / 2) % m == 0): return (steps / 2) return (steps / 2) + m - ((steps / 2) % m)
Vasya and Stairs
55251c0d2142d7b4ab000aef
[ "Algorithms", "Mathematics", "Logic", "Numbers", "Fundamentals" ]
https://www.codewars.com/kata/55251c0d2142d7b4ab000aef
6 kyu
# Feynman's squares Richard Phillips Feynman was a well-known American physicist and a recipient of the Nobel Prize in Physics. He worked in theoretical physics and pioneered the field of quantum computing. Recently, an old farmer found some papers and notes that are believed to have belonged to Feynman. Among notes a...
games
def count_squares(n): return n * (n + 1) * (2 * n + 1) / / 6
Feynman's square question
551186edce486caa61000f5c
[ "Puzzles" ]
https://www.codewars.com/kata/551186edce486caa61000f5c
6 kyu
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion). When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it! Your task is to implement class ```Fraction``` that takes care of ...
games
from fractions import Fraction Fraction . to_decimal = lambda f: float(f . numerator) / f . denominator simple_fraction = Fraction . __str__ def mixed_fraction(f): n, d, s = abs(f . numerator), f . denominator, simple_fraction(f) return s . replace(str(n), '%d %d' % divmod(n, d), 1) if 1 < d < n else s Fr...
Precise fractions pt. 1 - basics
54cf4fc26b85dc27bf000a6b
[ "Algorithms", "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/54cf4fc26b85dc27bf000a6b
5 kyu
## Mastermind *Mastermind* is a two-player game where one player creates a four-color code from a possible six colors. The other player has ten turns to guess this code. After each guess, the "codemaker" places pegs corresponding to correct guesses and the "codebreaker" then guesses again, based on these pegs. Black p...
algorithms
def get_hints(answer, guess): black = 0 white = 0 for number in set(guess): white += min(answer . count(number), guess . count(number)) for i, number in enumerate(guess): if number == answer[i]: white -= 1 black += 1 return {"black": black, "white": white}
Mastermind Hint Pegs
54f0d905d49112f3a300055a
[ "Arrays", "Games", "Algorithms" ]
https://www.codewars.com/kata/54f0d905d49112f3a300055a
6 kyu
Calculus class...is awesome! But you are a programmer with no time for mindless repetition. Your teacher spent a whole day covering differentiation of polynomials, and by the time the bell rang, you had already conjured up a program to automate the process. You realize that a polynomial of degree n a<sub>n</sub>x<sup...
algorithms
def diff(poly): return [poly[i] * (len(poly) - 1 - i) for i in range(len(poly) - 1)]
Diff That Poly!
54f4b6e7576d7af70900092b
[ "Mathematics", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/54f4b6e7576d7af70900092b
6 kyu
> **Note**: This kata is a translation of this (Java) one: http://www.codewars.com/kata/rotate-array. I have not translated this first one as usual because I did not solved it, and I fear not being able to solve it (Java is **not** my cup of... tea). @cjmcgraw, if you want to use my translation on your kata feel free ...
algorithms
def rotate(arr, n): # ... n = n % len(arr) return arr[- n:] + arr[: - n]
Rotate Array (JS)
54f8b0c7a58bce9db6000dc4
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/54f8b0c7a58bce9db6000dc4
6 kyu
Build Tower Advanced --- Build Tower by the following given arguments:<br> * __number of floors__ (integer and always greater than 0)<br> * __block size__ (width, height) (integer pair and always greater than (0, 0)) *** Tower block unit is represented as `*`. Tower blocks of block size (2, 1) and (2, 3) would look l...
reference
def tower_builder(n_floors, block_size): w, h = block_size filled_block = '*' * w empty_block = ' ' * w tower = [] for n in range(1, n_floors + 1): for _ in range(h): tower . append(empty_block * (n_floors - n) + filled_block * (2 * n - 1) + empty_block * (n_floors...
Build Tower Advanced
57675f3dedc6f728ee000256
[ "Strings", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/57675f3dedc6f728ee000256
6 kyu
## Do you know how to make a spiral? Let's test it! --- *Classic definition: A spiral is a curve which emanates from a central point, getting progressively farther away as it revolves around the point.* --- Your objective is to complete a function `createSpiral(N)` that receives an integer `N` and returns an `NxN` ...
games
def createSpiral(n): if not isinstance(n, int): return [] d = iter(range(n * * 2)) a = r = [[[x, y] for y in range(n)] for x in range(n)] while a: for x, y in a[0]: r[x][y] = next(d) + 1 a = list(zip(* a[1:]))[:: - 1] return r
The Clockwise Spiral
536a155256eb459b8700077e
[ "Arrays", "Puzzles" ]
https://www.codewars.com/kata/536a155256eb459b8700077e
5 kyu
# Write this function ![](http://i.imgur.com/mlbRlEm.png) `for i from 1 to n`, do `i % m` and return the `sum` f(n=10, m=5) // returns 20 (1+2+3+4+0 + 1+2+3+4+0) *You'll need to get a little clever with performance, since n can be a very large number*
algorithms
def f(n, m): re, c = divmod(n, m) return m * (m - 1) / 2 * re + (c + 1) * c / 2
Sum of many ints
54c2fc0552791928c9000517
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/54c2fc0552791928c9000517
6 kyu
## The galactic games have begun! It's the galactic games! Beings of all worlds come together to compete in several interesting sports, like nroogring, fredling and buzzing (the beefolks love the last one). However, there's also the traditional marathon run. Unfortunately, there have been cheaters in the last years, ...
algorithms
def summ(number, d): n = (number - 1) / / d return n * (n + 1) * d / / 2 def solution(number): return summ(number, 3) + summ(number, 5) - summ(number, 15)
Multiples of 3 and 5 redux
54bb6ee72c4715684d0008f9
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/54bb6ee72c4715684d0008f9
6 kyu
For a given nonempty string `s` find a minimum substring `t` and the maximum number `k`, such that the entire string `s` is equal to `t` repeated `k` times. The input string consists of lowercase latin letters. Your function should return : * a tuple `(t, k)` (in Python) * an array `[t, k]` (in Ruby and JavaScript) *...
algorithms
def f(s): m = __import__('re'). match(r'^(.+?)\1*$', s) return (m . group(1), len(s) / len(m . group(1)))
Repeated Substring
5491689aff74b9b292000334
[ "Algorithms" ]
https://www.codewars.com/kata/5491689aff74b9b292000334
6 kyu
#Source This kata is an application of a magic trick. This magic trick is based on a mathematic algorithm: the Zeckendorf theorem: ``` Every positive integer can be expressed uniquely as a sum of distinct non-consecutive Fibonacci numbers. ``` **Don't be afraid, you don't need to understand the theorem to solve this ...
games
class magicZ (): def __init__(self): self . fib = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89] def gueZZ(self, indexes=[]): return sum(self . fib[i] for i in set(indexes)) def get_magicZ_index(self, n): indexes = [] for i, f in list(enumerate(self . fib))[:: - 1]: if n >= f: n -=...
Magic Zeckendorf
549013f6f71e7786aa0002a8
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/549013f6f71e7786aa0002a8
6 kyu
> [Run-length encoding](https://en.wikipedia.org/w/index.php?title=Run-length_encoding) (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the origina...
algorithms
from itertools import groupby def run_length_encoding(s): return [[sum(1 for _ in g), c] for c, g in groupby(s)]
Run-length encoding
546dba39fa8da224e8000467
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/546dba39fa8da224e8000467
6 kyu
The method below, is the most simple string search algorithm. It will find the first occurrence of a word in a text string. `haystack = the whole text` `needle = searchword` `wildcard = _` ``` find("strike", "i will strike down upon thee"); // return 7 ``` The find method is already made. The problem is to impl...
algorithms
import re def find(needle, haystack): matched = re . search(re . escape(needle). replace('_', '.'), haystack) if matched: return matched . start() return - 1
String searching with wildcard
546c7f89bed2e12fb300056f
[ "Algorithms" ]
https://www.codewars.com/kata/546c7f89bed2e12fb300056f
6 kyu
Given an array (or list) of scores, return the array of _ranks_ for each value in the array. The largest value has rank 1, the second largest value has rank 2, and so on. Ties should be handled by assigning the same rank to all tied values. For example: ranks([9,3,6,10]) = [2,4,3,1] and ranks([3,3,3,3,3,5,1...
algorithms
def ranks(a): sortA = sorted(a, reverse=True) return [sortA . index(s) + 1 for s in a]
Rank Vector
545f05676b42a0a195000d95
[ "Arrays", "Sorting", "Algorithms" ]
https://www.codewars.com/kata/545f05676b42a0a195000d95
6 kyu
There are a **n** balls numbered from 0 to **n-1** (0,1,2,3,etc). Most of them have the same weight, but one is heavier. Your task is to find it. Your function will receive two arguments - a `scales` object, and a ball count. The `scales` object has only one method: ```javascript getWeight(left, right) ``` ```pyt...
games
def find_ball(scales, n): select = list(range(n)) while len(select) > 1: left, right, unused = select[:: 3], select[1:: 3], select[2:: 3] if len(select) % 3 == 1: unused . append(left . pop()) select = [left, unused, right][scales . get_weight(left, right) + 1] return select . pop...
Find heavy ball - level: ubermaster
545c4f7682e55d3c6e0011a1
[ "Algorithms", "Logic", "Puzzles" ]
https://www.codewars.com/kata/545c4f7682e55d3c6e0011a1
5 kyu
Maya writes weekly articles to a well known magazine, but she is missing one word each time she is about to send the article to the editor. The article is not complete without this word. Maya has a friend, Dan, and he is very good with words, but he doesn't like to just give them away. He texts Maya a number and she ne...
reference
def hidden(n): return "" . join("oblietadnm" [int(d)] for d in str(n))
The Hidden Word
5906a218dfeb0dbb52000005
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5906a218dfeb0dbb52000005
7 kyu
There are 8 balls numbered from 0 to 7. Seven of them have the same weight. One is heavier. Your task is to find its number. Your function `findBall` will receive single argument - `scales` object. The `scales` object contains an internally stored array of 8 elements (indexes 0-7), each having the same value except o...
games
def find_ball(scales): part = [[None, 0, 1], [2, 3, 4], [5, 6, 7]] res1 = scales . get_weight(part[- 1], part[1]) res2 = scales . get_weight([part[res1][- 1]], [part[res1][1]]) return part[res1][res2]
Find heavy ball - level: master
544034f426bc6adda200000e
[ "Puzzles", "Logic", "Riddles" ]
https://www.codewars.com/kata/544034f426bc6adda200000e
5 kyu
There are 8 balls numbered from 0 to 7. Seven of them have the same weight. One is heavier. Your task is to find its number. Your function ```findBall``` will receive single argument - ```scales``` object. The ```scales``` object contains an internally stored array of 8 elements (indexes 0-7), each having the same va...
games
def find_ball(scales): balls = [0, 1, 2, 3, 4, 5, 6, 7] while len(balls) > 1: l, r = balls[: len(balls) / / 2], balls[len(balls) / / 2:] w = scales . get_weight(l, r) balls = l if w < 0 else r return balls[0]
Find heavy ball - level: conqueror
54404a06cf36258b08000364
[ "Puzzles", "Logic" ]
https://www.codewars.com/kata/54404a06cf36258b08000364
6 kyu
### Task The __dot product__ is usually encountered in linear algebra or scientific computing. It's also called __scalar product__ or __inner product__ sometimes: > In mathematics, the __dot product__, or __scalar product__ (or sometimes __inner product__ in the context of Euclidean space), is an algebraic operation t...
algorithms
def min_dot(a, b): return sum(x * y for (x, y) in zip(sorted(a), sorted(b, reverse=True)))
Permutations and Dot Products
5457ea88aed18536fc000a2c
[ "Linear Algebra", "Algorithms" ]
https://www.codewars.com/kata/5457ea88aed18536fc000a2c
6 kyu
You want to build a standard house of cards, but you don't know how many cards you will need. Write a program which will count the minimal number of cards according to the number of floors you want to have. For example, if you want a one floor house, you will need 7 of them (two pairs of two cards on the base floor, on...
algorithms
def house_of_cards(n): assert n > 0 return (n + 1) * (3 * n + 4) / / 2
House of cards
543abbc35f0461d28f000c11
[ "Mathematics" ]
https://www.codewars.com/kata/543abbc35f0461d28f000c11
6 kyu
Zonk is an addictive dice game. In each round the player rolls 6 dice. Then (s)he composes combinations of them. Each combination gives certain points. Then player can take one or more dice combinations to their hand and re-roll remaining dice or save the score. Dice in the player's hand won't be taken into account i...
algorithms
from collections import Counter scores = { 1: [100, 200, 1000, 2000, 3000, 4000], 2: [0, 0, 200, 400, 600, 800], 3: [0, 0, 300, 600, 900, 1200], 4: [0, 0, 400, 800, 1200, 1600], 5: [50, 100, 500, 1000, 1500, 2000], 6: [0, 0, 600, 1200, 1800, 2400] } def get_score(dice): dice = ...
Zonk game
53837b8c94c170e55f000811
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/53837b8c94c170e55f000811
5 kyu
A circle is defined by three coplanar points that are not aligned. You will be given a list of circles and a point [xP, yP]. You have to create a function, ```count_circles()``` (Javascript ```countCircles()```), that will count the amount of circles that contains the point P inside (the circle border line is includ...
reference
def circum_curvat(points): A, B, C = [complex(* p) for p in points] BC, CA, AB = B - C, C - A, A - B D = 2. * (A . real * BC + B . real * CA + C . real * AB). imag if not D: return D, D U = (abs(A) * * 2 * BC + abs(B) * * 2 * CA + abs(C) * * 2 * AB) / D radius = (abs(BC) * abs(CA) * abs(...
Circles: Count the Circles Having a Given Internal Point.
57b840b2a6fdc7be02000123
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/57b840b2a6fdc7be02000123
5 kyu
We define the "unfairness" of a list/array as the *minimal* difference between max(x<sub>1</sub>,x<sub>2</sub>,...x<sub>k</sub>) and min(x<sub>1</sub>,x<sub>2</sub>,...x<sub>k</sub>), for all possible combinations of k elements you can take from the list/array; both minimum and maximum of an empty list/array are consid...
algorithms
def min_unfairness(arr, k): arr = sorted(arr) return min(b - a for a, b in zip(arr, arr[k - 1:])) if arr and k else 0
Minimum unfairness of a list/array
577bcb5dd48e5180030004de
[ "Algorithms" ]
https://www.codewars.com/kata/577bcb5dd48e5180030004de
5 kyu
Playing ping-pong can be **really fun**! Unfortunatelly after a long and exciting play you can forget who's service turn it is. Let's do something about that! Write a function that takes the **current score** as a string separated by ```:``` sign as an only parameter and returns ```"first"``` or ```"second"``` depend...
algorithms
def service(score): turn = sum(int(i) for i in score . split(":")) condition = (turn % 10 < 5) if turn < 40 else (turn % 4 < 2) return "first" if condition else "second"
Ping-Pong service problem
544bdc2ec29fb3456e00064a
[ "Algorithms" ]
https://www.codewars.com/kata/544bdc2ec29fb3456e00064a
6 kyu
The goal of this Kata is to return the greatest distance of index positions between matching number values in an array or 0 if there are no matching values. Example: In an array with the values `[0, 2, 1, 2, 4, 1]` the greatest index distance is between the matching '1' values at index 2 and 5. Executing `greatestD...
algorithms
def greatest_distance(arr): return max(i - arr . index(x) for i, x in enumerate(arr))
Greatest Position Distance Between Matching Array Values
5442e4fc7fc447653a0000d5
[ "Algorithms" ]
https://www.codewars.com/kata/5442e4fc7fc447653a0000d5
6 kyu
In another Kata I came across a weird `sort` function to implement. We had to sort characters as usual ( 'A' before 'Z' and 'Z' before 'a' ) except that the `numbers` had to be sorted **after** the `letters` ( '0' after 'z') !!! <p style='font-size:smaller'>(After a couple of hours trying to solve this unusual-sorting...
reference
def unusual_sort(array): return sorted(array, key=lambda x: (str(x). isdigit(), str(x), - isinstance(x, int)))
UN-usual Sort
5443b8857fc4473cb90008e4
[ "Sorting", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5443b8857fc4473cb90008e4
6 kyu