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
4,665
Because my other two parts of the serie were pretty well received I decided to do another part. Puzzle Tiles You will get two Integer n (width) and m (height) and your task is to draw following pattern. Each line is seperated with '\n'. Both integers are equal or greater than 1. No need to check for invalid paramet...
["def puzzle_tiles(width, height):\n def f():\n yield ' ' + ' _( )__' * width\n for i in range(height):\n if i % 2 == 0:\n yield ' _|' + ' _|' * width\n yield '(_' + ' _ (_' * width\n yield ' |' + '__( )_|' * width\n else: ...
{"fn_name": "puzzle_tiles", "inputs": [[1, 1], [3, 2]], "outputs": [[" _( )__\n _| _|\n(_ _ (_\n |__( )_|"], [" _( )__ _( )__ _( )__\n _| _| _| _|\n(_ _ (_ _ (_ _ (_\n |__( )_|__( )_|__( )_|\n |_ |_ |_ |_\n _) _ _) _ _) _ _)\n |__( )_|__( )_|__( )_|"]]}
introductory
https://www.codewars.com/kata/5947d86e07693bcf000000c4
def puzzle_tiles(width, height):
4,666
I'm new to coding and now I want to get the sum of two arrays...actually the sum of all their elements. I'll appreciate for your help. P.S. Each array includes only integer numbers. Output is a number too.
["def array_plus_array(arr1,arr2):\n return sum(arr1+arr2)\n", "def array_plus_array(arr1,arr2):\n return sum(arr1) + sum(arr2)", "def array_plus_array(*args):\n return sum(map(sum, args))\n", "def array_plus_array(a, b):\n return sum(a+b)", "def array_plus_array(arr1,arr2):\n counter = 0\n for i in a...
{"fn_name": "array_plus_array", "inputs": [[[1, 2, 3], [4, 5, 6]], [[-1, -2, -3], [-4, -5, -6]], [[0, 0, 0], [4, 5, 6]], [[100, 200, 300], [400, 500, 600]]], "outputs": [[21], [-21], [15], [2100]]}
introductory
https://www.codewars.com/kata/5a2be17aee1aaefe2a000151
def array_plus_array(arr1,arr2):
4,667
# Story Well, here I am stuck in another traffic jam. *Damn all those courteous people!* Cars are trying to enter the main road from side-streets somewhere ahead of me and people keep letting them cut in. Each time somebody is let in the effect ripples back down the road, so pretty soon I am not moving at all. (S...
["def traffic_jam(road, sides):\n X = road.index(\"X\")\n main = list(road[:X+1])\n \n for i in reversed(range( min(X,len(sides)) )):\n tmp = []\n for j in range(1, min(len(main)-i-1, len(sides[i]))+1 ):\n tmp.append(sides[i][-j])\n tmp.append(main[i+j])\n main[...
{"fn_name": "traffic_jam", "inputs": [["abcdeXghi", ["", "", "CCCCC", "", "EEEEEEEEEE", "FFFFFF", "", "", "IIIIII"]], ["abcdefX", []], ["abcXdef", []], ["Xabcdef", []], ["abcdefghijklmX", ["", "", "", "BBBBBB", "", "", "", "", "CCCCC"]], ["abcdefghijkX", ["", "AAAAAAAAAA", "", "BBBBBBBB", "", "CCCC"]], ["abcdefghijkX",...
introductory
https://www.codewars.com/kata/5a26073ce1ce0e3c01000023
def traffic_jam(main_road, side_streets):
4,668
# Task A masked number is a string that consists of digits and one asterisk (`*`) that should be replaced by exactly one digit. Given a masked number `s`, find all the possible options to replace the asterisk with a digit to produce an integer divisible by 6. # Input/Output `[input]` string `s` A masked number. `1...
["def is_divisible_by_6(s):\n all_numbers = [ int(s.replace('*', str(n))) for n in range(10) ]\n return [ str(n) for n in all_numbers if n % 6 == 0 ]", "def is_divisible_by_6(s):\n return [str(n) for n in [int(s.replace('*', str(i))) for i in range(10)] if n % 6 == 0]", "def is_divisible_by_6(stg):\n result =...
{"fn_name": "is_divisible_by_6", "inputs": [["1*0"], ["*"], ["*1"], ["*2"], ["81234567890*"], ["41*"], ["*6"], ["2345*345729"], ["34234*2"], ["1234567890123456789012345678*0"]], "outputs": [[["120", "150", "180"]], [["0", "6"]], [[]], [["12", "42", "72"]], [["812345678904"]], [["414"]], [["6", "36", "66", "96"]], [[]],...
introductory
https://www.codewars.com/kata/5911385598dcd432ae000004
def is_divisible_by_6(s):
4,669
Born a misinterpretation of [this kata](https://www.codewars.com/kata/simple-fun-number-334-two-beggars-and-gold/), your task here is pretty simple: given an array of values and an amount of beggars, you are supposed to return an array with the sum of what each beggar brings home, assuming they all take regular turns, ...
["def beggars(values, n):\n return [sum(values[i::n]) for i in range(n)]", "def beggars(a, n): \n return [sum(a[i::n]) for i in range(n)]", "def beggars(values, n):\n if n == 0:\n return []\n i=0\n take=[]\n for x in range(n):\n take.append(0)\n for val in values:\n take[i%n...
{"fn_name": "beggars", "inputs": [[[1, 2, 3, 4, 5], 1], [[1, 2, 3, 4, 5], 2], [[1, 2, 3, 4, 5], 3], [[1, 2, 3, 4, 5], 6], [[1, 2, 3, 4, 5], 0]], "outputs": [[[15]], [[9, 6]], [[5, 7, 3]], [[1, 2, 3, 4, 5, 0]], [[]]]}
introductory
https://www.codewars.com/kata/59590976838112bfea0000fa
def beggars(values, n):
4,670
Note: This kata is inspired by [Convert a Number to a String!](http://www.codewars.com/kata/convert-a-number-to-a-string/). Try that one too. ## Description We need a function that can transform a string into a number. What ways of achieving this do you know? Note: Don't worry, all inputs will be strings, and every ...
["def string_to_number(s):\n return int(s)", "string_to_number = int", "string_to_number = lambda n: int(n)", "string_to_number=lambda s:int(s)", "def string_to_number(s):\n # ... your code here\n s = int(s)\n return s", "def string_to_number(s):\n i = int(s)\n return i", "def string_to_number(s):\n ...
{"fn_name": "string_to_number", "inputs": [["4"]], "outputs": [[4]]}
introductory
https://www.codewars.com/kata/544675c6f971f7399a000e79
def string_to_number(s):
4,671
In graph theory, a graph is a collection of nodes with connections between them. Any node can be connected to any other node exactly once, and can be connected to no nodes, to some nodes, or to every other node. Nodes cannot be connected to themselves A path through a graph is a sequence of nodes, with every node conne...
["def isTree(matrix):\n visited_nodes = set([0])\n crossed_edges = set()\n agenda = [0]\n\n while agenda:\n node = agenda.pop()\n for i in matrix[node]:\n if (node, i) in crossed_edges: continue \n if i in visited_nodes: return False\n agenda.append(i)\n ...
{"fn_name": "isTree", "inputs": [[[[], []]], [[[1], [0]]], [[[1, 2], [0, 2], [0, 1]]], [[[1, 2, 3], [0, 2], [1, 2], [0]]], [[[1, 2, 3], [0], [0], [0, 4], [3]]], [[[1, 2, 3], [0], [0], [0, 4], [3], []]], [[[1], [0, 2], [1, 3, 5], [2, 4], [3, 5], [4, 2]]], [[[1], [0, 2, 3, 4], [1], [1], [1]]], [[[1], [0, 2, 3], [1], [1],...
introductory
https://www.codewars.com/kata/5a752a0b0136a1266c0000b5
def isTree(matrix):
4,672
In this Kata, you will create a function that converts a string with letters and numbers to the inverse of that string (with regards to Alpha and Numeric characters). So, e.g. the letter `a` will become `1` and number `1` will become `a`; `z` will become `26` and `26` will become `z`. Example: `"a25bz"` would become `...
["import re\ndef AlphaNum_NumAlpha(string):\n return re.sub( r'[0-9]{1,2}|[a-z]', lambda x:str(ord(x.group() )-96) if x.group().isalpha() else chr(int(x.group())+96) , string)\n \n #\\w\n", "import re\nfrom string import ascii_lowercase\n\ndef repl(m):\n x = m.group()\n if x.isdigit():\n return a...
{"fn_name": "AlphaNum_NumAlpha", "inputs": [["25abcd26"], ["18zyz14"], ["a1b2c3d4"], ["5a8p17"], ["w6aa4ct24m5"], ["17dh"], ["25gj8sk6r17"], ["18zzz14"], ["y17kg5et11"], ["abcdefghijklmnopqrstuvwxyz"], ["1a2b3c4d5e6f7g8h9i10j11k12l13m14n15o16p17q18r19s20t21u22v23w24x25y26z"], ["h15q4pc6yw23nmx19y"], ["p16k11o25x7m6m20c...
introductory
https://www.codewars.com/kata/5995ceb5d4280d07f6000822
def AlphaNum_NumAlpha(string):
4,673
Convert a hash into an array. Nothing more, Nothing less. ``` {name: 'Jeremy', age: 24, role: 'Software Engineer'} ``` should be converted into ``` [["name", "Jeremy"], ["age", 24], ["role", "Software Engineer"]] ``` ```if:python,javascript,crystal **Note**: The output array should be sorted alphabetically. ``` Goo...
["def convert_hash_to_array(hash):\n return sorted(map(list, hash.items()))", "def convert_hash_to_array(hash):\n return [[k, hash[k]] for k in sorted(hash)]", "def convert_hash_to_array(d):\n return [ [k,v] for k,v in sorted(d.items()) ] ", "def convert_hash_to_array(dct):\n return sorted(list(item) for it...
{"fn_name": "convert_hash_to_array", "inputs": [[{"name": "Jeremy"}], [{"name": "Jeremy", "age": 24}], [{"name": "Jeremy", "age": 24, "role": "Software Engineer"}], [{"product": "CodeWars", "power_level_over": 9000}], [{}]], "outputs": [[[["name", "Jeremy"]]], [[["age", 24], ["name", "Jeremy"]]], [[["age", 24], ["name"...
introductory
https://www.codewars.com/kata/59557b2a6e595316ab000046
def convert_hash_to_array(hash):
4,674
To participate in a prize draw each one gives his/her firstname. Each letter of a firstname has a value which is its rank in the English alphabet. `A` and `a` have rank `1`, `B` and `b` rank `2` and so on. The *length* of the firstname is added to the *sum* of these ranks hence a number `som`. An array of random ...
["def rank(st, we, n):\n if not st:\n return \"No participants\"\n \n if n>len(we):\n return \"Not enough participants\"\n\n name_score = lambda name,w: w*(len(name)+sum([ord(c.lower())-96for c in name]))\n \n scores= [name_score(s,we[i]) for i,s in enumerate(st.split(','))]\n \n s...
{"fn_name": "rank", "inputs": [["Addison,Jayden,Sofia,Michael,Andrew,Lily,Benjamin", [4, 2, 1, 4, 3, 1, 2], 4], ["Elijah,Chloe,Elizabeth,Matthew,Natalie,Jayden", [1, 3, 5, 5, 3, 6], 2], ["Aubrey,Olivai,Abigail,Chloe,Andrew,Elizabeth", [3, 1, 4, 4, 3, 2], 4], ["Lagon,Lily", [1, 5], 2], ["Elijah,Michael,Avery,Sophia,Sama...
introductory
https://www.codewars.com/kata/5616868c81a0f281e500005c
def rank(st, we, n):
4,675
Write a function named setAlarm which receives two parameters. The first parameter, employed, is true whenever you are employed and the second parameter, vacation is true whenever you are on vacation. The function should return true if you are employed and not on vacation (because these are the circumstances under whic...
["def set_alarm(employed, vacation):\n return employed and not vacation", "def set_alarm(employed, vacation):\n # Your code here\n if employed:\n if vacation:\n return False\n return True\n return False", "def set_alarm(employed, vacation):\n return employed==True and vacation==F...
{"fn_name": "set_alarm", "inputs": [[true, true], [false, true], [false, false], [true, false]], "outputs": [[false], [false], [false], [true]]}
introductory
https://www.codewars.com/kata/568dcc3c7f12767a62000038
def set_alarm(employed, vacation):
4,676
Calculus class...is awesome! But you are a programmer with no time for mindless repetition. Your teacher spent a whole day covering differentiation of polynomials, and by the time the bell rang, you had already conjured up a program to automate the process. You realize that a polynomial of degree n anx^(n) + an-1x^(n...
["def diff(poly):\n return [poly[i] * (len(poly)-1-i) for i in range(len(poly)-1)]", "def diff(poly):\n return [d*c for d,c in enumerate(poly[::-1]) if d][::-1]", "diff=lambda s:[i*j for i,j in enumerate(s[:-1][::-1],1)][::-1]", "def diff(poly):\n return [i * n for i, n in enumerate(poly[-2::-1], 1)][::-1]", "de...
{"fn_name": "diff", "inputs": [[[]]], "outputs": [[[]]]}
introductory
https://www.codewars.com/kata/54f4b6e7576d7af70900092b
def diff(poly):
4,677
Given is a md5 hash of a five digits long PIN. It is given as string. Md5 is a function to hash your password: "password123" ===> "482c811da5d5b4bc6d497ffa98491e38" Why is this useful? Hash functions like md5 can create a hash from string in a short time and it is impossible to find out the password, if you only got t...
["import hashlib\ndef crack(hash):\n for i in range(100000):\n if hashlib.md5(str(i).zfill(5).encode()).hexdigest() == hash:\n return str(i).zfill(5)", "from hashlib import md5\nfrom itertools import product\n\ndef crack(hash):\n for bs in map(bytes, product(b'0123456789', repeat=5)):\n i...
{"fn_name": "crack", "inputs": [["827ccb0eea8a706c4c34a16891f84e7b"], ["86aa400b65433b608a9db30070ec60cd"]], "outputs": [["12345"], ["00078"]]}
introductory
https://www.codewars.com/kata/5efae11e2d12df00331f91a6
def crack(hash):
4,678
# Task After a long night (work, play, study) you find yourself sleeping on a bench in a park. As you wake up and try to figure out what happened you start counting trees. You notice there are different tree sizes but there's always one size which is unbalanced. For example there are 2 size 2, 2 size 1 and 1 size 3. (...
["def find_the_missing_tree(trees):\n return sorted(trees, key=trees.count)[0]", "from collections import Counter\ndef find_the_missing_tree(trees):\n return Counter(trees).most_common()[-1][0] ", "def find_the_missing_tree(trees):\n return min(trees, key = lambda n: trees.count(n))", "def find_the_missing_tr...
{"fn_name": "find_the_missing_tree", "inputs": [[[1, 2, 2, 3, 3]], [[11, 2, 3, 3, 3, 11, 2, 2]], [[234, 76, 45, 99, 99, 99, 99, 45, 234, 234, 45, 45, 76, 234, 76]], [[1, 1, 1, 1, 1, 1, 1, 22, 22, 22, 22, 22, 22, 22, 3, 3, 3, 3, 3, 3]], [[10, 205, 3000, 3000, 10]], [[50, 408, 50, 50, 50, 50, 408, 408, 408, 680, 408, 680...
introductory
https://www.codewars.com/kata/58aa8698ae929e1c830001c7
def find_the_missing_tree(trees):
4,679
You probably know the 42 number as "The answer to life, the universe and everything" according to Douglas Adams' "The Hitchhiker's Guide to the Galaxy". For Freud, the answer was quite different. In the society he lived in, people-women in particular- had to repress their sexual needs and desires. This was simply how ...
["def to_freud(sentence):\n return ' '.join('sex' for _ in sentence.split())\n", "def to_freud(s):\n return (len(s.split()) * \"sex \").strip()", "def to_freud(sentence):\n words = sentence.split()\n wordcount = len(words)\n print(wordcount)\n s = \"\"\n while wordcount > 0:\n s = s + \"sex ...
{"fn_name": "to_freud", "inputs": [["test"], ["sexy sex"], ["This is a test"], ["This is a longer test"], ["You're becoming a true freudian expert"]], "outputs": [["sex"], ["sex sex"], ["sex sex sex sex"], ["sex sex sex sex sex"], ["sex sex sex sex sex sex"]]}
introductory
https://www.codewars.com/kata/5713bc89c82eff33c60009f7
def to_freud(sentence):
4,680
# Making Change Complete the method that will determine the minimum number of coins needed to make change for a given amount in American currency. Coins used will be half-dollars, quarters, dimes, nickels, and pennies, worth 50¢, 25¢, 10¢, 5¢ and 1¢, respectively. They'll be represented by the symbols `H`, `Q`, `D`, ...
["BASE = {\"H\": 50, \"Q\": 25, \"D\": 10, \"N\": 5, \"P\": 1}\n\ndef make_change(n):\n r = {}\n for x, y in BASE.items():\n if n >= y:\n r[x], n = divmod(n, y)\n return r", "def make_change(amount):\n H = 50\n Q = 25\n D = 10\n N = 5\n P = 1\n change = {}\n while amount ...
{"fn_name": "make_change", "inputs": [[0], [1], [5], [43], [91], [101], [239]], "outputs": [[{}], [{"P": 1}], [{"N": 1}], [{"Q": 1, "D": 1, "N": 1, "P": 3}], [{"H": 1, "Q": 1, "D": 1, "N": 1, "P": 1}], [{"H": 2, "P": 1}], [{"H": 4, "Q": 1, "D": 1, "P": 4}]]}
introductory
https://www.codewars.com/kata/5365bb5d5d0266cd010009be
def make_change(amount):
4,681
The alphabetized kata --------------------- Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed! The input is restricted to contain no numerals and only words containing ...
["def alphabetized(s):\n return \"\".join(sorted(filter(str.isalpha, s),key=str.lower))\n", "import re\n\ndef alphabetized(s):\n return ''.join(sorted(re.sub(r'[^A-Za-z]','',s), key=str.lower))", "alphabetized = lambda s: \"\".join(sorted(filter(str.isalpha, s), key=str.lower))", "def xx_key(a):\n if a.islower...
{"fn_name": "alphabetized", "inputs": [[""], [" "], [" a"], ["a "], [" a "], ["A b B a"], [" a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"], ["!@$%^&*()_+=-`,"], ["The Holy Bible"], ["CodeWars can't Load Today"]], "outputs": [[""], [""], ["a"], ["a"], ["a"], ["...
introductory
https://www.codewars.com/kata/5970df092ef474680a0000c9
def alphabetized(s):
4,682
A very easy task for you! You have to create a method, that corrects a given date string. There was a problem in addition, so many of the date strings are broken. Date-Format is european. That means "DD.MM.YYYY". Some examples: "30.02.2016" -> "01.03.2016" "40.06.2015" -> "10.07.2015" "11.13.2014" -> "11.01.2015" "...
["import re\nfrom datetime import date, timedelta\n\ndef date_correct(text):\n if not text:\n return text\n try:\n d, m, y = map(int, re.match(r'^(\\d{2})\\.(\\d{2})\\.(\\d{4})$', text).groups())\n mo, m = divmod(m - 1, 12)\n return (date(y + mo, m + 1, 1) + timedelta(days=d - 1)).strf...
{"fn_name": "date_correct", "inputs": [[null], [""], ["01112016"], ["01,11,2016"], ["0a.1c.2016"], ["03.12.2016"], ["30.02.2016"], ["40.06.2015"], ["11.13.2014"], ["33.13.2014"], ["99.11.2010"]], "outputs": [[null], [""], [null], [null], [null], ["03.12.2016"], ["01.03.2016"], ["10.07.2015"], ["11.01.2015"], ["02.02.20...
introductory
https://www.codewars.com/kata/5787628de55533d8ce000b84
def date_correct(date):
4,683
The aim of the kata is to try to show how difficult it can be to calculate decimals of an irrational number with a certain precision. We have chosen to get a few decimals of the number "pi" using the following infinite series (Leibniz 1646–1716): PI / 4 = 1 - 1/3 + 1/5 - 1/7 + ... which gives an approximation of PI /...
["from math import pi\n\ndef iter_pi(epsilon):\n n = 1\n approx = 4\n while abs(approx - pi) > epsilon:\n n += 1\n approx += (-4, 4)[n % 2] / (n * 2 - 1.0)\n return [n, round(approx, 10)]", "from math import pi\n\ndef iter_pi(epsilon):\n pi_4 = 0\n k = 0\n while abs(pi_4 * 4 - pi) > e...
{"fn_name": "iter_pi", "inputs": [[0.1], [0.01], [0.001], [0.0001], [1e-05], [1e-06]], "outputs": [[[10, 3.0418396189]], [[100, 3.1315929036]], [[1000, 3.1405926538]], [[10000, 3.1414926536]], [[100001, 3.1416026535]], [[1000001, 3.1415936536]]]}
introductory
https://www.codewars.com/kata/550527b108b86f700000073f
def iter_pi(epsilon):
4,684
An array is said to be `hollow` if it contains `3` or more `0`s in the middle that are preceded and followed by the same number of non-zero elements. Furthermore, all the zeroes in the array must be in the middle of the array. Write a function named `isHollow`/`is_hollow`/`IsHollow` that accepts an integer array and ...
["def is_hollow(x):\n while x and x[0] != 0 and x[-1] != 0: x = x[1:-1]\n return len(x) > 2 and set(x) == {0}", "from itertools import groupby\nfrom operator import not_\n\ndef is_hollow(a):\n b = [(x, [*y]) for x, y in groupby(a, key=not_)]\n return len(b) == 1 and b[0][0] and len(b[0][1]) > 2 or len(b) ==...
{"fn_name": "is_hollow", "inputs": [[[-1, 0, 0, 0, 3]], [[1, 0, 0, 0, 0]]], "outputs": [[true], [false]]}
introductory
https://www.codewars.com/kata/59b72376460387017e000062
def is_hollow(x):
4,685
A number is self-descriptive when the n'th digit describes the amount n appears in the number. E.g. 21200: There are two 0's in the number, so the first digit is 2. There is one 1 in the number, so the second digit is 1. There are two 2's in the number, so the third digit is 2. There are no 3's in the number, so t...
["from collections import Counter\n\n\ndef self_descriptive(num):\n s = [int(a) for a in str(num)]\n cnt = Counter(s)\n return all(cnt[i] == b for i, b in enumerate(s))\n", "def self_descriptive(num):\n numList = list(str(num))\n for i, s in enumerate(numList):\n if int(s) != numList.count(str(i))...
{"fn_name": "self_descriptive", "inputs": [[21200], [3211000], [42101000], [21230], [11200], [1210], [51120111], [2020], [11201], [6210001000]], "outputs": [[true], [true], [true], [false], [false], [true], [false], [true], [false], [true]]}
introductory
https://www.codewars.com/kata/56a628758f8d06b59800000f
def self_descriptive(num):
4,686
Write a function, that doubles every second integer in a list starting from the left.
["def double_every_other(l):\n return [x * 2 if i % 2 else x for i, x in enumerate(l)]", "double_every_other = lambda l: [e * (1 + i % 2) for i, e in enumerate(l)]", "def double_every_other(lst):\n return [x * (i % 2 + 1) for i, x in enumerate(lst)]", "def double_every_other(lst):\n return [2*v if i&1 else v f...
{"fn_name": "double_every_other", "inputs": [[[1, 2, 3, 4, 5]], [[1, 19, 6, 2, 12, -3]], [[-1000, 1653, 210, 0, 1]]], "outputs": [[[1, 4, 3, 8, 5]], [[1, 38, 6, 4, 12, -6]], [[-1000, 3306, 210, 0, 1]]]}
introductory
https://www.codewars.com/kata/5809c661f15835266900010a
def double_every_other(lst):
4,687
The aim of the kata is to decompose `n!` (factorial n) into its prime factors. Examples: ``` n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11" since 12! is divisible by 2 ten times, by 3 five times, by 5 two times and by 7 and 11 only once. n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19" n = 25;...
["from collections import defaultdict\n\ndef dec(n):\n decomp = defaultdict(lambda:0)\n i = 2\n while n > 1:\n while n % i == 0:\n n /= i\n decomp[i] += 1\n i += 1\n return decomp\n \n\ndef decomp(n):\n ans = defaultdict(lambda:0)\n for i in range(2, n + ...
{"fn_name": "decomp", "inputs": [[5], [14], [17], [22], [25], [79], [98], [3988], [3989], [3990]], "outputs": [["2^3 * 3 * 5"], ["2^11 * 3^5 * 5^2 * 7^2 * 11 * 13"], ["2^15 * 3^6 * 5^3 * 7^2 * 11 * 13 * 17"], ["2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19"], ["2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23"], ["2^7...
introductory
https://www.codewars.com/kata/5a045fee46d843effa000070
def decomp(n):
4,688
# Write Number in Expanded Form - Part 2 This is version 2 of my ['Write Number in Exanded Form' Kata](https://www.codewars.com/kata/write-number-in-expanded-form). You will be given a number and you will need to return it as a string in [Expanded Form](https://www.mathplacementreview.com/arithmetic/decimals.php#writ...
["def expanded_form(num):\n integer_part, fractional_part = str(num).split('.')\n\n result = [str(int(num) * (10 ** i)) for i, num in enumerate(integer_part[::-1]) if num != '0'][::-1]\n result += [str(num) + '/' + str(10 ** (i + 1)) for i, num in enumerate(fractional_part) if num != '0']\n\n return ' + '.j...
{"fn_name": "expanded_form", "inputs": [[1.24], [7.304], [0.04], [1.04], [7.3004], [0.004], [693.230459]], "outputs": [["1 + 2/10 + 4/100"], ["7 + 3/10 + 4/1000"], ["4/100"], ["1 + 4/100"], ["7 + 3/10 + 4/10000"], ["4/1000"], ["600 + 90 + 3 + 2/10 + 3/100 + 4/10000 + 5/100000 + 9/1000000"]]}
introductory
https://www.codewars.com/kata/58cda88814e65627c5000045
def expanded_form(num):
4,689
A wildlife study involving ducks is taking place in North America. Researchers are visiting some wetlands in a certain area taking a survey of what they see. The researchers will submit reports that need to be processed by your function. ## Input The input for your function will be an array with a list of common duc...
["def create_report(names):\n result = {}\n \n for name in names:\n if name.startswith(\"Labrador Duck\"):\n return [\"Disqualified data\"]\n \n name = name.upper().replace(\"-\", \" \").split()\n count = int(name.pop())\n \n if len(name) == 1: code = nam...
{"fn_name": "create_report", "inputs": [[["Redhead 5", "Labrador Duck 9", "Blue-Winged Teal 25", "Steller's Eider 200"]], [["Canvasback 10", "Mallard 150", "American Wigeon 45", "Baikal Teal 3", "Barrow's Goldeneye 6", "Surf Scoter 12"]], [["Redhead 3", "Gadwall 1", "Smew 4", "Greater Scaup 10", "Redhead 3", "Ga...
introductory
https://www.codewars.com/kata/5b0737c724c0686bf8000172
def create_report(names):
4,690
`This kata is the first of the ADFGX Ciphers, the harder version can be found `here. The ADFGX Cipher is a pretty well-known Cryptographic tool, and is essentially a modified Polybius Square. Rather than having numbers as coordinates on the table, it has the letters: `A, D, F, G, X` Also, because this is the first...
["from itertools import product\nimport re\n\nKEY = [ a+b for a, b in product(\"ADFGX\", repeat=2) ]\n \n\ndef adfgx_encrypt(plaintext, square):\n d = dict(zip(square, KEY))\n oddity = d['i'] if 'i' in d else d['j']\n return ''.join(d.get(c, oddity) for c in plaintext)\n \n \ndef adfgx_decrypt(cip...
{"fn_name": "adfgx_encrypt", "inputs": [["helloworld", "bchigklnmoqprstuvwxyzadef"]], "outputs": [["AFXGDDDDDXGFDXFFDDXF"]]}
introductory
https://www.codewars.com/kata/57f171f618e9fa58ef000083
def adfgx_encrypt(plaintext, square):
4,691
In this Kata, you will be given a string and your task will be to return a list of ints detailing the count of uppercase letters, lowercase, numbers and special characters, as follows. ```Haskell Solve("*'&ABCDabcde12345") = [4,5,5,3]. --the order is: uppercase letters, lowercase, numbers and special characters. ``` ...
["def solve(s):\n uc, lc, num, sp = 0, 0, 0, 0\n for ch in s:\n if ch.isupper(): uc += 1\n elif ch.islower(): lc += 1\n elif ch.isdigit(): num += 1\n else: sp += 1\n return [uc, lc, num, sp]", "import re\ndef solve(s):\n return [len(re.findall(i,s)) for i in ('[A-Z]','[a-z]','\\d','[^a-zA-Z0-9]')]\n",...
{"fn_name": "solve", "inputs": [["Codewars@codewars123.com"], ["bgA5<1d-tOwUZTS8yQ"], ["P*K4%>mQUDaG$h=cx2?.Czt7!Zn16p@5H"], ["RYT'>s&gO-.CM9AKeH?,5317tWGpS<*x2ukXZD"], ["$Cnl)Sr<7bBW-&qLHI!mY41ODe"], ["@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft"]], "outputs": [[[1, 18, 3, 2]], [[7, 6, 3, 2]], [[9, 9, 6, 9]], [[15, 8, 6, 9]], ...
introductory
https://www.codewars.com/kata/5a29a0898f27f2d9c9000058
def solve(s):
4,692
You're a buyer/seller and your buisness is at stake... You ___need___ to make profit... Or at least, you need to lose the least amount of money! Knowing a list of prices for buy/sell operations, you need to pick two of them. Buy/sell market is evolving across time and the list represent this evolution. First, you nee...
["def max_profit(prices):\n m = best = float('-inf')\n for v in reversed(prices):\n m, best = max(m, best-v), max(best,v)\n return m", "def max_profit(prices):\n out = prices[1] - prices[0]\n min_price = prices[0]\n \n for i in prices[1:]:\n if i - min_price > out:\n out = ...
{"fn_name": "max_profit", "inputs": [[[10, 7, 5, 8, 11, 9]], [[3, 4]], [[9, 9]], [[10, 7, 5, 4, 1]]], "outputs": [[6], [1], [0], [-1]]}
introductory
https://www.codewars.com/kata/58f174ed7e9b1f32b40000ec
def max_profit(prices):
4,693
Every Turkish citizen has an identity number whose validity can be checked by these set of rules: - It is an 11 digit number - First digit can't be zero - Take the sum of 1st, 3rd, 5th, 7th and 9th digit and multiply it by 7. Then subtract the sum of 2nd, 4th, 6th and 8th digits from this value. Modulus 10 of the resu...
["def check_valid_tr_number(n):\n return type(n) == int and len(str(n)) == 11 and \\\n 8*sum(map(int, str(n)[:-1:2])) % 10 == sum(map(int, str(n)[:-1])) % 10 == n % 10", "import re\n\ndef check_valid_tr_number(n):\n lst = list(map(int,str(n) if isinstance(n,int) else '0'))\n return (isinstance(n,int)\n ...
{"fn_name": "check_valid_tr_number", "inputs": [[6923522112], [692352217312], ["x5810a78432"], [36637640050], [12762438338], ["03868894286"], [10000000146], [19415235426], [16691067984], [72097107542], [57040492705]], "outputs": [[false], [false], [false], [true], [false], [false], [true], [true], [false], [true], [fal...
introductory
https://www.codewars.com/kata/556021360863a1708900007b
def check_valid_tr_number(number):
4,694
# Task: Write a function that accepts an integer `n` and returns **the sum of the factorials of the first **`n`** Fibonacci numbers** ## Examples: ```python sum_fib(2) = 2 # 0! + 1! = 2 sum_fib(3) = 3 # 0! + 1! + 1! = 3 sum_fib(4) = 5 # 0! + 1! + 1! + 2! = 5 sum_fib(10) = 295232799039604140898709551821456...
["from math import factorial\n\nfib = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]\n\ndef sum_fib(n):\n return sum( factorial(x) for x in fib[:n] )", "from math import factorial\n\ndef sum_fib(n):\n a, b, s = 0, 1, 0\n while n:\n s += factorial(a)\n a...
{"fn_name": "sum_fib", "inputs": [[2], [3]], "outputs": [[2], [3]]}
introductory
https://www.codewars.com/kata/589926bf7a2a3992050014f1
def sum_fib(n):
4,695
# Feynman's squares Richard Phillips Feynman was a well-known American physicist and a recipient of the Nobel Prize in Physics. He worked in theoretical physics and pioneered the field of quantum computing. Recently, an old farmer found some papers and notes that are believed to have belonged to Feynman. Among notes a...
["def count_squares(n):\n return sum([i * i for i in range(n + 1 ) ] )", "def count_squares(n):\n return n*(n+1)*(2*n+1)/6", "def count_squares(n): \n \"\"\" Function that uses recursion to calculate the number of square units in an n X n square\"\"\"\n if n == 1:\n return 1\n else:\n retu...
{"fn_name": "count_squares", "inputs": [[1], [2], [3], [5], [8], [15]], "outputs": [[1], [5], [14], [55], [204], [1240]]}
introductory
https://www.codewars.com/kata/551186edce486caa61000f5c
def count_squares(n):
4,696
# Task John loves encryption. He can encrypt any string by the following algorithm: ``` take the first and the last letters of the word; replace the letters between them with their number; replace this number with the sum of it digits until a single digit is obtained.``` Given two strings(`s1` and `s2`), re...
["def same_encryption(s1, s2):\n return (s1[0], s1[-1], len(s1) % 9) == (s2[0], s2[-1], len(s2) % 9)", "def same_encryption(s1, s2):\n encrypt = lambda s: f\"{s[0]}{len(s[1:-1]) % 9}{s[-1]}\"\n return encrypt(s1) == encrypt(s2)", "def same_encryption(s1, s2):\n return ( s1[0] == s2[0]\n and s1[-...
{"fn_name": "same_encryption", "inputs": [["abc", "abc"], ["abc", "abd"], ["fKhjuytrdfcdc", "flJc"], ["OKhjuytrdfcdc", "OijK"]], "outputs": [[true], [false], [true], [false]]}
introductory
https://www.codewars.com/kata/58b6c403a38abaaf6c00006b
def same_encryption(s1, s2):
4,697
Given three arrays of integers, return the sum of elements that are common in all three arrays. For example: ``` common([1,2,3],[5,3,2],[7,3,2]) = 5 because 2 & 3 are common in all 3 arrays common([1,2,2,3],[5,3,2,2],[7,3,2,2]) = 7 because 2,2 & 3 are common in the 3 arrays ``` More examples in the test cases. Go...
["from collections import Counter\ndef common(a,b,c):\n return sum((Counter(a) & Counter(b) & Counter(c)).elements())", "from functools import reduce\nfrom operator import and_\nfrom collections import Counter\n\ndef common(a,b,c):\n return sum(reduce(and_,map(Counter, (a,b,c))).elements())", "from collections im...
{"fn_name": "common", "inputs": [[[1, 2, 3], [5, 3, 2], [7, 3, 2]], [[1, 2, 2, 3], [5, 3, 2, 2], [7, 3, 2, 2]], [[1], [1], [1]], [[1], [1], [2]]], "outputs": [[5], [7], [1], [0]]}
introductory
https://www.codewars.com/kata/5a6225e5d8e145b540000127
def common(a,b,c):
4,698
Write a function with the signature shown below: ```python def is_int_array(arr): return True ``` * returns `true / True` if every element in an array is an integer or a float with no decimals. * returns `true / True` if array is empty. * returns `false / False` for every other input.
["def is_int_array(a):\n return isinstance(a, list) and all(isinstance(x, (int, float)) and x == int(x) for x in a)", "def is_int_array(arr):\n if arr == []:\n return True\n if arr in [None, \"\"]:\n return False\n for i in arr:\n if type(i) in [int, float]:\n if int(i) != i:...
{"fn_name": "is_int_array", "inputs": [[[]], [[1, 2, 3, 4]], [[-11, -12, -13, -14]], [[1.0, 2.0, 3.0]], [[1, 2, null]], [null], [""], [[null]], [[1.0, 2.0, 3.0001]], [["-1"]]], "outputs": [[true], [true], [true], [true], [false], [false], [false], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/52a112d9488f506ae7000b95
def is_int_array(arr):
4,699
Imagine two rings with numbers on them. The inner ring spins clockwise (decreasing by 1 each spin) and the outer ring spins counter clockwise (increasing by 1 each spin). We start with both rings aligned on 0 at the top, and on each move we spin each ring one increment. How many moves will it take before both rings sho...
["from itertools import count\n\ndef spinning_rings(inner_max, outer_max):\n return next(i for i in count(1) if i % (outer_max + 1) == -i % (inner_max + 1))", "def spinning_rings(inner_max, outer_max):\n a,b,res = inner_max,1,1\n while a != b:\n a = (a + inner_max) % (inner_max+1)\n b = (b + 1) %...
{"fn_name": "spinning_rings", "inputs": [[2, 3], [3, 2], [1, 1], [2, 2], [3, 3]], "outputs": [[5], [2], [1], [3], [2]]}
introductory
https://www.codewars.com/kata/59afff65f1c8274f270020f5
def spinning_rings(inner_max, outer_max):
4,700
In this Kata, you will be given a multi-dimensional array containing `2 or more` sub-arrays of integers. Your task is to find the maximum product that can be formed by taking any one element from each sub-array. ``` Examples: solve( [[1, 2],[3, 4]] ) = 8. The max product is given by 2 * 4 solve( [[10,-15],[-1,-3]] ) =...
["def solve(arr):\n \n p, q = 1, 1\n \n for k in arr:\n \n x, y = max(k), min(k)\n \n a = p * x\n b = q * x\n c = p * y\n d = q * y\n \n p = max(a, b, c, d)\n q = min(a, b, c, d)\n \n return max(p, q)", "def solve(arr):\n ...
{"fn_name": "solve", "inputs": [[[[1, 2], [3, 4]]], [[[10, -15], [-1, -3]]], [[[-1, 2, -3, 4], [1, -2, 3, -4]]], [[[-11, -6], [-20, -20], [18, -4], [-20, 1]]], [[[14, 2], [0, -16], [-12, -16]]], [[[-3, -4], [1, 2, -3]]], [[[-2, -15, -12, -8, -16], [-4, -15, -7], [-10, -5]]]], "outputs": [[8], [45], [12], [17600], [3584...
introductory
https://www.codewars.com/kata/5d0365accfd09600130a00c9
def solve(arr):
4,701
Mr Leicester's cheese factory is the pride of the East Midlands, but he's feeling a little blue. It's the time of the year when **the taxman is coming round to take a slice of his cheddar** - and the final thing he has to work out is how much money he's spending on his staff. Poor Mr Leicester can barely sleep he's so ...
["from math import ceil\ndef pay_cheese(arr):\n return f'L{ceil(sum(arr) / 100) * 35}'", "from math import ceil\n\ndef pay_cheese(lst):\n return f\"L{35 * ceil(sum(lst) / 100)}\"", "from math import ceil\ndef pay_cheese(a): \n return f\"L{round(ceil(((sum(a)*6.)/10.)/60.)*35)}\"", "pay_cheese=lambda l:f\"L{...
{"fn_name": "pay_cheese", "inputs": [[[750, 750, 750, 750, 600]], [[700, 750, 700, 750, 600]], [[574, 574, 574, 574, 574]], [[1, 1, 1, 1, 1]], [[0, 0, 0, 0, 0]]], "outputs": [["L1260"], ["L1225"], ["L1015"], ["L35"], ["L0"]]}
introductory
https://www.codewars.com/kata/5ab7ee556a176b1043000047
def pay_cheese(arr):
4,702
# Task Given an integer `product`, find the smallest positive integer the product of whose digits is equal to product. If there is no such integer, return -1 instead. # Example For `product = 1`, the output should be `11`; `1 x 1 = 1` (1 is not a valid result, because it has only 1 digit) For `product = 12`, ...
["def digits_product(product):\n if product < 10:\n return 10 + product\n n = ''\n for d in range(9, 1, -1):\n while not product % d:\n n += str(d)\n product //= d\n return int(n[::-1]) if product == 1 else -1", "from functools import reduce\nfrom operator import mul\n\nd...
{"fn_name": "digits_product", "inputs": [[12], [19], [450], [0], [13], [1], [5], [10]], "outputs": [[26], [-1], [2559], [10], [-1], [11], [15], [25]]}
introductory
https://www.codewars.com/kata/589436311a8808bf560000f9
def digits_product(product):
4,703
The medians of a triangle are the segments that unit the vertices with the midpoint of their opposite sides. The three medians of a triangle intersect at the same point, called the barycenter or the centroid. Given a triangle, defined by the cartesian coordinates of its vertices we need to localize its barycenter or ce...
["def bar_triang(a, b, c):\n return [round(sum(x)/3.0, 4) for x in zip(a, b, c)]", "def bar_triang(pointA, pointB, pointC): \n a = (pointA[0] + pointB[0] + pointC[0]) / 3.0\n b = (pointA[1] + pointB[1] + pointC[1]) / 3.0\n return [round(a, 4), round(b, 4)]", "def bar_triang(pointA, pointB, pointC): # points...
{"fn_name": "bar_triang", "inputs": [[[4, 6], [12, 4], [10, 10]], [[4, 2], [12, 2], [6, 10]], [[4, 8], [8, 2], [16, 6]]], "outputs": [[[8.6667, 6.6667]], [[7.3333, 4.6667]], [[9.3333, 5.3333]]]}
introductory
https://www.codewars.com/kata/5601c5f6ba804403c7000004
def bar_triang(pointA, pointB, pointC):
4,704
In this kata you must take an input string, reverse the order of the words, and reverse the order of the letters within the words. But, as a bonus, every test input will end with a punctuation mark (! ? .) and the output should be returned with the mark at the end. A few examples should help clarify: ```python esrev...
["def esrever(s):\n return s[:-1][::-1] + s[-1] if s else ''", "def esrever(string):\n return string and string[-2::-1] + string[-1]", "def esrever(string):\n return string[:-1][::-1] + string[-1:]", "def esrever(string):\n return string[-2::-1] + string[-1:]", "esrever = lambda s: s[-2::-1] + s[:-2:-1]", "...
{"fn_name": "esrever", "inputs": [["an Easy one?"], ["a small lOan OF 1,000,000 $!"], ["<?> &!.\"."], ["b3tTer p4ss thIS 0ne."], [""]], "outputs": [["eno ysaE na?"], ["$ 000,000,1 FO naOl llams a!"], ["\".!& >?<."], ["en0 SIht ss4p reTt3b."], [""]]}
introductory
https://www.codewars.com/kata/57e0206335e198f82b00001d
def esrever(string):
4,705
This is the simple version of Fastest Code series. If you need some challenges, please try the [Performance version](http://www.codewars.com/kata/5714594d2817ff681c000783) ## Task: Give you a number array ```numbers``` and a number ```c```. Find out a pair of numbers(we called them number a and number b) from t...
["def find_a_b(numbers,c):\n for i, a in enumerate(numbers, 1):\n for b in numbers[i:]:\n if a * b == c: return [a, b]", "from itertools import combinations\n\ndef find_a_b(numbers,c):\n return next(([a,b] for a,b in combinations(numbers,2) if a*b==c),None)", "def find_a_b(numbers, c):\n for ...
{"fn_name": "find_a_b", "inputs": [[[1, 2, 3], 3], [[1, 2, 3], 6], [[1, 2, 3], 7], [[1, 2, 3, 6], 6], [[1, 2, 3, 4, 5, 6], 15], [[0, 0, 2], 4], [[0, 0, 2, 2], 4], [[-3, -2, -2, -1, 0, 1, 2, 3, 4], 4], [[-3, -2, -2, -1, 0, 1, 2, 3, 4], 0], [[-3, -2, -1, 0, 1, 2, 3, 4], 4]], "outputs": [[[1, 3]], [[2, 3]], [null], [[1, 6...
introductory
https://www.codewars.com/kata/5714803d2817ffce17000a35
def find_a_b(numbers,c):
4,706
# Task You are given a decimal number `n` as a **string**. Transform it into an array of numbers (given as **strings** again), such that each number has only one nonzero digit and their sum equals n. Each number in the output array should be written without any leading and trailing zeros. # Input/Output - `[inpu...
["def split_exp(n):\n dot = n.find('.')\n if dot == -1: dot = len(n)\n return [d+\"0\"*(dot-i-1) if i<dot else \".{}{}\".format(\"0\"*(i-dot-1), d)\n for i,d in enumerate(n) if i != dot and d != '0']", "def split_exp(n):\n j = n.find('.') + 1 or len(n) + 1\n return [f\"{c}{'0'*(j-i-2)}\" if i ...
{"fn_name": "split_exp", "inputs": [["7970521.5544"], ["7496314"], ["0"], ["6"], ["1.0000000000"], ["0000000000.1"], ["1010101"], ["1234567890.1234567890"]], "outputs": [[["7000000", "900000", "70000", "500", "20", "1", ".5", ".05", ".004", ".0004"]], [["7000000", "400000", "90000", "6000", "300", "10", "4"]], [[]], [[...
introductory
https://www.codewars.com/kata/58fd9f6213b00172ce0000c9
def split_exp(n):
4,707
In this kata, your task is to write a function `to_bytes(n)` (or `toBytes(n)` depending on language) that produces a list of bytes that represent a given non-negative integer `n`. Each byte in the list is represented by a string of `'0'` and `'1'` of length 8. The most significant byte is first in the list. The example...
["def to_bytes(n):\n if not n:\n return ['00000000']\n \n res = []\n while n:\n res.append('{:08b}'.format(n % 256))\n n //= 256\n \n return res[::-1]", "import re\nfrom math import ceil\ndef to_bytes(n):\n return re.findall('.{8}', '{:0{}b}'.format(n, int(8 * ceil(n.bit_length...
{"fn_name": "to_bytes", "inputs": [[0], [1]], "outputs": [[["00000000"]], [["00000001"]]]}
introductory
https://www.codewars.com/kata/5705601c5eef1fad69000674
def to_bytes(n):
4,708
# Kata Task I have a cat and a dog. I got them at the same time as kitten/puppy. That was `humanYears` years ago. Return their respective ages now as [`humanYears`,`catYears`,`dogYears`] NOTES: * humanYears >= 1 * humanYears are whole numbers only ## Cat Years * `15` cat years for first year * `+9` cat years for ...
["def human_years_cat_years_dog_years(x):\n return [x, 24+(x-2)*4 if (x != 1) else 15, 24+(x-2)*5 if (x != 1) else 15]", "def human_years_cat_years_dog_years(human_years):\n catYears = 0\n dogYears = 0\n if human_years == 1:\n catYears += 15\n dogYears += 15\n return [human_years, catYe...
{"fn_name": "human_years_cat_years_dog_years", "inputs": [[1], [2], [10]], "outputs": [[[1, 15, 15]], [[2, 24, 24]], [[10, 56, 64]]]}
introductory
https://www.codewars.com/kata/5a6663e9fd56cb5ab800008b
def human_years_cat_years_dog_years(human_years):
4,709
Consider a sequence, which is formed by the following rule: next term is taken as the smallest possible non-negative integer, which is not yet in the sequence, so that `no 3` terms of sequence form an arithmetic progression. ## Example `f(0) = 0` -- smallest non-negative `f(1) = 1` -- smallest non-negative, which i...
["sequence=lambda n:int(format(n,'b'),3)", "def sequence(n):\n return int(format(n, 'b'), 3)", "sequence=lambda n:int(bin(n)[2:],3)", "# A005836\ndef sequence(n):\n return n and 3*sequence(n>>1) + (n&1)", "from math import log2\n\ndef sequence(i):\n if i == 0:\n return 0\n e = int(log2(i))\n retur...
{"fn_name": "sequence", "inputs": [[0], [1], [2], [3], [4], [5], [334], [123], [546], [1634], [14514]], "outputs": [[0], [1], [3], [4], [9], [10], [7329], [1084], [19929], [79707], [2305425]]}
introductory
https://www.codewars.com/kata/5e0607115654a900140b3ce3
def sequence(n):
4,710
In some countries of former Soviet Union there was a belief about lucky tickets. A transport ticket of any sort was believed to posess luck if sum of digits on the left half of its number was equal to the sum of digits on the right half. Here are examples of such numbers: ``` 003111 # 3 = 1 + 1 + 1 81337...
["def luck_check(string):\n e0, b1 = len(string) // 2, (len(string) + 1) // 2\n return sum(map(int, string[:e0])) == sum(map(int, string[b1:]))", "def luck_check(s):\n if not s or not all(c in '0123456789' for c in s):\n raise ValueError('Invalid ticket number')\n e0, b1 = len(s) // 2, (len(s) + 1) /...
{"fn_name": "luck_check", "inputs": [["5555"], ["003111"], ["543970707"], ["439924"], ["943294329932"], ["000000"], ["454319"], ["1233499943"], ["935336"]], "outputs": [[true], [true], [false], [false], [false], [true], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/5314b3c6bb244a48ab00076c
def luck_check(string):
4,711
Write a program that will calculate the number of trailing zeros in a factorial of a given number. `N! = 1 * 2 * 3 * ... * N` Be careful `1000!` has 2568 digits... For more info, see: http://mathworld.wolfram.com/Factorial.html ## Examples ```python zeros(6) = 1 # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing ...
["def zeros(n):\n \"\"\"\n No factorial is going to have fewer zeros than the factorial of a smaller\n number.\n\n Each multiple of 5 adds a 0, so first we count how many multiples of 5 are\n smaller than `n` (`n // 5`).\n\n Each multiple of 25 adds two 0's, so next we add another 0 for each multiple\...
{"fn_name": "zeros", "inputs": [[0], [6], [30], [100], [1000], [100000], [1000000000]], "outputs": [[0], [1], [7], [24], [249], [24999], [249999998]]}
introductory
https://www.codewars.com/kata/52f787eb172a8b4ae1000a34
def zeros(n):
4,712
Lucas numbers are numbers in a sequence defined like this: ``` L(0) = 2 L(1) = 1 L(n) = L(n-1) + L(n-2) ``` Your mission is to complete the function that returns the `n`th term of this sequence. **Note:** It should work for negative numbers as well; how you do this is you flip the equation around, so for negative num...
["def lucasnum(n):\n a = 2\n b = 1\n\n flip = n < 0 and n % 2 != 0\n\n for _ in range(abs(n)):\n a, b = b, a + b\n \n return -a if flip else a", "SEQUENCE = [2, 1]\n\ndef lucasnum(n):\n try:\n return SEQUENCE[abs(n)] * (1, -1)[n < 0 and n % 2]\n except IndexError:\n while l...
{"fn_name": "lucasnum", "inputs": [[-10], [-1]], "outputs": [[123], [-1]]}
introductory
https://www.codewars.com/kata/55a7de09273f6652b200002e
def lucasnum(n):
4,713
`late_clock` function receive an array with 4 digits and should return the latest time that can be built with those digits. The time should be in `HH:MM` format. Examples: ``` [1, 9, 8, 3] => 19:38 [9, 1, 2, 5] => 21:59 ``` You can suppose the input is correct and you can build from it a correct 24-hour time.
["from itertools import permutations\n\ndef late_clock(digits):\n for p in permutations(sorted(digits, reverse=True)):\n if p[0] > 2 or (p[0] == 2 and p[1] > 3) or p[2] > 5: continue\n return '{}{}:{}{}'.format(*p)", "def late_clock(digits):\n res, digits = [], digits[:]\n def rec(i):\n if i == 3:\n...
{"fn_name": "late_clock", "inputs": [[[9, 1, 2, 5]], [[1, 9, 8, 3]], [[0, 2, 2, 2]], [[3, 5, 0, 2]], [[9, 0, 1, 1]], [[2, 3, 2, 4]], [[1, 2, 8, 9]]], "outputs": [["21:59"], ["19:38"], ["22:20"], ["23:50"], ["19:10"], ["23:42"], ["19:28"]]}
introductory
https://www.codewars.com/kata/58925dcb71f43f30cd00005f
def late_clock(digits):
4,714
## Task Write a method `remainder` which takes two integer arguments, `dividend` and `divisor`, and returns the remainder when dividend is divided by divisor. Do NOT use the modulus operator (%) to calculate the remainder! #### Assumption Dividend will always be `greater than or equal to` divisor. #### Notes Make ...
["def remainder(dividend,divisor):\n while divisor <= dividend:\n dividend = dividend - divisor\n return dividend", "# Take your pick\nfrom operator import mod as remainder\nremainder = int.__mod__", "def remainder(d1,d2):\n return d1%d2", "def remainder(dividend,divisor):\n return dividend - (dividend...
{"fn_name": "remainder", "inputs": [[3, 2], [19, 2], [10, 2], [34, 7], [27, 5]], "outputs": [[1], [1], [0], [6], [2]]}
introductory
https://www.codewars.com/kata/564f458b4d75e24fc9000041
def remainder(dividend, divisor):
4,715
## Task Given a string, add the fewest number of characters possible from the front or back to make it a palindrome. ## Example For the input `cdcab`, the output should be `bacdcab` ## Input/Output Input is a string consisting of lowercase latin letters with length 3 <= str.length <= 10 The output is a palindrome...
["def build_palindrome(s):\n for n in range(len(s), -1, -1):\n if s[:n] == s[:n][::-1]:\n return s[n:][::-1] + s\n if s[-n:] == s[-n:][::-1]:\n return s + s[:-n][::-1]", "def build_palindrome(s):\n a = s[1:][::-1] + s\n temp = s\n for i in range(len(s)+1):\n temp =...
{"fn_name": "build_palindrome", "inputs": [["abcdc"], ["ababa"]], "outputs": [["abcdcba"], ["ababa"]]}
introductory
https://www.codewars.com/kata/58efb6ef0849132bf000008f
def build_palindrome(s):
4,716
# Task In the field, two beggars A and B found some gold at the same time. They all wanted the gold, and they decided to use simple rules to distribute gold: ``` They divided gold into n piles and be in line. The amount of each pile and the order of piles all are randomly. They took turns to take away a pile of gold...
["def distribution_of(golds):\n g = golds[:]\n turn, total = 0, [0, 0]\n while g:\n total[turn % 2] += g.pop(-(g[0] < g[-1]))\n turn += 1\n return total\n", "from collections import deque\ndef distribution_of(golds):\n g = deque(golds)\n s = [0, 0]\n t = 0\n while g:\n s[t] ...
{"fn_name": "distribution_of", "inputs": [[[4, 7, 2, 9, 5, 2]], [[10, 1000, 2, 1]]], "outputs": [[[11, 18]], [[12, 1001]]]}
introductory
https://www.codewars.com/kata/59547688d8e005759e000092
def distribution_of(golds):
4,717
## Task: You have to write a function **pattern** which returns the following Pattern(See Examples) upto (2n-1) rows, where n is parameter. ### Rules/Note: * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * All the lines in the pattern have same length i.e equal to the number o...
["def pattern(n):\n lines = []\n for i in range(1, n + 1):\n line = ' ' * (n - i)\n line += ''.join(str(j % 10) for j in range(1, i + 1))\n line += line[::-1][1:]\n lines.append(line)\n return '\\n'.join(lines + lines[::-1][1:])\n", "def pattern(n):\n lines = []\n for c in ran...
{"fn_name": "pattern", "inputs": [[1], [3], [7], [0], [-25]], "outputs": [["1"], [" 1 \n 121 \n12321\n 121 \n 1 "], [" 1 \n 121 \n 12321 \n 1234321 \n 123454321 \n 12345654321 \n1234567654321\n 12345654321 \n 123454321 \n 1234321 \n 12321 \n 121 \n 1 "], [...
introductory
https://www.codewars.com/kata/5579e6a5256bac65e4000060
def pattern(n):
4,718
Write a function ```x(n)``` that takes in a number ```n``` and returns an ```nxn``` array with an ```X``` in the middle. The ```X``` will be represented by ```1's``` and the rest will be ```0's```. E.g. ```python x(5) == [[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0]...
["def x(n): \n d = [[0] * n for i in range (n)]\n for i in range(n):\n d[i][i] = 1\n d[i][-i-1] = 1\n return d", "def fill(i, j, n):\n if i == j or i + j == n - 1:\n return 1\n else:\n return 0\n\ndef x(n):\n return [[fill(i, j, n) for j in range(n)] for i in range(n)]", "...
{"fn_name": "x", "inputs": [[1], [2], [3], [4], [5], [6]], "outputs": [[[[1]]], [[[1, 1], [1, 1]]], [[[1, 0, 1], [0, 1, 0], [1, 0, 1]]], [[[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]], [[[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 1]]], [[[1, 0, 0, 0, 0, 1], [0, 1, 0, 0,...
introductory
https://www.codewars.com/kata/55cc20eb943f1d8b11000045
def x(n):
4,719
You are given an array of integers. Your task is to sort odd numbers within the array in ascending order, and even numbers in descending order. Note that zero is an even number. If you have an empty array, you need to return it. For example: ``` [5, 3, 2, 8, 1, 4] --> [1, 3, 8, 4, 5, 2] odd numbers ascending: [...
["def sort_array(xs):\n es = sorted(x for x in xs if x % 2 == 0)\n os = sorted((x for x in xs if x % 2 != 0), reverse=True)\n return [(es if x % 2 == 0 else os).pop() for x in xs]", "def sort_array(a):\n odds = []; evens = []; newArray = []\n for i in a:\n if i % 2 == 0:\n evens.append(...
{"fn_name": "sort_array", "inputs": [[[5, 3, 2, 8, 1, 4, 11]], [[2, 22, 37, 11, 4, 1, 5, 0]], [[1, 111, 11, 11, 2, 1, 5, 0]], [[]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 9, 8, 7, 6, 5]]], "outputs": [[[1, 3, 8, 4, 5, 2, 11]], [[22, 4, 1, 5, 2, 11, 37, 0]], [[1, 1, 5, 11, 2...
introductory
https://www.codewars.com/kata/5a1cb5406975987dd9000028
def sort_array(a):
4,720
In this kata, we will check is an array is (hyper)rectangular. A rectangular array is an N-dimensional array with fixed sized within one dimension. Its sizes can be repsented like A1xA2xA3...xAN. That means a N-dimensional array has N sizes. The 'As' are the hyperrectangular properties of an array. You should implem...
["from itertools import chain\n\ndef hyperrectangularity_properties(arr):\n hr, arr = [], [arr]\n while 1:\n check = sum(isinstance(v, int) for v in arr) # Check homogeneity\n if check or not arr: # some int are present or empty array (edge case)\n if...
{"fn_name": "hyperrectangularity_properties", "inputs": [[[]]], "outputs": [[[0]]]}
introductory
https://www.codewars.com/kata/5b33e9c291c746b102000290
def hyperrectangularity_properties(arr):
4,721
Write a function ```convert_temp(temp, from_scale, to_scale)``` converting temperature from one scale to another. Return converted temp value. Round converted temp value to an integer(!). Reading: http://en.wikipedia.org/wiki/Conversion_of_units_of_temperature ``` possible scale inputs: "C" for Celsius "F...
["TO_KELVIN = {\n 'C': (1, 273.15),\n 'F': (5.0 / 9, 459.67 * 5.0 / 9),\n 'R': (5.0 / 9, 0),\n 'De': (-2.0 / 3, 373.15),\n 'N': (100.0 / 33, 273.15),\n 'Re': (5.0 / 4, 273.15),\n 'Ro': (40.0 / 21, -7.5 * 40 / 21 + 273.15),\n}\n\ndef convert_temp(temp, from_scale, to_scale):\n if from_scale == to...
{"fn_name": "convert_temp", "inputs": [[100, "C", "F"], [-30, "De", "K"], [40, "Re", "C"], [60, "De", "F"], [373.15, "K", "N"], [666, "K", "K"], [60, "C", "F"], [60, "De", "C"], [128.25, "Ro", "C"], [-273.15, "C", "R"], [0, "K", "R"]], "outputs": [[212], [393], [50], [140], [33], [666], [140], [60], [230], [0], [0]]}
introductory
https://www.codewars.com/kata/54ce9497975ca65e1a0008c6
def convert_temp(temp, from_scale, to_scale):
4,722
# Challenge : Write a function that takes a single argument `n` that is a string representation of a simple mathematical expression and evaluates it as a floating point value. # Commands : - positive or negative decimal numbers - `+, -, *, /, ( / ).` --- Expressions use [infix notation](https://en.wikipedia.org/...
["def e(s):return f([*s,'+'])\ndef f(s,r=0,o=0,x='',c=0):\n while s and')'!=c:\n c=s.pop(0);i='+-*/)('.find(c)\n if c=='-'>x or i<0:x+=c\n elif c=='(':x=str(f(s))\n elif i>-1:a=float(x);r=[r+a,r-a,r*a,r/a][o];o=i;x=''\n return r", "def e(s,t=[],x=0,o='+',m=')*+-/'):\n if s:t+=list(s.replace(' ','')+')')\n while o!=...
{"fn_name": "e", "inputs": [["2*3*4*5+99"]], "outputs": [[219]]}
introductory
https://www.codewars.com/kata/5b05a8dd91cc5739df0000aa
def e(s):
4,723
Write a method that takes one argument as name and then greets that name, capitalized and ends with an exclamation point. Example: ``` "riley" --> "Hello Riley!" "JACK" --> "Hello Jack!" ```
["def greet(name): \n return f'Hello {name.title()}!'", "def greet(name): \n return f\"Hello {name.capitalize()}!\"", "def greet(name):\n name = name.lower()\n return \"Hello \" + name[0].upper() + name[1:] + \"!\"\n \n \nprint((greet(\"BILLY\")))\n", "def greet(name): \n name = name.lower() # Conv...
{"fn_name": "greet", "inputs": [["riley"], ["molly"], ["BILLY"]], "outputs": [["Hello Riley!"], ["Hello Molly!"], ["Hello Billy!"]]}
introductory
https://www.codewars.com/kata/535474308bb336c9980006f2
def greet(name):
4,724
DropCaps means that the first letter of the starting word of the paragraph should be in caps and the remaining lowercase, just like you see in the newspaper. But for a change, let's do that for each and every word of the given String. Your task is to capitalize every word that has length greater than 2, leaving small...
["def drop_cap(str_):\n return ' '.join( w.capitalize() if len(w) > 2 else w for w in str_.split(' ') )\n", "import re\n\ndef drop_cap(s):\n return re.sub(r'\\w{3,}', lambda m: m[0].title(), s)", "def drop_cap(str_):\n return \" \".join([i[0].upper() + i[1::].lower() if len(i) > 2 else i for i in str_.split(\"...
{"fn_name": "drop_cap", "inputs": [["Apple Banana"], ["Apple"], [""], ["of"], ["Revelation of the contents outraged American public opinion, and helped generate"], ["more than one space between words"], [" leading spaces"], ["trailing spaces "], ["ALL CAPS CRAZINESS"], ["rAnDoM CaPs CrAzInEsS"]], "outputs": [["A...
introductory
https://www.codewars.com/kata/559e5b717dd758a3eb00005a
def drop_cap(str_):
4,725
Impliment the reverse function, which takes in input n and reverses it. For instance, `reverse(123)` should return `321`. You should do this without converting the inputted number into a string.
["def reverse(n):\n m = 0\n while n > 0:\n n, m = n // 10, m * 10 + n % 10\n return m", "def reverse(n):\n return int(str(n)[::-1])", "def reverse(n):\n r = 0\n while n:\n r = r*10 + n%10\n n //= 10\n return r", "def reverse(n):\n \"\"\"Returns n with all digits reversed. As...
{"fn_name": "reverse", "inputs": [[1234], [4321], [1001], [1010], [12005000]], "outputs": [[4321], [1234], [1001], [101], [50021]]}
introductory
https://www.codewars.com/kata/58069e4cf3c13ef3a6000168
def reverse(n):
4,726
Given a string `s` of uppercase letters, your task is to determine how many strings `t` (also uppercase) with length equal to that of `s` satisfy the followng conditions: * `t` is lexicographical larger than `s`, and * when you write both `s` and `t` in reverse order, `t` is still lexicographical larger than `s`. ``...
["def solve(s):\n r, l = 0, 0\n for c in s:\n m = ord('Z') - ord(c)\n r, l = r + m + l * m, m + l * 26\n return r % 1000000007", "def solve(s, z=ord('Z')):\n a = r = 0\n for i in (z - ord(c) for c in s):\n r += (a + 1) * i\n a = a * 26 + i\n r %= 1000000007\n a %...
{"fn_name": "solve", "inputs": [["XYZ"], ["ABC"], ["ABCD"], ["ZAZ"], ["XYZA"]], "outputs": [[5], [16174], [402230], [25], [34480]]}
introductory
https://www.codewars.com/kata/5cfd36ea4c60c3001884ed42
def solve(s):
4,727
**This Kata is intended as a small challenge for my students** Create a function, called ``removeVowels`` (or ``remove_vowels``), that takes a string argument and returns that same string with all vowels removed (vowels are "a", "e", "i", "o", "u").
["REMOVE_VOWS = str.maketrans('','','aeiou')\n\ndef remove_vowels(s):\n return s.translate(REMOVE_VOWS)", "def remove_vowels(strng):\n return ''.join([i for i in strng if i not in 'aeiou'])", "def remove_vowels(stg):\n return \"\".join(c for c in stg if c not in \"aeiou\")", "def remove_vowels(s):\n return ...
{"fn_name": "remove_vowels", "inputs": [["drake"], ["scholarstem"], ["codewars"], ["high fives!"], [""], ["i"], ["b"]], "outputs": [["drk"], ["schlrstm"], ["cdwrs"], ["hgh fvs!"], [""], [""], ["b"]]}
introductory
https://www.codewars.com/kata/58640340b3a675d9a70000b9
def remove_vowels(s):
4,728
Complete the function so that it takes an array of keys and a default value and returns a hash (Ruby) / dictionary (Python) with all keys set to the default value. ## Example ```python ["draft", "completed"], 0 # should return {"draft": 0, "completed: 0} ```
["def populate_dict(keys, default):\n return {key: default for key in keys}", "populate_dict = dict.fromkeys", "def populate_dict(keys, default):\n return dict.fromkeys(keys, default)", "def populate_dict(keys, default):\n return {k:default for k in keys}", "from itertools import repeat\ndef populate_dict(keys...
{"fn_name": "populate_dict", "inputs": [[["draft", "completed"], 0], [["a", "b", "c"], null], [[1, 2, 3, 4], "OK"]], "outputs": [[{"completed": 0, "draft": 0}], [{"c": null, "b": null, "a": null}], [{"1": "OK", "2": "OK", "3": "OK", "4": "OK"}]]}
introductory
https://www.codewars.com/kata/51c38e14ea1c97ffaf000003
def populate_dict(keys, default):
4,729
If we write out the digits of "60" as English words we get "sixzero"; the number of letters in "sixzero" is seven. The number of letters in "seven" is five. The number of letters in "five" is four. The number of letters in "four" is four: we have reached a stable equilibrium. Note: for integers larger than 9, write ou...
["digits = 'zero one two three four five six seven eight nine'.split()\n\ndef f(n):\n return ''.join(map(digits.__getitem__, map(int, str(n))))\n\ndef numbers_of_letters(n):\n result = [f(n)]\n print(n, result)\n while result[-1] != 'four':\n result.append(f(len(result[-1])))\n return result", "wo...
{"fn_name": "numbers_of_letters", "inputs": [[1], [2], [3], [4], [12], [37], [311], [999]], "outputs": [[["one", "three", "five", "four"]], [["two", "three", "five", "four"]], [["three", "five", "four"]], [["four"]], [["onetwo", "six", "three", "five", "four"]], [["threeseven", "onezero", "seven", "five", "four"]], [["...
introductory
https://www.codewars.com/kata/599febdc3f64cd21d8000117
def numbers_of_letters(n):
4,730
We need a function ```prime_bef_aft()``` that gives the largest prime below a certain given value ```n```, ```befPrime or bef_prime``` (depending on the language), and the smallest prime larger than this value, ```aftPrime/aft_prime``` (depending on the language). The result should be output in a list like the f...
["def prime(a):\n if a < 2: return False\n if a == 2 or a == 3: return True \n if a % 2 == 0 or a % 3 == 0: return False\n maxDivisor = a**0.5\n d, i = 5, 2\n while d <= maxDivisor:\n if a % d == 0: return False\n d += i \n i = 6 - i\n \n return True\n\ndef prime_bef_aft(num)...
{"fn_name": "prime_bef_aft", "inputs": [[3], [4], [100], [97], [101], [120], [130]], "outputs": [[[2, 5]], [[3, 5]], [[97, 101]], [[89, 101]], [[97, 103]], [[113, 127]], [[127, 131]]]}
introductory
https://www.codewars.com/kata/560b8d7106ede725dd0000e2
def prime_bef_aft(num):
4,731
It is 2050 and romance has long gone, relationships exist solely for practicality. MatchMyHusband is a website that matches busy working women with perfect house husbands. You have been employed by MatchMyHusband to write a function that determines who matches!! The rules are... a match occurs providing the husband's...
["def match(usefulness, months):\n return \"Match!\" if sum(usefulness) >= 0.85**months * 100 else \"No match!\"", "def match(usefulness, months):\n return 'Match!' if sum(usefulness) >= 100*0.85**months else 'No match!'", "def current(usefulness):\n return sum(usefulness)\n\ndef needed(months):\n if months...
{"fn_name": "match", "inputs": [[[15, 24, 12], 4], [[26, 23, 19], 3], [[11, 25, 36], 1], [[22, 9, 24], 5], [[8, 11, 4], 10], [[17, 31, 21], 2], [[34, 25, 36], 1], [[35, 35, 29], 0], [[35, 35, 30], 0], [[35, 35, 31], 0]], "outputs": [["No match!"], ["Match!"], ["No match!"], ["Match!"], ["Match!"], ["No match!"], ["Matc...
introductory
https://www.codewars.com/kata/5750699bcac40b3ed80001ca
def match(usefulness, months):
4,732
Your job is to figure out the index of which vowel is missing from a given string: * `A` has an index of 0, * `E` has an index of 1, * `I` has an index of 2, * `O` has an index of 3, * `U` has an index of 4. **Notes:** There is no need for string validation and every sentence given will contain all vowles but one. ...
["def absent_vowel(x): \n return ['aeiou'.index(i) for i in 'aeiou' if i not in x][0]", "def absent_vowel(x): \n return 'aeiou'.index((set('aeiou') - set(x.lower())).pop())", "def absent_vowel(stg): \n return next(i for i, v in enumerate(\"aeiou\") if v not in stg)", "def absent_vowel(x): \n strings = ['a',...
{"fn_name": "absent_vowel", "inputs": [["John Doe hs seven red pples under his bsket"], ["Bb Smith sent us six neatly arranged range bicycles"]], "outputs": [[0], [3]]}
introductory
https://www.codewars.com/kata/56414fdc6488ee99db00002c
def absent_vowel(x):
4,733
Quantum mechanics tells us that a molecule is only allowed to have specific, discrete amounts of internal energy. The 'rigid rotor model', a model for describing rotations, tells us that the amount of rotational energy a molecule can have is given by: `E = B * J * (J + 1)`, where J is the state the molecule is in...
["def rot_energies(B, Jmin, Jmax):\n return [B * J * (J + 1) for J in range(Jmin, Jmax + 1)] if B > 0 else []", "def rot_energies(rot, energy_min, energy_max):\n # We're programmers, not scientists or mathematicians, we can use legible variable names.\n if rot <= 0:\n return []\n else:\n retur...
{"fn_name": "rot_energies", "inputs": [[1, 1, 2], [2, 0, 3], [423, 100, 150], [1, 2, 0], [1, 2, 2], [-1.0, 2, 2]], "outputs": [[[2, 6]], [[0, 4, 12, 24]], [[4272300, 4357746, 4444038, 4531176, 4619160, 4707990, 4797666, 4888188, 4979556, 5071770, 5164830, 5258736, 5353488, 5449086, 5545530, 5642820, 5740956, 5839938, 5...
introductory
https://www.codewars.com/kata/587b6a5e8726476f9b0000e7
def rot_energies(B, Jmin, Jmax):
4,734
It's bonus time in the big city! The fatcats are rubbing their paws in anticipation... but who is going to make the most money? Build a function that takes in two arguments (salary, bonus). Salary will be an integer, and bonus a boolean. If bonus is true, the salary should be multiplied by 10. If bonus is false, the...
["def bonus_time(salary, bonus):\n return \"${}\".format(salary * (10 if bonus else 1))", "def bonus_time(salary, bonus):\n #your code here\n if bonus :\n return \"$\" + str(salary * 10)\n else:\n return \"$\" + str(salary)", "def bonus_time(salary, bonus):\n return '$' + str(salary * [1,10...
{"fn_name": "bonus_time", "inputs": [[10000, true], [25000, true], [10000, false], [60000, false], [2, true], [78, false], [67890, true]], "outputs": [["$100000"], ["$250000"], ["$10000"], ["$60000"], ["$20"], ["$78"], ["$678900"]]}
introductory
https://www.codewars.com/kata/56f6ad906b88de513f000d96
def bonus_time(salary, bonus):
4,735
#### Task: Your job here is to write a function (`keepOrder` in JS/CoffeeScript, `keep_order` in Ruby/Crystal/Python, `keeporder` in Julia), which takes a sorted array `ary` and a value `val`, and returns the lowest index where you could insert `val` to maintain the sorted-ness of the array. The input array will alway...
["from bisect import bisect_left as keep_order", "from bisect import bisect_left\n\ndef keep_order(arr, val):\n return bisect_left(arr, val)", "def keep_order(ary, val):\n for i, x in enumerate(ary):\n if x >= val:\n return i\n return len(ary)", "def keep_order(arr, val):\n for i in range(...
{"fn_name": "keep_order", "inputs": [[[1, 2, 3, 4, 7], 5], [[1, 2, 3, 4, 7], 0], [[1, 1, 2, 2, 2], 2], [[1, 2, 3, 4], 5], [[1, 2, 3, 4], -1], [[1, 2, 3, 4], 2], [[1, 2, 3, 4], 0], [[1, 2, 3, 4], 1], [[1, 2, 3, 4], 3], [[], 1], [[], 0], [[1, 1, 1, 1], 2], [[1, 1, 1, 1], 1], [[1, 1, 1, 1], 0], [[1, 3, 5, 6], 0], [[1, 3, ...
introductory
https://www.codewars.com/kata/582aafca2d44a4a4560000e7
def keep_order(ary, val):
4,736
How many bees are in the beehive? * bees can be facing UP, DOWN, LEFT, or RIGHT * bees can share parts of other bees Examples Ex1 ``` bee.bee .e..e.. .b..eeb ``` *Answer: 5* Ex2 ``` bee.bee e.e.e.e eeb.eeb ``` *Answer: 8* # Notes * The hive may be empty or null/None/nil/... * Python: the hive is passe...
["from itertools import chain\ndef how_many_bees(hive):\n return bool(hive) and sum(s.count('bee') + s.count('eeb') for s in map(''.join, chain(hive, zip(*hive))))", "def count(it):\n return sum(''.join(x).count('bee') + ''.join(x).count('eeb') for x in it)\n\ndef how_many_bees(hive):\n return count(hive) ...
{"fn_name": "how_many_bees", "inputs": [[null]], "outputs": [[0]]}
introductory
https://www.codewars.com/kata/57d6b40fbfcdc5e9280002ee
def how_many_bees(hive):
4,737
```if:python,php In this kata you will have to write a function that takes `litres` and `price_per_litre` as arguments. Purchases of 2 or more litres get a discount of 5 cents per litre, purchases of 4 or more litres get a discount of 10 cents per litre, and so on every two litres, up to a maximum discount of 25 cents ...
["def fuel_price(litres, price_per_liter):\n discount = int(min(litres, 10)/2) * 5 / 100\n return round((price_per_liter - discount) * litres, 2)", "fuel_price = lambda l,p: round(l*(p-min(0.05*(l//2), 0.25)), 2)", "from bisect import bisect\n\n\ndef fuel_price(litres, price_per_liter):\n discount = (0, 5, 10,...
{"fn_name": "fuel_price", "inputs": [[10, 21.5], [40, 10], [15, 5.83]], "outputs": [[212.5], [390], [83.7]]}
introductory
https://www.codewars.com/kata/57b58827d2a31c57720012e8
def fuel_price(litres, price_per_liter):
4,738
## The Riddle The King of a small country invites 1000 senators to his annual party. As a tradition, each senator brings the King a bottle of wine. Soon after, the Queen discovers that one of the senators is trying to assassinate the King by giving him a bottle of poisoned wine. Unfortunately, they do not know which s...
["def find(r):\n return sum(2**i for i in r)", "def find(rats):\n \"\"\"\n The rule the king should use is the following:\n 1) Label all bottle from 1 to 1000\n 2) Label all rats from 0 to 9\n 3) For each rat r, make it drink the bottle b if the binary representation of b has it's rth bit\...
{"fn_name": "find", "inputs": [[[0]], [[1]], [[2]], [[3]], [[4]], [[5]], [[6]], [[7]], [[8]], [[9]], [[3, 5, 6, 7, 8, 9]], [[0, 3, 5, 4, 9, 8]], [[0, 1, 9, 3, 5]], [[0, 1, 2, 3, 4, 6]], [[0, 1, 3, 4]]], "outputs": [[1], [2], [4], [8], [16], [32], [64], [128], [256], [512], [1000], [825], [555], [95], [27]]}
introductory
https://www.codewars.com/kata/58c47a95e4eb57a5b9000094
def find(r):
4,739
We have the numbers with different colours with the sequence: ['red', 'yellow', 'blue']. That sequence colours the numbers in the following way: 1 2 3 4 5 6 7 8 9 10 11 12 13 ..... We have got the following recursive function: ``` f(1) = 1 f(n) = f(n - 1) + n ``` Some terms of this seque...
["D, R = {}, [[], [], []]\nfor i in range(10000):\n D[i] = D.get(i - 1, 0) + i\n R[D[i]%3].append(D[i])\n \ndef same_col_seq(val, k, col):\n r = ['blue', 'red', 'yellow'].index(col)\n return [e for e in R[r] if e > val][:k] ", "def same_col_seq(val, k, col):\n colDct = {'red': 1, 'blue': 0}\n\n ...
{"fn_name": "same_col_seq", "inputs": [[3, 3, "blue"], [100, 4, "red"], [250, 6, "yellow"], [1000, 7, "red"]], "outputs": [[[6, 15, 21]], [[136, 190, 253, 325]], [[]], [[1081, 1225, 1378, 1540, 1711, 1891, 2080]]]}
introductory
https://www.codewars.com/kata/57f891255cae44b2e10000c5
def same_col_seq(val, k, col):
4,740
Given the triangle of consecutive odd numbers: ``` 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... ``` Calculate the row sums of this triangle from the row index (starting at index 1) e.g.: ```python row_sum_odd_numbers(1); # 1 row_sum_odd_numbers(2); # 3 ...
["def row_sum_odd_numbers(n):\n #your code here\n return n ** 3", "def row_sum_odd_numbers(n):\n if type(n)==int and n>0:\n return n**3\n else:\n return \"Input a positive integer\"", "def row_sum_odd_numbers(n):\n return n*n*n", "def row_sum_odd_numbers(n):\n return pow(n, 3)", "def row...
{"fn_name": "row_sum_odd_numbers", "inputs": [[1], [2], [13], [19], [41], [42], [74], [86], [93], [101]], "outputs": [[1], [8], [2197], [6859], [68921], [74088], [405224], [636056], [804357], [1030301]]}
introductory
https://www.codewars.com/kata/55fd2d567d94ac3bc9000064
def row_sum_odd_numbers(n):
4,741
Given a standard english sentence passed in as a string, write a method that will return a sentence made up of the same words, but sorted by their first letter. However, the method of sorting has a twist to it: * All words that begin with a lower case letter should be at the beginning of the sorted sentence, and sorted...
["from string import punctuation\n\nt = str.maketrans(\"\", \"\", punctuation)\n\ndef pseudo_sort(s):\n a = s.translate(t).split()\n b = sorted(x for x in a if x[0].islower())\n c = sorted((x for x in a if x[0].isupper()), reverse=True)\n return \" \".join(b + c)", "from string import punctuation\ndef pseud...
{"fn_name": "pseudo_sort", "inputs": [["I, habitan of the Alleghanies, treating of him as he is in himself in his own rights"], ["take up the task eternal, and the burden and the lesson"], ["Land of the eastern Chesapeake"], ["And I send these words to Paris with my love"], ["O Liberty! O mate for me!"], ["With Egypt, ...
introductory
https://www.codewars.com/kata/52dffa05467ee54b93000712
def pseudo_sort(st):
4,742
You are given array of integers, your task will be to count all pairs in that array and return their count. **Notes:** * Array can be empty or contain only one value; in this case return `0` * If there are more pairs of a certain number, count each pair only once. E.g.: for `[0, 0, 0, 0]` the return value is `2` ...
["def duplicates(arr):\n return sum(arr.count(i)//2 for i in set(arr))", "from collections import Counter\n\ndef duplicates(arr):\n return sum(v//2 for v in list(Counter(arr).values()))\n", "def duplicates(arr):\n return sum((arr.count(n) // 2 for n in set(arr))) ", "from collections import Counter\n\ndef d...
{"fn_name": "duplicates", "inputs": [[[1, 2, 2, 20, 6, 20, 2, 6, 2]], [[1000, 1000]], [[]], [[54]]], "outputs": [[4], [1], [0], [0]]}
introductory
https://www.codewars.com/kata/5c55ad8c9d76d41a62b4ede3
def duplicates(arr):
4,743
## Task In your favorite game, you must shoot a target with a water-gun to gain points. Each target can be worth a different amount of points. You are guaranteed to hit every target that you try to hit. You cannot hit consecutive targets though because targets are only visible for one second (one at a time) and it...
["def target_game(values):\n a = b = 0\n for n in values:\n a, b = b, max(a + n, b)\n return max(a, b)", "def target_game(values):\n max_can_shoot, max_can_not_shoot = 0, 0\n for val in values:\n new = max_can_shoot + val\n max_can_shoot = max(max_can_not_shoot, new)\n max_can...
{"fn_name": "target_game", "inputs": [[[1, 2, 3, 4]], [[1, 3, 1]], [[5, 5, 5, 5, 5]], [[36, 42, 93, 29, 0, 33, 15, 84, 14, 24, 81, 11]], [[73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]], [[11, 82, 47, 48, 80, 35, 73, 99, 86, 32, 32]], [[26, 54, 36, 35, 63, 58, 31, 80, 59, 61, 34, 54, 62, 73, 89, 7, 98, 91, 78]], ...
introductory
https://www.codewars.com/kata/58acf858154165363c00004e
def target_game(values):
4,744
My friend wants a new band name for her band. She like bands that use the formula: "The" + a noun with the first letter capitalized, for example: `"dolphin" -> "The Dolphin"` However, when a noun STARTS and ENDS with the same letter, she likes to repeat the noun twice and connect them together with the first and last...
["def band_name_generator(name):\n return name.capitalize()+name[1:] if name[0]==name[-1] else 'The '+ name.capitalize()", "def band_name_generator(name):\n if name[0] == name[-1]:\n return name.title()+name[1:]\n return (\"the \"+name).title()", "def band_name_generator(name):\n if name[0] != name[-...
{"fn_name": "band_name_generator", "inputs": [["knife"], ["tart"], ["sandles"], ["bed"], ["qq"]], "outputs": [["The Knife"], ["Tartart"], ["Sandlesandles"], ["The Bed"], ["Qqq"]]}
introductory
https://www.codewars.com/kata/59727ff285281a44e3000011
def band_name_generator(name):
4,745
Ever since you started work at the grocer, you have been faithfully logging down each item and its category that passes through. One day, your boss walks in and asks, "Why are we just randomly placing the items everywhere? It's too difficult to find anything in this place!" Now's your chance to improve the system, impr...
["def group_groceries(groceries):\n categories = {\"fruit\": [], \"meat\": [], \"other\": [], \"vegetable\": []}\n for entry in groceries.split(\",\"):\n category, item = entry.split(\"_\")\n categories[category if category in categories else \"other\"].append(item)\n return \"\\n\".join([f\"{cat...
{"fn_name": "group_groceries", "inputs": [["fruit_banana,vegetable_carrot,meat_chicken,drink_juice"], ["fruit_banana,vegetable_carrot,fruit_apple,canned_sardines,drink_juice,fruit_orange"], ["vegetable_celery,meat_chicken,meat_beef,fruit_banana,vegetable_carrot,canned_sardines,drink_juice,frozen_fries,fruit_lemon"], ["...
introductory
https://www.codewars.com/kata/593c0ebf8b90525a62000221
def group_groceries(groceries):
4,746
# How much is the fish! (- Scooter ) The ocean is full of colorful fishes. We as programmers want to know the hexadecimal value of these fishes. ## Task Take all hexadecimal valid characters (a,b,c,d,e,f) of the given name and XOR them. Return the result as an integer. ## Input The input is always a string, which can...
["from functools import reduce\nVALID = frozenset('abcdefABCDEF')\n\n\ndef fisHex(s):\n return reduce(lambda b, c: b ^ c, (int(a, 16) for a in s if a in VALID), 0)\n", "def fisHex(name):\n # fish is 15\n hexdict={'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}\n res=0\n for c in name.upper():\n if c in...
{"fn_name": "fisHex", "inputs": [["pufferfish"], ["puffers"], ["balloonfish"], ["blowfish"], ["bubblefish"], ["globefish"], ["swellfish"], ["toadfish"], ["toadies"], ["honey toads"], ["sugar toads"], ["sea squab"], [""], ["Aeneus corydoras"], ["African glass catfish"], ["African lungfish"], ["Aholehole"], ["Airbreathin...
introductory
https://www.codewars.com/kata/5714eb80e1bf814e53000c06
def fisHex(name):
4,747
```if-not:racket Write a function called `repeat_str` which repeats the given string `src` exactly `count` times. ``` ```if:racket Write a function called `repeat-string` which repeats the given string `str` exactly `count` times. ```
["def repeat_str(repeat, string):\n return repeat * string", "def repeat_str(a,b):\n '''crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a cr...
{"fn_name": "repeat_str", "inputs": [[4, "a"], [3, "hello "], [2, "abc"]], "outputs": [["aaaa"], ["hello hello hello "], ["abcabc"]]}
introductory
https://www.codewars.com/kata/57a0e5c372292dd76d000d7e
def repeat_str(repeat, string):
4,748
This is a follow up from my kata Insert Dashes. Write a function ```insertDashII(num)``` that will insert dashes ('-') between each two odd numbers and asterisk ('\*') between each even numbers in ```num``` For example: ```insertDashII(454793)``` --> 4547-9-3 ```insertDashII(1012356895)``` --> 10123-56*89-5 Zero...
["def insert_dash2(num):\n \n prev = 0\n out = ''\n\n for dig in str(num):\n if int(dig) % 2 == int(prev) % 2 and int(prev) and int(dig):\n out += '*-'[int(prev) % 2]\n out += dig\n prev = dig\n return out", "import re\n\ndef insert_dash2(num):\n s = str(num)\n s = r...
{"fn_name": "insert_dash2", "inputs": [[454793], [123456], [40546793], [1012356895], [0]], "outputs": [["4547-9-3"], ["123456"], ["4054*67-9-3"], ["10123-56*89-5"], ["0"]]}
introductory
https://www.codewars.com/kata/55c3026406402936bc000026
def insert_dash2(num):
4,749
Uh oh, Someone at the office has dropped all these sequences on the floor and forgotten to label them with their correct bases. We have to fix this before the boss gets back or we're all going to be fired! This is what your years of coding have been leading up to, now is your time to shine! ## Task You will have t...
["def base_finder(seq):\n return len(set(''.join(seq)))", "def base_finder(a):\n return int(max(x[-1] for x in a)) + 1", "def base_finder(seq):\n base = 0\n for i in range(10): #as the sequence will always be 10 numbers long\n number = seq[i] # converting each list element to a string\n for i ...
{"fn_name": "base_finder", "inputs": [[["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]], [["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]], [["1", "2", "3", "4", "5", "6", "10", "11", "12", "13"]], [["301", "302", "303", "304", "305", "310", "311", "312", "313", "314"]], [["50", "51", "61", "53", "54", "60", "52...
introductory
https://www.codewars.com/kata/5f47e79e18330d001a195b55
def base_finder(seq):
4,750
Write a function that flattens an `Array` of `Array` objects into a flat `Array`. Your function must only do one level of flattening. ```python flatten [1,2,3] # => [1,2,3] flatten [[1,2,3],["a","b","c"],[1,2,3]] # => [1,2,3,"a","b","c",1,2,3] flatten [[[1,2,3]]] # => [[1,2,3]] ```
["def flatten(lst):\n r = []\n for x in lst:\n if type(x) is list:\n r.extend(x)\n else:\n r.append(x)\n return r ", "def flatten(lst):\n return sum(([i] if not isinstance(i, list) else i for i in lst), [])", "from itertools import chain\ndef flatten(lst):\n try:\n re...
{"fn_name": "flatten", "inputs": [[[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3]]]], [[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3], [77777]]]], [[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3], [77777]], "a"]], [[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3], [77777]], [["a"]]]]], "outputs": [[[[3], [4], [5], 9, 9, 9...
introductory
https://www.codewars.com/kata/5250a89b1625e5decd000413
def flatten(lst):
4,751
For a given two numbers your mission is to derive a function that evaluates whether two given numbers are **abundant**, **deficient** or **perfect** and whether together they are **amicable**. ### Abundant Numbers An abundant number or excessive number is a number for which the sum of its proper divisors is greater ...
["def deficiently_abundant_amicable_numbers(a,b):\n c,d = list(map(sumOfDivs,(a,b)))\n return f'{ kind(a,c)} { kind(b,d) } { \"not \"*(a!=d or b!=c or a==b) }amicable'\n\ndef kind(n,sD): return 'abundant' if sD>n else 'perfect' if sD==n else 'deficient'\ndef sumOfDivs(n): return sum(d for d in range(1,int(n/2+1...
{"fn_name": "deficiently_abundant_amicable_numbers", "inputs": [[220, 284], [220, 280], [1184, 1210], [220221, 282224], [10744, 10856], [299920, 9284], [999220, 2849], [139815, 122265], [496, 28], [8128, 8128]], "outputs": [["abundant deficient amicable"], ["abundant abundant not amicable"], ["abundant deficient amicab...
introductory
https://www.codewars.com/kata/56bc7687e8936faed5000c09
def deficiently_abundant_amicable_numbers(n1, n2):
4,752
Similar to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/), but this time you need to operate with shuffled strings to identify if they are composed repeating a subpattern Since there is no deterministic way to tell which pattern was really the original one among all the possible p...
["from collections import Counter\nfrom functools import reduce\nfrom fractions import gcd\n\ndef has_subpattern(s):\n c = Counter(s)\n m = reduce(gcd, c.values())\n return ''.join(sorted(k*(v//m) for k,v in c.items()))", "from collections import Counter\nfrom functools import reduce\nfrom math import gcd\n\n\...
{"fn_name": "has_subpattern", "inputs": [["a"], ["aaaa"], ["abcd"], ["babababababababa"], ["bbabbaaabbaaaabb"], ["123a123a123a"], ["123A123a123a"], ["12aa13a21233"], ["12aa13a21233A"], ["abcdabcaccd"]], "outputs": [["a"], ["a"], ["abcd"], ["ab"], ["ab"], ["123a"], ["111222333Aaa"], ["123a"], ["111222333Aaaa"], ["aaabbc...
introductory
https://www.codewars.com/kata/5a4a2973d8e14586c700000a
def has_subpattern(string):
4,753
Write a function, `gooseFilter` / `goose-filter` / `goose_filter` /` GooseFilter`, that takes an array of strings as an argument and returns a filtered array containing the same elements but with the 'geese' removed. The geese are any strings in the following array, which is pre-populated in your solution: ```python ...
["geese = {\"African\", \"Roman Tufted\", \"Toulouse\", \"Pilgrim\", \"Steinbacher\"}\n\ndef goose_filter(birds):\n return [bird for bird in birds if bird not in geese]", "geese = [\"African\", \"Roman Tufted\", \"Toulouse\", \"Pilgrim\", \"Steinbacher\"]\ndef goose_filter(birds):\n return list(filter(lambda x: x...
{"fn_name": "goose_filter", "inputs": [[["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"]], [["Mallard", "Barbary", "Hook Bill", "Blue Swedish", "Crested"]], [["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"]]], "outputs": [[["Mallard", "Hook Bill", "Crested", "Blue S...
introductory
https://www.codewars.com/kata/57ee4a67108d3fd9eb0000e7
def goose_filter(birds):
4,754
Hi! Welcome to my first kata. In this kata the task is to take a list of integers (positive and negative) and split them according to a simple rule; those ints greater than or equal to the key, and those ints less than the key (the itself key will always be positive). However, in this kata the goal is to sort the num...
["from itertools import groupby\n\n\ndef group_ints(lst, key=0):\n return [list(g) for _, g in groupby(lst, lambda a: a < key)]\n\n\n# PEP8: function name should use snake_case\ngroupInts = group_ints", "from itertools import groupby\n\ndef group_ints(lst, key=0):\n return [list(g) for _, g in groupby(lst, key.__...
{"fn_name": "group_ints", "inputs": [[[], 0], [[1], 1], [[1, 2, 3], 0], [[1, 2, 3], 3], [[1, 1, 1, 0, 0, 6, 10, 5, 10], 6]], "outputs": [[[]], [[[1]]], [[[1, 2, 3]]], [[[1, 2], [3]]], [[[1, 1, 1, 0, 0], [6, 10], [5], [10]]]]}
introductory
https://www.codewars.com/kata/583fe48ca20cfc3a230009a1
def group_ints(lst, key=0):
4,755
Every non-negative integer N has a binary representation.  For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on.  Note that except for N = 0, there are no leading zeroes in any binary representation. The complement of a binary representation is the number in binary you get when changi...
["class Solution:\n def bitwiseComplement(self, N: int) -> int:\n return (1 << len(bin(N))-2) - N - 1", "class Solution:\n def bitwiseComplement(self, N: int) -> int:\n \n if N==0:\n return 1\n \n dummy_num=N\n \n n=0\n while(dummy_num):\n ...
{"fn_name": "bitwiseComplement", "inputs": [[5]], "outputs": [2]}
introductory
https://leetcode.com/problems/complement-of-base-10-integer/
class Solution: def bitwiseComplement(self, N: int) -> int:
4,756
=====Function Descriptions===== re.findall() The expression re.findall() returns all the non-overlapping matches of patterns in a string as a list of strings. Code >>> import re >>> re.findall(r'\w','http://www.hackerrank.com/') ['h', 't', 't', 'p', 'w', 'w', 'w', 'h', 'a', 'c', 'k', 'e', 'r', 'r', 'a', 'n', 'k', 'c'...
["import re\ns = input()\nresult = re.findall(r'(?<=[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm])([AEIOUaeiou]{2,})(?=[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm])',s)\nif result:\n for i in result:\n print(i)\nelse:\n print((-1))\n", "#!/usr/bin/env python3\n\nimport re\n\ncons = 'QWRTYPSDFGHJKLZXCVBNMqwr...
{"inputs": ["rabcdeefgyYhFjkIoomnpOeorteeeeet"], "outputs": ["ee\nIoo\nOeo\neeeee"]}
introductory
https://www.hackerrank.com/challenges/re-findall-re-finditer/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
4,757
You are given four positive integers $n$, $m$, $a$, $b$ ($1 \le b \le n \le 50$; $1 \le a \le m \le 50$). Find any such rectangular matrix of size $n \times m$ that satisfies all of the following conditions: each row of the matrix contains exactly $a$ ones; each column of the matrix contains exactly $b$ ones; all ...
["for _ in range(int(input())):\n n, m, a, b = list(map(int, input().split()))\n if a * n != b * m:\n print('NO')\n else:\n ar = []\n for i in range(n):\n ar.append([0] * m)\n x, y = 0, a\n for i in range(n):\n if x < y:\n for j in range(x...
{ "inputs": [ "5\n3 6 2 1\n2 2 2 1\n2 2 2 2\n4 4 2 2\n2 1 1 2\n" ], "outputs": [ "YES\n110000\n001100\n000011\nNO\nYES\n11\n11\nYES\n1100\n0110\n0011\n1001\nYES\n1\n1\n" ] }
introductory
https://codeforces.com/problemset/problem/1360/G
4,998
The principal of a school likes to put challenges to the students related with finding words of certain features. One day she said: "Dear students, the challenge for today is to find a word that has only one vowel and seven consonants but cannot have the letters "y" and "m". I'll give a special award for the first stud...
["def wanted_words(vowels, consonants, forbidden):\n return [w for w in WORD_LIST\n if len(w) == vowels + consonants\n and sum(map(w.count, 'aeiou')) == vowels\n and not any(c in w for c in forbidden)]", "from collections import defaultdict\nWORD_INDEX = defaultdict(list)...
{"fn_name": "wanted_words", "inputs": [[1, 7, ["m", "y"]], [3, 7, ["m", "y"]], [3, 7, ["a", "s", "m", "y"]]], "outputs": [[["strength"]], [["afterwards", "background", "photograph", "successful", "understand"]], [[]]]}
introductory
https://www.codewars.com/kata/580be55ca671827cfd000043
def wanted_words(n, m, forbid_let):