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
# Do you speak retsec? You and your friends want to play undercover agents. In order to exchange your *secret* messages, you've come up with the following system: you take the word, cut it in half, and place the first half behind the latter. If the word has an uneven number of characters, you leave the middle at its pr...
reference
def reverse_by_center(s): n = len(s) / / 2; return s[- n:] + s[n: - n] + s[: n]
Do you speak retsec?
5516ab668915478845000780
[ "Fundamentals" ]
https://www.codewars.com/kata/5516ab668915478845000780
7 kyu
# Task Write a function that returns `true` if a given point `(x,y)` is inside of a unit circle (that is, a "normal" circle with a radius of one) centered at the origin `(0,0)` and returns `false` if the point is outside. # Input * `x`: The first coordinate of the given point. * `y`: The second coordinate of the given...
reference
def point_in_circle(x, y): return (x * x + y * y) < 1
Point in a unit circle
58da7ae9b340a2440500009c
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/58da7ae9b340a2440500009c
7 kyu
In your class, you have started lessons about "arithmetic progression". Because you are also a programmer, you have decided to write a function. This function, arithmetic_sequence_sum(a, r, n), should return the sum of the first (n) elements of a sequence in which each element is the sum of the given integer (a), and ...
reference
def arithmetic_sequence_sum(a, r, n): return n * (a + a + (n - 1) * r) / 2
Arithmetic sequence - sum of n elements
55cb0597e12e896ab6000099
[ "Fundamentals" ]
https://www.codewars.com/kata/55cb0597e12e896ab6000099
7 kyu
Create a rigged dice function that 22% of the time returns the number 6. The rest of the time it returns the integers 1,2,3,4,5 uniformly. --- About the test case There will only be one test case which calls the throw_rigged function 100k times and checks that 6 is returned in the range of 21700-22300 (inclusive) ti...
refactoring
import random def throw_rigged(): return 6 if random . random() <= .22 else random . randrange(1, 6)
Rigged Dice
573acc8cffc3d13f61000533
[ "Probability", "Refactoring" ]
https://www.codewars.com/kata/573acc8cffc3d13f61000533
7 kyu
You found a magic dice which has infinitely many faces showing all the numbers 1,2,3,4,5,.... By rolling the magic dice infinitely many times, you find out that the probability to get the number n is 1/2^n. You meet your friend who tells you that he has found another magic dice with infinitely many faces 0,1,2,3,4,5 ....
games
def magicdice(n): return ((2 * * n) * * 3 - (2 * * n - 1) * * 3, (2 * * n) * * 3)
Magic Dice: Who wins?
589e2af835999cbe2f000229
[ "Puzzles" ]
https://www.codewars.com/kata/589e2af835999cbe2f000229
6 kyu
Given an integer, return a string with dash `'-'` marks before and after each odd digit, but do not begin or end the string with a dash mark. Ex: ```javascript 274 -> '2-7-4' 6815 -> '68-1-5' ```
reference
import re def dashatize(num): try: return '' . join(['-' + i + '-' if int(i) % 2 else i for i in str(abs(num))]). replace('--', '-'). strip('-') except: return 'None'
Dashatize it
58223370aef9fc03fd000071
[ "Strings", "Arrays", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/58223370aef9fc03fd000071
6 kyu
Given a string, swap the case for each of the letters. ### Examples ``` "" --> "" "CodeWars" --> "cODEwARS" "abc" --> "ABC" "ABC" --> "abc" "123235" --> "123235" ```
reference
def swap(string_): return string_ . swapcase()
Case Swapping
5590961e6620c0825000008f
[ "Fundamentals" ]
https://www.codewars.com/kata/5590961e6620c0825000008f
7 kyu
*Are you a file extension master? Let's find out by checking if Bill's files are images or audio files. Please use regex if available natively for your language.* You will create 2 string methods: - **isAudio/is_audio**, matching 1 or + uppercase/lowercase letter(s) (combination possible), with the extension .mp3, .f...
reference
def is_audio(filename): name, ext = filename . split('.') return name . isalpha() and ext in {'mp3', 'flac', 'alac', 'aac'} def is_img(filename): name, ext = filename . split('.') return name . isalpha() and ext in {'jpg', 'jpeg', 'png', 'bmp', 'gif'}
Master of Files
574bd867d277832448000adf
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/574bd867d277832448000adf
6 kyu
Each floating-point number should be formatted that only the first two decimal places are returned. You don't need to check whether the input is a valid number because only valid numbers are used in the tests. Don't round the numbers! Just cut them after two decimal places! ``` Right examples: 32.8493 is 32.84 1...
reference
def two_decimal_places(number): return int(number * 100) / 100.0
Formatting decimal places #1
5641c3f809bf31f008000042
[ "Fundamentals" ]
https://www.codewars.com/kata/5641c3f809bf31f008000042
7 kyu
## Task Remove all exclamation marks from the end of words. Words are separated by a single space. There are no exclamation marks within a word. ### Examples ``` remove("Hi!") === "Hi" remove("Hi!!!") === "Hi" remove("!Hi") === "!Hi" remove("!Hi!") === "!Hi" remove("Hi! Hi!") === "Hi Hi" remove("!!!Hi !!hi!!! !hi") ...
reference
def remove(s): return ' ' . join(w . rstrip('!') or w for w in s . split())
Exclamation marks series #5: Remove all exclamation marks from the end of words
57faf32df815ebd49e000117
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/57faf32df815ebd49e000117
7 kyu
Complete the method which accepts an array of integers, and returns one of the following: * `"yes, ascending"` - if the numbers in the array are sorted in an ascending order * `"yes, descending"` - if the numbers in the array are sorted in a descending order * `"no"` - otherwise You can assume the array will always ...
reference
def is_sorted_and_how(arr): if arr == sorted(arr): return 'yes, ascending' elif arr == sorted(arr)[:: - 1]: return 'yes, descending' else: return 'no'
Sorted? yes? no? how?
580a4734d6df748060000045
[ "Arrays", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/580a4734d6df748060000045
7 kyu
Your friend Rick is trying to send you a message, but he is concerned that it would get intercepted by his partner. He came up with a solution: 1) Add digits in random places within the message. 2) Split the resulting message in two. He wrote down every second character on one page, and the remaining ones on another....
reference
def interweave(s1, s2): s = [''] * (len(s1) + len(s2)) s[:: 2], s[1:: 2] = s1, s2 return '' . join(c for c in s if not c . isdigit()). strip()
Interweaving strings and removing digits
588a7d45019c42be61000009
[ "Fundamentals" ]
https://www.codewars.com/kata/588a7d45019c42be61000009
7 kyu
<div style="border:1px solid; padding:1ex;">Inspired by <a href="/kata/55d1d6d5955ec6365400006d">Round to the next 5</a>. <strong>Warning!</strong> This kata contains spoilers on the mentioned one. Solve that one first!</div> # The Coins of Ter Ter is a small country, located between Brelnam and the Orange juice ocea...
games
def adjust(coin, price): return price + (coin - price) % coin
The Coins of Ter | Round to the Next N
55d38b959f9c33f3fb00007d
[ "Puzzles" ]
https://www.codewars.com/kata/55d38b959f9c33f3fb00007d
7 kyu
Given an integer as input, can you round it to the next (meaning, "greater than or equal") multiple of 5? Examples: input: output: 0 -> 0 2 -> 5 3 -> 5 12 -> 15 21 -> 25 30 -> 30 -2 -> 0 -5 -> -5 etc. Input may be any positive or negative...
reference
def round_to_next5(n): return n + (5 - n) % 5
Round up to the next multiple of 5
55d1d6d5955ec6365400006d
[ "Fundamentals" ]
https://www.codewars.com/kata/55d1d6d5955ec6365400006d
7 kyu
Given a credit card number we can determine who the issuer/vendor is with a few basic knowns. ```if:python Complete the function `get_issuer()` that will use the values shown below to determine the card issuer for a given card number. If the number cannot be matched then the function should return the string `Unknown`...
algorithms
def get_issuer(number): s = str(number) return ("AMEX" if len(s) == 15 and s[: 2] in ("34", "37") else "Discover" if len(s) == 16 and s . startswith("6011") else "Mastercard" if len(s) == 16 and s[0] == "5" and s[1] in "12345" else "VISA" if len(s) in [13, 16] and s[0] == '4'...
Credit card issuer checking
5701e43f86306a615c001868
[ "Algorithms" ]
https://www.codewars.com/kata/5701e43f86306a615c001868
7 kyu
# Valid HK Phone Number ## Overview In Hong Kong, a valid phone number has the format ```xxxx xxxx``` where ```x``` is a decimal digit (0-9). For example: ```javascript "1234 5678" // is valid "2359 1478" // is valid "85748475" // invalid, as there are no spaces separating the first 4 and last 4 digits "3857 4756"...
reference
import re HK_PHONE_NUMBER = '\d{4} \d{4}' def is_valid_HK_phone_number(number): return bool(re . match(HK_PHONE_NUMBER + '\Z', number)) def has_valid_HK_phone_number(number): return bool(re . search(HK_PHONE_NUMBER, number))
Valid HK Phone Number
56f54d45af5b1fec4b000cce
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/56f54d45af5b1fec4b000cce
7 kyu
Write a function that takes one or more arrays and returns a new array of unique values in the order of the original provided arrays. In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array. The unique numbers should be sorted by their o...
algorithms
def unite_unique(* arg): res = [] for arr in arg: for val in arr: if not val in res: res . append(val) return res
Sorted Union
5729c30961cecadc4f001878
[ "Arrays", "Lists", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/5729c30961cecadc4f001878
7 kyu
Your job is to build a function which determines whether or not there are double characters in a string (including whitespace characters). For example ```aa```, ``!!`` or ``` ```. You want the function to return true if the string contains double characters and false if not. The test should not be case sensitive; ...
reference
import re def double_check(str): return bool(re . search(r"(.)\1", str . lower()))
Are there doubles?
56a24b4d9f3671584d000039
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/56a24b4d9f3671584d000039
7 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
def testit(act, s): dic = {("run", "_"): "_", ("run", "|"): "/", ("jump", "|"): "|", ("jump", "_"): "x"} return "" . join([dic[act[i], s[i]] for i in range(len(s))])
Thinking & Testing : Sport Star
56dd927e4c9055f8470013a5
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56dd927e4c9055f8470013a5
7 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! ## Series 01. [A and B?](http://www.codewars.com/kata/56d904db9963e9cf5000037d) 02. [Incomplete string](http://www.codewars.com/kata/56d9292cc11bcc3629000533) 03. [True or False](http://www.codewars.com/kata/56d931ecc4...
games
def testit(a, b): return sorted(list(set(a)) + list(set(b)))
Thinking & Testing : Uniq or not Uniq
56d949281b5fdc7666000004
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56d949281b5fdc7666000004
7 kyu
Implement `String#ipv4_address?`, which should return true if given object is an IPv4 address - four numbers (0-255) separated by dots. It should only accept addresses in canonical representation, so no leading `0`s, spaces etc.
reference
from re import compile, match REGEX = compile(r'((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){4}$') def ipv4_address(address): # refactored thanks to @leonoverweel on CodeWars return bool(match(REGEX, address + '.'))
Regexp Basics - is it IPv4 address?
567fe8b50c201947bc000056
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/567fe8b50c201947bc000056
6 kyu
For every positive integer N, there exists a unique sequence starting with 1 and ending with N and such that every number in the sequence is either the double of the preceeding number or the double plus 1. For example, given N = 13, the sequence is [1, 3, 6, 13], because . . . : ``` 3 = 2*1 +1 6 = 2*3 13 = 2*6 +...
reference
# If we write the decision tree for the problem we can see # that we can traverse upwards from any node simply by # dividing by two and taking the floor. This would require # a reversal of the list generated since we're building it # backwards. # # If we examine the successor function (x -> {2x, 2x + 1}) # we can deduc...
Number climber
559760bae64c31556c00006b
[ "Fundamentals" ]
https://www.codewars.com/kata/559760bae64c31556c00006b
7 kyu
# Task Let's consider a table consisting of `n` rows and `n` columns. The cell located at the intersection of the i-th row and the j-th column contains number i × j. The rows and columns are numbered starting from 1. You are given a positive integer `x`. Your task is to count the number of cells in a table that cont...
algorithms
def count_number(n, x): return len([j for j in range(1, n + 1) if x % j == 0 and x / j <= n])
Simple Fun #172: Count Number
58b635903e78b34958000056
[ "Algorithms" ]
https://www.codewars.com/kata/58b635903e78b34958000056
7 kyu
Welcome. In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. `"a" = 1`, `"b" = 2`, etc. ## Example <!-- unlisted languages will use the first entry. please keep python up top. --> ```python ...
reference
def alphabet_position(text): return ' ' . join(str(ord(c) - 96) for c in text . lower() if c . isalpha())
Replace With Alphabet Position
546f922b54af40e1e90001da
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/546f922b54af40e1e90001da
6 kyu
Write a function that returns the number of occurrences of an element in an array. ~~~if:javascript This function will be defined as a property of Array with the help of the method `Object.defineProperty`, which allows to define a new method **directly** on the object (more info about that you can find on [MDN](https:...
reference
def number_of_occurrences(s, xs): return xs . count(s)
Number Of Occurrences
52829c5fe08baf7edc00122b
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/52829c5fe08baf7edc00122b
7 kyu
# Task We define the weakness of number `n` as the number of positive integers smaller than `n` that have more divisors than `n`. It follows that the weaker the number, the greater overall weakness it has. For the given integer `n`, you need to answer two questions: * what is the weakness of the weakest numbers in t...
games
def weak_numbers(n): d = [0] + [len([1 for i in range(1, j + 1) if j % i == 0]) for j in range(1, n + 1)] w = [len([1 for i in range(1, j) if d[i] > d[j]]) for j in range(1, n + 1)] m = max(w) return [m, w . count(m)]
Simple Fun #26: Weak Numbers
5886dea04703f1712d000051
[ "Puzzles" ]
https://www.codewars.com/kata/5886dea04703f1712d000051
5 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! # #Series:<br> <a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br> <a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br> <a href="http://www.c...
games
def mystery((a, b, c, d), (e, f, g, h)): return [a * e + b * g, a * f + b * h, c * e + d * g, c * f + d * h]
Thinking & Testing : Math of Middle school
56d9c274c550b4a5c2000d92
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56d9c274c550b4a5c2000d92
7 kyu
No Story No Description Only by Thinking and Testing Look at the results of the testcases, and guess the code! --- ## Series: 01. [A and B?](http://www.codewars.com/kata/56d904db9963e9cf5000037d) 02. [Incomplete string](http://www.codewars.com/kata/56d9292cc11bcc3629000533) 03. [True or False](http://www.codewars...
games
def mystery(n): return [i for i in range(1, n + 1, 2) if n % i == 0]
Thinking & Testing : Retention and discard
56ee0448588cbb60740013b9
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56ee0448588cbb60740013b9
7 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
from itertools import compress def mystery(s, n): return '' . join(compress(s, map(int, format(n, 'b'))))
Thinking & Testing : Retention and discard II
56eee006ff32e1b5b0000c32
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56eee006ff32e1b5b0000c32
7 kyu
# Task Initially a number `1` is written on a board. It is possible to do the following operations with it: ``` multiply the number by 3; increase the number by 5.``` Your task is to determine that using this two operations step by step, is it possible to obtain number `n`? # Example For `n = 1`, the result should ...
games
def number_increasing(n): return n not in {2, 4, 7, 12, 17, 22} and n % 5 != 0
Simple Fun #113: Number Increasing
589d1e88e8afb7a85e00004e
[ "Puzzles" ]
https://www.codewars.com/kata/589d1e88e8afb7a85e00004e
7 kyu
# Task Call two arms equally strong if the heaviest weights they each are able to lift are equal. Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms. Given your and your friend's arms' lifting capabilities ...
games
def are_equally_strong(your_left, your_right, friends_left, friends_right): return sorted([your_left, your_right]) == sorted([friends_left, friends_right])
Simple Fun #69: Are Equally Strong?
5894017082b9fb62c50000df
[ "Puzzles" ]
https://www.codewars.com/kata/5894017082b9fb62c50000df
7 kyu
# Task Let's call two integers A and B friends if each integer from the array divisors is either a divisor of both A and B or neither A nor B. If two integers are friends, they are said to be in the same clan. How many clans are the integers from 1 to k, inclusive, broken into? # Example For `divisors = [2, 3] and ...
games
def number_of_clans(divisors, k): return len({tuple(d for d in divisors if not n % d) for n in range(1, k + 1)})
Simple Fun #21: Number Of Clans
5886cab0a95e17e61600009d
[ "Puzzles" ]
https://www.codewars.com/kata/5886cab0a95e17e61600009d
7 kyu
We are still with squared integers. Given 4 integers `a, b, c, d` we form the sum of the squares of `a` and `b` and then the sum of the squares of `c` and `d`. We multiply the two sums hence a number `n` and we try to decompose `n` in a sum of two squares `e` and `f` (e and f integers >= 0) so that `n = e² + f²`. Mo...
reference
def prod2sum(a, b, c, d): e = sorted([abs(a * d - b * c), abs(a * c + b * d)]) f = sorted([abs(a * c - b * d), abs(a * d + b * c)]) if e == f: return [e] else: return sorted([e, f])
Integers: Recreation Two
55e86e212fce2aae75000060
[ "Fundamentals", "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/55e86e212fce2aae75000060
6 kyu
# Task You are given a sequence of positive ints where every element appears `three times`, except one that appears only `once` (let's call it `x`) and one that appears only `twice` (let's call it `y`). Your task is to find `x * x * y`. # Example For `arr=[1, 1, 1, 2, 2, 3]`, the result should be `18` `3 x 3 ...
games
def missing_values(seq): a, b = sorted(seq, key=seq . count)[: 2] return a * a * b
Simple Fun #136: Missing Values
58a66c208b88b2de660000c3
[ "Puzzles" ]
https://www.codewars.com/kata/58a66c208b88b2de660000c3
7 kyu
In this kata we have to create a function that will give us some specific information of a data base. We have a sequence of postive integers that is registered by OEIS with the code [001055](https://oeis.org/A001055). This sequence give us the amount of ways that a number may be expressed as a product of its factors (i...
reference
import operator def inf_database(range_, str_, val): ops = {"higher than": operator . gt, "lower than": operator . lt, "equals to": operator . eq, "higher and equals to": operator . ge, "lower and equals to": operator . le} if str_ not in ops: return "wrong constraint" result = [i f...
Working with Dictionaries
5639302a802494696d000077
[ "Fundamentals", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/5639302a802494696d000077
7 kyu
# Task Reversing an array can be a tough task, especially for a novice programmer. Mary just started coding, so she would like to start with something basic at first. Instead of reversing the array entirely, she wants to swap just its first and last elements. Given an array `arr`, swap its `first` and `last` element...
games
def first_reverse_try(arr): if arr: arr[0], arr[- 1] = arr[- 1], arr[0] return arr
Simple Fun #20: First Reverse Try
5886c6b2f3b6ae33dd0000be
[ "Puzzles" ]
https://www.codewars.com/kata/5886c6b2f3b6ae33dd0000be
7 kyu
# Task We define the middle of the array `arr` as follows: if `arr` contains an odd number of elements, its middle is the element whose index number is the same when counting from the beginning of the array and from its end; if `arr` contains an even number of elements, its middle is the sum of the two elements wh...
games
def is_smooth(arr): d, m = divmod(len(arr), 2) return arr[0] == arr[- 1] == arr[d] + arr[d - 1] * (m == 0)
Simple Fun #22: Is Smooth?
5886d35d4703f125a6000008
[ "Puzzles" ]
https://www.codewars.com/kata/5886d35d4703f125a6000008
7 kyu
# Task You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it. Given the starting HTML tag, find the appropriate end tag which your editor should propose. # Example For startTag = "&lt;button type='button' disabled>", the output...
games
def html_end_tag_by_start_tag(start_tag): return "</" + start_tag[1: - 1]. split(" ")[0] + ">"
Simple Fun #28: Html End Tag By Start Tag
5886f3713a111b620f0000dc
[ "Puzzles" ]
https://www.codewars.com/kata/5886f3713a111b620f0000dc
7 kyu
# Task How many strings equal to A can be constructed using letters from the string B? Each letter can be used only once and in one string only. # Example For `A = "abc" and B = "abccba"`, the output should be `2`. We can construct 2 strings `A` with letters from `B`. # Input/Output - `[input]` string `A` ...
games
def strings_construction(A, B): return min(B . count(i) / / A . count(i) for i in set(A))
Simple Fun #30: Strings Construction
58870402c81516bbdb000088
[ "Puzzles" ]
https://www.codewars.com/kata/58870402c81516bbdb000088
7 kyu
# Task Elections are in progress! Given an array of numbers representing votes given to each of the candidates, and an integer which is equal to the number of voters who haven't cast their vote yet, find the number of candidates who still have a chance to win the election. The winner of the election must secure stri...
games
def elections_winners(votes, k): m = max(votes) return sum(x + k > m for x in votes) or votes . count(m) == 1
Simple Fun #41: Elections Winners
58881b859ab1e053240000cc
[ "Puzzles" ]
https://www.codewars.com/kata/58881b859ab1e053240000cc
7 kyu
## Your story You've always loved both <a href="https://en.wikipedia.org/wiki/Fizz_buzz">Fizz Buzz</a> katas and <a href="https://en.wikipedia.org/wiki/Cuckoo_clock">cuckoo clocks</a>, and when you walked by a garage sale and saw an ornate cuckoo clock with a missing pendulum, and a "Beyond-Ultimate <a href="https://en...
reference
def fizz_buzz_cuckoo_clock(time): hh, mm = map(int, time . split(":")) if mm == 0: return " " . join(["Cuckoo"] * (hh % 12 or 12)) elif mm == 30: return "Cuckoo" elif mm % 15 == 0: return "Fizz Buzz" elif mm % 3 == 0: return "Fizz" elif mm % 5 == 0: ...
Fizz Buzz Cuckoo Clock
58485a43d750d23bad0000e6
[ "Fundamentals" ]
https://www.codewars.com/kata/58485a43d750d23bad0000e6
7 kyu
You're familiar with [list slicing](https://docs.python.org/3/library/functions.html#slice) in Python and know, for example, that: ```python >>> ages = [12, 14, 63, 72, 55, 24] >>> ages[2:4] [63, 72] >>> ages[2:] [63, 72, 55, 24] >>> ages[:3] [12, 14, 63] ``` Write a function `inverse_slice` that takes three argument...
reference
def inverse_slice(items, a, b): return items[: a] + items[b:]
Thinkful - List and Loop Drills: Inverse Slicer
586ec0b8d098206cce001141
[ "Fundamentals", "Lists" ]
https://www.codewars.com/kata/586ec0b8d098206cce001141
7 kyu
# Task You are given a digital `number` written down on a sheet of paper. Your task is to figure out if you rotate the given sheet of paper by 180 degrees would the number still look exactly the same. Note: You can assume that the digital number is written like the following image: <svg xmlns="http://www.w3.or...
games
def rotate_paper(number): return number == number . translate(str . maketrans('69', '96', '1347'))[:: - 1]
Simple Fun #156: Rotate Paper By 180 Degrees
58ad230ce0201e17080001c5
[ "Puzzles" ]
https://www.codewars.com/kata/58ad230ce0201e17080001c5
6 kyu
# Task John loves encryption. He can encrypt any string by the following algorithm: ``` take the first and the last letters of the word; replace the letters between them with their number; replace this number with the sum of it digits until a single digit is obtained.``` Given two strings(`s1` and `s2`), re...
algorithms
def same_encryption(s1, s2): return (s1[0], s1[- 1], len(s1) % 9) == (s2[0], s2[- 1], len(s2) % 9)
Simple Fun #175: Same Encryption
58b6c403a38abaaf6c00006b
[ "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/58b6c403a38abaaf6c00006b
7 kyu
# Task Given some sticks by an array `V` of positive integers, where V[i] represents the length of the sticks, find the number of ways we can choose three of them to form a triangle. # Example For `V = [2, 3, 7, 4]`, the result should be `1`. There is only `(2, 3, 4)` can form a triangle. For `V = [5, 6, 7, 8]`...
algorithms
from itertools import combinations def counting_triangles(v): v . sort() return sum(a + b > c for a, b, c in combinations(v, 3))
Simple Fun #157: Counting Triangles
58ad29bc4b852b14a4000050
[ "Algorithms" ]
https://www.codewars.com/kata/58ad29bc4b852b14a4000050
7 kyu
# Task When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover. You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles a...
games
def candles(candles, make_new): return candles + (candles - 1) / / (make_new - 1)
Simple Fun #18: Candles
5884731139a9b4b7a8000002
[ "Puzzles" ]
https://www.codewars.com/kata/5884731139a9b4b7a8000002
7 kyu
# Task We want to turn the given integer into a number that has only one non-zero digit using a tail rounding approach. This means that at each step we take the last non 0 digit of the number and round it to 0 or to 10. If it's less than 5 we round it to 0 if it's larger than or equal to 5 we round it to 10 (rounding ...
reference
def rounders(value): mag = 1 while value > 10: value, r = divmod(value, 10) value += r > 4 mag *= 10 return value * mag
Simple Fun #17: Rounders
58846d50f54f021d90000012
[ "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/58846d50f54f021d90000012
7 kyu
# Task There're `k` square apple boxes full of apples. If a box is of size `m`, then it contains m × m apples. You noticed two interesting properties about the boxes: ``` The smallest box is of size 1, the next one is of size 2,..., all the way up to size k. Boxes that have an odd size contain only yellow app...
games
def apple_boxes(k): return sum(- (i * i) if i & 1 else i * i for i in range(1, k + 1))
Simple Fun #16: Apple Boxes
58846b46f4456a8919000025
[ "Puzzles" ]
https://www.codewars.com/kata/58846b46f4456a8919000025
7 kyu
# Task You are standing at a magical well. It has two positive integers written on it: `a` and `b`. Each time you cast a magic marble into the well, it gives you `a * b` dollars and then both `a` and `b` increase by 1. You have `n` magic marbles. How much money will you make? # Example For a = 1, b = 2 and n = 2, t...
games
def magical_well(a, b, n): return sum((a + i) * (b + i) for i in range(n))
Simple Fun #13: Magical Well
588463cae61257e44600006d
[ "Puzzles" ]
https://www.codewars.com/kata/588463cae61257e44600006d
7 kyu
# Task Given integers `n`, `l` and `r`, find the number of ways to represent `n` as a sum of two integers A and B such that `l ≤ A ≤ B ≤ r`. # Example For n = 6, l = 2 and r = 4, the output should be `2` There are just two ways to write 6 as A + B, where 2 ≤ A ≤ B ≤ 4: `6 = 2 + 4` and `6 = 3 + 3` # Input/Out...
games
def count_sum_of_two_representations(n, l, r): return max((min(r, n - l) - max(l, n - r)) / / 2 + 1, 0)
Simple Fun #12: Count Sum of Two Representions
5884615cbd573356ab000050
[ "Puzzles" ]
https://www.codewars.com/kata/5884615cbd573356ab000050
7 kyu
# Task You are given a 32-bit integer `n`. Swap each pair of adjacent bits in its binary representation and return the result as a decimal number. The potential leading zeroes of the binary representations have to be taken into account, e.g. `0b100` as a 32-bit integer is `0b00000000000000000000000000000100` and is r...
games
def swap_adjacent_bits(n): return (n & 0x55555555) << 1 | (n & 0xaaaaaaaa) >> 1
Simple Fun #11: Swap Adjacent Bits
58845a92bd573378f4000035
[ "Puzzles" ]
https://www.codewars.com/kata/58845a92bd573378f4000035
7 kyu
# Task Let's say that number a feels comfortable with number b if a ≠ b and b lies in the segment` [a - s(a), a + s(a)]`, where `s(x)` is the sum of x's digits. How many pairs (a, b) are there, such that a < b, both a and b lie on the segment `[L, R]`, and each number feels comfortable with the other? # Example F...
games
def comfortable_numbers(l, r): s = [sum(map(int, str(n))) for n in range(l, r + 1)] return sum(s[i] >= i - j <= s[j] for i in range(1, len(s)) for j in range(i))
Simple Fun #25: Comfortable Numbers
5886dbc685d5788715000071
[ "Puzzles" ]
https://www.codewars.com/kata/5886dbc685d5788715000071
6 kyu
We want to generate all the numbers of three digits where: - the sum of their digits is equal to `10` - their digits are in increasing order (the numbers may have two or more equal contiguous digits) The numbers that fulfill these constraints are: `[118, 127, 136, 145, 226, 235, 244, 334]`. There're `8` numbers in to...
reference
from itertools import combinations_with_replacement def find_all(sum_dig, digs): combs = combinations_with_replacement(list(range(1, 10)), digs) target = ['' . join(str(x) for x in list(comb)) for comb in combs if sum(comb) == sum_dig] if not target: return [] return [len(ta...
How many numbers III?
5877e7d568909e5ff90017e6
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/5877e7d568909e5ff90017e6
4 kyu
# Task A cake is sliced with `n` straight lines. Your task is to calculate the maximum number of pieces the cake can have. # Example For `n = 0`, the output should be `1`. For `n = 1`, the output should be `2`. For `n = 2`, the output should be `4`. For `n = 3`, the output should be `7`. See the followin...
games
def cake_slice(n): return (n * * 2 + n + 2) / / 2
Simple Fun #198: Cake Slice
58c8a41bedb423240a000007
[ "Puzzles" ]
https://www.codewars.com/kata/58c8a41bedb423240a000007
7 kyu
Today was a sad day. Having bought a new beard trimmer, I set it to the max setting and shaved away at my joyous beard. Stupidly, I hadnt checked just how long the max setting was, and now I look like Ive just started growing it! Your task, given a beard represented as an arrayof arrays, is to trim the beard as follow...
reference
def trim(beard): return [[h . replace("J", "|") for h in b] for b in beard[: - 1]] + [["..."] * len(beard[0])]
Shaving the Beard
57efa1a2108d3f73f60000e9
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/57efa1a2108d3f73f60000e9
7 kyu
You would like to get the 'weight' of a name by getting the sum of the ascii values. However you believe that capital letters should be worth more than mere lowercase letters. Spaces, numbers, or any other character are worth 0. Normally in ascii a has a value of 97 A has a value of 65 ' ' has a value of ...
reference
def get_weight(name): return sum(ord(a) for a in name . swapcase() if a . isalpha())
Disagreeable ascii
582cb3a637c5583f2200005d
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/582cb3a637c5583f2200005d
7 kyu
Finding your seat on a plane is never fun, particularly for a long haul flight... You arrive, realise again just how little leg room you get, and sort of climb into the seat covered in a pile of your own stuff. To help confuse matters (although they claim in an effort to do the opposite) many airlines omit the letters...
reference
def plane_seat(a): front, middle, back = (range(1, 21), range(21, 41), range(41, 61)) left, center, right = ('ABC', 'DEF', "GHK") x, y = ('', '') if int(a[: - 1]) in front: x = 'Front-' if int(a[: - 1]) in middle: x = 'Middle-' if int(a[: - 1]) in back: x = 'Back-' i...
Holiday II - Plane Seating
57e8f757085f7c7d6300009a
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57e8f757085f7c7d6300009a
7 kyu
Your dad doesn't really *get* punctuation, and he's always putting extra commas in when he posts. You can tolerate the run-on sentences, as he does actually talk like that, but those extra commas have to go! Write a function called ```dadFilter``` that takes a string as argument and returns a string with the extraneou...
reference
from re import compile, sub REGEX = compile(r',+') def dad_filter(strng): return sub(REGEX, ',', strng). rstrip(' ,')
Dad is Commatose
56a24b309f3671608b00003a
[ "Fundamentals", "Strings", "Regular Expressions" ]
https://www.codewars.com/kata/56a24b309f3671608b00003a
7 kyu
**Task:** Find the number couple with the greatest difference from a list of number-couples. **Input:** A list of number-couples, where each couple is represented as a string containing two positive integers separated by a hyphen ("-"). **Output:** The number couple with the greatest difference, or `False` if there i...
reference
def diff(arr): r = arr and max(arr, key=lambda x: abs(eval(x))) return bool(arr and eval(r)) and r
Greatest Difference
56b12e3ad2387de332000041
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/56b12e3ad2387de332000041
7 kyu
Implement function `createTemplate` which takes string with tags wrapped in `{{brackets}}` as input and returns closure, which can fill string with data (flat object, where keys are tag names). ```javascript let personTmpl = createTemplate("{{name}} likes {{animalType}}"); personTmpl({ name: "John", animalType: "dogs"...
reference
from jinja2 import Template def create_template(template): return lambda * * vals: Template(template). render(vals)
Simple template
56ae72854d005c7447000023
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/56ae72854d005c7447000023
7 kyu
Just as the title suggestes :D . For example -> ``` largest(1); //Should return 7 largest(2); //Should return 97 .... ``` Do not mind the pattern as it is just an incident ! And make sure to return false if the input is not an integer :D This might seem simple at first, it is, but keep an eye on the performance. Go for...
games
def largest(n): return [7, 97, 997, 9973, 99991, 999983][n - 1] if type(n) == int and n > 0 else False
Largest prime number containing n digit
5676f07029da352ba2000065
[ "Algorithms", "Puzzles", "Fundamentals", "Performance" ]
https://www.codewars.com/kata/5676f07029da352ba2000065
7 kyu
A *perfect number* is a number in which the sum of its divisors (excluding itself) are equal to itself. Write a function that can verify if the given integer `n` is a perfect number, and return `True` if it is, or return `False` if not. ## Examples `n = 28` has the following divisors: `1, 2, 4, 7, 14, 28` `1 + 2 ...
algorithms
def isPerfect(n): return n in [6, 28, 496, 8128, 33550336, 8589869056, 137438691328]
Perfect Number Verifier
56a28c30d7eb6acef700004d
[ "Algorithms" ]
https://www.codewars.com/kata/56a28c30d7eb6acef700004d
7 kyu
~~~if-not:prolog ## Write a generic function chainer Write a generic function chainer that takes a starting value, and an array of functions to execute on it (array of symbols for Ruby). The input for each function is the output of the previous function (except the first function, which takes the starting value as it...
reference
def chain(value, functions): for f in functions: value = f(value) return value
Chain me
54fb853b2c8785dd5e000957
[ "Fundamentals" ]
https://www.codewars.com/kata/54fb853b2c8785dd5e000957
7 kyu
Given a sequence of numbers, find the largest pair sum in the sequence. For example ``` [10, 14, 2, 23, 19] --> 42 (= 23 + 19) [99, 2, 2, 23, 19] --> 122 (= 99 + 23) ``` Input sequence contains minimum two elements and every element is an integer.
reference
def largest_pair_sum(numbers): return sum(sorted(numbers)[- 2:])
Largest pair sum in array
556196a6091a7e7f58000018
[ "Fundamentals" ]
https://www.codewars.com/kata/556196a6091a7e7f58000018
7 kyu
It is 2050 and romance has long gone, relationships exist solely for practicality. MatchMyHusband is a website that matches busy working women with perfect house husbands. You have been employed by MatchMyHusband to write a function that determines who matches!! The rules are... a match occurs providing the husband's...
reference
def match(usefulness, months): return "Match!" if sum(usefulness) >= 0.85 * * months * 100 else "No match!"
Match My Husband
5750699bcac40b3ed80001ca
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5750699bcac40b3ed80001ca
7 kyu
Apparently "Put A Pillow On Your Fridge Day is celebrated on the 29th of May each year, in Europe and the U.S. The day is all about prosperity, good fortune, and having bit of fun along the way." All seems very weird to me. Nevertheless, you will be given an array of two strings (s). First find out if the first strin...
reference
def pillow(s): return ('n', 'B') in zip(* s)
Pillow on the Fridge
57d147bcc98a521016000320
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57d147bcc98a521016000320
7 kyu
# Story Once Mary heard a famous song, and a line from it stuck in her head. That line was "Will you still love me when I'm no longer young and beautiful?". Mary believes that a person is loved if and only if he/she is both young and beautiful, but this is quite a depressing thought, so she wants to put her belief to t...
games
def will_you(young, beautiful, loved): return (young and beautiful) != loved
Simple Fun #7: Will You?
58844a13aa037ff143000072
[ "Puzzles" ]
https://www.codewars.com/kata/58844a13aa037ff143000072
7 kyu
Fast & Furious Driving School's (F&F) charges for lessons are as below: <p><table> <tr> <th>Time</th> <th>Cost</th> </tr> <tr> <td>Up to 1st hour</td> <td>$30</td> </tr> <tr> <td>Every subsequent half hour**</td> <td>$10</td> </tr> <tr> <td><h6>** Subsequent charges are calcula...
reference
import math def cost(mins): return 30 + 10 * math . ceil(max(0, mins - 60 - 5) / 30)
Driving School Series #2
589b1c15081bcbfe6700017a
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/589b1c15081bcbfe6700017a
7 kyu
A Narcissistic Number is a number of length `l` in which the sum of its digits to the power of `l` is equal to the original number. If this seems confusing, refer to the example below. Ex: `153`, where `l = 3` ( the number of digits in `153` ) 1<sup>3</sup> + 5<sup>3</sup> + 3<sup>3</sup> = 153 Write a function tha...
reference
def is_narcissistic(n): num = str(n) length = len(num) return sum(int(a) * * length for a in num) == n
Narcissistic Numbers
56b22765e1007b79f2000079
[ "Fundamentals" ]
https://www.codewars.com/kata/56b22765e1007b79f2000079
7 kyu
On the Forex Market the currency symbols for exchange between two currencies are put together in regards to their strength and weakness. The order of the currency strength is as follows: "EUR", "GBP", "AUD", "NZD", "USD", "CAD", "CHF", "JPY" So for AUD the currency matrix would be as follows EURAUD, GBPAUD, AUDNZD, A...
reference
def generate_currency_matrix(c): t = ("EUR", "GBP", "AUD", "NZD", "USD", "CAD", "CHF", "JPY") return ["%s%s" % tuple(sorted((c, o), key=t . index)) for o in t if o != c]
Currency Matrix Generator
57bec3bc5640aa5f3f00003e
[ "Fundamentals" ]
https://www.codewars.com/kata/57bec3bc5640aa5f3f00003e
7 kyu
Note : Issues Fixed with python 2.7.6 , Use any one you like :D , ( Thanks to Time , time , time . Your task is to write a function that will return the degrees on a analog clock from a digital time that is passed in as parameter . The digital time is type string and will be in the format 00:00 . You also need to ret...
reference
def clock_degree(clock_time): hour, minutes = (int(a) for a in clock_time . split(':')) if not (24 > hour >= 0 and 60 > minutes >= 0): return 'Check your time !' return '{}:{}' . format((hour % 12) * 30 or 360, minutes * 6 or 360)
Time Degrees
5782a87d9fb2a5e623000158
[ "Fundamentals" ]
https://www.codewars.com/kata/5782a87d9fb2a5e623000158
7 kyu
Complete the function that returns a christmas tree of the given height. The height is passed through to the function and the function should return a list containing each line of the tree. ``` XMasTree(5) should return : ['____#____', '___###___', '__#####__', '_#######_', '#########', '____#____', '____#____'] XMasT...
algorithms
def xMasTree(n): return [("#" * (x * 2 + 1)). center(n * 2 - 1, "_") for x in list(range(n)) + [0] * 2]
Xmas Tree
577c349edf78c178a1000108
[ "Algorithms" ]
https://www.codewars.com/kata/577c349edf78c178a1000108
7 kyu
###BACKGROUND: Jacob recently decided to get healthy and lose some weight. He did a lot of reading and research and after focusing on steady exercise and a healthy diet for several months, was able to shed over 50 pounds! Now he wants to share his success, and has decided to tell his friends and family how much weight ...
reference
def lose_weight(gender, weight, duration): if not gender in ['M', 'F']: return 'Invalid gender' if weight <= 0: return 'Invalid weight' if duration <= 0: return 'Invalid duration' nl = 0.985 if gender == 'M' else 0.988 for i in range(duration): weight *= nl return...
Jacob's Weight Loss Program
573b216f5328ffcd710013b3
[ "Fundamentals" ]
https://www.codewars.com/kata/573b216f5328ffcd710013b3
7 kyu
Build a function that will take the length of each side of a triangle and return if it's either an Equilateral, an Isosceles, a Scalene or an invalid triangle. It has to return a string with the type of triangle. For example: ```javascript typeOfTriangle(2,2,1) --> "Isosceles" ``` ```coffeescript typeOfTriangl...
algorithms
def type_of_triangle(a, b, c): if any(not isinstance(x, int) for x in (a, b, c)): return "Not a valid triangle" a, b, c = sorted((a, b, c)) if a + b <= c: return "Not a valid triangle" if a == b and b == c: return "Equilateral" if a == b or a == c or b == c: return "Isoscele...
Which triangle is that?
564d398e2ecf66cec00000a9
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/564d398e2ecf66cec00000a9
7 kyu
**This Kata is intended as a small challenge for my students** All Star Code Challenge #31 Walter has a doctor's appointment and has to leave Jesse in charge of preparing their next "cook". He left Jesse an array of Instruction objects, which contain solutions, amounts, and the appropriate scientific instrument to us...
reference
def help_jesse(arr): fmt = 'Pour {a.amount} mL of {a.solution} into a {a.instrument}' . format note = ' ({a.note})' . format return [fmt(a=a) + (note(a=a) if hasattr(a, 'note') else '') for a in arr]
All Star Code Challenge #31
5866f10311ceec6ac10001e8
[ "Fundamentals" ]
https://www.codewars.com/kata/5866f10311ceec6ac10001e8
7 kyu
## Task You need to create a function, `helloWorld`, that will return the String `Hello, World!` without actually using raw strings. This includes quotes, double quotes and template strings. You can, however, use the `String` constructor and any related functions. You cannot use the following: ``` "Hello, World!" 'He...
games
def hello_world(): return bytes( [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]). decode()
Hello World - Without Strings
584c7b1e2cb5e1a727000047
[ "Strings", "Restricted", "Puzzles" ]
https://www.codewars.com/kata/584c7b1e2cb5e1a727000047
7 kyu
If you did Geometric Mean I ( http://www.codewars.com/kata/geometric-mean-i), you may continue with this second part. We have seen the formula: <a href="http://imgur.com/tD9bZui"><img src="http://i.imgur.com/tD9bZui.png?1" title="source: imgur.com" /></a> This expression is not convenient to apply to statistical res...
reference
import math def geometric_meanII(arr): gm = 0 c = 0 f = 0 l = len(arr) for a in arr: if type(a) == int and a >= 0: gm += math . log(a) c += 1 else: f += 1 if l <= 10: if c < l - 1: return 0 else: if f * 100 / l > 10: return 0 retu...
Geometric Mean II
56ec6016a9dfe3346e001242
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/56ec6016a9dfe3346e001242
6 kyu
For a variable, ```x```, that may have different values, ```the geometric mean``` is defined as: ```math G = \sqrt[\large{n}]{x_1 \cdot x_2 \cdot \ldots \cdot x_n} ``` Suposse that you have to calculate **the geometric mean** for a research where the amount of values of x is rather small. Implement the function ```g...
reference
# No need to reinvent the wheel from scipy . stats . mstats import gmean def geometric_meanI(arr): if 0 in arr: return 0 L = list(filter(lambda x: isinstance(x, int) and x > 0, arr)) if 9 * len(arr) > 9 * len(L) + (len(L) if len(arr) > 10 else 9): return 0 return gmean(L)
Geometric Mean I
56ebcea1b9d927f9bf000544
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/56ebcea1b9d927f9bf000544
7 kyu
Find the volume of a cone whose radius and height are provided as parameters to the function `volume`. Use the value of PI provided by your language (for example: `Math.PI` in JS, `math.pi` in Python or `Math::PI` in Ruby) and round down the volume to an Interger. If you complete this kata and there are no issues, ple...
reference
from math import pi def volume(r, h): return pi * r * * 2 * h / / 3
Find the volume of a Cone.
57b2e428d24156b312000114
[ "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/57b2e428d24156b312000114
7 kyu
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 × 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 × 2 squares: ```...
games
def different_squares(matrix): s = set() rows, cols = len(matrix), len(matrix[0]) for row in range(rows - 1): for col in range(cols - 1): s . add((matrix[row][col], matrix[row][col + 1], matrix[row + 1][col], matrix[row + 1][col + 1])) return len(s)
Simple Fun #35: Different Squares
588805ca44c7e8c3a100013c
[ "Puzzles" ]
https://www.codewars.com/kata/588805ca44c7e8c3a100013c
7 kyu
# Task You work in a company that prints and publishes books. You are responsible for designing the page numbering mechanism in the printer. You know how many digits a printer can print with the leftover ink. Now you want to write a function to determine what the last page of the book is that you can number given ...
games
def pages_numbering_with_ink(current, digits): while digits >= len(str(current)): digits = digits - len(str(current)) current = current + 1 return current - 1
Simple Fun #24: Pages Numbering with Ink
5886da134703f125a6000033
[ "Puzzles" ]
https://www.codewars.com/kata/5886da134703f125a6000033
7 kyu
# Task A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the n...
games
def house_numbers_sum(inp): return sum(inp[: inp . index(0)])
Simple Fun #37: House Numbers Sum
58880c6e79a0a3e459000004
[ "Puzzles" ]
https://www.codewars.com/kata/58880c6e79a0a3e459000004
7 kyu
# Task There are some people and cats in a house. You are given the number of legs they have all together. Your task is to return an array containing every possible number of people that could be in the house sorted in ascending order. It's guaranteed that each person has 2 legs and each cat has 4 legs. # Example F...
games
def house_of_cats(legs): return list(range(legs % 4 / / 2, legs / / 2 + 1, 2))
Simple Fun #38: House Of Cats
588810c99fb63e49e1000606
[ "Puzzles" ]
https://www.codewars.com/kata/588810c99fb63e49e1000606
7 kyu
# Task Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements. Given two arrays, check whether they are similar. # Example For `A = [1, 2, 3]` and `B = [1, 2, 3]`, the output should be `true;` For `A = [1, 2, 3]` and `B = [2, 1, 3]`, the output should be `tru...
games
def are_similar(a, b): return sorted(a) == sorted(b) and sum(i != j for i, j in zip(a, b)) in [0, 2]
Simple Fun #42: Are Similar?
588820169ab1e053240000e0
[ "Puzzles" ]
https://www.codewars.com/kata/588820169ab1e053240000e0
7 kyu
# Story&Task There are three parties in parliament. The "Conservative Party", the "Reformist Party", and a group of independants. You are a member of the “Conservative Party” and you party is trying to pass a bill. The “Reformist Party” is trying to block it. In order for a bill to pass, it must have a majority vo...
games
def pass_the_bill(t, c, r): return - 1 if t < 2 * r + 1 else max(0, t / / 2 + 1 - c)
Simple Fun #199: Pass The Bill
58c8a6daa7f31a623200016a
[ "Puzzles" ]
https://www.codewars.com/kata/58c8a6daa7f31a623200016a
7 kyu
# Task Given an array of 2<sup>k</sup> integers (for some integer `k`), perform the following operations until the array contains only one element: ``` On the 1st, 3rd, 5th, etc. iterations (1-based) replace each pair of consecutive elements with their sum; On the 2nd, 4th, 6th, etc. iterations replace each pair of ...
games
def array_conversion(arr): sign = 0 while len(arr) > 1: sign = 1 ^ sign arr = list(map(lambda x, y: x + y, arr[0:: 2], arr[1:: 2]) if sign else map(lambda x, y: x * y, arr[0:: 2], arr[1:: 2])) return arr[0]
Simple Fun #50: Array Conversion
588854201361435f5e0000bd
[ "Puzzles" ]
https://www.codewars.com/kata/588854201361435f5e0000bd
7 kyu
# Task Given array of integers, for each position i, search among the previous positions for the last (from the left) position that contains a smaller value. Store this value at position i in the answer. If no such value can be found, store `-1` instead. # Example For `items = [3, 5, 2, 4, 5]`, the output should be...
games
def array_previous_less(arr): return [next((y for y in arr[: i][:: - 1] if y < x), - 1) for i, x in enumerate(arr)]
Simple Fun #51: Array Previous Less
588856a82ffea640c80000cc
[ "Puzzles" ]
https://www.codewars.com/kata/588856a82ffea640c80000cc
7 kyu
# Task Your Informatics teacher at school likes coming up with new ways to help you understand the material. When you started studying numeral systems, he introduced his own numeral system, which he's convinced will help clarify things. His numeral system has base 26, and its digits are represented by English capital ...
games
def new_numeral_system(number): outputs = { 'A': ['A + A'], 'B': ['A + B'], 'C': ['A + C', 'B + B'], 'D': ['A + D', 'B + C'], 'E': ['A + E', 'B + D', 'C + C'], 'F': ['A + F', 'B + E', 'C + D'], 'G': ['A + G', 'B + F', 'C + E', 'D + D'], 'H': [...
Simple Fun #45: New Numeral System
5888445107a0d57711000032
[ "Puzzles" ]
https://www.codewars.com/kata/5888445107a0d57711000032
7 kyu
# Task Below we will define what and n-interesting polygon is and your task is to find its area for a given n. A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim side by side. Y...
games
def shape_area(n): return n * * 2 + (n - 1) * * 2
Simple Fun #63: Shape Area
5893e0c41a88085c330000a0
[ "Puzzles" ]
https://www.codewars.com/kata/5893e0c41a88085c330000a0
7 kyu
# Task Your task is to find the sum for the range `0 ... m` for all powers from `0 ... n. # Example For `m = 2, n = 3`, the result should be `20` `0^0+1^0+2^0 + 0^1+1^1+2^1 + 0^2+1^2+2^2 + 0^3+1^3+2^3 = 20` Note, that no output ever exceeds 2e9. # Input/Output - `[input]` integer m `0 <= m <= 50000` ...
games
def S2N(m, n): return sum(i * * j for i in range(m + 1) for j in range(n + 1))
Simple Fun #137: S2N
58a6742c14b042a042000038
[ "Puzzles" ]
https://www.codewars.com/kata/58a6742c14b042a042000038
7 kyu
# Task Given two integers `a` and `b`, return the sum of the numerator and the denominator of the reduced fraction `a/b`. # Example For `a = 2, b = 4`, the result should be `3` Since `2/4 = 1/2 => 1 + 2 = 3`. For `a = 10, b = 100`, the result should be `11` Since `10/100 = 1/10 => 1 + 10 = 11`. For `a = 5...
reference
from fractions import gcd def fraction(a, b): return (a + b) / / gcd(a, b)
Simple Fun #179: Fraction
58b8db810f40ea7788000126
[ "Fundamentals" ]
https://www.codewars.com/kata/58b8db810f40ea7788000126
7 kyu
# Task To prepare his students for an upcoming game, the sports coach decides to try some new training drills. To begin with, he lines them up and starts with the following warm-up exercise: ``` when the coach says 'L', he instructs the students to turn to the left. Alternatively, when he says 'R', they should tur...
games
def line_up(commands): same = True count = 0 for c in commands: if c in "LR": same = not same if same: count += 1 return count
Simple Fun #14: Line Up
5884658d02accbd0a7000039
[ "Puzzles" ]
https://www.codewars.com/kata/5884658d02accbd0a7000039
6 kyu
# Task You found two items in a treasure chest! The first item weighs `weight1` and is worth `value1`, and the second item weighs `weight2` and is worth `value2`. What is the total maximum value of the items you can take with you, assuming that your max weight capacity is `maxW`/`max_w` and you can't come back for the...
games
def knapsack_light(v1, w1, v2, w2, W): return max(v for v, w in [(0, 0), (v1, w1), (v2, w2), (v1 + v2, w1 + w2)] if w <= W)
Simple Fun #5: Knapsack Light
58842a2b4e8efb92b7000080
[ "Puzzles" ]
https://www.codewars.com/kata/58842a2b4e8efb92b7000080
7 kyu
## Task In order to stop the Mad Coder evil genius you need to decipher the encrypted message he sent to his minions. The message contains several numbers that, when typed into a supercomputer, will launch a missile into the sky blocking out the sun, and making all the people on Earth grumpy and sad. You figured out...
games
def kill_kth_bit(n, k): return n & ~ (1 << k - 1)
Simple Fun #8: Kill K-th Bit
58844f1a76933b1cd0000023
[ "Puzzles", "Bits", "Binary" ]
https://www.codewars.com/kata/58844f1a76933b1cd0000023
7 kyu
# Task Given integers `a` and `b`, determine whether the following pseudocode results in an infinite loop ```javascript while (a !== b){ a++ b-- } ``` Assume that the program is executed on a virtual machine which can store arbitrary long numbers and execute forever. # Example For a = 2 and b = 6, t...
games
def is_infinite_process(a, b): return b < a or (b - a) % 2
Simple Fun #6: Is Infinite Process?
588431bb76933b84520000d3
[ "Puzzles" ]
https://www.codewars.com/kata/588431bb76933b84520000d3
7 kyu
# Task Some phone usage rate may be described as follows: first minute of a call costs `min1` cents, each minute from the 2nd up to 10th (inclusive) costs `min2_10` cents each minute after 10th costs `min11` cents. You have `s` cents on your account before the call. What is the duration of the longest call ...
games
def phone_call(min1, min2_10, min11, s): minutes, cost = 0, min1 while s >= cost: minutes += 1 s -= cost if minutes == 1: cost = min2_10 if minutes == 10: cost = min11 return minutes
Simple Fun #4: Phone Call
588425ee4e8efb583d000088
[ "Puzzles" ]
https://www.codewars.com/kata/588425ee4e8efb583d000088
7 kyu
Truncate the given string (first argument) if it is longer than the given maximum length (second argument). Return the truncated string with a `"..."` ending. Note that inserting the three dots to the end will add to the string length. However, if the given maximum string length num is less than or equal to 3, then t...
reference
def truncate_string(s, n): return s if len(s) <= n else s[: n if n <= 3 else n - 3] + '...'
Truncate a string!
57af26297f75b57d1f000225
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57af26297f75b57d1f000225
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 va...
games
def find_ball(scales): for i in range(0, 8, 2): result = scales . get_weight([i], [i + 1]) if result: return i + (result > 0)
Find heavy ball - level: novice
544047f0cf362503e000036e
[ "Puzzles", "Logic", "Riddles" ]
https://www.codewars.com/kata/544047f0cf362503e000036e
7 kyu
#### Background: <p align="center"> <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Linear_regression.svg/438px-Linear_regression.svg.png" alt="sample linear regression, curtesy of wikipedia"></p> A linear regression line has an equation in the form `$Y = a + bX$`, where `$X$` is the explanatory va...
reference
import numpy as np def regressionLine(x, y): """ Return the a (intercept) and b (slope) of Regression Line (Y on X). """ a, b = np . polyfit(x, y, 1) return round(b, 4), round(a, 4)
Linear Regression of Y on X
5515395b9cd40b2c3e00116c
[ "Statistics", "Geometry", "Fundamentals", "Data Science" ]
https://www.codewars.com/kata/5515395b9cd40b2c3e00116c
6 kyu
This is a follow up from my kata <a href="http://www.codewars.com/kata/insert-dashes/">Insert Dashes</a>. <br/> Write a function ```insertDashII(num)``` that will insert dashes ('-') between each two odd numbers and asterisk ('\*') between each even numbers in ```num``` <br/> For example: <br/> ```insertDashII(454793)`...
reference
import re def insert_dash2(num): s = str(num) s = re . sub('(?<=[13579])(?=[13579])', '-', s) s = re . sub('(?<=[2468])(?=[2468])', '*', s) return s
Insert Dashes 2
55c3026406402936bc000026
[ "Fundamentals" ]
https://www.codewars.com/kata/55c3026406402936bc000026
7 kyu