problem_id
int64
2.36k
5k
question
stringlengths
52
14k
solutions
stringlengths
79
675k
input_output
stringlengths
37
505k
difficulty
stringclasses
1 value
url
stringlengths
36
94
starter_code
stringlengths
0
952
3,864
Take the following IPv4 address: `128.32.10.1` This address has 4 octets where each octet is a single byte (or 8 bits). * 1st octet `128` has the binary representation: `10000000` * 2nd octet `32` has the binary representation: `00100000` * 3rd octet `10` has the binary representation: `00001010` * 4th octet `1` has ...
["from ipaddress import IPv4Address\n\ndef int32_to_ip(int32):\n return str(IPv4Address(int32))", "def int32_to_ip(int32):\n return '{}.{}.{}.{}'.format(*int32.to_bytes(4, 'big'))", "from ipaddress import ip_address\n\ndef int32_to_ip(int32):\n return str(ip_address(int32))", "def int32_to_ip(i):\n return '...
{"fn_name": "int32_to_ip", "inputs": [[2154959208], [0], [2149583361]], "outputs": [["128.114.17.104"], ["0.0.0.0"], ["128.32.10.1"]]}
introductory
https://www.codewars.com/kata/52e88b39ffb6ac53a400022e
def int32_to_ip(int32):
3,865
In this kata we are focusing on the Numpy python package. You must write a function called `looper` which takes three integers `start, stop and number` as input and returns a list from `start` to `stop` with `number` total values in the list. Five examples are shown below: ``` looper(1, 5, 1) = [1.0] looper(1, 5, 2) ...
["from numpy import linspace\n\n\ndef looper(start, stop, number):\n return list(linspace(start, stop, number))", "def looper(start, stop, number):\n if number == 1:\n return [start]\n elif number == 2:\n return [start, stop] \n \n increment = (stop - start) / (number - 1) \n ...
{"fn_name": "looper", "inputs": [[1, 5, 1], [1, 5, 2], [1, 5, 3], [1, 5, 4], [1, 5, 5]], "outputs": [[[1.0]], [[1.0, 5.0]], [[1.0, 3.0, 5.0]], [[1.0, 2.333333333333333, 3.6666666666666665, 5.0]], [[1.0, 2.0, 3.0, 4.0, 5.0]]]}
introductory
https://www.codewars.com/kata/5a35f08b9e5f4923790010dc
def looper(start, stop, number):
3,866
Three candidates take part in a TV show. In order to decide who will take part in the final game and probably become rich, they have to roll the Wheel of Fortune! The Wheel of Fortune is divided into 20 sections, each with a number from 5 to 100 (only mulitples of 5). Each candidate can roll the wheel once or twice ...
["def winner(candidates):\n try:\n assert len(candidates) == 3\n max_total = 0\n for c in candidates:\n name, scores = c['name'], c['scores']\n assert 1 <= len(scores) <= 2\n assert all(not s % 5 and 0 < s <= 100 for s in scores)\n total = sum(scores)\...
{"fn_name": "winner", "inputs": [[[]]], "outputs": [[false]]}
introductory
https://www.codewars.com/kata/55191f78cd82ff246f000784
def winner(candidates):
3,867
Our fruit guy has a bag of fruit (represented as an array of strings) where some fruits are rotten. He wants to replace all the rotten pieces of fruit with fresh ones. For example, given `["apple","rottenBanana","apple"]` the replaced array should be `["apple","banana","apple"]`. Your task is to implement a method that...
["def remove_rotten(bag_of_fruits):\n return [x.replace('rotten', '').lower() for x in bag_of_fruits] if bag_of_fruits else []", "def remove_rotten(fruit_bag):\n # Checking\n if not fruit_bag:\n return []\n # Processing\n temp = []\n for i in fruit_bag:\n i = i.replace(\"rotten\", \"\", ...
{"fn_name": "remove_rotten", "inputs": [[["apple", "banana", "kiwi", "melone", "orange"]], [["rottenApple", "rottenBanana", "rottenApple", "rottenPineapple", "rottenKiwi"]], [[]], [null], [["apple", "rottenBanana", "rottenApple", "pineapple", "kiwi"]]], "outputs": [[["apple", "banana", "kiwi", "melone", "orange"]], [["...
introductory
https://www.codewars.com/kata/557af4c6169ac832300000ba
def remove_rotten(bag_of_fruits):
3,868
Given an array (ints) of n integers, find three integers in arr such that the sum is closest to a given number (num), target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: Note: your solution should not modify the input array.
["from itertools import combinations\n\n\ndef closest_sum(ints, num):\n return sum(min(combinations(ints, 3), key=lambda a: abs(num - sum(a))))", "from itertools import combinations\n\ndef closest_sum(ints, num):\n ss = map(sum, combinations(ints, 3))\n return min(ss, key=lambda x: abs(x-num))", "from itertool...
{"fn_name": "closest_sum", "inputs": [[[-1, 2, 1, -4], 1], [[5, 4, 0, 3], 3], [[1, 2, 3, 4], 4], [[-2, 2, -3, 1], 3]], "outputs": [[2], [7], [6], [1]]}
introductory
https://www.codewars.com/kata/577e694af5db624cf30002d0
def closest_sum(ints, num):
3,869
# 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...
["def shape_area(n):\n return n**2 + (n - 1) ** 2", "def shape_area(n):\n return 2 * n * (n - 1) + 1", "def shape_area(n):\n if n==1:\n return 1\n return n*n*2-n-(n-1)", "def shape_area(n):\n p = 0\n area = 1\n for i in range (1, n):\n p = n*4-4\n n -= 1\n area += p\n return area\n...
{"fn_name": "shape_area", "inputs": [[2], [3], [1], [5]], "outputs": [[5], [13], [1], [41]]}
introductory
https://www.codewars.com/kata/5893e0c41a88085c330000a0
def shape_area(n):
3,870
In this Kata, we are going to reverse a string while maintaining the spaces (if any) in their original place. For example: ``` solve("our code") = "edo cruo" -- Normal reversal without spaces is "edocruo". -- However, there is a space at index 3, so the string becomes "edo cruo" solve("your code rocks") = "skco redo...
["def solve(s):\n it = reversed(s.replace(' ',''))\n return ''.join(c if c == ' ' else next(it) for c in s)", "def solve(s):\n space_index=[i for i in range(len(s)) if s[i]==\" \"] #find index of saces \n s = ''.join(s.split()) #remove spaces\n s=s[::-1] ...
{"fn_name": "solve", "inputs": [["codewars"], ["your code"], ["your code rocks"], ["i love codewars"]], "outputs": [["srawedoc"], ["edoc ruoy"], ["skco redo cruoy"], ["s rawe docevoli"]]}
introductory
https://www.codewars.com/kata/5a71939d373c2e634200008e
def solve(s):
3,871
# Task Given a binary number, we are about to do some operations on the number. Two types of operations can be here: * ['I', i, j] : Which means invert the bit from i to j (inclusive). * ['Q', i] : Answer whether the i'th bit is 0 or 1. The MSB (most significant bit) is the first bit (i.e. i = `1`). The binary numb...
["def binary_simulation(s, q):\n out,n,s = [],int(s,2),len(s)\n for cmd,*i in q:\n if cmd=='I':\n a,b=i\n n ^= (1<<b-a+1)-1<<s-b\n else:\n out.append( str(int(0 < 1<<s-i[0] & n )) )\n return out", "import numpy as np\n\ndef binary_simulation(s, b):\n a, r = np....
{"fn_name": "binary_simulation", "inputs": [["0011001100", [["I", 1, 10], ["I", 2, 7], ["Q", 2], ["Q", 1], ["Q", 7], ["Q", 5]]], ["1011110111", [["I", 1, 10], ["I", 2, 7], ["Q", 2], ["Q", 1], ["Q", 7], ["Q", 5]]], ["1011110111", [["I", 1, 10], ["I", 2, 7]]], ["0000000000", [["I", 1, 10], ["Q", 2]]]], "outputs": [[["0",...
introductory
https://www.codewars.com/kata/5cb9f138b5c9080019683864
def binary_simulation(s, q):
3,872
Write a function that accepts two parameters, i) a string (containing a list of words) and ii) an integer (n). The function should alphabetize the list based on the nth letter of each word. The letters should be compared case-insensitive. If both letters are the same, order them normally (lexicographically), again, c...
["def sort_it(list_, n): \n return ', '.join(sorted(list_.split(', '), key=lambda i: i[n-1]))", "from operator import itemgetter\n\ndef sort_it(list_, n):\n return ', '.join(sorted(list_.split(', '), key=itemgetter(n - 1)))\n", "def sort_it(words, i):\n return \", \".join(sorted(words.split(\", \"), key=lam...
{"fn_name": "sort_it", "inputs": [["bill, bell, ball, bull", 2], ["words, wordz, wordy, wording", 5], ["he, hi, ha, ho", 2], ["zephyr, yellow, wax, a, ba, cat", 1], ["hello, how, are, you, doing, today", 3]], "outputs": [["ball, bell, bill, bull"], ["wording, words, wordy, wordz"], ["ha, he, hi, ho"], ["a, ba, cat, wax...
introductory
https://www.codewars.com/kata/54eea36b7f914221eb000e2f
def sort_it(list_, n):
3,873
Related to MrZizoScream's Product Array kata. You might want to solve that one first :) ```if:javascript **Note:** Node 10 has now been enabled, and you can now use its BigInt capabilities if you wish, though your resulting array must still contain strings (e.g. "99999999999", not 9999999999n) Pre-node 10: You will n...
["from functools import reduce\n\ndef product_sans_n(nums):\n z = nums.count(0)\n if z > 1: return [0] * len(nums)\n \n p = reduce(int.__mul__, (v for v in nums if v))\n return [not v and p for v in nums] if z else [p//v for v in nums]", "from functools import reduce\n\n\ndef product_sans_n(nums):\n z...
{"fn_name": "product_sans_n", "inputs": [[[1, 1, 1]], [[0, -99, 0]], [[9, 0, -2]], [[1, 2, 3, 4]], [[2, 3, 4, 5]], [[-8, 1, 5, 13, -1]], [[3, 14, 9, 11, 11]], [[4, 7, 3, 6, 2, 11, 14, 4, 7, 5]]], "outputs": [[[1, 1, 1]], [[0, 0, 0]], [[0, -18, 0]], [[24, 12, 8, 6]], [[60, 40, 30, 24]], [[-65, 520, 104, 40, -520]], [[15...
introductory
https://www.codewars.com/kata/5b3e609cd58499284100007a
def product_sans_n(nums):
3,874
#Sorting on planet Twisted-3-7 There is a planet... in a galaxy far far away. It is exactly like our planet, but it has one difference: #The values of the digits 3 and 7 are twisted. Our 3 means 7 on the planet Twisted-3-7. And 7 means 3. Your task is to create a method, that can sort an array the way it would be sor...
["def sort_twisted37(arr):\n def key(x):\n return int(str(x).translate(str.maketrans('37', '73')))\n return sorted(arr, key=key)", "tr=str.maketrans('37','73')\n\ndef sort_twisted37(arr):\n return sorted(arr,key=lambda n:int(str(n).translate(tr)))", "def sort_twisted37(arr):\n twisted = lambda n: int('...
{"fn_name": "sort_twisted37", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[12, 13, 14]], [[9, 2, 4, 7, 3]]], "outputs": [[[1, 2, 7, 4, 5, 6, 3, 8, 9]], [[12, 14, 13]], [[2, 7, 4, 3, 9]]]}
introductory
https://www.codewars.com/kata/58068479c27998b11900056e
def sort_twisted37(arr):
3,875
# # Task: * #### Complete the pattern, using the special character ```■ □``` * #### In this kata, we draw some histogram of the sound performance of ups and downs. # # Rules: - parameter ```waves``` The value of sound waves, an array of number, all number in array >=0. - return a string, ```■``` represent...
["def draw(waves):\n m = max(waves)\n rotHist = [ ('\u25a0'*v).rjust(m, '\u25a1') for v in waves ]\n return '\\n'.join( map(''.join, zip(*rotHist)) )", "def draw(waves):\n m = max(waves)\n return '\\n'.join(\n ''.join('\u25a1\u25a0'[x > i] for x in waves) for i in reversed(range(m))\n )",...
{"fn_name": "draw", "inputs": [[[1, 2, 3, 4]], [[1, 2, 3, 3, 2, 1]], [[1, 2, 3, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7]], [[5, 3, 1, 2, 4, 6, 5, 4, 2, 3, 5, 2, 1]], [[1, 0, 1, 0, 1, 0, 1, 0]]], "outputs": [["\u25a1\u25a1\u25a1\u25a0\n\u25a1\u25a1\u25a0\u25a0\n\u25a1\u25a0\u25a0\u25a0\n\u25a0\u25a0\u25a0\u25a0"], ["\u25a1\u25a1\u...
introductory
https://www.codewars.com/kata/56e67d6166d442121800074c
def draw(waves):
3,876
Your task is to write function ```findSum```. Upto and including ```n```, this function will return the sum of all multiples of 3 and 5. For example: ```findSum(5)``` should return 8 (3 + 5) ```findSum(10)``` should return 33 (3 + 5 + 6 + 9 + 10)
["def find(n):\n return sum(e for e in range(1, n+1) if e % 3 == 0 or e % 5 == 0)", "def find(n):\n sum = 0\n for i in range(1,n+1):\n if i % 3 == 0 or i % 5 == 0:\n sum += i\n return sum", "def find(n):\n return sum(range(0, n+1, 3)) + sum(range(0, n+1, 5)) - sum(range(0, n+1, 15))", "...
{"fn_name": "find", "inputs": [[5], [10], [100], [1000]], "outputs": [[8], [33], [2418], [234168]]}
introductory
https://www.codewars.com/kata/57f36495c0bb25ecf50000e7
def find(n):
3,877
The T9 typing predictor helps with suggestions for possible word combinations on an old-style numeric keypad phone. Each digit in the keypad (2-9) represents a group of 3-4 letters. To type a letter, press once the key which corresponds to the letter group that contains the required letter. Typing words is done by typi...
["FROM = \"abc def ghi jkl mno pqrs tuv wxyz\".split()\nTO_NUM = \"222 333 444 555 666 7777 888 9999\".split()\n\nTABLE_TO_NUM = str.maketrans( *map(''.join, (FROM, TO_NUM)) )\nTABLE_TO_CHAR = str.maketrans( *map(lambda lst: ''.join(x[0] for x in lst), (TO_NUM, FROM)))\n\n\ndef T9(words, seq):\n return ( [w for w...
{"fn_name": "T9", "inputs": [[["hello", "world"], "43556"], [["good", "home", "new"], "4663"], [["gone", "hood", "good", "old"], "4663"], [["Hello", "world"], "43556"], [["gOOD", "hOmE", "NeW"], "4663"], [["goNe", "hood", "GOOD", "old"], "4663"], [[], "43556"], [["gold"], "4663"], [["gone", "hood", "good", "old"], "729...
introductory
https://www.codewars.com/kata/5b085335abe956c1ef000266
def T9(words, seq):
3,878
Adapted from here, with less terrible instructions and a couple tweaks. Two kangaroos are jumping on a line. They start out at different points on the line, and jump in the same direction at different speeds. Your task is to determine whether or not they'll ever land in the same spot at the same time (you'll just have...
["def kangaroo(k1, r1, k2, r2):\n if r1==r2: return k1==k2\n cross, r = divmod(k1-k2, r2-r1)\n return cross >= 0 and not r", "def kangaroo(x1, v1, x2, v2):\n if x1 > x2 and v1 > v2:\n return False\n if (v1 > v2 and (x2-x1)%(v1-v2)==0):\n return True\n else:\n return False", "def k...
{"fn_name": "kangaroo", "inputs": [[0, 3, 4, 2], [0, 9, 16, 4], [-1, 3, 0, 2], [-1571, 4240, 9023, 4234], [-7855, 4240, 9023, 4234], [43, 5, 49, 3], [9023, 4240, 1571, 4234], [129, 15, 147, 9], [129, 15, 147, 90], [0, 2, 100000, 1], [72893, 11125, 24432, 4202], [13613, 299, 65130, 73]], "outputs": [[true], [false], [tr...
introductory
https://www.codewars.com/kata/5ae7e1522c5061beb7000051
def kangaroo(kanga1, rate1, kanga2, rate2):
3,879
You love coffee and want to know what beans you can afford to buy it. The first argument to your search function will be a number which represents your budget. The second argument will be an array of coffee bean prices. Your 'search' function should return the stores that sell coffee within your budget. The search...
["def search(budget, prices):\n return ','.join(str(a) for a in sorted(prices) if a <= budget)\n", "search = lambda budget, prices: \",\".join(map(str, sorted([x for x in prices if x <= budget])))", "def search(budget, prices):\n return \",\".join(map(str, sorted([n for n in prices if n <= budget])))", "def searc...
{"fn_name": "search", "inputs": [[3, [6, 1, 2, 9, 2]], [14, [7, 3, 23, 9, 14, 20, 7]], [0, [6, 1, 2, 9, 2]], [10, []], [24, [24, 0, 100, 2, 5]], [24, [2.7, 0, 100.9, 1, 5.5]], [-1, [1, 2, 3, 4]], [-1, [-1, 0, 1, 2, 3, 4]], [14, [17, 33, 23, 19, 19, 20, 17]], [14, [13, 15, 14, 14, 15, 13]]], "outputs": [["1,2,2"], ["3,7...
introductory
https://www.codewars.com/kata/56069d0c4af7f633910000d3
def search(budget,prices):
3,880
The concept of "[smooth number](https://en.wikipedia.org/wiki/Smooth_number)" is applied to all those numbers whose prime factors are lesser than or equal to `7`: `60` is a smooth number (`2 * 2 * 3 * 5`), `111` is not (`3 * 37`). More specifically, smooth numbers are classified by their highest prime factor and your ...
["def is_smooth(n):\n for x in [2,3,5,7]:\n while n%x==0:n//=x\n if n==1:return (\"power of 2\",'3-smooth','Hamming number','humble number')[(2<x)+(3<x)+(5<x)] \n return \"non-smooth\"", "from collections import defaultdict\n\n\nnames = defaultdict(lambda: 'non-smooth', {\n 2: 'power of 2',\n ...
{"fn_name": "is_smooth", "inputs": [[16], [36], [60], [98], [111], [4096], [729], [3125], [7], [17]], "outputs": [["power of 2"], ["3-smooth"], ["Hamming number"], ["humble number"], ["non-smooth"], ["power of 2"], ["3-smooth"], ["Hamming number"], ["humble number"], ["non-smooth"]]}
introductory
https://www.codewars.com/kata/5b2f6ad842b27ea689000082
def is_smooth(n):
3,881
The central dogma of molecular biology is that DNA is transcribed into RNA, which is then tranlsated into protein. RNA, like DNA, is a long strand of nucleic acids held together by a sugar backbone (ribose in this case). Each segment of three bases is called a codon. Molecular machines called ribosomes translate the RN...
["import re\ndict = {'UUC':'F','UUU':'F','UUA':'L','UUG':'L','CUU':'L','CUC':'L','CUA':'L','CUG':'L','AUU':'I','AUC':'I','AUA':'I','AUG':'M','GUU':'V','GUC':'V','GUA':'V','GUG':'V','UCU':'S','UCC':'S','UCA':'S','UCG':'S','AGU':'S','AGC':'S','CCU':'P','CCC':'P','CCA':'P','CCG':'P','ACU':'T','ACC':'T','ACA':'T','ACG':'T'...
{"fn_name": "protein", "inputs": [["AUGUGA"], ["AUGUAUAAA"], ["UGCGAUGAAUGGGCUCGCUCC"], ["AUGUUAAUUUGA"], ["AUGUCCUUCCAUCAAGGAAACCAUGCGCGUUCAGCUUUCUGA"], ["AUGCUUCAAGUGCACUGGAAAAGGAGAGGGAAAACCAGUUGA"], ["AUGGCGUUCAGCUUUCUAUGGAGGGUAGUGUACCCAUGCUGA"], ["AUGCAGCUUUCUAUGGAGGGUAGUGUUAACUACCACGCCUGA"], ["AUGCUAUGGAGGGUAGUGUU...
introductory
https://www.codewars.com/kata/555a03f259e2d1788c000077
def protein(rna):
3,882
# Sort an array by value and index Your task is to sort an array of integer numbers by the product of the value and the index of the positions. For sorting the index starts at 1, NOT at 0! The sorting has to be ascending. The array will never be null and will always contain numbers. Example: ``` Input: 23, 2, 3, 4, ...
["def sort_by_value_and_index(arr):\n return [y[1] for y in sorted(enumerate(arr),key=lambda x:(x[0] + 1) * x[1])]", "def sort_by_value_and_index(arr):\n return [b for _, b in sorted(enumerate(arr, 1), key=lambda x: int.__mul__(*x))]", "def sort_by_value_and_index(arr):\n return [b for _, b in sorted(enumerate...
{"fn_name": "sort_by_value_and_index", "inputs": [[[1, 2, 3, 4, 5]], [[23, 2, 3, 4, 5]], [[26, 2, 3, 4, 5]], [[9, 5, 1, 4, 3]]], "outputs": [[[1, 2, 3, 4, 5]], [[2, 3, 4, 23, 5]], [[2, 3, 4, 5, 26]], [[1, 9, 5, 3, 4]]]}
introductory
https://www.codewars.com/kata/58e0cb3634a3027180000040
def sort_by_value_and_index(arr):
3,883
If we alternate the vowels and consonants in the string `"have"`, we get the following list, arranged alphabetically: `['ahev', 'aveh', 'ehav', 'evah', 'vahe', 'veha']`. These are the only possibilities in which vowels and consonants are alternated. The first element, `ahev`, is alphabetically lowest. Given a string:...
["def solve(s):\n vowels = sorted(c for c in s if c in \"aeiou\")\n consonants = sorted(c for c in s if c not in \"aeiou\")\n part1, part2 = sorted((vowels, consonants), key=len, reverse=True)\n part2.append('')\n if len(part1) > len(part2):\n return \"failed\"\n return \"\".join(a + b for a, b...
{"fn_name": "solve", "inputs": [["java"], ["oruder"], ["zodiac"], ["apple"], ["acidity"], ["codewars"], ["orudere"]], "outputs": [["ajav"], ["edorur"], ["acidoz"], ["lapep"], ["caditiy"], ["failed"], ["ederoru"]]}
introductory
https://www.codewars.com/kata/59cf8bed1a68b75ffb000026
def solve(s):
3,884
# RegExp Fun #1 - When I miss few days of gym ## Disclaimer The background story of this Kata is 100% fiction. Any resemblance to real people or real events is **nothing more than a coincidence** and should be regarded as such. ## Background Story You are a person who loves to go to the gym everyday with the squad...
["import re\n\ndef gym_slang(phrase):\n phrase = re.sub(r'([pP])robably', r'\\1rolly', phrase)\n phrase = re.sub(r'([iI]) am', r\"\\1'm\", phrase)\n phrase = re.sub(r'([iI])nstagram', r'\\1nsta', phrase)\n phrase = re.sub(r'([dD])o not', r\"\\1on't\", phrase)\n phrase = re.sub(r'([gG])oing to', r'\\1onna...
{"fn_name": "gym_slang", "inputs": [["When I miss few days of gym"], ["Squad probably think I am fake"], ["Whole squad probably bigger than me now"], ["No selfie to post on Instagram either"], ["Gym crush probably found someone else"], ["What if I die fat"], ["What if I do not fit in my clothes now"], ["Going to feel l...
introductory
https://www.codewars.com/kata/5720a81309e1f9b232001c5b
def gym_slang(phrase):
3,885
The palindromic number `595` is interesting because it can be written as the sum of consecutive squares: `6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2 = 595`. There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums. Note that `1 = 0^2 + 1^2` has not been included as this pr...
["l, m, p = [1], 10 ** 7, []\nfor n in range(2, int(m ** .5) + 1):\n l = [n*n + j for j in [0]+l]\n p += [int(k) for k in map(str, l[1:]) if k == k[::-1]]\np = sorted(set(p))\n\nfrom bisect import bisect_left\ndef values(n): return bisect_left(p, n)", "def values(n):\n pal = set()\n for i in range(1, int(n*...
{"fn_name": "values", "inputs": [[100], [200], [300], [400], [1000], [100000], [1000000], [5000000], [9000000], [10000000]], "outputs": [[3], [4], [4], [5], [11], [30], [59], [78], [98], [110]]}
introductory
https://www.codewars.com/kata/599b1a4a3c5292b4cc0000d5
def values(n):
3,886
In this Kata, you will be given an integer array and your task is to return the sum of elements occupying prime-numbered indices. ~~~if-not:fortran The first element of the array is at index `0`. ~~~ ~~~if:fortran The first element of an array is at index `1`. ~~~ Good luck! If you like this Kata, try: [Dominan...
["def is_prime(n):\n return n >= 2 and all(n%i for i in range(2, 1+int(n**.5)))\n \ndef total(arr):\n return sum(n for i, n in enumerate(arr) if is_prime(i))", "def sieve(n):\n sieve, primes = [0]*(n+1), set()\n for i in range(2, n+1):\n if not sieve[i]:\n primes.add(i)\n for...
{"fn_name": "total", "inputs": [[[]], [[1, 2, 3, 4]], [[1, 2, 3, 4, 5, 6]], [[1, 2, 3, 4, 5, 6, 7, 8]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]], "outputs": [[0], [7], [13], [21], [21], [33], [47]]}
introductory
https://www.codewars.com/kata/59f38b033640ce9fc700015b
def total(arr):
3,887
< PREVIOUS KATA NEXT KATA > ###Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto (3n-2) rows, where n is parameter. * Note:`Returning` the pattern is not the same as `Printing` the pattern. ####Rules/Note: * The pattern should be created using only unit digits. * I...
["def pattern(n):\n top = [(str(i % 10) * n).center(n * 3 - 2) for i in range(1, n)]\n left = ''.join(str(i % 10) for i in range(1, n))\n middle = left + str(n % 10) * n + left[::-1]\n return '\\n'.join(top + [middle] * n + top[::-1])\n", "def f(n):\n w = 3*n - 2\n for i in range(1, n):\n yield...
{"fn_name": "pattern", "inputs": [[3], [5], [-3], [-11], [-25], [0]], "outputs": [[" 111 \n 222 \n1233321\n1233321\n1233321\n 222 \n 111 "], [" 11111 \n 22222 \n 33333 \n 44444 \n1234555554321\n1234555554321\n1234555554321\n1234555554321\n1234555554321\n 44444 \n 33333 \n ...
introductory
https://www.codewars.com/kata/5589ad588ee1db3f5e00005a
def pattern(n):
3,888
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...
["def clock_degree(clock_time):\n hour, minutes = (int(a) for a in clock_time.split(':'))\n if not (24 > hour >= 0 and 60 > minutes >= 0):\n return 'Check your time !'\n return '{}:{}'.format((hour % 12) * 30 or 360, minutes * 6 or 360)", "def clock_degree(stg):\n try:\n h, m = (int(n) for n i...
{"fn_name": "clock_degree", "inputs": [["01:01"], ["00:00"], ["01:03"], ["01:30"], ["12:05"], ["26:78"], ["16:25"], ["17:09"], ["19:00"], ["20:34"], ["23:20"], ["24:00"], ["-09:00"]], "outputs": [["30:6"], ["360:360"], ["30:18"], ["30:180"], ["360:30"], ["Check your time !"], ["120:150"], ["150:54"], ["210:360"], ["240...
introductory
https://www.codewars.com/kata/5782a87d9fb2a5e623000158
def clock_degree(s) :
3,889
You've got a bunch of textual data with embedded phone numbers. Write a function `area_code()` that finds and returns just the area code portion of the phone number. ```python >>> message = "The supplier's phone number is (555) 867-5309" >>> area_code(message) '555' ``` The returned area code should be a string, not a ...
["def area_code(text):\n return text[text.find(\"(\")+1:text.find(\")\")]", "import re\ndef area_code(text):\n return re.search(\"\\((\\d{3})\\)\", text).group(1)", "def area_code(text):\n return text[text.index('(')+1:text.index(')')]", "def area_code(text):\n # Your code goes here\n area = text.find('(')...
{"fn_name": "area_code", "inputs": [["The supplier's phone number is (555) 867-5309"], ["Grae's cell number used to be (123) 456-7890"], ["The 102nd district court's fax line is (124) 816-3264"]], "outputs": [["555"], ["123"], ["124"]]}
introductory
https://www.codewars.com/kata/585a36b445376cbc22000072
def area_code(text):
3,890
Let's say that in a hypothetical platform that resembles Codewars there is a clan with 2 warriors. The 2nd one in ranking (lets call him **D**) wants to at least reach the honor score of his ally (lets call her **M**). *(Let's say that there is no antagonism here, he just wants to prove his ally that she should be pro...
["def get_honor_path(honor, target):\n return dict(list(zip([\"1kyus\", \"2kyus\"], divmod(target - honor, 2)))) if target > honor else {}\n", "def get_honor_path(score, target):\n return {'1kyus':(target-score)//2, '2kyus':(target-score)%2} if target > score else {}", "def get_honor_path(honor_score, target_hono...
{"fn_name": "get_honor_path", "inputs": [[11, 2], [11, 11]], "outputs": [[{}], [{}]]}
introductory
https://www.codewars.com/kata/5660aa6fa60f03856c000045
def get_honor_path(honor_score, target_honor_score):
3,891
The new £5 notes have been recently released in the UK and they've certainly became a sensation! Even those of us who haven't been carrying any cash around for a while, having given in to the convenience of cards, suddenly like to have some of these in their purses and pockets. But how many of them could you get with w...
["def get_new_notes(salary, bills):\n return max((salary - sum(bills)), 0) // 5", "def get_new_notes(salary,bills):\n return max((salary-sum(bills))//5, 0)", "def get_new_notes(salary,bills):\n return max(0, (salary - sum(bills)) // 5)", "def get_new_notes(salary, bills):\n disposable_income = salary - sum(...
{"fn_name": "get_new_notes", "inputs": [[2000, [500, 160, 400]], [1260, [500, 50, 100]], [3600, [1800, 350, 460, 500, 15]], [1995, [1500, 19, 44]], [10000, [1800, 500, 1200, 655, 150]], [2300, [590, 1500, 45, 655, 150]], [5300, [1190, 1010, 1045, 55, 10, 19, 55]], [2000, [500, 495, 100, 900]], [2000, [500, 496, 100, 90...
introductory
https://www.codewars.com/kata/58029cc9af749f80e3001e34
def get_new_notes(salary,bills):
3,892
Create a function that takes a number as an argument and returns a grade based on that number. Score | Grade -----------------------------------------|----- Anything greater than 1 or less than 0.6 | "F" 0.9 or greater | "A" 0.8 or greater ...
["def grader(x):\n if 0.9 <= x <= 1: return \"A\"\n elif 0.8 <= x < 0.9: return \"B\"\n elif 0.7 <= x < 0.8: return \"C\"\n elif 0.6 <= x < 0.7: return \"D\"\n else: return \"F\"", "def grader(score):\n for limit, grade in [(0.9, \"A\"), (0.8, \"B\"), (0.7, \"C\"), (0.6, \"D\")]:\n if limit <= score <= 1...
{"fn_name": "grader", "inputs": [[1], [1.01], [0.2], [0.7], [0.8], [0.9], [0.6], [0.5], [0]], "outputs": [["A"], ["F"], ["F"], ["C"], ["B"], ["A"], ["D"], ["F"], ["F"]]}
introductory
https://www.codewars.com/kata/53d16bd82578b1fb5b00128c
def grader(score):
3,893
Create a function named `divisors`/`Divisors` that takes an integer `n > 1` and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime' (`null` in C#) (use `Either String a` in Haskell and `Result, S...
["def divisors(num):\n l = [a for a in range(2,num) if num%a == 0]\n if len(l) == 0:\n return str(num) + \" is prime\"\n return l", "def divisors(integer):\n a = []\n for i in range(2, integer):\n if integer % i == 0:\n a.append(i)\n return a if a else str(integer) + \" is prime\"", "def divi...
{"fn_name": "divisors", "inputs": [[15], [253], [24], [13], [3], [29]], "outputs": [[[3, 5]], [[11, 23]], [[2, 3, 4, 6, 8, 12]], ["13 is prime"], ["3 is prime"], ["29 is prime"]]}
introductory
https://www.codewars.com/kata/544aed4c4a30184e960010f4
def divisors(integer):
3,894
In this Kata, you will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on: * make as few changes as possible. * if the string contains equal number of uppercase and lowercase letters, convert the string to ...
["def solve(s):\n return s.upper() if sum(map(str.isupper, s)) * 2 > len(s) else s.lower()", "def solve(s):\n upper = 0\n lower = 0\n \n for char in s:\n if char.islower():\n lower += 1\n else:\n upper += 1\n \n if upper == lower or lower > upper:\n ...
{"fn_name": "solve", "inputs": [["code"], ["CODe"], ["COde"], ["Code"]], "outputs": [["code"], ["CODE"], ["code"], ["code"]]}
introductory
https://www.codewars.com/kata/5b180e9fedaa564a7000009a
def solve(s):
3,895
Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5 characters forward to produce the second string,...
["def shifted_diff(first, second):\n return (second + second).find(first) if len(first) == len(second) else - 1;", "def shifted_diff(first, second):\n for i in range(len(first)):\n if first == second[i:] + second[:i]:\n return i\n return -1", "def shifted_diff(first, second):\n return next(i...
{"fn_name": "shifted_diff", "inputs": [["fatigue", "tiguefa"], ["hoop", "pooh"], ["eecoff", "coffee"], ["Moose", "moose"], ["isn't", "'tisn"], ["Esham", "Esham"], [" ", " "], ["dog", "god"], [" ", " "], ["doomhouse", "hoodmouse"], ["123456789!@#$%^&*( )qwerty", "9!@#$%^&*( )qwerty12345678"]], "outputs": [[5], [-1], [4...
introductory
https://www.codewars.com/kata/5596f6e9529e9ab6fb000014
def shifted_diff(first, second):
3,896
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 **below** the number passed in. > Note: If the number is a multiple of **both** 3 and 5, only count it *once*...
["def solution(number):\n return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0)\n", "def solution(number):\n sum = 0\n for i in range(number):\n if (i % 3) == 0 or (i % 5) == 0:\n sum += i\n return sum", "def solution(number):\n return sum([x for x in range(number) if x % 3 == ...
{"fn_name": "solution", "inputs": [[10], [20], [0], [1], [200]], "outputs": [[23], [78], [0], [0], [9168]]}
introductory
https://www.codewars.com/kata/514b92a657cdc65150000006
def solution(number):
3,897
Jack and Jill are playing a game. They have balls numbered from `0` to `n - 1`. Jack looks the other way and asks Jill to reverse the position of the balls, for instance, to change the order from say, `0,1,2,3` to `3,2,1,0`. He further asks Jill to reverse the position of the balls `n` times, each time starting from on...
["def solve(count, ball_number):\n \"\"\"\n Return the position of the `ball_number` after the game with `count` balls\n\n :param count: Number of balls\n :type count: int\n :param ball_number: Number of ball to be found in the end\n :type ball_number: int\n :return: Return the index of the ball `b...
{"fn_name": "solve", "inputs": [[4, 1], [4, 2], [4, 3], [20, 8], [20, 9], [20, 10]], "outputs": [[3], [2], [0], [17], [19], [18]]}
introductory
https://www.codewars.com/kata/5b93636ba28ce032600000b7
def solve(n,k):
3,898
Convert DD (decimal degrees) position to DMS (degrees, minutes, seconds). ##### Inputs: `dd_lat` and `dd_lon` 2 strings representing the latitude and the longitude in degree -i.e. 2 floats included in [-90, 90] and [-180, 180]. Note that latitude 0 is north, longitude 0 is east. ##### Outputs: A tuple of DMS latitude...
["from math import floor\n\ndef convert(dd, direction):\n degrees = floor(dd)\n seconds = round((dd % 1) * 3600000)\n return \"%03d*%02d\\'%06.3f\\\"%s\" % (degrees, \n seconds // 60000,\n seconds % 60000 / 1000,\n ...
{"fn_name": "convert_to_dms", "inputs": [["35.03299485527936", "33.233755230903625"], ["-37.111415669561595", "-12.284317023586482"], ["19.61499312350978", "-155.48217818140984"]], "outputs": [["035*01'58.781\"N", "033*14'01.519\"E"], ["037*06'41.096\"S", "012*17'03.541\"W"], ["019*36'53.975\"N", "155*28'55.841\"W"]]}
introductory
https://www.codewars.com/kata/5a72fd224a6b3463b00000a0
def convert_to_dms(dd_lat, dd_lon):
3,899
Your Goal is to create a function that takes two strings, a guess and a phone number. Based on the guess, the function should display a portion of the phone number: guess_my_number('052', '123-451-2345') would return the string: '#2#-#5#-2##5' or guess_my_number('142', '123-451-2345') ...
["def guess_my_number(guess, number = '123-451-2345'):\n return \"\".join(c if c in guess+\"-\" else \"#\" for c in number)\n", "from re import sub\ndef guess_my_number(guess, number = '123-451-2345'):\n return sub('[^{}-]'.format(guess), '#', number)", "guess_my_number=lambda g,n='123-451-2345':''.join(('#'+c)[c...
{"fn_name": "guess_my_number", "inputs": [["0"], ["01"], ["012"], ["0123"], ["01234"], ["012345"]], "outputs": [["###-###-####"], ["1##-##1-####"], ["12#-##1-2###"], ["123-##1-23##"], ["123-4#1-234#"], ["123-451-2345"]]}
introductory
https://www.codewars.com/kata/5654d2428be803670a000030
def guess_my_number(guess, number = '123-451-2345'):
3,900
A **Seven Segment Display** is an electronic display device, used to display decimal or hexadecimal numerals. It involves seven led segments that are lit in specific combinations to represent a specific numeral. An example of each combination is shown below: ![seven segment display](https://upload.wikimedia.org/wikipe...
["BASE = [r.split('|') for r in '''\\\n ### | | ### | ### | | ### | ### | ### | ### | ### | \n # # | # | # | # | # # | # | # | # | # # | # # | \n # # | # | # | # | # # | # | # | # | # # | # # | \n # # | #...
{"fn_name": "segment_display", "inputs": [[123456], [987654], [0]], "outputs": [["| | ### | ### | | ### | ### |\n| # | # | # | # # | # | # |\n| # | # | # | # # | # | # |\n| # | # | # | # # | # | # |\n| | ### | ### | ### | ...
introductory
https://www.codewars.com/kata/5d7091aa7bf8d0001200c133
def segment_display(num):
3,901
In this Kata, you will be given a ```number```, two indexes (```index1``` and ```index2```) and a ```digit``` to look for. Your task will be to check if the ```digit``` exists in the ```number```, within the ```indexes``` given. Be careful, the ```index2``` is not necessarily more than the ```index1```. ``` index1 ...
["def check_digit(n, idx1, idx2, digit):\n return str(digit) in str(n)[idx1:idx2+1] + str(n)[idx2:idx1+1]", "def check_digit(n, i1, i2, d):\n return str(d) in str(n)[min(i1,i2):max(i1,i2)+1]", "def check_digit(number, index1, index2, digit):\n number, digit = str(number), str(digit)\n index1, index2 = sorte...
{"fn_name": "check_digit", "inputs": [[1234567, 1, 0, 1], [1234567, 0, 1, 2], [67845123654, 4, 2, 4], [6668844536485, 0, 0, 6], [9999999999, 2, 5, 1]], "outputs": [[true], [true], [true], [true], [false]]}
introductory
https://www.codewars.com/kata/5a2e8c0955519e54bf0000bd
def check_digit(number, index1, index2, digit):
3,902
The purpose of this kata is to work out just how many bottles of duty free whiskey you would have to buy such that the saving over the normal high street price would effectively cover the cost of your holiday. You will be given the high street price (normPrice), the duty free discount (discount) and the cost of the h...
["def duty_free(price, discount, holiday_cost):\n saving = price * discount / 100.0\n return int(holiday_cost / saving)", "def duty_free(price, discount, holiday_cost):\n return holiday_cost * 100 // price // discount", "def duty_free(price, discount, holiday_cost):\n return holiday_cost // (price * (discount /...
{"fn_name": "duty_free", "inputs": [[12, 50, 1000], [17, 10, 500], [24, 35, 3000], [1400, 35, 10000], [700, 26, 7000]], "outputs": [[166], [294], [357], [20], [38]]}
introductory
https://www.codewars.com/kata/57e92e91b63b6cbac20001e5
def duty_free(price, discount, holiday_cost):
3,903
In Russia, there is an army-purposed station named UVB-76 or "Buzzer" (see also https://en.wikipedia.org/wiki/UVB-76). Most of time specific "buzz" noise is being broadcasted, but on very rare occasions, the buzzer signal is interrupted and a voice transmission in Russian takes place. Transmitted messages have always t...
["import re\nvalidate = lambda msg: bool(re.match('^MDZHB \\d\\d \\d\\d\\d [A-Z]+ \\d\\d \\d\\d \\d\\d \\d\\d$', msg))", "import re\ndef validate(message):\n return bool(re.match(r\"^MDZHB \\d{2} \\d{3} [A-Z]+ \\d{2} \\d{2} \\d{2} \\d{2}$\", message))", "import re\ndef validate(message):\n return re.match(r'^MDZHB(...
{"fn_name": "validate", "inputs": [["Is this a right message?"], ["MDZHB 85 596 KLASA 81 00 02 91"], ["MDZHB 12 733 EDINENIE 67 79 66 32"], ["MDZHV 60 130 VATRUKH 58 89 54 54"], ["MDZHB 85 596 BRAMIRKA 81 00 02 91"], ["MDZHB 12 733 INITIAL 67 79 66 32"], ["MDZHB 60 130 KROLI5T 58 89 54 54"], ["MDZHB 85 596 KAMASIT 81 0...
introductory
https://www.codewars.com/kata/56445cc2e5747d513c000033
def validate(message):
3,904
Same as [the original](https://www.codewars.com/kata/simple-fun-number-258-is-divisible-by-6) (same rules, really, go there for example and I strongly recommend completing it first), but with more than one asterisk (but always at least one). For example, `"*2"` should return `["12", "42", "72"]`. Similarly, `"*2*"` s...
["from itertools import product\n\ndef is_divisible_by_6(s):\n if s[-1] in '13579': return []\n ss = s.replace('*','{}')\n return [ v for v in (ss.format(*p) for p in product(*(['0123456789']*s.count('*')))) if not int(v)%6]", "def create_permutations(string):\n if '*' not in string:\n return [int(st...
{"fn_name": "is_divisible_by_6", "inputs": [["*2"], ["*21"], ["**1"], ["*2*"], ["***"]], "outputs": [[["12", "42", "72"]], [[]], [[]], [["024", "120", "126", "222", "228", "324", "420", "426", "522", "528", "624", "720", "726", "822", "828", "924"]], [["000", "006", "012", "018", "024", "030", "036", "042", "048", "054...
introductory
https://www.codewars.com/kata/5a1a8b7ec374cbea92000086
def is_divisible_by_6(s):
3,905
In this Kata, you will be given a string of numbers in sequence and your task will be to return the missing number. If there is no number missing or there is an error in the sequence, return `-1`. For example: ```Haskell missing("123567") = 4 missing("899091939495") = 92 missing("9899101102") = 100 missing("599600601...
["def missing(seq):\n for digits in range(1, len(seq) // 2 + 1):\n my_seq = last = seq[:digits]\n n = int(my_seq)\n missing = None\n \n while len(my_seq) < len(seq):\n n += 1\n my_seq += str(n)\n \n if not seq.startswith(my_seq):\n ...
{"fn_name": "missing", "inputs": [["123567"], ["899091939495"], ["9899101102"], ["599600601602"], ["8990919395"], ["998999100010011003"], ["99991000110002"], ["979899100101102"], ["900001900002900004900005900006"]], "outputs": [[4], [92], [100], [-1], [-1], [1002], [10000], [-1], [900003]]}
introductory
https://www.codewars.com/kata/5a28cf591f7f7019a80000de
def missing(s):
3,906
Write a function that takes an array/list of numbers and returns a number such that Explanation total([1,2,3,4,5]) => 48 1+2=3--\ 3+5 => 8 \ 2+3=5--/ \ == 8+12=>20\ ==>5+7=> 12 / \ 20+28 => 48 3+4=7--\ / == 12+16=>28/ 4+5=9--/ 7+9 => 16 / if total([1,2,3]) =...
["def total(arr):\n while len(arr) > 1:\n arr = [x+y for x,y in zip(arr,arr[1:])]\n return arr[0]", "def total(arr):\n from math import factorial as fact\n\n choose = lambda a, b: fact(a) / (fact(a-b) * fact(b))\n\n return sum(choose(len(arr)-1, i) * v for i, v in enumerate(arr))", "def total(xs):\n ...
{"fn_name": "total", "inputs": [[[1, 2, 3, 4, 5]], [[1, 2, 3, 4]], [[1, 2, 3]], [[4, 4, 52, 23, 32, 1, -1]], [[4, 4, 5, -1]], [[-1, -1, -1]], [[-1, -1, -10, 42, 92, 1, 23, 6, -3]], [[-1, 1, -1, 1]], [[42]]], "outputs": [[48], [20], [8], [1753], [30], [-4], [9248], [0], [42]]}
introductory
https://www.codewars.com/kata/559fed8454b12433ff0000a2
def total(arr):
3,907
We need you to implement a method of receiving commands over a network, processing the information and responding. Our device will send a single packet to you containing data and an instruction which you must perform before returning your reply. To keep things simple, we will be passing a single "packet" as a string....
["INSTRUCTIONS = {\"0F12\": int.__add__, \"B7A2\": int.__sub__, \"C3D9\": int.__mul__}\n\ndef communication_module(packet):\n header,inst,d1,d2,footer = (packet[i:i+4] for i in range(0,20,4))\n res = max(0, min(9999, INSTRUCTIONS[inst](int(d1), int(d2)) ))\n \n return f\"{header}FFFF{res:0>4}0000{footer}\""...
{"fn_name": "communication_module", "inputs": [["H1H10F1200120008F4F4"], ["D7D70F1200250015G8G8"], ["X7X7B7A201400058L0L0"], ["Y2Y2B7A210000902N5N5"], ["R5R5C3D900120008K4K4"], ["S2S2C3D900250005I9I9"], ["E4E40F1239128908Z3Z3"], ["A6A6C3D911150015M0M0"], ["T7T7B7A200258908P2P2"], ["S4S4B7A201153215U8U8"]], "outputs": [...
introductory
https://www.codewars.com/kata/5b2be37991c7460d17000009
def communication_module(packet):
3,908
In this Kata, you will sort elements in an array by decreasing frequency of elements. If two elements have the same frequency, sort them by increasing value. More examples in test cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
["from collections import Counter\n\ndef solve(a):\n c = Counter(a)\n return sorted(a, key=lambda k: (-c[k], k))", "def solve(arr):\n return sorted(arr, key= lambda x: (-arr.count(x), x))", "def solve(arr):\n return sorted(sorted(arr), key=lambda n: arr.count(n), reverse=True)", "def solve(arr):\n freq =...
{"fn_name": "solve", "inputs": [[[2, 3, 5, 3, 7, 9, 5, 3, 7]], [[1, 2, 3, 0, 5, 0, 1, 6, 8, 8, 6, 9, 1]], [[5, 9, 6, 9, 6, 5, 9, 9, 4, 4]], [[4, 4, 2, 5, 1, 1, 3, 3, 2, 8]], [[4, 9, 5, 0, 7, 3, 8, 4, 9, 0]]], "outputs": [[[3, 3, 3, 5, 5, 7, 7, 2, 9]], [[1, 1, 1, 0, 0, 6, 6, 8, 8, 2, 3, 5, 9]], [[9, 9, 9, 9, 4, 4, 5, 5,...
introductory
https://www.codewars.com/kata/5a8d2bf60025e9163c0000bc
def solve(arr):
3,909
In recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence: `14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequence A007629 in the ...
["def is_keith_number(n):\n numList = [int(i) for i in str(n)] # int array\n if len(numList) > 1: # min 2 digits\n itr = 0\n while numList[0] <= n:\n # replace array entries by its sum:\n numList[itr % len(numList)] = sum(numList)\n itr += 1\n if n in nu...
{"fn_name": "is_keith_number", "inputs": [[14], [10], [4], [28], [23], [0], [19], [47], [34], [61], [58], [75], [197], [742], [1104], [1537], [2208], [2697], [7385], [31331], [120284], [1084051], [44121607], [251133297], [96189170155], [11812665388886672], [855191324330802397989], [18354972585225358067718266], [4179620...
introductory
https://www.codewars.com/kata/590e4940defcf1751c000009
def is_keith_number(n):
3,910
An expression is formed by taking the digits 1 to 9 in numerical order and then inserting into each gap between the numbers either a plus sign or a minus sign or neither. Your task is to write a method which takes one parameter and returns the **smallest possible number** of plus and minus signs necessary to form such...
["from itertools import product\n\ndef operator_insertor(n):\n result = []\n \n for ops in product([\"+\", \"-\", \"\"], repeat=8):\n expression = \"\".join(a+b for a, b in zip(\"123456789\", list(ops) + [\"\"]))\n res = eval(expression)\n if res == n:\n result.append(len(expres...
{"fn_name": "operator_insertor", "inputs": [[11], [100], [766], [160], [70], [389]], "outputs": [[5], [3], [4], [null], [6], [2]]}
introductory
https://www.codewars.com/kata/596b7f284f232df61e00001b
def operator_insertor(n):
3,911
I always thought that my old friend John was rather richer than he looked, but I never knew exactly how much money he actually had. One day (as I was plying him with questions) he said: * "Imagine I have between `m` and `n` Zloty..." (or did he say Quetzal? I can't remember!) * "If I were to buy **9** cars costing `c`...
["def howmuch(m, n): \n return [['M: %d'%i, 'B: %d'%(i/7), 'C: %d'%(i/9)] for i in range(min(m,n), max(m,n)+1) if i%7 == 2 and i%9 == 1]\n \n \n \n", "def howmuch(m, n):\n i = min(m, n)\n j = max(m, n)\n res = []\n while (i <= j):\n if ((i % 9 == 1) and (i %7 == 2))...
{"fn_name": "howmuch", "inputs": [[1, 100], [1000, 1100], [10000, 9950], [0, 200], [1500, 1600], [2950, 2950], [20000, 20100]], "outputs": [[[["M: 37", "B: 5", "C: 4"], ["M: 100", "B: 14", "C: 11"]]], [[["M: 1045", "B: 149", "C: 116"]]], [[["M: 9991", "B: 1427", "C: 1110"]]], [[["M: 37", "B: 5", "C: 4"], ["M: 100", "B:...
introductory
https://www.codewars.com/kata/55b4d87a3766d9873a0000d4
def howmuch(m, n):
3,912
Given an array containing only integers, add all the elements and return the binary equivalent of that sum. If the array contains any non-integer element (e.g. an object, a float, a string and so on), return false. **Note:** The sum of an empty array is zero. ```python arr2bin([1,2]) == '11' arr2bin([1,2,'a']) == Fa...
["def arr2bin(arr):\n for x in arr:\n if(type(x) != int):\n return False\n return '{0:b}'.format(sum(arr))", "def arr2bin(arr):\n return all(type(n) == int for n in arr) and format(sum(arr), 'b')", "def arr2bin(arr):\n\n s = 0\n \n for x in arr:\n if type(x) is int:\n s += x\n e...
{"fn_name": "arr2bin", "inputs": [[[1, 2]], [[1, 2, 3, 4, 5]], [[1, 10, 100, 1000]], [[1, 2, -1, -2]], [[1, 2, -1, -2, 1]], [[]]], "outputs": [["11"], ["1111"], ["10001010111"], ["0"], ["1"], ["0"]]}
introductory
https://www.codewars.com/kata/559576d984d6962f8c00003c
def arr2bin(arr):
3,913
Given the current exchange rate between the USD and the EUR is 1.1363636 write a function that will accept the Curency type to be returned and a list of the amounts that need to be converted. Don't forget this is a currency so the result will need to be rounded to the second decimal. 'USD' Return format should be `'...
["def solution(to,lst):\n dolSym, eurSym, power = ('', '\u20ac', -1) if to=='EUR' else ('$','', 1)\n return [f\"{ dolSym }{ v*1.1363636**power :,.2f}{ eurSym }\" for v in lst]", "def solution(to_cur, values):\n rate, fmt = {\n 'USD': (1.1363636, '${:,.2f}'),\n 'EUR': (1 / 1.1363636, '{:,.2f}\u20a...
{"fn_name": "solution", "inputs": [["USD", [1.01, 83.29, 5.0, 23.23, 724.22]], ["USD", [1394.0, 250.85, 721.3, 911.25, 1170.67]], ["EUR", [109.45, 640.31, 1310.99, 669.51, 415.54]], ["EUR", [589.29, 662.31, 1349.71, 117.93, 8.25]], ["USD", [0, 0, 0, 0]], ["EUR", [0, 0, 0, 0]], ["USD", [154, 99]]], "outputs": [[["$1.15"...
introductory
https://www.codewars.com/kata/5c744111cb0cdd3206f96665
def solution(to_cur,value):
3,914
A zero-indexed array ```arr``` consisting of n integers is given. The dominator of array ```arr``` is the value that occurs in more than half of the elements of ```arr```. For example, consider array ```arr``` such that ```arr = [3,4,3,2,3,1,3,3]``` The dominator of ```arr``` is 3 because it occurs in 5 out of 8 elemen...
["def dominator(arr):\n for x in set(arr):\n if arr.count(x) > len(arr)/2.0:\n return x\n return -1", "from collections import Counter\n\n\ndef dominator(arr):\n if not arr:\n return -1\n k, v = Counter(arr).most_common(1)[0]\n return k if v > len(arr) / 2 else -1\n", "dominator=...
{"fn_name": "dominator", "inputs": [[[3, 4, 3, 2, 3, 1, 3, 3]], [[1, 2, 3, 4, 5]], [[1, 1, 1, 2, 2, 2]], [[1, 1, 1, 2, 2, 2, 2]], [[]]], "outputs": [[3], [-1], [-1], [2], [-1]]}
introductory
https://www.codewars.com/kata/559e10e2e162b69f750000b4
def dominator(arr):
3,915
In elementary arithmetic a "carry" is a digit that is transferred from one column of digits to another column of more significant digits during a calculation algorithm. This Kata is about determining the number of carries performed during the addition of multi-digit numbers. You will receive an input string containin...
["def solve(s):\n ans = []\n for ab in s.split('\\n'):\n carry, carried = 0, 0\n for a,b in zip(*map(lambda ss: map(int,ss[::-1]), ab.split())):\n carried += a+b\n carry += carried > 9\n carried //= 10\n ans.append(carry)\n \n return '\\n'.join(\"N...
{"fn_name": "solve", "inputs": [["123 456\n555 555\n123 594"], ["321 679\n098 805\n123 867"], ["123 457\n631 372\n999 111"], ["123 457\n123 456\n654 312\n999 000\n123 457"], ["1 9\n123456789 111111101\n01 09\n11 09\n123 457"], ["99 99"]], "outputs": [["No carry operation\n3 carry operations\n1 carry operations"], ["3 c...
introductory
https://www.codewars.com/kata/529fdef7488f509b81000061
def solve(s):
3,916
Your goal is to implement the method **meanVsMedian** which accepts an *odd-length* array of integers and returns one of the following: * 'mean' - in case **mean** value is **larger than** median value * 'median' - in case **median** value is **larger than** mean value * 'same' - in case both mean and median share the...
["from numpy import mean, median\n\ndef mean_vs_median(numbers):\n if mean(numbers) > median(numbers):\n return 'mean'\n elif mean(numbers) < median(numbers):\n return 'median'\n else:\n return 'same'", "def mean_vs_median(numbers):\n mean = sum(numbers)/len(numbers)\n med = sorted(n...
{"fn_name": "mean_vs_median", "inputs": [[[1, 1, 1]], [[1, 2, 37]], [[7, 14, -70]], [[-10, 20, 5]]], "outputs": [["same"], ["mean"], ["median"], ["same"]]}
introductory
https://www.codewars.com/kata/5806445c3f1f9c2f72000031
def mean_vs_median(numbers):
3,917
# Back-Story Every day I travel on the freeway. When I am more bored than usual I sometimes like to play the following counting game I made up: * As I join the freeway my count is ```0``` * Add ```1``` for every car that I overtake * Subtract ```1``` for every car that overtakes me * Stop counting when I reach my ex...
["def freeway_game(km, kph, cars):\n t = km / kph\n c = 0\n for dt, speed in cars:\n d = km - (t - dt/60) * speed\n if dt <= 0:\n c += d > 0\n else:\n c -= d < 0\n return c", "def freeway_game(dist_km_to_exit, my_speed_kmph, other_cars):\n my_time_to_exit = dist...
{"fn_name": "freeway_game", "inputs": [[50.0, 130.0, [[-1.0, 120.0], [-1.5, 120.0]]], [50.0, 110.0, [[1.0, 120.0], [1.5, 125.0]]], [50.0, 120.0, [[-1.0, 115.0], [-1.5, 110.0], [1.0, 130.0], [1.5, 130.0]]], [30.0, 100.0, [[-1.0, 110.0], [-0.7, 102.0], [-1.5, 108.0]]], [30.0, 130.0, [[1.0, 120.0], [0.7, 125.0], [1.5, 110...
introductory
https://www.codewars.com/kata/59279aea8270cc30080000df
def freeway_game(dist_km_to_exit, my_speed_kph, other_cars):
3,918
You've had a baby. Well done. Nice isn't it? Life destroying... but in a good way. Part of your new routine is lying awake at night worrying that you've either lost the baby... or that you have more than 1! Given a string of words (x), you need to calculate how many babies are in it. To count as a baby you must have...
["def baby_count(x):\n x = x.lower()\n return min(x.count('a'), x.count('b') // 2, x.count('y')) or \"Where's the baby?!\"", "from collections import Counter\n\ndef baby_count(x):\n c = Counter(x.lower())\n return min(c['b'] // 2, c['a'], c['y']) or \"Where's the baby?!\"", "from collections import Counter\...
{"fn_name": "baby_count", "inputs": [["baby"], ["abby"], ["baby baby baby"], ["Why the hell are there so many babies?!"], ["Anyone remember life before babies?"], ["Happy babies boom ba by?"], ["b a b y"], [""], ["none here"]], "outputs": [[1], [1], [3], [1], [1], [2], [1], ["Where's the baby?!"], ["Where's the baby?!"...
introductory
https://www.codewars.com/kata/5bc9951026f1cdc77400011c
def baby_count(x):
3,919
# Task A noob programmer was given two simple tasks: sum and sort the elements of the given array `arr` = [a1, a2, ..., an]. He started with summing and did it easily, but decided to store the sum he found in some random position of the original array which was a bad idea. Now he needs to cope with the second task...
["def shuffled_array(s):\n result = sorted(s)\n result.remove(sum(result) // 2)\n return result\n", "def shuffled_array(s):\n for i in s:\n if sum(s)-i == i: \n s.pop(s.index(i))\n break\n return sorted(s)", "def shuffled_array(s):\n s.pop(s.index(sum(s) /2))\n return s...
{"fn_name": "shuffled_array", "inputs": [[[1, 12, 3, 6, 2]], [[1, -3, -5, 7, 2]], [[2, -1, 2, 2, -1]], [[-3, -3]]], "outputs": [[[1, 2, 3, 6]], [[-5, -3, 2, 7]], [[-1, -1, 2, 2]], [[-3]]]}
introductory
https://www.codewars.com/kata/589573e3f0902e8919000109
def shuffled_array(s):
3,920
# Task The `hamming distance` between a pair of numbers is the number of binary bits that differ in their binary notation. # Example For `a = 25, b= 87`, the result should be `4` ``` 25: 00011001 87: 01010111 ``` The `hamming distance` between these two would be 4 ( the `2nd, 5th, 6th, 7th` bit ). # Input/Outpu...
["def hamming_distance(a, b):\n return bin(a ^ b).count('1')", "from itertools import zip_longest\ndef hamming_distance(a, b):\n return(sum(x != y for x,y in zip_longest(*[bin(x)[-1:1:-1] for x in (a,b)],fillvalue='0')))\n", "def hamming_distance(a, b):\n return sum(int(i) for i in bin(a^b)[2:])", "def hamming...
{"fn_name": "hamming_distance", "inputs": [[25, 87], [256, 302], [543, 634], [34013, 702]], "outputs": [[4], [4], [4], [7]]}
introductory
https://www.codewars.com/kata/58a6af7e8c08b1e9c40001c1
def hamming_distance(a, b):
3,921
Correct this code so that it takes one argument, `x`, and returns "`x` is more than zero" if `x` is positive (and nonzero), and otherwise, returns "`x` is equal to or less than zero." In both cases, replace `x` with the actual value of `x`.
["def corrections(x):\n str = \"{0} is more than zero.\" if x > 0 else \"{0} is equal to or less than zero.\"\n return str.format(x)", "def corrections(x):\n if x > 0:\n return f'{x} is more than zero.'\n else:\n return f'{x} is equal to or less than zero.'", "corrections = lambda x: '%s is %s...
{"fn_name": "corrections", "inputs": [[8], [1], [-2], [-1], [0]], "outputs": [["8 is more than zero."], ["1 is more than zero."], ["-2 is equal to or less than zero."], ["-1 is equal to or less than zero."], ["0 is equal to or less than zero."]]}
introductory
https://www.codewars.com/kata/55a710b462afc49a540000b9
def corrections(x):
3,922
# Task You are a lonely frog. You live on an integer array. The meaning of your life is to jump and jump.. Now, here comes your new task. You are given an integer array `arr` and a positive integer `n`. You will jump following the rules below: - Your initial position at `arr[0]`. arr[0] will always be `0`. - ...
["def jumping(arr, n):\n i = 0\n while i < len(arr):\n x = arr[i]\n arr[i] += 1 if x < n else -1\n i += x\n return arr.count(n)", "def jumping(arr, n):\n i, arr = 0, arr[:]\n arr[0] += 1\n while i<len(arr):\n delta = arr[i]\n arr[i] += (arr[i]<n) - (arr[i]>=n)\n ...
{"fn_name": "jumping", "inputs": [[[0, 3, 0, 1, -3], 3], [[0, -1, -2, -3, -4], 4], [[0, -1, -2, -3, -4], 3], [[0, -1, -2, -3, -4], 2], [[0, -1, -2, -3, -4], 1]], "outputs": [[2], [2], [0], [3], [0]]}
introductory
https://www.codewars.com/kata/5a274c9fc5e284a9f7000072
def jumping(arr, n):
3,923
# Your Task You have a Petri dish with bacteria, and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them. You know that you have `n` bacteria in the Petri dish and size of the i-th bacteria is bacteriai. Also you know intergalactic pos...
["def micro_world(bacteria, k):\n return sum(1 for e in bacteria if not [j for j in bacteria if e<j<=e+k])\n", "def micro_world(bact, k):\n bact = sorted(bact)\n return sum(1 for i, a in enumerate(bact) if all(a == b or a + k < b for b in bact[i+1:]))", "from collections import Counter\n\ndef micro_world(bacte...
{"fn_name": "micro_world", "inputs": [[[101, 53, 42, 102, 101, 55, 54], 1], [[20, 15, 10, 15, 20, 25], 5], [[5, 3, 1, 5], 1]], "outputs": [[3], [1], [4]]}
introductory
https://www.codewars.com/kata/5ba068642ab67b95da00011d
def micro_world(bacteria, k):
3,924
Complete the function that accepts a string parameter, and reverses each word in the string. **All** spaces in the string should be retained. ## Examples ``` "This is an example!" ==> "sihT si na !elpmaxe" "double spaces" ==> "elbuod secaps" ```
["def reverse_words(str):\n return ' '.join(s[::-1] for s in str.split(' '))", "def reverse_words(str_):\n return ' '.join(s[::-1] for s in str_.split(' '))\n", "import re\n\ndef reverse_words(str):\n return re.sub(r'\\S+', lambda w: w.group(0)[::-1], str)", "def reverse_words(str):\n return ' '.join(w[::-1] fo...
{"fn_name": "reverse_words", "inputs": [["The quick brown fox jumps over the lazy dog."], ["apple"], ["a b c d"], ["double spaced words"], ["stressed desserts"], ["hello hello"]], "outputs": [["ehT kciuq nworb xof spmuj revo eht yzal .god"], ["elppa"], ["a b c d"], ["elbuod decaps sdrow"], ["desserts stressed"], ["...
introductory
https://www.codewars.com/kata/5259b20d6021e9e14c0010d4
def reverse_words(text):
3,925
# Task John and Alice have an appointment today. In the morning, John starts from (`0,0`) and goes to the place (`a,b`) where he is dating. Unfortunately, John had no sense of direction at all, so he moved 1 step in a random direction(up, down, left or right) each time. For example, if John at (x,y), next step he ma...
["def is_john_lying(a,b,s):\n delta = abs(a) + abs(b) - s\n return delta <= 0 and delta % 2 == 0", "def is_john_lying(a,b,s):\n a, b = abs(a), abs(b)\n return s-a-b>=0 and (s-a-b)%2 == 0", "def is_john_lying(a, b, s):\n return s >= abs(a) + abs(b) and s % 2 == (a + b) % 2", "def is_john_lying(a,b,s):\n ...
{"fn_name": "is_john_lying", "inputs": [[3, 3, 6], [4, 5, 10], [-5, -5, 10], [-5, -5, 8], [10, -10, 10]], "outputs": [[true], [false], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/594cd799c08247a55a000004
def is_john_lying(a,b,s):
3,926
While surfing in web I found interesting math problem called "Always perfect". That means if you add 1 to the product of four consecutive numbers the answer is ALWAYS a perfect square. For example we have: 1,2,3,4 and the product will be 1X2X3X4=24. If we add 1 to the product that would become 25, since the result numb...
["def check_root(string):\n try:\n a,b,c,d = [int(i) for i in string.split(',')]\n if not (a == b-1 and a == c-2 and a == d-3):\n return 'not consecutive'\n s = a*b*c*d+1\n return str(s)+', '+str(int(s**0.5))\n except:\n return 'incorrect input'", "import re\ndef chec...
{"fn_name": "check_root", "inputs": [["4,5,6,7"], ["3,s,5,6"], ["11,13,14,15"], ["10,11,12,13,15"], ["10,11,12,13"], ["ad,d,q,tt,v"], ["//,;;,/,..,"], ["1,2,3,4"], ["1015,1016,1017,1018"], ["555,777,444,111"], ["20,21,22,24"], ["9,10,10,11"], ["11254,11255,11256,11258"], ["25000,25001,25002,25003"], ["2000000,2000001,2...
introductory
https://www.codewars.com/kata/55f3facb78a9fd5b26000036
def check_root(string):
3,927
Some numbers have funny properties. For example: > 89 --> 8¹ + 9² = 89 * 1 > 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2 > 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51 Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p - we want to find a positive integer k, if i...
["def dig_pow(n, p):\n s = 0\n for i,c in enumerate(str(n)):\n s += pow(int(c),p+i)\n return s/n if s%n==0 else -1\n", "def dig_pow(n, p):\n k, fail = divmod(sum(int(d)**(p + i) for i, d in enumerate(str(n))), n)\n return -1 if fail else k\n", "def dig_pow(n, p):\n t = sum( int(d) ** (p+i) for i, d in enu...
{"fn_name": "dig_pow", "inputs": [[89, 1], [92, 1], [46288, 3], [114, 3], [46288, 5], [135, 1], [175, 1], [518, 1], [598, 1], [1306, 1], [2427, 1], [2646798, 1], [3456789, 1], [3456789, 5], [198, 1], [249, 1], [1377, 1], [1676, 1], [695, 2], [1878, 2], [7388, 2], [47016, 2], [542186, 2], [261, 3], [1385, 3], [2697, 3],...
introductory
https://www.codewars.com/kata/5552101f47fc5178b1000050
def dig_pow(n, p):
3,928
You can print your name on a billboard ad. Find out how much it will cost you. Each letter has a default price of £30, but that can be different if you are given 2 parameters instead of 1. You can not use multiplier "*" operator. If your name would be Jeong-Ho Aristotelis, ad would cost £600. 20 leters * 30 = 600 (Sp...
["def billboard(name, price=30):\n return sum(price for letter in name)", "def billboard(name, price = 30):\n return len(name) * price", "def billboard(name, price = 30):\n return sum([price for l in name])", "def billboard(name, price=30):\n return sum(price for _ in name)", "def billboard(name, price=30):...
{"fn_name": "billboard", "inputs": [["Jeong-Ho Aristotelis"], ["Abishai Charalampos"], ["Idwal Augustin"], ["Hadufuns John", 20], ["Zoroaster Donnchadh"], ["Claude Miljenko"], ["Werner Vigi", 15], ["Anani Fridumar"], ["Paolo Oli"], ["Hjalmar Liupold", 40], ["Simon Eadwulf"]], "outputs": [[600], [570], [420], [260], [57...
introductory
https://www.codewars.com/kata/570e8ec4127ad143660001fd
def billboard(name, price=30):
3,929
You need to write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples: As the input may have trailing spaces, you will also need to ignore unneccesary whitespace. ```python reverse('Hello World') == 'World Hello' reverse('Hi Th...
["def reverse(st):\n return \" \".join(reversed(st.split())).strip()", "def reverse(st):\n st = st.split()\n st.reverse()\n return ' '.join(st)", "def reverse(stg):\n return ' '.join(reversed(stg.split()))", "def reverse(st):\n s = st.split()\n return ' '.join(s[::-1])", "def reverse(st): \n wo...
{"fn_name": "reverse", "inputs": [["I am an expert at this"], ["This is so easy"], ["no one cares"]], "outputs": [["this at expert an am I"], ["easy so is This"], ["cares one no"]]}
introductory
https://www.codewars.com/kata/57a55c8b72292d057b000594
def reverse(st):
3,930
You start with a value in dollar form, e.g. $5.00. You must convert this value to a string in which the value is said, like '5 dollars' for example. This should account for ones, cents, zeroes, and negative values. Here are some examples: ```python dollar_to_speech('$0.00') == '0 dollars.' dollar_to_speech('$1.00') == ...
["def dollar_to_speech(value):\n if \"-\" in value:\n return \"No negative numbers are allowed!\"\n d, c = (int(n) for n in value.replace(\"$\", \"\").split(\".\"))\n dollars = \"{} dollar{}\".format(str(d), \"s\" if d != 1 else \"\") if d or not c else \"\"\n link = \" and \" if (d and c) else \"\"\...
{"fn_name": "dollar_to_speech", "inputs": [["$20.18"], ["$5.62"], ["$83.47"], ["$16.93"], ["$0.00"], ["$0.01"], ["$0.63"], ["$0.28"], ["$1.00"], ["$2.00"], ["$31.00"], ["$45.00"], ["$-5843.21"], ["$-45.32"], ["$-2.63"], ["$-234.48"]], "outputs": [["20 dollars and 18 cents."], ["5 dollars and 62 cents."], ["83 dollars a...
introductory
https://www.codewars.com/kata/5b23d98da97f02a5f4000a4c
def dollar_to_speech(value):
3,931
# Letterss of Natac In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build settlements, roads, and cities or buy a development. Other kata about this game can be found [here](https://www....
["from collections import Counter\n\nREQUIRE = {x: Counter(s) for x,s in [('road', 'bw'), ('settlement', 'bwsg'), ('city', 'ooogg'), ('development', 'osg')] }\n\ndef build_or_buy(hand):\n h = Counter(hand)\n return [item for item,c in REQUIRE.items() if not c-h]", "def build_or_buy(hand):\n d = {'bw': 'road', ...
{"fn_name": "build_or_buy", "inputs": [["bwoo"], [""], ["ogogoogogo"], ["bwbwwwbb"]], "outputs": [[["road"]], [[]], [["city"]], [["road"]]]}
introductory
https://www.codewars.com/kata/59e6aec2b2c32c9d8b000184
def build_or_buy(hand):
3,932
# Story&Task The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all houses in the city were built in one row. Let's enumerate all the houses from left to right, starting with 0. A house is considered to be luxurious if the number of floors in it is strictl...
["def luxhouse(houses):\n return [max(0, max(houses[i:]) - h + 1) for i, h in enumerate(houses[:-1], 1)] + [0]", "from itertools import accumulate\n\ndef luxhouse(houses):\n return [max(0, y-x+1) for x,y in zip(houses[::-1], accumulate([0] + houses[:0:-1], max))][::-1]", "def luxhouse(a):\n li = []\n for i,...
{"fn_name": "luxhouse", "inputs": [[[1, 2, 3, 1, 2]], [[3, 2, 1, 4]], [[1, 2, 3]], [[3, 2, 1]], [[1, 1, 1]]], "outputs": [[[3, 2, 0, 2, 0]], [[2, 3, 4, 0]], [[3, 2, 0]], [[0, 0, 0]], [[1, 1, 0]]]}
introductory
https://www.codewars.com/kata/58c8af49fd407dea5f000042
def luxhouse(houses):
3,933
# Welcome to the Codewars Bar! Codewars Bar recommends you drink 1 glass of water per standard drink so you're not hungover tomorrow morning. Your fellow coders have bought you several drinks tonight in the form of a string. Return a string suggesting how many glasses of water you should drink to not be hungover. ##...
["def hydrate(drink_string): \n c=sum(int(c) for c in drink_string if c.isdigit())\n return \"{} {} of water\".format(c,'glass') if c==1 else \"{} {} of water\".format(c,'glasses')", "import re\n\ndef hydrate(s):\n n = sum(map(int,re.findall(r'\\d+',s)))\n return f\"{ n } glass{ 'es'*(n!=1) } of water\"", "...
{"fn_name": "hydrate", "inputs": [["1 beer"], ["2 glasses of wine and 1 shot"], ["1 shot, 5 beers, 2 shots, 1 glass of wine, 1 beer"]], "outputs": [["1 glass of water"], ["3 glasses of water"], ["10 glasses of water"]]}
introductory
https://www.codewars.com/kata/5aee86c5783bb432cd000018
def hydrate(drink_string):
3,934
## Task: You have to write a function `pattern` which returns the following Pattern (See Pattern & Examples) upto `n` number of rows. * Note: `Returning` the pattern is not the same as `Printing` the pattern. ### Rules/Note: * If `n < 1` then it should return "" i.e. empty string. * There are `no whitespaces` in the...
["def pattern(n):\n return \"\\n\".join([\"\".join([str(y) for y in range(n, x, -1)]) for x in range(n)]);", "def pattern(n):\n return '\\n'.join([''.join(map(str, list(range(n, x, -1)))) for x in range(n)])\n", "def pattern(n):\n return('\\n'.join(''.join(str(i) for i in range(n,j,-1)) for j in range(n)))", "def ...
{"fn_name": "pattern", "inputs": [[1], [2], [5], [0], [-25]], "outputs": [["1"], ["21\n2"], ["54321\n5432\n543\n54\n5"], [""], [""]]}
introductory
https://www.codewars.com/kata/55733d3ef7c43f8b0700007c
def pattern(n):
3,935
`{a, e, i, o, u, A, E, I, O, U}` Natural Language Understanding is the subdomain of Natural Language Processing where people used to design AI based applications have ability to understand the human languages. HashInclude Speech Processing team has a project named Virtual Assistant. For this project they appointed you...
["def vowel_recognition(input):\n vowels = set('aeiouAEIOU')\n s = t = 0\n for c, e in enumerate(input, 1):\n if e in vowels:\n t += c\n s += t\n return s", "def vowel_recognition(input):\n chars = input.lower()\n N = len(chars)\n count = 0\n \n for i, c in enumerate(...
{"fn_name": "vowel_recognition", "inputs": [["bbbb"], ["baceb"], ["aeiou"], ["aeiouAEIOU"]], "outputs": [[0], [16], [35], [220]]}
introductory
https://www.codewars.com/kata/5bed96b9a68c19d394000b1d
def vowel_recognition(s):
3,936
# History This kata is a sequel of my [Mixbonacci](https://www.codewars.com/kata/mixbonacci/python) kata. Zozonacci is a special integer sequence named after [**ZozoFouchtra**](https://www.codewars.com/users/ZozoFouchtra), who came up with this kata idea in the [Mixbonacci discussion](https://www.codewars.com/kata/mix...
["from itertools import cycle\n\nROOT = {'fib': [0, 0, 0, 1],\n 'jac': [0, 0, 0, 1],\n 'pad': [0, 1, 0, 0],\n 'pel': [0, 0, 0, 1],\n 'tet': [0, 0, 0, 1],\n 'tri': [0, 0, 0, 1]}\nGEN = {'fib': lambda a: a[-1] + a[-2],\n 'jac': lambda a: a[-1] + 2 * a[-2],\n 'pad': lambda...
{"fn_name": "zozonacci", "inputs": [[["fib"], 0], [[], 10], [["fib"], 10], [["tri"], 10], [["tet"], 10], [["pad"], 10], [["pel"], 10], [["jac"], 10], [["fib", "tri"], 10], [["tri", "fib"], 10], [["pad", "fib"], 10], [["tri", "tet"], 10], [["fib", "pel", "tri"], 10], [["tet", "jac"], 10]], "outputs": [[[]], [[]], [[0, 0...
introductory
https://www.codewars.com/kata/5b7c80094a6aca207000004d
def zozonacci(pattern, length):
3,937
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...
["def check(num,max_sum):\n l = [int(i) for i in str(num)]\n for i in range(0,len(l) - 3):\n if sum(l[i:i+4]) > max_sum:return False\n return True\n\ndef max_sumDig(nMax, maxSum):\n found = [i for i in range(1000,nMax + 1) if check(i,maxSum)]\n mean = sum(found) / float(len(found))\n for i in r...
{"fn_name": "max_sumDig", "inputs": [[2000, 3], [2000, 4], [2000, 7], [3000, 7], [4000, 4], [5000, 2], [5000, 3], [5000, 4], [5000, 5], [5000, 6], [5000, 7], [5000, 8], [5000, 9]], "outputs": [[[11, 1110, 12555]], [[21, 1120, 23665]], [[85, 1200, 99986]], [[141, 1600, 220756]], [[35, 2000, 58331]], [[5, 1100, 6111]], [...
introductory
https://www.codewars.com/kata/55f5efd21ad2b48895000040
def max_sumDig(nMax, maxSum):
3,938
Assume you are creating a webshop and you would like to help the user in the search. You have products with brands, prices and name. You have the history of opened products (the most recently opened being the first item). Your task is to create a list of brands ordered by popularity, if two brands have the same popula...
["from collections import Counter\n\ndef sorted_brands(history):\n brands = [x['brand'] for x in history]\n counter = Counter(brands)\n return sorted(set(brands), key=lambda x: (-counter[x], brands.index(x)))", "def sorted_brands(history):\n brands = [item['brand'] for item in history]\n return sorted(se...
{"fn_name": "sorted_brands", "inputs": [[[]]], "outputs": [[[]]]}
introductory
https://www.codewars.com/kata/57cb12aa40e3020bb4001d2e
def sorted_brands(history):
3,939
# Rock Paper Scissors Let's play! You have to return which player won! In case of a draw return `Draw!`. Examples: ![rockpaperscissors](http://i.imgur.com/aimOQVX.png)
["def rps(p1, p2):\n beats = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}\n if beats[p1] == p2:\n return \"Player 1 won!\"\n if beats[p2] == p1:\n return \"Player 2 won!\"\n return \"Draw!\"", "def rps(p1, p2):\n hand = {'rock':0, 'paper':1, 'scissors':2}\n results = ['Draw...
{"fn_name": "rps", "inputs": [["rock", "scissors"], ["scissors", "paper"], ["paper", "rock"], ["scissors", "rock"], ["paper", "scissors"], ["rock", "paper"], ["rock", "rock"], ["scissors", "scissors"], ["paper", "paper"]], "outputs": [["Player 1 won!"], ["Player 1 won!"], ["Player 1 won!"], ["Player 2 won!"], ["Player ...
introductory
https://www.codewars.com/kata/5672a98bdbdd995fad00000f
def rps(p1, p2):
3,940
Christmas is coming, and Santa has a long list to go through, to find who deserves presents for the big day. Go through a list of children, and return a list containing every child who appeared on Santa's list. Do not add any child more than once. Output should be sorted. ~~~if:java For java, use Lists. ~~~ Comparison...
["def find_children(santas_list, children):\n return sorted(set(santas_list) & set(children))", "def find_children(a, b):\n return sorted(set(a) & set(b))", "find_children=lambda s,c:sorted(e for e in c if e in s)", "find_children = lambda x, s: sorted(set(x) & set(s))", "def find_children(arr1,arr2):\n L=[]\n...
{"fn_name": "find_children", "inputs": [[["Jason", "Jackson", "Jordan", "Johnny"], ["Jason", "Jordan", "Jennifer"]], [["Jason", "Jackson", "Johnson", "JJ"], ["Jason", "James", "JJ"]], [["jASon", "JAsoN", "JaSON", "jasON"], ["JasoN", "jASOn", "JAsoN", "jASon", "JASON"]]], "outputs": [[["Jason", "Jordan"]], [["JJ", "Jaso...
introductory
https://www.codewars.com/kata/5a0b4dc2ffe75f72f70000ef
def find_children(santas_list, children):
3,941
FizzBuzz is often one of the first programming puzzles people learn. Now undo it with reverse FizzBuzz! Write a function that accepts a string, which will always be a valid section of FizzBuzz. Your function must return an array that contains the numbers in order to generate the given section of FizzBuzz. Notes: - If...
["def reverse_fizzbuzz(s):\n if s == 'Fizz': return [3]\n if s == 'Buzz': return [5]\n if s == 'Fizz Buzz': return [9, 10]\n if s == 'Buzz Fizz': return [5, 6]\n if s == 'FizzBuzz': return [15]\n s = s.split()\n for i in range(len(s)):\n if s[i].isdigit():\n start = int(s[i]) - i\...
{"fn_name": "reverse_fizzbuzz", "inputs": [["1 2 Fizz 4 Buzz"], ["Fizz 688 689 FizzBuzz"], ["Fizz Buzz"], ["Fizz"], ["Buzz"], ["Buzz Fizz"], ["FizzBuzz"]], "outputs": [[[1, 2, 3, 4, 5]], [[687, 688, 689, 690]], [[9, 10]], [[3]], [[5]], [[5, 6]], [[15]]]}
introductory
https://www.codewars.com/kata/5a622f5f85bef7a9e90009e2
def reverse_fizzbuzz(s):
3,942
There is enough money available on ATM in nominal value 10, 20, 50, 100, 200 and 500 dollars. You are given money in nominal value of `n` with `1<=n<=1500`. Try to find minimal number of notes that must be used to repay in dollars, or output -1 if it is impossible. Good Luck!!!
["def solve(n):\n if n%10: return -1\n c, billet = 0, iter((500,200,100,50,20,10))\n while n:\n x, r = divmod(n, next(billet))\n c, n = c+x, r\n return c", "def solve(n):\n t=0\n for d in [500,200,100,50,20,10]:\n a,n=divmod(n,d)\n t+=a\n if n: return -1\n return t", ...
{"fn_name": "solve", "inputs": [[770], [550], [10], [1250], [125], [666], [42]], "outputs": [[4], [2], [1], [4], [-1], [-1], [-1]]}
introductory
https://www.codewars.com/kata/5635e7cb49adc7b54500001c
def solve(n):
3,943
# Task: Based on the received dimensions, `a` and `b`, of an ellipse, calculare its area and perimeter. ## Example: ```python Input: ellipse(5,2) Output: "Area: 31.4, perimeter: 23.1" ``` **Note:** The perimeter approximation formula you should use: `π * (3/2(a+b) - sqrt(ab))` ___ ## Have fun :)
["from math import pi\n\ndef ellipse(a, b):\n return f\"Area: {pi*a*b:.1f}, perimeter: {pi*( 1.5*(a+b) - (a*b)**.5 ):.1f}\"", "from math import pi\n\ndef ellipse(a, b):\n perimeter = pi * (3/2*(a+b) - (a*b)**0.5)\n area = pi * a*b\n return f'Area: {area:.1f}, perimeter: {perimeter:.1f}'", "def ellipse(a, b)...
{"fn_name": "ellipse", "inputs": [[5, 2], [6, 8], [13, 1]], "outputs": [["Area: 31.4, perimeter: 23.1"], ["Area: 150.8, perimeter: 44.2"], ["Area: 40.8, perimeter: 54.6"]]}
introductory
https://www.codewars.com/kata/5830e7feff1a3ce8d4000062
def ellipse(a, b):
3,944
Your task is to return the sum of Triangular Numbers up-to-and-including the `nth` Triangular Number. Triangular Number: "any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc." ``` [01] 02 [03] 04 05 [06] 07 08 09 [10] 11 12 13 14 [15] 16 17 18...
["def sum_triangular_numbers(n):\n return n*(n+1)*(n+2)/6 if n>0 else 0", "def sum_triangular_numbers(n):\n return 0 if n < 0 else n * (n + 1) * (n + 2) // 6", "def sum_triangular_numbers(n):\n #your code here\n return sum(sum(range(x+1)) for x in range(n+1))", "def sum_triangular_numbers(n):\n total, a ...
{"fn_name": "sum_triangular_numbers", "inputs": [[6], [34], [-291], [943], [-971]], "outputs": [[56], [7140], [0], [140205240], [0]]}
introductory
https://www.codewars.com/kata/580878d5d27b84b64c000b51
def sum_triangular_numbers(n):
3,945
Student A and student B are giving each other test answers during a test. They don't want to be caught so they are sending each other coded messages. Student A is sending student B the message: `Answer to Number 5 Part b`. He starts of with a square grid (in this example the grid = 5x5). He writes the message do...
["def decipher_message(message):\n n = int(len(message) ** 0.5)\n return ''.join(message[i::n] for i in range(n))", "from math import sqrt\ndef decipher_message(message):\n key = int(sqrt(len(message)))\n plaintext = [\"\"] * key\n current_row = 0\n for symbol in message:\n plaintext[current_ro...
{"fn_name": "decipher_message", "inputs": [["ArNran u rstm5twob e ePb"], ["ArNran u rstm8twob e ePc"], ["92287a76 585a2y0"], [" a29068686a275y5"], ["8a 55y0y0y5a7 78"], ["9y98a877a95976a758726a89a5659957ya y"], ["aa297625 88a02670997 86ya880 00a9067"], ["826a976a508a9a 687600a2800 895055y a"], [" a702a067629y022ay86...
introductory
https://www.codewars.com/kata/5a1a144f8ba914bbe800003f
def decipher_message(message):
3,946
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....
["def interweave(s1, s2):\n s = [''] * (len(s1) + len(s2))\n s[::2], s[1::2] = s1, s2\n return ''.join(c for c in s if not c.isdigit()).strip()", "from itertools import chain, zip_longest\ndef interweave(s1, s2):\n return ''.join(char for char in chain.from_iterable(zip_longest(s1, s2, fillvalue='')) if not...
{"fn_name": "interweave", "inputs": [["", ""], ["hlo", "el"], ["h3lo", "el4"]], "outputs": [[""], ["hello"], ["hello"]]}
introductory
https://www.codewars.com/kata/588a7d45019c42be61000009
def interweave(s1, s2):
3,947
Welcome. In this kata, you are asked to square every digit of a number and concatenate them. For example, if we run 9119 through the function, 811181 will come out, because 9^(2) is 81 and 1^(2) is 1. **Note:** The function accepts an integer and returns an integer
["def square_digits(num):\n ret = \"\"\n for x in str(num):\n ret += str(int(x)**2)\n return int(ret)", "def square_digits(num):\n return int(''.join(str(int(d)**2) for d in str(num)))", "def square_digits(num):\n l = []\n for d in str(num):\n l.append(str(int(d)**2));\n return int(''...
{"fn_name": "square_digits", "inputs": [[3212], [2112]], "outputs": [[9414], [4114]]}
introductory
https://www.codewars.com/kata/546e2562b03326a88e000020
def square_digits(num):
3,948
Given an array, return the reversed version of the array (a different kind of reverse though), you reverse portions of the array, you'll be given a length argument which represents the length of each portion you are to reverse. E.g if after reversing some portions of the array and the length of the remaining port...
["def sel_reverse(arr,l):\n return [ elt for i in range(0, len(arr), l) for elt in arr[i:i+l][::-1] ] if l != 0 else arr", "from itertools import chain\n\ndef gen(arr, l):\n for i in range(0, len(arr), l):\n yield arr[i:i+l][::-1]\n\ndef sel_reverse(arr,l):\n return list(chain.from_iterable(gen(arr, l o...
{"fn_name": "sel_reverse", "inputs": [[[2, 4, 6, 8, 10, 12, 14, 16], 3], [[2, 4, 6, 8, 10, 12, 14, 16], 2], [[1, 2, 3, 4, 5, 6], 2], [[1, 2, 3, 4, 5, 6], 0], [[1, 2, 3, 4, 5, 6], 10]], "outputs": [[[6, 4, 2, 12, 10, 8, 16, 14]], [[4, 2, 8, 6, 12, 10, 16, 14]], [[2, 1, 4, 3, 6, 5]], [[1, 2, 3, 4, 5, 6]], [[6, 5, 4, 3, 2...
introductory
https://www.codewars.com/kata/58f6000bc0ec6451960000fd
def sel_reverse(arr,l):
3,949
Complete the function, which calculates how much you need to tip based on the total amount of the bill and the service. You need to consider the following ratings: - Terrible: tip 0% - Poor: tip 5% - Good: tip 10% - Great: tip 15% - Excellent: tip 20% The rating is **case insensitive** (so "great" = "GREAT"). If an...
["from math import ceil\ndef calculate_tip(amount, rating):\n tips = {\n 'terrible': 0,\n 'poor' : .05,\n 'good' : .1,\n 'great' : .15,\n 'excellent' : .2\n }\n if rating.lower() in tips:\n return ceil(amount * tips[rating.lower()])\n else:\n return 'Rating n...
{"fn_name": "calculate_tip", "inputs": [[30, "poor"], [20, "Excellent"], [20, "hi"], [107.65, "GReat"], [20, "great!"]], "outputs": [[2], [4], ["Rating not recognised"], [17], ["Rating not recognised"]]}
introductory
https://www.codewars.com/kata/56598d8076ee7a0759000087
def calculate_tip(amount, rating):
3,950
We are interested in obtaining two scores from a given integer: **First score**: The sum of all the integers obtained from the power set of the digits of the given integer that have the same order E.g: ``` integer = 1234 ---> (1 + 2 + 3 + 4) + (12 + 13 + 14 + 23 + 24 + 34) + (123 + 124 + 134 + 234) + 1234 = 10 + 12...
["score = lambda sub_gen: lambda n: sum(int(''.join(sub)) for length in range(1, len(str(n)) + 1) for sub in sub_gen(str(n), length))\nscore1 = score(__import__('itertools').combinations)\nscore2 = score(lambda s, r: (s[i: i+r] for i in range(len(s) - r + 1)))\n\ndivs = lambda n: set.union(*({d, n // d} for d in range(...
{"fn_name": "find_int_inrange", "inputs": [[100, 300], [100, 500], [300, 900]], "outputs": [[[7, 294]], [[7, 294, 468]], [[7, 468, 834]]]}
introductory
https://www.codewars.com/kata/58e8561f06db4d4cc600008c
def find_int_inrange(a, b):
3,951
### Count the number of Duplicates Write a function that will return the count of **distinct case-insensitive** alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. ### Ex...
["def duplicate_count(s):\n return len([c for c in set(s.lower()) if s.lower().count(c)>1])\n", "# My 1st Solution \n\ndef duplicate_count(text): \n count = 0 \n counted = [] \n test = list(text.lower()) \n for i, c in enumerate(test): \n if test.count(test[i]) >= 2 and counted.count(test[i]) ...
{"fn_name": "duplicate_count", "inputs": [[""], ["abcde"], ["abcdeaa"], ["abcdeaB"], ["Indivisibilities"]], "outputs": [[0], [0], [1], [2], [2]]}
introductory
https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1
def duplicate_count(text):
3,952
The [half-life](https://en.wikipedia.org/wiki/Half-life) of a radioactive substance is the time it takes (on average) for one-half of its atoms to undergo radioactive decay. # Task Overview Given the initial quantity of a radioactive substance, the quantity remaining after a given period of time, and the period of tim...
["from math import log\n\ndef half_life(N0, N, t):\n return t / log(N0/N, 2)", "from math import log2\n\ndef half_life(ini, rem, t):\n return t / log2(ini / rem)", "from math import log\n\n\ndef half_life(initial, remaining, time):\n return time*log(2.0)/log(initial/remaining)", "from math import log2\n\ndef h...
{"fn_name": "half_life", "inputs": [[10, 5, 1], [8, 4, 2], [12, 3, 2]], "outputs": [[1], [2], [1]]}
introductory
https://www.codewars.com/kata/59f33b86a01431d5ae000032
def half_life(initial, remaining, time):
3,953
#Detail [Countdown](https://en.wikipedia.org/wiki/Countdown_(game_show) is a British game show with number and word puzzles. The letters round consists of the contestant picking 9 shuffled letters - either picking from the vowel pile or the consonant pile. The contestants are given 30 seconds to try to come up with th...
["def longest_word(letters):\n try:\n word_list = [w for w in words if all(w.count(c) <= letters.count(c) for c in w)]\n largest = sorted([w for w in word_list if len(w) == len(max(word_list, key=len))])\n return largest if largest else None\n except:\n return None"]
{"fn_name": "longest_word", "inputs": [[""], ["MKMKMKMKM"], ["IIIWUGEZI"]], "outputs": [[null], [null], [null]]}
introductory
https://www.codewars.com/kata/57a4c85de298a795210002da
def longest_word(letters):
3,954
# Task A lock has `n` buttons in it, numbered from `1 to n`. To open the lock, you have to press all buttons in some order, i.e. a key to the lock is a permutation of the first `n` integers. If you push the right button in the right order, it will be pressed into the lock. Otherwise all pressed buttons will pop out. W...
["def press_button(n):\n return (n*n+5)*n/6", "def press_button(n):\n return sum((n-i)*(i+1)-i for i in range(n))", "press_button=lambda n:sum(i*(n-i) for i in range(1,n))+n", "def press_button(n):\n return n + sum(i * (n-i) for i in range(1, n))", "def press_button(n):\n return n*(n**2 + 5)/6", "def press_butt...
{"fn_name": "press_button", "inputs": [[1], [3], [4], [10], [2000]], "outputs": [[1], [7], [14], [175], [1333335000]]}
introductory
https://www.codewars.com/kata/58b3bb9347117f4aa7000096
def press_button(n):
3,955
Write a function which outputs the positions of matching bracket pairs. The output should be a dictionary with keys the positions of the open brackets '(' and values the corresponding positions of the closing brackets ')'. For example: input = "(first)and(second)" should return {0:6, 10:17} If brackets cannot be pair...
["def bracket_pairs(string):\n brackets = {}\n open_brackets = []\n\n for i, c in enumerate(string):\n if c == '(':\n open_brackets.append(i)\n elif c == ')':\n if not open_brackets:\n return False\n brackets[open_brackets.pop()] = i\n\n return F...
{"fn_name": "bracket_pairs", "inputs": [["len(list)"], ["string"], [""], ["def f(x"], [")("], ["(a(b)c()d)"], ["f(x[0])"]], "outputs": [[{"3": 8}], [{}], [{}], [false], [false], [{"0": 9, "2": 4, "6": 7}], [{"1": 6}]]}
introductory
https://www.codewars.com/kata/5708e3f53f100874b60015ff
def bracket_pairs(string):
3,956
# Task Your task is to sort the characters in a string according to the following rules: ``` - Rule1: English alphabets are arranged from A to Z, case insensitive. ie. "Type" --> "epTy" - Rule2: If the uppercase and lowercase of an English alphabet exist at the same time, they are arranged in the order of oringal ...
["def sort_string(s):\n a = iter(sorted((c for c in s if c.isalpha()), key=str.lower))\n return ''.join(next(a) if c.isalpha() else c for c in s)", "import re\n\ndef sort_string(s):\n sortedChr = iter(sorted(re.sub(r'[^a-zA-Z]', '', s), key=str.lower))\n return re.sub(r'[a-zA-Z]', lambda m: next(sortedChr),...
{"fn_name": "sort_string", "inputs": [["a"], ["cba"], ["Cba"], ["cCBbAa"], ["!"], ["c b a"], ["-c--b--a-"], ["cbaCcC"], ["Codewars"], [" MkWD{RB=//k-^ J@,xH Vfi uAz+$ kV _[ }a!}%pSBwn !kKB (b q PQF +}wS .kfU r wFNEs#NsR UVMdG"]], "outputs": [["a"], ["abc"], ["abC"], ["AaBbcC"], ["!"], ["a b c"], ["-a--b--c-"], ["abcC...
introductory
https://www.codewars.com/kata/5936256f2e2a27edc9000047
def sort_string(s):
3,957
Implement a function which behaves like the 'uniq -c' command in UNIX. It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance together with the number of times a duplicate elements occurred in the original array. Example: ```python ...
["from itertools import groupby\n\ndef uniq_c(seq): \n return [ (k,sum(1 for _ in g)) for k,g in groupby(seq)]", "\n\ndef uniq_c(s):\n lst = []\n c = 1\n for i in range(len(s)-1):\n if s[i] != s[i+1]:\n lst.append((s[i],c))\n c = 1\n else:\n c += 1\n if s:\n...
{"fn_name": "uniq_c", "inputs": [[["a", "a", "b", "b", "c", "a", "b", "c"]], [["a", "a", "a", "b", "b", "b", "c", "c", "c"]], [[null, "a", "a"]], [["foo"]], [[""]], [[]]], "outputs": [[[["a", 2], ["b", 2], ["c", 1], ["a", 1], ["b", 1], ["c", 1]]], [[["a", 3], ["b", 3], ["c", 3]]], [[[null, 1], ["a", 2]]], [[["foo", 1]]...
introductory
https://www.codewars.com/kata/52250aca906b0c28f80003a1
def uniq_c(seq):
3,958
Leonardo Fibonacci in a rare portrait of his younger days I assume you are all familiar with the famous Fibonacci sequence, having to get each number as the sum of the previous two (and typically starting with either `[0,1]` or `[1,1]` as the first numbers). While there are plenty of variation on it ([including](http...
["from collections import deque\n\ndef custom_fib(signature, indexes, n):\n fib = deque(signature)\n for _ in range(n):\n fib.append(sum(map(fib.__getitem__, indexes)))\n fib.popleft()\n return fib[0]", "def custom_fib(signature,indexes,n):\n for _ in range(n):\n signature = signature[1...
{"fn_name": "custom_fib", "inputs": [[[1, 1], [0, 1], 2], [[1, 1], [0, 1], 3], [[1, 1], [0, 1], 4], [[3, 5, 2], [0, 1, 2], 4], [[7, 3, 4, 1], [1, 1], 6]], "outputs": [[2], [3], [5], [17], [2]]}
introductory
https://www.codewars.com/kata/596144f0ada6db581200004f
def custom_fib(signature, indexes, n):
3,959
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: ```if:javascript Given an array `arr` that contains some integers(positive, negative or 0), and a `range` list such as `[[start1,end1],[start2,end2],...]`,...
["def max_sum(arr, ranges):\n return max( sum(arr[start:stop+1]) for start, stop in ranges )", "from itertools import accumulate\n\ndef max_sum(arr, ranges): \n xs = list(accumulate(arr)) + [0]\n return max(xs[j] - xs[i-1] for i, j in ranges)", "def max_sum(arr,ranges): \n return max(sum(arr[start:end+1]) f...
{"fn_name": "max_sum", "inputs": [[[1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 3], [0, 4], [6, 8]]], [[1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 3]]], [[1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 4], [2, 5]]], [[11, -22, 31, 34, -45, -46, 35, 32, 21], [[1, 4], [0, 3], [6, 8], [0, 8]]]], "outputs": [[6], [5], [0], [88]]}
introductory
https://www.codewars.com/kata/583d10c03f02f41462000137
def max_sum(arr,ranges):
3,960
Your task in this Kata is to emulate text justify right in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width. Here are the rules: - Use spaces to fill in the gaps on the left side of the words. - Each line should contain ...
["import textwrap\n\ndef align_right(text,width):\n return \"\\n\".join([l.rjust(width, ' ') for l in textwrap.wrap(text, width)])", "def align_right(text, width):\n res = []\n line = []\n \n for word in text.split():\n if len(' '.join(line + [word])) <= width:\n line.append(word)\n ...
{"fn_name": "align_right", "inputs": [["abc def", 10], ["I take up the whole line", 24], ["Two lines, I am", 10]], "outputs": [[" abc def"], ["I take up the whole line"], ["Two lines,\n I am"]]}
introductory
https://www.codewars.com/kata/583601518d3b9b8d3b0000c9
def align_right(text, width):
3,961
## Debugging sayHello function The starship Enterprise has run into some problem when creating a program to greet everyone as they come aboard. It is your job to fix the code and get the program working again! Example output: ``` Hello, Mr. Spock ```
["def say_hello(name):\n return f\"Hello, {name}\"", "def say_hello(name):\n return\"Hello, \" +name", "def say_hello(name):\n return \"Hello, {0}\".format(name)", "def say_hello(name):\n return \"Hello, {}\".format(name)", "def say_hello(name):\n return f'Hello, {name}'\n\n# how about you tell us proper...
{"fn_name": "say_hello", "inputs": [["Mr. Spock"], ["Captain Kirk"], ["Liutenant Uhura"], ["Dr. McCoy"], ["Mr. Scott"]], "outputs": [["Hello, Mr. Spock"], ["Hello, Captain Kirk"], ["Hello, Liutenant Uhura"], ["Hello, Dr. McCoy"], ["Hello, Mr. Scott"]]}
introductory
https://www.codewars.com/kata/5625618b1fe21ab49f00001f
def say_hello(name):
3,962
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...
["def house_of_cards(n):\n if n>=1:\n return(n+1)*n/2 + (n+2)*(n+1)\n raise ValueError", "def house_of_cards(n):\n assert n > 0\n return (n + 1) * (3 * n + 4) // 2", "def house_of_cards(floors):\n assert isinstance(floors, int) and floors > 0\n return (floors + 1) * (3 * floors + 4) // 2", "def...
{"fn_name": "house_of_cards", "inputs": [[1], [2], [3]], "outputs": [[7], [15], [26]]}
introductory
https://www.codewars.com/kata/543abbc35f0461d28f000c11
def house_of_cards(floors):
3,963
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) For example, the smallest pair of amic...
["def getDivs(n):\n return {1} | {y for x in range(2,int(n**.5)+1) for y in [n//x, x] if not n%x}\n\ndef amicable_numbers(n1,n2):\n return sum(getDivs(n1)) == n2 and sum(getDivs(n2)) == n1", "def amicable_numbers(n1, n2):\n return spd(n1) == n2 and spd(n2) == n1\n\ndef spd(n):\n return sum(i for i in range(...
{"fn_name": "amicable_numbers", "inputs": [[220, 284], [220, 280], [1184, 1210], [220221, 282224], [10744, 10856], [299920, 9284], [999220, 2849], [122265, 139815]], "outputs": [[true], [false], [true], [false], [true], [false], [false], [true]]}
introductory
https://www.codewars.com/kata/56b5ebaa26fd54188b000018
def amicable_numbers(n1,n2):