problem_id int64 80 5k | question stringlengths 170 10.1k | solutions stringlengths 0 675k | input_output stringlengths 0 33.5k | difficulty stringclasses 3
values | url stringlengths 38 68 | starter_code stringlengths 0 315 |
|---|---|---|---|---|---|---|
80 | While doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute $1 + 3$ using the calculator, he gets $2$ instead of $4$. But when he tries computing $1 + 4$, he gets the correct answer, $5$. Puzzled by this mystery, he opened up his ... | ["def solve(L, R):\n res = 0\n for i in range(32):\n for j in range(32):\n l = (L >> i) << i\n r = (R >> j) << j\n #print(l, r)\n if l>>i&1==0 or r>>j&1==0:\n continue\n l -= 1<<i\n r -= 1<<j\n if l & r:\n ... | {
"inputs": [
"3\n1 4\n323 323\n1 1000000\n"
],
"outputs": [
"8\n0\n3439863766\n"
]
} | interview | https://codeforces.com/problemset/problem/1245/F | |
756 | Farmer Feb has three fields with potatoes planted in them. He harvested x potatoes from the first field, y potatoes from the second field and is yet to harvest potatoes from the third field. Feb is very superstitious and believes that if the sum of potatoes he harvests from the three fields is a prime number (http://en... | ["# cook your dish here\nimport math\ntry:\n def prime(n):\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n \n for t in range(int(input())):\n x, y = list(map(int, input().split()))\n s = x + y \n i = s\n while(1):\n if prime(s + 1):\n ans = s + 1\n break... | {"inputs": [["2", "1 3", "4 3"]], "outputs": [["1", "4"]]} | interview | https://www.codechef.com/problems/POTATOES | |
849 | We all know how great ABD aka AB-DE-VILLIERS is. However his team mates were jealous of him and posed a problem for him to solve.The problem description is as follows :
Given an array of integers,find the length of the largest subarray(contiguous) of the given array with the maximum possible GCD (Greatest Common Divis... | ["n=eval(input())\na=list(map(int,input().split()))\nc=m=0\nmaxi=max(a)\nfor i in range(n):\n if a[i]==maxi:\n c+=1\n m=max(c,m)\n else:\n c=0\nprint(m) ", "from fractions import gcd as G\nn=eval(input())\nflag=1\narr=list(map(int,input().split()))\na=max(arr)\nbest = 0\nI_I = 0\nwhile I_I<n:\n if arr[I_I]==a:\n k=... | {"inputs": [["4", "2 4 8 3"]], "outputs": [["1"]]} | interview | https://www.codechef.com/BYTE2016/problems/BYTES11 | |
1,215 | Two friends David and Rojer were preparing for their weekly class-test.
The are preparing for the math test, but because of continuously adding big integers and solving equations they got exhausted. They decided to take break and play a game. They play a game which will help them in both(for having fun and will also he... | ["def isSolvable( W, R):\r\n LW, LR, F, ML, AW, V, LMap = len(W), len(R), set([w[0] for w in W+[R]]), max(map(len, W+[R])), W+[R], set(), {}\r\n if LR < ML: return False\r\n def dfs(d,i,c):\r\n if d == ML: return c == 0\r\n if i == len(W) + 1:\r\n s = sum(LMap[w... | {"inputs": [["3", "THIS", "IS", "TOO", "FUNNY"]], "outputs": [["true"]]}
| interview | https://www.codechef.com/CHLG2020/problems/MATH88 | |
1,232 | AND gates and OR gates are basic components used in building digital circuits. Both gates have two input lines and one output line. The output of an AND gate is 1 if both inputs are 1, otherwise the output is 0. The output of an OR gate is 1 if at least one input is 1, otherwise the output is 0.
You are given a digita... | ["# cook your dish here\nclass node:\n\tdef __init__(self,a,b=0,c=0):\n\t\tself.val=a\n\t\tself.a=b\n\t\tself.b=c\n\narr=[]\n\ndef finder(node,val):\n\tif(arr[node].val==0):\n\t\treturn val\n\telse:\n\t\ta=finder(arr[node].a,val)\n\t\tb=finder(arr[node].b,val)\n\t\tif(arr[node].val==1):\n\t\t\treturn a+b-a*b\n\t\telse:... | {"inputs": [["4", "", "1", "0", "", "3", "0", "0", "1 1 2", "", "3", "0", "0", "2 1 2", "", "5", "0", "0", "0", "2 1 2", "1 3 4", "", ""]], "outputs": [["0.50000", "0.29289", "0.70711", "0.40303"]]} | interview | https://www.codechef.com/problems/CIRCUITS | |
1,436 | Harrenhal is the largest castle in the Seven Kingdoms and is the seat of House Whent in the Riverlands, on the north shore of the Gods Eye lake. Since the War of Conquest, however, it has become a dark and ruinous place.
(c) A Wiki of Ice and Fire
Now Harrenhal is too dangerous since it's a nice place for bandits to h... | ["# cook your dish here\nfor _ in range(int(input())):\n g=input()\n h=g[::-1]\n if h==g :\n print(1)\n else:\n print(2)\n ", "# cook your dish here\nfor _ in range(int(input())):\n string = input()\n if string == string[::-1]:\n print('1')\n else:\n print('2')\n "... | {"inputs": [["1", "abbabaab", "", ""]], "outputs": [["2"]]} | interview | https://www.codechef.com/problems/HHAL | |
1,603 | There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.
You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[... | ["# Bartek Kostka\n# You are not prepared!\n\n#include \"bits/stdc++.h\"\n\nn = int(input())\nW = {}\nfor i in range(n):\n adr = input()\n adr = adr.split(\"/\")\n if adr[-1] == '':\n adr[-1] = '?'\n domena = \"/\".join(adr[:3])\n adres = \"/\".join(adr[3:])\n #print(domena, adres)\n if dom... | {
"inputs": [
"10\nhttp://abacaba.ru/test\nhttp://abacaba.ru/\nhttp://abacaba.com\nhttp://abacaba.com/test\nhttp://abacaba.de/\nhttp://abacaba.ru/test\nhttp://abacaba.de/test\nhttp://abacaba.com/\nhttp://abacaba.com/t\nhttp://abacaba.com/test\n",
"14\nhttp://c\nhttp://ccc.bbbb/aba..b\nhttp://cba.com\nhttp://a... | interview | https://codeforces.com/problemset/problem/644/C | |
1,604 | You are at the top left cell $(1, 1)$ of an $n \times m$ labyrinth. Your goal is to get to the bottom right cell $(n, m)$. You can only move right or down, one cell per step. Moving right from a cell $(x, y)$ takes you to the cell $(x, y + 1)$, while moving down takes you to the cell $(x + 1, y)$.
Some cells of the la... | ["def getSum(dp, pos, s, e, type_):\n if e < s:\n return 0\n \n if type_=='D':\n if e==m-1:\n return dp[pos][s]\n return dp[pos][s]-dp[pos][e+1]\n else:\n if e==n-1:\n return dp[s][pos]\n return dp[s][pos]-dp[e+1][pos]\n\nmod = 10**9+7\nn, m =... | {
"inputs": [
"1 1\n.\n",
"2 3\n...\n..R\n",
"4 4\n...R\n.RR.\n.RR.\nR...\n",
"1 3\n.R.\n",
"2 2\n.R\nR.\n",
"10 10\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n"
],
"outputs": [
"1\n",
"0\n",
"4\n",
... | interview | https://codeforces.com/problemset/problem/1225/E | |
1,605 | Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if $\operatorname{mod}(x, b) \neq 0$ and $\frac{\operatorname{div}(x, b)}{\operatorname{mod}(x, b)} = k$, where k is some integer... | ["a,b=map(int,input().split())\nprint(((b-1)*a*b//2+(a+1)*a*b*b*(b-1)//4)%1000000007)", "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n(a, b) = list(map(int, input().split()))\n\n# ans = a * a * (a - 1) * (a + 1) * b\n# ans //= 4\n# ans += a * (a - 1)\n\nans = a * (a + 1) * b * b * (b - 1)\nans //= 4\nans += a * b... | {
"inputs": [
"1 1\n",
"2 2\n",
"4 1\n",
"4 2\n",
"4 3\n",
"4 4\n",
"3 4\n",
"2 4\n",
"1 4\n",
"1000 1000\n",
"10000000 10000000\n",
"10000000 9999999\n",
"2 10000000\n",
"10000000 2\n",
"9999999 2\n",
"9999999 9999999\n",
"10000000 10000\n",
"10... | interview | https://codeforces.com/problemset/problem/476/C | |
1,606 | Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve... | ["l,r = map(int, input().split(\" \"))\nif l == r:\n print (l)\nelse:\n print (2)", "a, b = list(map(int, input().split()))\nif a != b:\n print(2)\nelse:\n print(a)\n", "l,r=map(int,input().split())\nif abs(l-r)>0:\n print(2)\nelse:\n print(l)", "L, R = [int(i) for i in input().split()]\n\nif L == R:... | {
"inputs": [
"19 29\n",
"3 6\n",
"39 91\n",
"76 134\n",
"93 95\n",
"17 35\n",
"94 95\n",
"51 52\n",
"47 52\n",
"38 98\n",
"30 37\n",
"56 92\n",
"900000000 1000000000\n",
"37622224 162971117\n",
"760632746 850720703\n",
"908580370 968054552\n",
"9515... | interview | https://codeforces.com/problemset/problem/805/A | |
1,607 | "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). $8$ illustration by 猫屋 https://twitter.com/nekoyaliu ... | ["s=input()\nans = 0\nfor i in range(len(s)):\n if s[i] == 'A':\n ans += s[:i].count('Q') * s[i:].count('Q')\nprint(ans)", "from sys import stdin, stdout\nfrom random import randrange\n\ns = stdin.readline().strip()\nn = len(s)\nans = 0\n\nfor i in range(n):\n for j in range(i + 1, n):\n for z in range(j ... | {
"inputs": [
"QAQAQYSYIOIWIN\n",
"QAQQQZZYNOIWIN\n",
"QA\n",
"IAQVAQZLQBQVQFTQQQADAQJA\n",
"QQAAQASGAYAAAAKAKAQIQEAQAIAAIAQQQQQ\n",
"AMVFNFJIAVNQJWIVONQOAOOQSNQSONOASONAONQINAONAOIQONANOIQOANOQINAONOQINAONOXJCOIAQOAOQAQAQAQAQWWWAQQAQ\n",
"AAQQAXBQQBQQXBNQRJAQKQNAQNQVDQASAGGANQQQQTJFFQQQTQ... | interview | https://codeforces.com/problemset/problem/894/A | |
1,611 | # 'Magic' recursion call depth number
This Kata was designed as a Fork to the one from donaldsebleung Roboscript series with a reference to:
https://www.codewars.com/collections/roboscript
It is not more than an extension of Roboscript infinite "single-" mutual recursion handling to a "multiple-" case.
One can supp... | ["from collections import defaultdict\nfrom itertools import chain\nimport re\n\nPARSE = re.compile(r'[pP]\\d+|q')\n\ndef magic_call_depth_number(prog):\n \n def parse(it, p=''):\n for m in it:\n if m[0].startswith('p'): parse(it, m[0])\n elif m[0]=='q': return\n e... | {"fn_name": "magic_call_depth_number", "inputs": [["p0F2LF2RqP0"], ["p1P2P3qp2P1qp3P1qP3"], ["p1P2qp2P3qP4p3P4qp4P1q"], ["p1P2P4qp2P3qp3P4qP1p4P1q"], ["p1P2P3qP2P1p2P3qp3P4qp4P1q"], ["p1P2qp2P3qp3P4qP6p4P1qp5P7qp6P5qp7P6qP1"], ["P1P2P7p1P2qp2P3qp3P4qp4P1qp5P7qp6P5qp7P5q"], ["P2P7P6p1P2qp2P3qp3P4qp4P1qp5P8qp6P5qp7P5qp8P... | interview | https://www.codewars.com/kata/5c1b23aa34fb628f2e000043 |
def magic_call_depth_number(pattern):
|
1,614 | # Connect Four
Take a look at wiki description of Connect Four game:
[Wiki Connect Four](https://en.wikipedia.org/wiki/Connect_Four)
The grid is 6 row by 7 columns, those being named from A to G.
You will receive a list of strings showing the order of the pieces which dropped in columns:
```python
pieces_positio... | ["COLUMNS, ROWS = 'ABCDEFG', range(6)\nLINES = [{(COLUMNS[i+k], ROWS[j]) for k in range(4)}\n for i in range(len(COLUMNS) - 3) for j in range(len(ROWS))] \\\n + [{(COLUMNS[i], ROWS[j+k]) for k in range(4)}\n for i in range(len(COLUMNS)) for j in range(len(ROWS) - 3)] \\\n + [{(COLUMNS[... | {"fn_name": "who_is_winner", "inputs": [[["C_Yellow", "E_Red", "G_Yellow", "B_Red", "D_Yellow", "B_Red", "B_Yellow", "G_Red", "C_Yellow", "C_Red", "D_Yellow", "F_Red", "E_Yellow", "A_Red", "A_Yellow", "G_Red", "A_Yellow", "F_Red", "F_Yellow", "D_Red", "B_Yellow", "E_Red", "D_Yellow", "A_Red", "G_Yellow", "D_Red", "D_Ye... | interview | https://www.codewars.com/kata/56882731514ec3ec3d000009 |
def who_is_winner(pieces_position_list):
|
1,615 | ### Lyrics...
Pyramids are amazing! Both in architectural and mathematical sense. If you have a computer, you can mess with pyramids even if you are not in Egypt at the time. For example, let's consider the following problem. Imagine that you have a pyramid built of numbers, like this one here:
```
/3/
\7\ 4
2... | ["def longest_slide_down(p):\n res = p.pop()\n while p:\n tmp = p.pop()\n res = [tmp[i] + max(res[i],res[i+1]) for i in range(len(tmp))] \n return res.pop()", "def longest_slide_down(pyr):\n for row in range(len(pyr)-1, 0, -1):\n for col in range(0, row):\n pyr[row-1][col] +... | {"fn_name": "longest_slide_down", "inputs": [[[[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]], [[[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29]... | interview | https://www.codewars.com/kata/551f23362ff852e2ab000037 |
def longest_slide_down(pyramid):
|
1,617 | I started this as a joke among friends, telling that converting numbers to other integer bases is for n00bs, while an actual coder at least converts numbers to more complex bases like [pi (or π or however you wish to spell it in your language)](http://en.wikipedia.org/wiki/Pi), so they dared me proving I was better.
A... | ["from math import *\n\nDIGS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\ndef converter(n, decimals=0, base=pi):\n lst,n = ['-'*(n<0)], abs(n)\n pMax = max(0, n and int(log(n,base)))\n \n for p in reversed(range(-decimals,pMax+1)):\n if p==-1: lst.append('.')\n p = base**p\n d,n = n/p... | {"fn_name": "converter", "inputs": [[13], [10], [13, 3], [13, 0, 8], [10, 0, 16], [10000, 4, 13], [7, 0, 19], [13.5, 4, 16], [10.81, 0, 16], [1, 2, 2], [-10, 0, 23], [0, 4, 26], [-15.5, 2, 23], [13, 0, 10], [5.5, 1, 10]], "outputs": [["103"], ["100"], ["103.010"], ["15"], ["A"], ["4723.0000"], ["7"], ["D.8000"], ["A"],... | interview | https://www.codewars.com/kata/5509609d1dbf20a324000714 |
def converter(n, decimals=0, base=pi):
|
1,620 | This kata generalizes [Twice Linear](https://www.codewars.com/kata/5672682212c8ecf83e000050). You may want to attempt that kata first.
## Sequence
Consider an integer sequence `U(m)` defined as:
1. `m` is a given non-empty set of positive integers.
2. `U(m)[0] = 1`, the first number is always 1.
3. For each `x` in `... | ["from heapq import *\n\ndef n_linear(ms, n):\n lst = [1] * (n+1)\n q = [(1+v,v,1) for v in ms]\n heapify(q)\n for i in range(1,n+1):\n v,x,j = heappop(q)\n lst[i] = v\n heappush(q, (lst[j]*x+1, x, j+1) )\n while q[0][0]==lst[i]:\n v,x,j = heappop(q)\n he... | {"fn_name": "n_linear", "inputs": [[[2, 3], 0], [[3, 2, 5], 0], [[2, 3], 1], [[2, 3], 2], [[2, 3], 3], [[2, 3], 4], [[2, 3], 5], [[2, 3], 6], [[2, 3], 7], [[2, 3], 8], [[2, 3], 9], [[2, 3], 10], [[2, 3], 11], [[2, 3], 12], [[2, 3], 13], [[2, 3], 14], [[2, 3], 15], [[2, 3], 16], [[2, 3], 17], [[2, 3], 18], [[2, 3], 19],... | interview | https://www.codewars.com/kata/5aa417aa4a6b344e2200009d |
def n_linear(m,n):
|
1,622 | # Ten-Pin Bowling
In the game of ten-pin bowling, a player rolls a bowling ball down a lane to knock over pins. There are ten pins set at the end of the bowling lane. Each player has 10 frames to roll a bowling ball down a lane and knock over as many pins as possible. The first nine frames are ended after two rolls or... | ["def bowling_score(frames):\n rolls = list(frames.replace(' ',''))\n for i, hit in enumerate(rolls):\n if hit == 'X':\n rolls[i] = 10\n elif hit == '/':\n rolls[i] = 10 - rolls[i - 1]\n else:\n rolls[i] = int(hit)\n score = 0\n for i in range(10):\n ... | {"fn_name": "bowling_score", "inputs": [["11 11 11 11 11 11 11 11 11 11"], ["X X X X X X X X X XXX"], ["00 5/ 4/ 53 33 22 4/ 5/ 45 XXX"], ["5/ 4/ 3/ 2/ 1/ 0/ X 9/ 4/ 8/8"], ["5/ 4/ 3/ 2/ 1/ 0/ X 9/ 4/ 7/2"], ["X X 9/ 80 X X 90 8/ 7/ 44"], ["6/ 5/ 6/ 2/ 3/ 0/ 1/ 8/ 3/ 6/5"], ["00 00 00 00 00 00 00 00 00 0/X"], ["00 00 0... | interview | https://www.codewars.com/kata/5531abe4855bcc8d1f00004c |
def bowling_score(frames):
|
1,623 | ## Story
Before we dive into the exercise, I would like to show you why these numbers are so important in computer programming today.
It all goes back to the time of 19th century. Where computers we know today were non-existing. The first ever **computer program** was for the Analytical Engine to compute **Bernoulli ... | ["from fractions import Fraction as frac\ndef ber():\n res, m = [], 0\n while True:\n res.append(frac(1, m+1))\n for j in range(m, 0, -1):\n res[j-1] = j*(res[j-1] - res[j])\n yield res[0]\n m += 1\ndef bernoulli_number(n): \n if n == 1: return Fraction(-1, 2)\n if n %... | {"fn_name": "bernoulli_number", "inputs": [[0], [3], [1337]], "outputs": [[1], [0], [0]]} | interview | https://www.codewars.com/kata/567ffb369f7f92e53800005b |
def bernoulli_number(n):
|
1,624 | The number ```89``` is the first positive integer that has a particular, curious property:
The square of ```89``` is ```7921```; ```89² = 7921```
The reverse of ```7921``` is ```1297```, and ```1297``` is a prime number.
The cube of ```89``` is ```704969```; ```89³ = 704969```
The reverse of ```704969``` is ```9694... | ["sq_cub_rev_prime = (None, 89, 271, 325, 328, 890, 1025, 1055, 1081, 1129, 1169, 1241, 2657, 2710, 3112, 3121, 3149, 3244, 3250, 3263, 3280, 3335, 3346, 3403, 4193, 4222, 4231, 4289, 4291, 5531, 5584, 5653, 5678, 5716, 5791, 5795, 5836, 5837, 8882, 8900, 8926, 8942, 9664, 9794, 9875, 9962, 10178, 10250, 10393, 10429, ... | {"fn_name": "sq_cub_rev_prime", "inputs": [[1], [2], [3], [4]], "outputs": [[89], [271], [325], [328]]} | interview | https://www.codewars.com/kata/5644a69f7849c9c097000073 |
def sq_cub_rev_prime(n):
|
1,625 | A chess board is normally played with 16 pawns and 16 other pieces, for this kata a variant will be played with only the pawns. All other pieces will not be on the board.
For information on how pawns move, refer [here](http://www.chesscorner.com/tutorial/basic/pawn/pawn.htm)
Write a function that can turn a li... | ["LETTERS = 'abcdefgh' # Defining some constants\nNUMBERS = '87654321'\nW, B = WB = 'Pp'\nEMPTY, CAPTURE = '.x'\nWHITEHOME = '12'\nBLACKHOME = '87'\nJUMP = '54'\n\ndef pawn_move_tracker(moves):\n board = {letter + number : ... | {"fn_name": "pawn_move_tracker", "inputs": [[[]], [["e3", "e6", "d3", "g6"]], [["d3", "e5", "d4", "f5"]], [["d3", "e5", "d4", "f5", "dxe5", "f4"]], [["d4", "f6", "d5", "f6", "dxe5", "f4"]], [["d4", "a5", "d5", "f6", "dxe7", "f4"]], [["a4", "a5", "b4", "b5", "c4", "b4"]], [["h3", "h5", "h4", "g5", "hxg5", "h4"]], [["e5"... | interview | https://www.codewars.com/kata/56b012bbee8829c4ea00002c |
def pawn_move_tracker(moves):
|
1,627 | ### Background
I was reading a [book](http://www.amazon.co.uk/Things-Make-Do-Fourth-Dimension/dp/1846147646/) recently, "Things to Make and Do in the Fourth Dimension" by comedian and mathematician Matt Parker, and in the first chapter of the book Matt talks about problems he likes to solve in his head to take his min... | ["l = {j:i for i,j in enumerate('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')}\nl_ = dict(enumerate('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'))\n\nis_polydivisible = lambda n, base:next((0 for i in range(1, len(n) + 1) if get_base(n[:i], base) % i),1)\nget_base = lambda n, bas... | {"fn_name": "is_polydivisible", "inputs": [["123", 10], ["1234", 10], ["12345", 10], ["12365", 10], ["123220", 10], ["50041", 6], ["140410", 6], ["203230", 6], ["30043052", 6]], "outputs": [[true], [false], [false], [true], [false], [true], [true], [true], [true]]} | interview | https://www.codewars.com/kata/556206664efbe6376700005c |
def is_polydivisible(s, b):
|
1,628 | If n is the numerator and d the denominator of a fraction, that fraction is defined a (reduced) proper fraction if and only if GCD(n,d)==1.
For example `5/16` is a proper fraction, while `6/16` is not, as both 6 and 16 are divisible by 2, thus the fraction can be reduced to `3/8`.
Now, if you consider a given number ... | ["def proper_fractions(n):\n phi = n > 1 and n\n for p in range(2, int(n ** .5) + 1):\n if not n % p:\n phi -= phi // p\n while not n % p:\n n //= p\n if n > 1: phi -= phi // n\n return phi", "def proper_fractions(n):\n #find all prime factors (without repetiti... | {"fn_name": "proper_fractions", "inputs": [[1], [2], [5], [15], [25], [9999999], [500000003], [1532420], [123456789], [9999999999]], "outputs": [[0], [1], [4], [8], [20], [6637344], [500000002], [608256], [82260072], [5890320000]]} | interview | https://www.codewars.com/kata/55b7bb74a0256d4467000070 |
def proper_fractions(n):
|
1,633 | Create a function that takes a Number as its argument and returns a Chinese numeral string. You don't need to validate the input argument, it will always be a Number in the range `[-99999.999, 99999.999]`, rounded to 8 decimal places.
Simplified Chinese numerals have characters representing each number from 0 to 9 and... | ["import re\n\nNEG, DOT, _, *DIGS = \"\u8d1f\u70b9 \u96f6\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\"\nPOWS = \" \u5341 \u767e \u5343 \u4e07\".split(' ')\nNUMS = {str(i):c for i,c in enumerate(DIGS)}\nfor n in range(10): NUMS[str(n+10)] = POWS[1] + DIGS[n]*bool(n)\n\n\ndef to_chinese_numeral(n):\n ss = s... | {"fn_name": "to_chinese_numeral", "inputs": [[0], [9], [99], [999], [9999], [99999], [-5], [-54], [-543], [-5432], [-54321], [0.5], [0.25], [0.125], [0.0625], [0.03125], [10], [14], [18], [20], [24], [50], [100], [110], [111], [-10], [-14], [-18], [-20], [-100], [-110], [-111], [1000], [10000], [10306], [10006], [10006... | interview | https://www.codewars.com/kata/52608f5345d4a19bed000b31 |
def to_chinese_numeral(n):
|
1,637 | Motivation
---------
When compressing sequences of symbols, it is useful to have many equal symbols follow each other, because then they can be encoded with a run length encoding. For example, RLE encoding of `"aaaabbbbbbbbbbbcccccc"` would give something like `4a 11b 6c`.
(Look [here](http://www.codewars.com/kata/ru... | ["def encode(s):\n lst = sorted( s[i or len(s):] + s[:i or len(s)] for i in reversed(range(len(s))) )\n return ''.join(ss[-1] for ss in lst), s and lst.index(s) or 0\n\ndef decode(s, n):\n out, lst = [], sorted((c,i) for i,c in enumerate(s))\n for _ in range(len(s)):\n c,n = lst[n]\n out.appen... | {"fn_name": "encode", "inputs": [["bananabar"], ["Humble Bundle"], ["Mellow Yellow"]], "outputs": [[["nnbbraaaa", 4]], [["e emnllbduuHB", 2]], [["ww MYeelllloo", 1]]]} | interview | https://www.codewars.com/kata/54ce4c6804fcc440a1000ecb |
def encode(s):
|
1,638 | # Longest Palindromic Substring (Linear)
A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g.,
'madam' or 'racecar'. Even the letter 'x' is considered a palindrome.
For this Kata, you are given a string ```s```. Write a function that returns the longest _contiguous_ palindromic s... | ["'''\n Write a function that returns the longest contiguous palindromic substring in s. \n In the event that there are multiple longest palindromic substrings, return the \n first to occur.\n'''\n\ndef longest_palindrome(s, sep=\" \"):\n # Interpolate some inert character between input characters\n # so... | {"fn_name": "longest_palindrome", "inputs": [["babad"], ["madam"], ["dde"], ["ababbab"], ["abababa"], ["banana"], ["abba"], ["cbbd"], ["zz"], ["dddd"], [""], ["abcdefghijklmnopqrstuvwxyz"], ["ttaaftffftfaafatf"], ["bbaaacc"], ["m"]], "outputs": [["bab"], ["madam"], ["dd"], ["babbab"], ["abababa"], ["anana"], ["abba"], ... | interview | https://www.codewars.com/kata/5dcde0b9fcb0d100349cb5c0 |
def longest_palindrome(s):
|
1,644 | [BasE91](http://base91.sourceforge.net/) is a method for encoding binary as ASCII characters. It is more efficient than Base64 and needs 91 characters to represent the encoded data.
The following ASCII charakters are used:
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
'!#$%&()*+,./:;<=>?@[]... | ["from math import ceil\ndef b91decode(strng):\n ret = ''\n base91_alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',\n 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',\n 'n', 'o', 'p', 'q', 'r', ... | {"fn_name": "b91decode", "inputs": [["fPNKd"], [">OwJh>Io0Tv!8PE"]], "outputs": [["test"], ["Hello World!"]]} | interview | https://www.codewars.com/kata/58a57c6bcebc069d7e0001fe |
def b91decode(strng):
|
1,645 | The task is simply stated. Given an integer n (3 < n < 10^(9)), find the length of the smallest list of [*perfect squares*](https://en.wikipedia.org/wiki/Square_number) which add up to n. Come up with the best algorithm you can; you'll need it!
Examples:
sum_of_squares(17) = 2 17 = 16 + 1 (4 and 1 are perfect square... | ["def one_square(n):\n return round(n ** .5) ** 2 == n\n\ndef two_squares(n):\n while n % 2 == 0: n //= 2\n p = 3\n while p * p <= n:\n while n % (p * p) == 0:\n n //= p * p\n while n % p == 0:\n if p % 4 == 3: return False\n n //= p\n p += 2\n return... | {"fn_name": "sum_of_squares", "inputs": [[15], [16], [17], [18], [19], [2017], [1008], [3456], [4000], [12321], [661915703], [999887641], [999950886], [999951173], [999998999]], "outputs": [[4], [1], [2], [2], [3], [2], [4], [3], [2], [1], [4], [1], [3], [2], [4]]} | interview | https://www.codewars.com/kata/5a3af5b1ee1aaeabfe000084 |
def sum_of_squares(n):
|
1,648 | This is the performance version of [this kata](https://www.codewars.com/kata/59afff65f1c8274f270020f5).
---
Imagine two rings with numbers on them. The inner ring spins clockwise and the outer ring spins anti-clockwise. We start with both rings aligned on 0 at the top, and on each move we spin each ring by 1. How man... | ["def spinning_rings(inner_max, outer_max):\n p = inner_max + 1\n q = outer_max + 1\n move = 1\n while (-move) % p != move % q:\n if (-move) % p >= q:\n move = move // p * p + p - q + 1\n elif move % q >= p:\n move = move // q * q + q\n elif (-move) % p > move % q ... | {"fn_name": "spinning_rings", "inputs": [[5, 5], [2, 10], [10, 2], [7, 9], [1, 1], [16777216, 14348907]], "outputs": [[3], [13], [10], [4], [1], [23951671]]} | interview | https://www.codewars.com/kata/59b0b7cd2a00d219ab0000c5 |
def spinning_rings(inner_max, outer_max):
|
1,649 | Automatons, or Finite State Machines (FSM), are extremely useful to programmers when it comes to software design. You will be given a simplistic version of an FSM to code for a basic TCP session.
The outcome of this exercise will be to return the correct state of the TCP FSM based on the array of events given.
------... | ["STATE_TO_COMMANDS = {\n 'CLOSED': {\n 'APP_PASSIVE_OPEN': 'LISTEN',\n 'APP_ACTIVE_OPEN': 'SYN_SENT'\n },\n 'LISTEN': {\n 'RCV_SYN': 'SYN_RCVD',\n 'APP_SEND': 'SYN_SENT',\n 'APP_CLOSE': 'CLOSED'\n },\n 'SYN_RCVD': {\n 'APP_CLOSE': 'FIN_WAIT_1',\n 'RCV_ACK': 'ESTABLISHED'\n },\n 'SYN_SENT': ... | {"fn_name": "traverse_TCP_states", "inputs": [[["APP_PASSIVE_OPEN", "RCV_SYN", "RCV_ACK", "APP_CLOSE"]], [["APP_PASSIVE_OPEN", "RCV_SYN", "RCV_ACK"]], [["APP_PASSIVE_OPEN", "RCV_SYN"]], [["APP_PASSIVE_OPEN"]], [["APP_ACTIVE_OPEN", "APP_CLOSE"]], [["APP_ACTIVE_OPEN", "RCV_SYN", "APP_CLOSE", "RCV_FIN", "RCV_ACK"]], [["AP... | interview | https://www.codewars.com/kata/54acc128329e634e9a000362 |
def traverse_TCP_states(events):
|
1,653 | This kata is a continuation of [Part 1](http://www.codewars.com/kata/the-fibfusc-function-part-1). The `fibfusc` function is defined recursively as follows:
fibfusc(0) = (1, 0)
fibfusc(1) = (0, 1)
fibfusc(2n) = ((x + y)(x - y), y(2x + 3y)), where (x, y) = fibfusc(n)
fibfusc(2n + 1) = (-y(2x + 3y), (x +... | ["def fibfusc(n, num_digits=None):\n if n < 2: return (1 - n, n)\n b = bin(n)[2:]\n \n x, y = fibfusc(int(b[0]))\n for bit in b[1:]:\n if bit == \"1\":\n x, y = (-y*(2*x + 3*y), (x + 2*y)*(x + 4*y))\n else:\n x, y = ((x + y) * (x - y), y * (2*x + 3*y))\n if num_... | {"fn_name": "fibfusc", "inputs": [[0], [1]], "outputs": [[[1, 0]], [[0, 1]]]} | interview | https://www.codewars.com/kata/570f1c56cd0531d88e000832 |
def fibfusc(n, num_digits=None):
|
1,655 | ```if:java
___Note for Java users:___ Due to type checking in Java, inputs and outputs are formated quite differently in this language. See the footnotes of the description.
```
You have the following lattice points with their corresponding coordinates and each one with an specific colour.
```
Point [x , y] ... | ["from itertools import combinations\n\ndef count_col_triang(a):\n p, r = {}, {}\n for xy, col in a:\n p[col] = p.get(col, []) + [xy]\n for k in p:\n r[k] = sum(1 for c in combinations(p[k], 3) if triangle(*c))\n mx = max(r.values())\n return [len(a), len(p), sum(r.values()), sorted(k for k... | {"fn_name": "count_col_triang", "inputs": [[[[[3, -4], "blue"], [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"], [[1, -5], "red"], [[-1, 4], "red"], [[1, 7], "red"], [[-3, 5], "red"], [[-3, -5], "blue"], [[4, 1], "blue"]]], [[[[3, -4], "blue"], [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"], [[1,... | interview | https://www.codewars.com/kata/57cebf1472f98327760003cd |
def count_col_triang(a):
|
1,657 | This kata is blatantly copied from inspired by This Kata
Welcome
this is the second in the series of the string iterations kata!
Here we go!
---------------------------------------------------------------------------------
We have a string s
Let's say you start with this: "String"
The first thing you do is reve... | ["def string_func(s, n):\n l, s = [s], list(s)\n while True:\n s[::2], s[1::2] = s[:len(s)//2-1:-1], s[:len(s)//2]\n l.append(''.join(s))\n if l[0] == l[-1]: del l[-1]; break\n return l[n % len(l)]", "# SOLUTION:\n# Actually doing the reversals repeatedly is slow. Through observeration\n# ... | {"fn_name": "string_func", "inputs": [["This is a string exemplification!", 0], ["String for test: incommensurability", 1], ["Ohh Man God Damn", 7], ["Ohh Man God Damnn", 19], ["I like it!", 1234], ["codingisfornerdsyounerd", 10101010], ["this_test_will_hurt_you", 12345678987654321]], "outputs": [["This is a string exe... | interview | https://www.codewars.com/kata/5ae64f28d2ee274164000118 |
def string_func(s, n):
|
1,658 | The aim is to calculate `exponential(x)` (written `exp(x)` in most math libraries) as an irreducible fraction, the numerator of this fraction having a given number of digits.
We call this function `expand`, it takes two parameters, `x` of which we want to evaluate the exponential, `digits` which is the required number... | ["from fractions import Fraction\n\ndef expand(x, digit):\n step = 0\n fact = 1\n expo = Fraction(1)\n n = 10 ** len(str(x).split('.')[-1])\n x = Fraction(int(x * n), n)\n while expo.numerator < 10 ** (digit - 1):\n step += 1\n fact *= step\n expo += x ** step / fact\n return [... | {"fn_name": "expand", "inputs": [[1, 2], [1, 5], [1, 6], [10, 3], [10, 4], [10, 40], [10, 39], [10, 38], [1.5, 10], [1.6, 10], [1.7, 10], [1.7, 12], [1.7, 15], [1.8, 20], [2.0, 20], [1.95, 60]], "outputs": [[[65, 24]], [[109601, 40320]], [[109601, 40320]], [[683, 3]], [[1933, 3]], [[123934329054285820429389726875580721... | interview | https://www.codewars.com/kata/54f5f22a00ecc4184c000034 |
def expand(x, digit):
|
1,659 | # How many ways can you make the sum of a number?
From wikipedia: https://en.wikipedia.org/wiki/Partition_(number_theory)#
>In number theory and combinatorics, a partition of a positive integer *n*, also called an *integer partition*, is a way of writing n as a sum of positive integers. Two sums that differ only in t... | ["ANSWERS = {\n 0: 1,\n 1: 1,\n 2: 2,\n 3: 3,\n 4: 5,\n 5: 7,\n 6: 11,\n 7: 15,\n 8: 22,\n 9: 30,\n 10: 42,\n 11: 56,\n 12: 77,\n 13: 101,\n 14: 135,\n 15: 176,\n 16: 231,\n 17: 297,\n 18: 385,\n 19: 490,\n 20: 627,\n 21: 792,\n 22: 1002,\n 23: 125... | {"fn_name": "exp_sum", "inputs": [[1], [2], [3], [4], [5], [20], [30], [40], [43], [60], [70], [90], [200], [275]], "outputs": [[1], [2], [3], [5], [7], [627], [5604], [37338], [63261], [966467], [4087968], [56634173], [3972999029388], [1520980492851175]]} | interview | https://www.codewars.com/kata/52ec24228a515e620b0005ef |
def exp_sum(n):
|
1,661 | # RoboScript #3 - Implement the RS2 Specification
## Disclaimer
The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental.
## About this Kata Series
This Kata Series is based on a fictional... | ["from collections import deque\nimport re\n\nTOKENIZER = re.compile(r'(R+|F+|L+|\\)|\\()(\\d*)')\n\ndef parseCode(code):\n cmds = [[]]\n for cmd,n in TOKENIZER.findall(code):\n s,r = cmd[0], int(n or '1') + len(cmd)-1\n if cmd == '(': cmds.append([])\n elif cmd == ')': lst = cmds.pop() ; c... | {"fn_name": "execute", "inputs": [["LF5(RF3)(RF3R)F7"], ["(L(F5(RF3))(((R(F3R)F7))))"], ["F4L(F4RF4RF4LF4L)2F4RF4RF4"], ["F4L((F4R)2(F4L)2)2(F4R)2F4"], ["F2LF3L(F2)2LF5L(F3)2LF7L((F2)2)2L(F3)3L(F5)2"], ["F2LF3L(F2)2LF5L(F3)2LF7L(F4)2L((F3)1)3L(F5)2"], ["(F5RF5R(F3R)2)3"], ["((F5R)2(F3R)2)3"], ["((F3LF3R)2FRF6L)2"], ["(... | interview | https://www.codewars.com/kata/58738d518ec3b4bf95000192 |
def execute(code):
|
1,664 | # Task
An `amazon` (also known as a queen+knight compound) is an imaginary chess piece that can move like a `queen` or a `knight` (or, equivalently, like a `rook`, `bishop`, or `knight`). The diagram below shows all squares which the amazon attacks from e4 (circles represent knight-like moves while crosses correspond ... | ["from itertools import count\n\nALL_MOVES = [(1,1), (0,1), ( 1,0), (-1,0), (0,-1), (-1,1), ( 1,-1), (-1,-1)] # Natural directions of moves for king or queen (one step)\nAMA_MOVES = [(1,2), (2,1), (-1,2), (2,-1), (1,-2), (-2,1), (-1,-2), (-2,-1)] # Knight moves for amazon queen\n\n\ndef amazon_check_mate(... | {"fn_name": "amazon_check_mate", "inputs": [["a1", "g5"], ["a3", "e4"], ["f3", "f2"], ["b7", "a8"], ["f7", "d3"], ["g2", "c3"], ["f3", "c1"], ["d4", "h8"], ["h6", "a7"], ["a6", "g3"], ["e1", "b4"], ["f4", "c4"], ["c3", "e8"], ["b5", "e5"], ["c8", "g8"], ["a6", "b5"], ["b3", "e2"], ["b7", "c3"], ["b5", "b3"], ["a4", "a6... | interview | https://www.codewars.com/kata/5897f30d948beb78580000b2 |
def amazon_check_mate(king, amazon):
|
1,668 | Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits.
For example:
```python
next_smaller(21) == 12
next_smaller(531) == 513
next_smaller(2071) == 2017
```
Return -1 (for `Haskell`: return `Nothing`, for `Rust`: return `None`), when there is no small... | ["def next_smaller(n):\n s = list(str(n))\n i = j = len(s) - 1\n while i > 0 and s[i - 1] <= s[i]: i -= 1\n if i <= 0: return -1\n while s[j] >= s[i - 1]: j -= 1\n s[i - 1], s[j] = s[j], s[i - 1]\n s[i:] = reversed(s[i:])\n if s[0] == '0': return -1\n return int(''.join(s))", "def next_smalle... | {"fn_name": "next_smaller", "inputs": [[21], [907], [531], [1027], [441], [123456798], [513], [351], [315], [153], [135], [100], [2071], [1207], [414], [123456789], [29009], [1234567908], [9999999999], [59884848483559], [1023456789], [51226262651257], [202233445566], [506789]], "outputs": [[12], [790], [513], [-1], [41... | interview | https://www.codewars.com/kata/5659c6d896bc135c4c00021e |
def next_smaller(n):
|
1,669 | Alice has a hand of cards, given as an array of integers.
Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.
Return true if and only if she can.
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
Output: true
Explanation: Alice's hand can be rearrang... | ["class Solution:\n def isNStraightHand(self, hand: List[int], W: int) -> bool:\n # 1, 2, 2, 3, 3, 4, 6, 7, 8\n # 1 2 3\n # 2 3 4\n # 6 7 8\n \n # W length Q\n # how many opened\n # # of the element is current opened one\n \n q = deque()... | {"fn_name": "isNStraightHand", "inputs": [[[1, 2, 3, 6, 2, 3, 4, 7, 8], 3]], "outputs": [true]} | interview | https://leetcode.com/problems/hand-of-straights/ |
class Solution:
def isNStraightHand(self, hand: List[int], W: int) -> bool:
|
1,670 | Finally the clowns of Synapse have decided to take their site online. The convener of the clowns has heard from somewhere that knowing URI's is very important for their website, so kindly help him with this task.
Uniform Resource Identifiers (or URIs) are strings like
http://synapse.daiict.ac.in/codemutants/, mailto:c... | ["import sys\ndef main():\n s = sys.stdin.readline\n save = {' ': '%20', '!': '%21', '$': '%24', '%': '%25', '(': '%28', ')': '%29', '*': '%2a'}\n string = s().strip()\n while True:\n output = []\n if '#' in string:\n return\n for i in string:\n if i in save:\n ... | {"inputs": [["Happy Joy Joy!", "http://synapse.daiict.ac.in/", "plain_vanilla", "(**)", "?", "the 7% solution", "#"]], "outputs": [["Happy%20Joy%20Joy%21", "http://synapse.daiict.ac.in/", "plain_vanilla", "%28%2a%2a%29", "?", "the%207%25%20solution"]]} | interview | https://www.codechef.com/CDMT2012/problems/SYNOL | |
1,697 | Once you complete this kata, there is a [15x15 Version](http://www.codewars.com/kata/15x15-nonogram-solver) that you can try.
And once you complete that, you can do the [Multisize Version](https://www.codewars.com/kata/5a5519858803853691000069) which goes up to 50x50.
# Description
For this kata, you will be making a... | ["import itertools\nclass Nonogram:\n poss = {(1,1,1): set([(1,0,1,0,1)]),\n (1,1): set([(0,0,1,0,1),(0,1,0,1,0),(1,0,1,0,0),(0,1,0,0,1),(1,0,0,1,0),(1,0,0,0,1)]),\n (1,2): set([(1,0,1,1,0),(1,0,0,1,1),(0,1,0,1,1)]),\n (1,3): set([(1,0,1,1,1)]),\n (2,1): set([(1,1,... | {"fn_name": "__init__", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5a479247e6be385a41000064 |
def __init__(self, clues):
|
1,699 | Professor Chambouliard hast just discovered a new type of magnet material. He put particles of this material in a box made of small boxes arranged
in K rows and N columns as a kind of **2D matrix** `K x N` where `K` and `N` are postive integers.
He thinks that his calculations show that the force exerted by the partic... | ["def doubles(maxk, maxn):\n return sum([ sum([ (n+1)**(-2*k) for n in range(1, maxn+1) ])/k for k in range(1, maxk+1) ])", "from scipy.special import zeta,zetac\n\ndef doubles(maxk, maxn):\n return sum((zetac(2*k)-zeta(2*k,2+maxn))/k for k in range(1,maxk+1))", "def v(k,n):\n return (1.0/k)*(n+1)**(-2*k)\n\nd... | {"fn_name": "doubles", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/56c04261c3fcf33f2d000534 |
def doubles(maxk, maxn):
|
1,704 | A famous casino is suddenly faced with a sharp decline of their revenues. They decide to offer Texas hold'em also online. Can you help them by writing an algorithm that can rank poker hands?
## Task
Create a poker hand that has a method to compare itself to another poker hand:
```python
compare_with(self, other_han... | ["class PokerHand(object):\n CARD = \"23456789TJQKA\"\n RESULT = [\"Loss\", \"Tie\", \"Win\"]\n\n def __init__(self, hand):\n values = ''.join(sorted(hand[::3], key=self.CARD.index))\n suits = set(hand[1::3])\n is_straight = values in self.CARD\n is_flush = len(suits) == 1\n ... | {"fn_name": "__init__", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5739174624fc28e188000465 |
def __init__(self, hand):
|
1,706 | # Task
A rectangle with sides equal to even integers a and b is drawn on the Cartesian plane. Its center (the intersection point of its diagonals) coincides with the point (0, 0), but the sides of the rectangle are not parallel to the axes; instead, they are forming `45 degree` angles with the axes.
How many points ... | ["def rectangle_rotation(a, b):\n a //= 2**0.5\n b //= 2**0.5\n r = (a + 1) * (b + 1) + a * b\n\n return r + r % 2 - 1", "def rectangle_rotation(a, b):\n \n wid_even = 2 * int(a / 2 /(2**0.5)) + 1\n hei_even = 2 * int(b / 2 /(2**0.5)) + 1\n \n wid_odd = 2 * int(a / 2 /(2**0.5) + 1/2)\n hei_odd = 2 * i... | {"fn_name": "rectangle_rotation", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5886e082a836a691340000c3 |
def rectangle_rotation(a, b):
|
1,710 | 
Create a class called `Warrior` which calculates and keeps track of their level and skills, and ranks them as the warrior they've proven to be.
Business Rules:
- A warrior starts at level 1 and can progress all the ... | ["class Warrior():\n \n def __init__(self):\n self._experience = 100\n self.rs = [\"Pushover\", \"Novice\", \"Fighter\", \"Warrior\", \"Veteran\", \"Sage\", \"Elite\", \"Conqueror\", \"Champion\", \"Master\", \"Greatest\"]\n self.achievements = []\n def training(self, train):\n if(t... | {"fn_name": "__init__", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5941c545f5c394fef900000c |
def __init__(self):
|
1,711 | ### Context and Definitions
You are in charge of developing a new cool JavaScript library that provides functionality similar to that of [Underscore.js](http://underscorejs.org/).
You have started by adding a new **list data type** to your library. You came up with a design of a data structure that represents an [al... | ["class Cons:\n def __init__(self, head, tail):\n self.head = head\n self.tail = tail\n\n def to_array(self):\n return [self.head] + (self.tail.to_array() if self.tail is not None else [])\n\n @classmethod\n def from_array(cls, arr):\n if not arr:\n return None\n ... | {"fn_name": "__init__", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/529a92d9aba78c356b000353 |
def __init__(self, head, tail):
|
1,714 | ### The Problem
Consider a flat board with pegs sticking out of one side. If you stretched a rubber band across the outermost pegs what is the set of pegs such that all other pegs are contained within the shape formed by the rubber band?

... | ["def hull_method(points):\n sorted_points = sorted(points)\n return half_hull(sorted_points) + half_hull(reversed(sorted_points))\n\ndef half_hull(sorted_points):\n hull = []\n for p in sorted_points:\n while len(hull) > 1 and not is_ccw_turn(hull[-2], hull[-1], p):\n hull.pop()\n ... | {"fn_name": "hull_method", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5657d8bdafec0a27c800000f |
def hull_method(pointlist):
|
1,716 | This is the simple version of [Fastest Code : Equal to 24](http://www.codewars.com/kata/574e890e296e412a0400149c).
## Task
A game I played when I was young: Draw 4 cards from playing cards, use ```+ - * / and ()``` to make the final results equal to 24.
You will coding in function ```equalTo24```. Function accept 4... | ["from itertools import permutations\n\ndef equal_to_24(*aceg):\n ops = '+-*/'\n \n for b in ops:\n for d in ops:\n for f in ops:\n for (a,c,e,g) in permutations(aceg):\n for s in make_string(a,b,c,d,e,f,g):\n try:\n ... | {"fn_name": "equal_to_24", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/574be65a974b95eaf40008da |
def equal_to_24(a,b,c,d):
|
1,719 | ### The problem
How many zeroes are at the **end** of the [factorial](https://en.wikipedia.org/wiki/Factorial) of `10`? 10! = 3628800, i.e. there are `2` zeroes.
16! (or 0x10!) in [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) would be 0x130777758000, which has `3` zeroes.
### Scalability
Unfortunately, ma... | ["def zeroes (base, number):\n pzeros = []\n for p in range(2, base+1):\n e = 0\n while base % p == 0:\n base /= p\n e += 1\n if e:\n f, m = 0, number\n while m:\n m /= p\n f += m\n pzeros.append(f / e)\n ... | {"fn_name": "zeroes ", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/55c4eb777e07c13528000021 |
def zeroes (base, number):
|
1,723 | ## Bezier curves
When a shape is described using vector graphics, its outline is often described as a sequence of linear, quadratic, and cubic Bezier curves. You can read about [Bézier curves](https://en.wikipedia.org/wiki/B%C3%A9zier_curve) on Wikipedia.
You don't need to know much about Bezier curves to solve this... | ["class Segment: # Instead of an abstract class, make it the implementation for all three subclasses\n def __init__(self, *coords):\n self.control_points = coords # IMHO a getter/setter is overkill here\n\n def control_points_at(self, t): # Helper function\n p = self.control_points\n resul... | {"fn_name": "control_points", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5a47391c80eba865ea00003e |
def control_points(self):
|
1,724 | This kata is inspired by Space Invaders (Japanese: スペースインベーダー), an arcade video game created by Tomohiro Nishikado and released in 1978.
Alien invaders are attacking Earth and you've been conscripted to defend.
The Bad News: You performed poorly in the manual training. As a result, you're ranked low priority and you're... | ["def blast_sequence(aliensStart,position):\n \n def moveAliens(aliens, furthest):\n lst, shootPath = [], []\n for x,y,s in aliens:\n y += s\n if not (0 <= y < N): #Out of the grid: move down and reverse\n x, s = x+1, -s\... | {"fn_name": "blast_sequence", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/59fabc2406d5b638f200004a |
def blast_sequence(aliens, position):
|
1,725 | # Problem Description
Let's imagine a function `F(n)`, which is defined over the integers
in the range of `1 <= n <= max_n`, and `0 <= F(n) <= max_fn` for every `n`.
There are `(1 + max_fn) ** max_n` possible definitions of `F` in total.
Out of those definitions, how many `F`s satisfy the following equations?
Since ... | ["mod = 12345787\nmat = [([1,1],[0,1,3]),\n ([2,1,-1],[0,2,6,11]),\n ([2,3,-1,-1],[0,2,10,23,70]),\n ([3,3,-4,-1,1],[0,3,15,42,155,533]),\n ([3,6,-4,-5,1,1],[0,3,21,69,301,1223,5103])]\n\nfor i in range(100): [m.append(sum(k*m[-1-i] for i,k in enumerate(c))%mod) for c,m in mat]\n\ndef circular_l... | {"fn_name": "circular_limited_sums", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/59951f21d65a27e95d00004f |
def circular_limited_sums(max_n, max_fn):
|
1,726 | ## Task
You are at position [0, 0] in maze NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West). Return `true` if you can reach position [N-1, N-1] or `false` otherwise.
Empty positions are marked `.`. Walls are marked `W`. Start and exit positions are empty in all tes... | ["def path_finder(maze):\n matrix = list(map(list, maze.splitlines()))\n stack, length = [[0, 0]], len(matrix)\n while len(stack):\n x, y = stack.pop()\n if matrix[x][y] == '.':\n matrix[x][y] = 'x'\n for x, y in (x, y-1), (x, y+1), (x-1, y), (x+1, y):\n if 0 <= x < length and ... | {"fn_name": "path_finder", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5765870e190b1472ec0022a2 |
def path_finder(maze):
|
1,729 | Hey, Path Finder, where are you?
## Path Finder Series:
- [#1: can you reach the exit?](https://www.codewars.com/kata/5765870e190b1472ec0022a2)
- [#2: shortest path](https://www.codewars.com/kata/57658bfa28ed87ecfa00058a)
- [#3: the Alpinist](https://www.codewars.com/kata/576986639772456f6f00030c)
- ... | ["import re\n\nclass Me(object):\n def __init__(self): self.x, self.y, self.dx, self.dy = 0,0,-1,0\n def move(self, n): self.x += n*self.dx ; self.y += n*self.dy\n def back(self): self.dx *= -1 ; self.dy *= -1\n def turn(self, d): self.dx,self.dy = (self.dy * (-1)**(d=='l'), 0) if self.dy else (0, sel... | {"fn_name": "i_am_here", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5a0573c446d8435b8e00009f |
def i_am_here(path):
|
1,730 | ### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)!
---
# Task
A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical.
```
## or #
#
```
You have in... | ["def two_by_n(n, k):\n vv, vh, hv, hh = k-1, (k-1)*(k-2), k-2, (k-1)*(k-2) + 1\n va, ha, vb, hb = 0, 0, 1, 1\n for i in range(n - 1):\n va, ha, vb, hb = vb, hb, vv*vb + vh*ha, hv*vb + hh*ha\n return (k * vb + k*(k-1) * ha) % 12345787\n", "def two_by_n(n, k):\n MOD = 12345787\n x1, x2 = [0, k, ... | {"fn_name": "two_by_n", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5a59e029145c46eaac000062 |
def two_by_n(n, k):
|
1,731 | Esoteric languages are pretty hard to program, but it's fairly interesting to write interpreters for them!
Your task is to write a method which will interpret Befunge-93 code! Befunge-93 is a language in which the code is presented not as a series of instructions, but as instructions scattered on a 2D plane; your poin... | ["from random import choice\n\ndef interpret(code):\n code = [list(l) for l in code.split('\\n')]\n x, y = 0, 0\n dx, dy = 1, 0\n output = ''\n stack = []\n string_mode = False\n \n while True:\n move = 1\n i = code[y][x]\n \n if string_mode:\n if i == '\"'... | {"fn_name": "interpret", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/526c7b931666d07889000a3c |
def interpret(code):
|
1,733 | Given two different positions on a chess board, find the least number of moves it would take a knight to get from one to the other.
The positions will be passed as two arguments in algebraic notation.
For example, `knight("a3", "b5")` should return 1.
The knight is not allowed to move off the board.
The board is 8x8.
... | ["from collections import deque\nmoves = ((1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1))\n\ndef knight(p1, p2):\n x, y = ord(p2[0])-97, int(p2[1])-1\n left, seen = deque([(ord(p1[0])-97, int(p1[1])-1, 0)]), set()\n while left:\n i, j, v = left.popleft()\n if i==x and j==y... | {"fn_name": "knight", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/549ee8b47111a81214000941 |
def knight(p1, p2):
|
1,737 | Your task is to implement a function that calculates an election winner from a list of voter selections using an [Instant Runoff Voting](http://en.wikipedia.org/wiki/Instant-runoff_voting) algorithm. If you haven't heard of IRV, here's a basic overview (slightly altered for this kata):
- Each voter selects several can... | ["from collections import Counter\n\ndef runoff(voters):\n while voters[0]:\n poll = Counter(ballot[0] for ballot in voters)\n winner, maxscore = max(poll.items(), key = lambda x: x[1])\n minscore = min(poll.values())\n if maxscore * 2 > len(voters):\n return winner\n vo... | {"fn_name": "runoff", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/52996b5c99fdcb5f20000004 |
def runoff(voters):
|
1,741 | ### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)!
---
# Task
A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical.
```
## or #
#
```
You have in... | ["import numpy as np\ndef five_by_2n(n):\n x=np.array([[1,1,1,1,1,1,1,1],[1,2,1,1,1,2,2,1],[1,1,2,1,1,1,2,1],[1,1,1,2,1,1,2,1],[1,1,1,1,2,1,2,2],[1,2,1,1,2,1,6,1],[1,2,1,1,2,1,6,1],[1,2,1,1,2,1,6,1]])\n y=np.array([1,1,1,1,1,1,1,1])\n z=y\n for i in range(n-1):\n z=np.mod(x@z,12345787*y)\n return ... | {"fn_name": "five_by_2n", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5a77f76bfd5777c6c300001c |
def five_by_2n(n):
|
1,743 | # Background
The famous Collatz Sequence is generated with the following rules:
* Start with a positive integer `a[0] = n`.
* If `a[i]` is even, `a[i+1] = a[i] / 2`.
* Otherwise, `a[i+1] = a[i] * 3 + 1`.
However, for the purpose of this Kata, I give a **slightly modified definition**:
* If `a[i]` is even, `a[i+1] =... | ["def collatz_steps(n, steps):\n while True:\n str = ''\n result = n\n \n while bool(str != steps) ^ bool(str != steps[:len(str)]):\n if result % 2 == 0:\n result = result/2\n str += 'D'\n else:\n result = (3*result + 1)/2\n ... | {"fn_name": "collatz_steps", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5992e103b1429877bb00006b |
def collatz_steps(n, steps):
|
1,744 | This Kata is a continuation of [Part 1](http://www.codewars.com/kata/the-fusc-function-part-1). The `fusc` function is defined recursively as follows:
fusc(0) = 0
fusc(1) = 1
fusc(2n) = fusc(n)
fusc(2n + 1) = fusc(n) + fusc(n + 1)
Your job is to produce the code for the `fusc` function. In this ka... | ["def fusc(n):\n a, b = 1, 0\n for i in bin(n)[2:]:\n if i == '1': b += a\n else: a += b\n return b\n", "def fusc(n):\n a, b = 0, 1\n while n > 0:\n if n & 1:\n a += b\n else:\n b += a\n n >>= 1\n return a", "def fusc(n):\n a, b = 0, 1\n w... | {"fn_name": "fusc", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/57040e445a726387a1001cf7 |
def fusc(n):
|
1,745 | This calculator takes values that could be written in a browsers route path as a single string. It then returns the result as a number (or an error message).
Route paths use the '/' symbol so this can't be in our calculator. Instead we are using the '$' symbol as our divide operator.
You will be passed a string of an... | ["import re\n\nADDSUB, MULDIV = '+-', '*$'\n\ndef calculate(expression):\n return \"400: Bad request\" if re.search(r'[^+*$\\d.-]', expression) else parseAndEval(expression, ADDSUB)\n\ndef parseAndEval(expression, ops):\n v = 0\n for op,part in re.findall(r'([{0}])?([^{0}]+)'.format(ops), expression):\n ... | {"fn_name": "calculate", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/581bc0629ad9ff9873000316 |
def calculate(expression):
|
1,748 | This kata is inspired by Tower Defense (TD), a subgenre of strategy video games where the goal is to defend a player's territories or possessions by obstructing enemy attackers, usually by placing defensive structures on or along their path of attack.
Objective
It's the future, and hostile aliens are attacking our pla... | ["import collections\n\nclass Tower:\n def __init__(self):\n indicesOfAlienPath = []\n shots = 0\n\nclass GameStats:\n def __init__(self):\n alienPath = collections.deque()\n towers = []\n waves = collections.deque()\n\nDirEOL = 0\nDirLeft = 1\nDirRight = 2\nDirUp = 3\nDirDown =... | {"fn_name": "__init__", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5a57faad880385f3b60000d0 |
def __init__(self):
|
1,749 | A factorial (of a large number) will usually contain some trailing zeros.
Your job is to make a function that calculates the number of trailing zeros, in any given base.
Factorial is defined like this:
```n! = 1 * 2 * 3 * 4 * ... * n-2 * n-1 * n```
Here's two examples to get you started:
```python
trailing_zeros(15,... | ["def isqrt(num):\n '''Compute int(sqrt(n)) for n integer > 0\n O(log4(n)) and no floating point operation, no division'''\n res, bit = 0, 1\n while bit <= num:\n bit <<= 2\n bit >>= 2\n\n while bit:\n if num >= res + bit:\n num -= res + bit\n res += bit << 1\n ... | {"fn_name": "trailing_zeros", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/544483c6435206617a00012c |
def trailing_zeros(num, base):
|
1,755 | This is the second part of a two-part challenge. See [part I](https://www.codewars.com/kata/587387d169b6fddc16000002) if you haven't done so already.
The problem is the same, only with longer lists and larger values.
Imagine you have a number of jobs to execute. Your workers are not permanently connected to your netwo... | ["def splitlist(l):\n half = sum(l) // 2\n sums = [(0, [])]\n for i, n in enumerate(l):\n sums = sums + [(m + n, a + [i]) for m, a in sums if m + n <= half]\n if max(s[0] for s in sums) == half:\n break\n sums.sort(key=lambda v: abs(v[0] - half))\n indices = sums[0][1]\n return [n for i, n in e... | {"fn_name": "splitlist", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/586e6b54c66d18ff6c0015cd |
def splitlist(lst):
|
1,757 | ## A Knight's Tour
A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once.
https://en.wikipedia.org/wiki/Knight%27s_tour
Traditional chess boards are 8x8 grids, but for this kata we are interested in generating tours for any square board sizes.
You will... | ["def knights_tour(start, size):\n \n MOVES = [(-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1), (2,1), (1,2), (-1,2)]\n \n def genNeighs(pos): return ((pos[0]+dx, pos[1]+dy) for dx,dy in MOVES if (pos[0]+dx, pos[1]+dy) in Warnsdorf_DP)\n \n def travel(pos):\n neighs = sorted( (Warnsdorf_DP[n], n) ... | {"fn_name": "knights_tour", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5664740e6072d2eebe00001b |
def knights_tour(start, size):
|
1,762 | Above: An overhead view of the house in one of the tests. The green outline indicates the path taken by K
A mouse named K has found a new home on Ash Tree Lane. K wants to know the size of the interior of the house (which consists of just one room). K is able to measure precise distances in any direction he runs. But K... | ["def add_point(ori,dis,c):\n lastPoint = c[-1]\n if ori == \"N\":\n c.append((lastPoint[0],lastPoint[1]+dis))\n elif ori == \"S\":\n c.append((lastPoint[0],lastPoint[1]-dis))\n elif ori == \"E\":\n c.append((lastPoint[0]+dis,lastPoint[1]))\n else: \n c.append((lastPoint[0]-di... | {"fn_name": "mouse_path", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5d2f93da71baf7000fe9f096 |
def mouse_path(s):
|
1,763 | # Disclaimer
This Kata is an insane step-up from [GiacomoSorbi's Kata](https://www.codewars.com/kata/total-increasing-or-decreasing-numbers-up-to-a-power-of-10/python),
so I recommend to solve it first before trying this one.
# Problem Description
A positive integer `n` is called an *increasing number* if its digits... | ["from functools import reduce\nfrom operator import mul\n\ndef insane_inc_or_dec(x): \n return (reduce(mul,[x + i + i * (i == 10) for i in range(1, 11)]) // 3628800 - 10 * x - 2) % 12345787 ", "MOD = 12345787\n\ndef n_choose_k(n,k):\n if not k or n == k: return 1\n if k < 0 or k > n: return 0\n if 2*k... | {"fn_name": "insane_inc_or_dec", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5993e6f701726f0998000030 |
def insane_inc_or_dec(x):
|
1,764 | In this kata you must determine the lowest floor in a building from which you cannot drop an egg without it breaking. You may assume that all eggs are the same; if one egg breaks when dropped from floor `n`, all eggs will. If an egg survives a drop from some floor, it will survive a drop from any floor below too.
You... | ["#THanks to easter eggs kata ;*\n\ndef height(n, m):\n if n >= m:\n return (2 ** (min(n, m)) - 1)\n f = 1\n res = 0\n for i in range(n):\n f = f * (m - i) // (i + 1)\n res += f\n return res\n\ndef solve(emulator):\n m = emulator.drops\n n = emulator.eggs\n h = 0\n tryh =... | {"fn_name": "solve", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/56d3f1743323a8399200063f |
def solve(emulator):
|
1,767 | ### **[Mahjong Series](/collections/mahjong)**
**Mahjong** is based on draw-and-discard card games that were popular in 18th and 19th century China and some are still popular today.
In each deck, there are three different suits numbered `1` to `9`, which are called **Simple tiles**. To simplify the problem, we talk a... | ["from collections import Counter\n\ndef solution(tiles):\n return \"\".join(\n tile for tile in \"123456789\"\n if tiles.count(tile) < 4\n and list(meld(meld(meld(meld(pair(Counter(map(int, tiles+tile))))))))\n )\n\ndef pair(c):\n yield from (c - Counter([t,t]) for t in c if c[t] ... | {"fn_name": "solution", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/56ad7a4978b5162445000056 |
def solution(tiles):
|
1,770 | ## Task
You are at position `[0, 0]` in maze NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West). Return the minimal number of steps to exit position `[N-1, N-1]` *if* it is possible to reach the exit from the starting position. Otherwise, return `false` in **JavaScrip... | ["def path_finder(maze):\n lst = maze.split('\\n')\n X, Y = len(lst)-1, len(lst[0])-1\n seen = {(x,y) for x,row in enumerate(lst) for y,c in enumerate(row) if c=='W'} | {(0,0)}\n end, bag, turn = (X,Y), {(0,0)}, 0\n \n while bag and end not in bag:\n bag = { (a,b) for a,b in {(x+dx,y+dy) for x... | {"fn_name": "path_finder", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/57658bfa28ed87ecfa00058a |
def path_finder(maze):
|
1,772 | The Vigenère cipher is a classic cipher originally developed by Italian cryptographer Giovan Battista Bellaso and published in 1553. It is named after a later French cryptographer Blaise de Vigenère, who had developed a stronger autokey cipher (a cipher that incorporates the message of the text into the key).
The cip... | ["from itertools import cycle\n\nclass VigenereCipher (object):\n def __init__(self, key, alphabet):\n self.key = key.decode('utf-8')\n self.alphabet = alphabet.decode('utf-8')\n \n def cipher(self, mode, str):\n return ''.join(self.alphabet[(self.alphabet.index(m) +\n mod... | {"fn_name": "__init__", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3 |
def __init__(self, key, alphabet):
|
1,773 | ### Sudoku Background
Sudoku is a game played on a 9x9 grid. The goal of the game is to fill all cells of the grid with digits from 1 to 9, so that each column, each row, and each of the nine 3x3 sub-grids (also known as blocks) contain all of the digits from 1 to 9.
(More info at: http://en.wikipedia.org/wiki/Sudoku... | ["def validSolution(board):\n boxes = validate_boxes(board)\n cols = validate_cols(board)\n rows = validate_rows(board)\n return boxes and cols and rows\n\ndef validate_boxes(board):\n for i in range(0, 9, 3):\n for j in range(0, 9, 3):\n nums = board[i][j:j+3] + board[i+1][j:j+3] + boa... | {"fn_name": "validSolution", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/529bf0e9bdf7657179000008 |
def validSolution(board):
|
1,776 | Stacey is a big [AD&D](https://en.wikipedia.org/wiki/Dungeons_%26_Dragons) games nerd. Moreover, she's a munchkin. Not a [cat breed](https://en.wikipedia.org/wiki/Munchkin_cat), but a person who likes to get maximum efficiency of their character.
As you might know, many aspects of such games are modelled by rolling di... | ["def roll_dice (rolls, sides, threshold):\n dp = [0] * (rolls * sides + 1)\n for i in range(1, sides+1):\n dp[i] = 1\n\n for _ in range(rolls-1):\n for x in range((rolls * sides), 0, -1):\n dp[x] = sum(dp[max(1, x-sides):x])\n\n return sum(dp[threshold:]) / sum(dp[1:])", "c = [[1]]... | {"fn_name": "roll_dice ", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/55d18ceefdc5aba4290000e5 |
def roll_dice (rolls, sides, threshold):
|
1,777 | # Task
IONU Satellite Imaging, Inc. records and stores very large images using run length encoding. You are to write a program that reads a compressed image, finds the edges in the image, as described below, and outputs another compressed image of the detected edges.
A simple edge detection algorithm sets an output... | ["'''\nChallenge Fun #20: Edge Detection\nhttps://www.codewars.com/kata/58bfa40c43fadb4edb0000b5/train/python\n\nFor a rectangular image given in run-length encoding (RLE) as\ndescribed below, return a RLE of the image processed by replacing\neach pixel by the maximum absolute value of the difference between\nit and ea... | {"fn_name": "edge_detection", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/58bfa40c43fadb4edb0000b5 |
def edge_detection(image):
|
1,778 | [The Vigenère cipher](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) is a classic cipher that was thought to be "unbreakable" for three centuries. We now know that this is not so and it can actually be broken pretty easily.
**How the Vigenère cipher works**:
The basic concept is that you have a `message` and a `... | ["from collections import Counter\n\ndef get_key_length(cipher_text, max_key_length):\n avg_IC_by_keylen = {}\n \n for key_len in range(1, max_key_length+1):\n ICs = []\n \n for i in range(key_len):\n sub_str = cipher_text[i::key_len]\n freq = Counter(sub_str)\n ... | {"fn_name": "get_key_length", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/55d6afe3423873eabe000069 |
def get_key_length(text, max_key_length):
|
1,780 | From wikipedia
In number theory and combinatorics, a partition of a positive integer n, also called an integer partition,
is a way of writing n as a sum of positive integers.
Two sums that differ only in the order of their summands are considered the **same** partition.
For example, 4 can be partitioned in five d... | ["def prod(n):\n ret = [{1.}]\n for i in range(1, n+1):\n ret.append({(i - x) * j for x, s in enumerate(ret) for j in s})\n return ret[-1]\n\ndef part(n):\n p = sorted(prod(n))\n return \"Range: %d Average: %.2f Median: %.2f\" % \\\n (p[-1] - p[0], sum(p) / len(p), (p[len(p)//2] + p[~le... | {"fn_name": "prod", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/55cf3b567fc0e02b0b00000b |
def prod(u):
|
1,784 | [Currying and partial application](http://www.2ality.com/2011/09/currying-vs-part-eval.html) are two ways of transforming a function into another function with a generally smaller arity. While they are often confused with each other, they work differently. The goal is to learn to differentiate them.
## Currying
> Is ... | ["class CurryPartial:\n def __init__(self, func, *args):\n self.func = func\n self.args = args\n \n def __call__(self, *args):\n return CurryPartial(self.func, *(self.args + args))\n \n def __eq__(self, other):\n try:\n return self.func(*self.args) == other\n ... | {"fn_name": "curry_partial", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/53cf7e37e9876c35a60002c9 |
def curry_partial(f,*args):
|
1,786 | Let's say you have a bunch of points, and you want to round them all up and calculate the area of the smallest polygon containing all of the points (nevermind why, you just want a challenge). What you're looking for is the area of the *convex hull* of these points. Here is an example, delimited in blue :
## Your tas... | ["import numpy as np\n\ndef slope(p1, p2):\n dx, dy = vectorize(p1, p2)\n return dy/dx if dx else float(\"inf\")\n\ndef vectorize(p1, p2): return [b-a for a,b in zip(p1, p2)]\ndef getArea (p1, p2, p3): return np.cross(vectorize(p1, p2), vectorize(p1, p3)) / 2\ndef isConcave(p1, pivot, p2): return ge... | {"fn_name": "cross", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/59c1d64b9f0cbcf5740001ab |
def cross(p1,p2,p):
|
1,789 | As [breadcrumb menùs](https://en.wikipedia.org/wiki/Breadcrumb_%28navigation%29) are quite popular today, I won't digress much on explaining them, leaving the wiki link to do all the dirty work in my place.
What might not be so trivial is instead to get a decent breadcrumb from your current url. For this kata, your pu... | ["from re import sub\n\nignoreList = [\"THE\", \"OF\", \"IN\", \"FROM\", \"BY\", \"WITH\", \"AND\", \"OR\", \"FOR\", \"TO\", \"AT\", \"A\"]\n\ndef generate_bc(url, separator):\n # remove leading http(s):// and trailing /\n url = sub(\"https?://\", \"\", url.strip(\"/\"))\n \n # skip index files\n ur... | {"fn_name": "generate_bc", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/563fbac924106b8bf7000046 |
def generate_bc(url, separator):
|
1,792 | ### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)!
---
# Task
A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical.
```
## or #
#
```
You have in... | ["def three_by_n(n):\n A = [1, 2] + [0]*(n-1)\n B = [0, 1] + [0]*(n-1)\n C = [1, 0] + [0]*(n-1)\n D = [0, 1] + [0]*(n-1)\n for i in range(2, n+1):\n A[i] = A[i-2] + 2*B[i-1] + 2*C[i-1] + 2*D[i] + 2*D[i-2]\n B[i] = A[i-1] + B[i-2] + C[i-2] + D[i-1]\n C[i] = C[i-2] + 2*D[i-1]\n ... | {"fn_name": "three_by_n", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5993dcfca6a7632807000017 |
def three_by_n(n):
|
1,793 | If you like cryptography and playing cards, have also a look at the kata [Card-Chameleon, a Cipher with Playing cards](http://www.codewars.com/kata/card-chameleon-a-cipher-with-playing-cards).
As a secret agent, you need a method to transmit a message to another secret agent. But an encrypted text written on a noteb... | ["from math import factorial as fac\ncards = [\n \"AC\", \"2C\", \"3C\", \"4C\", \"5C\", \"6C\", \"7C\", \"8C\", \"9C\", \"TC\", \"JC\", \"QC\", \"KC\",\n \"AD\", \"2D\", \"3D\", \"4D\", \"5D\", \"6D\", \"7D\", \"8D\", \"9D\", \"TD\", \"JD\", \"QD\", \"KD\",\n \"AH\", \"2H\", \"3H\", \"4H\", \"5H\", \"6H\", \"... | {"fn_name": "encode", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/59b9a92a6236547247000110 |
def encode(self, message):
|
1,795 | This is a classic needing (almost) no further introduction.
Given a N x N chess board, place N queens on it so none can attack another: I.e. no other queens can be found horizontally, vertically or diagonally to the current.
On the board below, no further queens can be positioned.
+-+-+
|Q| |
+-+-+
| | |
+-+-+
In t... | ["def nQueen(n):\n if n==2 or n==3: return []\n r, odds, evens = n%6, list(range(1,n,2)), list(range(0,n,2))\n if r==2:\n evens[:2] = evens[:2][::-1]\n evens.append(evens.pop(2))\n if r==3:\n odds.append(odds.pop(0))\n evens.extend(evens[:2])\n del evens[:2]\n return od... | {"fn_name": "nQueen", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/52cdc1b015db27c484000031 |
def nQueen(n):
|
1,796 | Construct a function that, when given a string containing an expression in infix notation, will return an identical expression in postfix notation.
The operators used will be `+`, `-`, `*`, `/`, and `^` with standard precedence rules and left-associativity of all operators but `^`.
The operands will be single-digit i... | ["def to_postfix (infix):\n prec = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3, '(': 0}\n postfix = []\n stack = []\n for ch in infix:\n if ch in '0123456789':\n postfix.append(ch)\n elif ch in '(':\n stack.append(ch)\n elif ch in ')':\n while stack and stac... | {"fn_name": "to_postfix ", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/52e864d1ffb6ac25db00017f |
def to_postfix (infix):
|
1,797 | A *[Hamming number][1]* is a positive integer of the form 2*i*3*j*5*k*, for some non-negative integers *i*, *j*, and *k*.
Write a function that computes the *n*th smallest Hamming number.
Specifically:
- The first smallest Hamming number is 1 = 2^(0)3^(0)5^(0)
- The second smallest Hamming number is 2 = 2^(1)3^... | ["def hamming(n):\n bases = [2, 3, 5]\n expos = [0, 0, 0]\n hamms = [1]\n for _ in range(1, n):\n next_hamms = [bases[i] * hamms[expos[i]] for i in range(3)]\n next_hamm = min(next_hamms)\n hamms.append(next_hamm)\n for i in range(3):\n expos[i] += int(next_hamms[i] ==... | {"fn_name": "hamming", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/526d84b98f428f14a60008da |
def hamming(n):
|
1,798 | Given a 2D array and a number of generations, compute n timesteps of [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).
The rules of the game are:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbou... | ["def get(cells, i, j):\n return cells[i][j] if i > -1 and j > -1 and i < len(cells) and j < len(cells[0]) else 0\n\ndef num_neighbors(cells, i, j):\n return (get(cells, i, j+1) + get(cells, i, j-1) + get(cells, i+1, j) +\n get(cells, i-1, j) + get(cells, i-1, j-1) + get(cells, i-1, j+1) +\n get(cel... | {"fn_name": "get_generation", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/52423db9add6f6fc39000354 |
def get_generation(cells, gen):
|
1,799 | Based on the well known ['Eight Queens' problem](https://en.wikipedia.org/wiki/Eight_queens_puzzle).
#### Summary
Your challenge is to place N queens on a chess board such that none of the queens are attacking each other.
#### Details
A standard 8x8 chess board has its rows (aka ranks) labelled 1-8 from bottom to top... | ["def queens(fixQ, S):\n \n def areClashing(i,x):\n j,y = qs[i],qs[x]\n return j==y or abs(i-x)==abs(j-y)\n \n def dfs(i=0):\n if i==iQ: return dfs(i+1)\n if i==len(qs): return 1\n \n for y in range(S):\n qs[i]=y\n if ( not any(areClashing... | {"fn_name": "queens", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/561bed6a31daa8df7400000e |
def queens(position, size):
|
1,801 | # Esolang Interpreters #3 - Custom Paintfuck Interpreter
## About this Kata Series
"Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were al... | ["def interpreter(code, iterations, width, height):\n code = \"\".join(c for c in code if c in \"[news]*\")\n canvas = [ [0] * width for _ in range(height) ]\n row = col = step = count = loop = 0\n \n while step < len(code) and count < iterations:\n command = code[step]\n \n if loop:... | {"fn_name": "interpreter", "inputs": [], "outputs": []} | interview | https://www.codewars.com/kata/5868a68ba44cfc763e00008d |
def interpreter(code, iterations, width, height):
|
1,980 | Design a Skiplist without using any built-in libraries.
A Skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists are just si... | ["class Skiplist:\n def __init__(self):\n self.skip_list={}\n \n\n def search(self, target: int) -> bool:\n if(target in self.skip_list):\n if(self.skip_list[target]>0):\n return True\n return False\n \n\n def add(self, num: int) -> None:\n if... | interview | https://leetcode.com/problems/design-skiplist/ |
class Skiplist:
def __init__(self):
def search(self, target: int) -> bool:
def add(self, num: int) -> None:
def erase(self, num: int) -> bool:
# Your Skiplist object will be instantiated and called as such:
# obj = Skiplist()
# param_1 = obj.search(target)
# obj.add(num)
# param_3 = obj.erase(num) | |
2,019 | One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play a_{i} rounds. What is the minimum numb... | ["n = int(input())\na = list(map(int, input().split()))\nr = n-2\nfor d in a:\n r += d\nprint(max(max(a), r//(n-1)))\n", "n = int(input())\nA = list(map(int, input().split()))\n\nans = (sum(A) + (n - 2)) // (n - 1)\nif (ans < max(A)):\n\tans = max(A)\nprint(ans)", "from math import ceil\nn = int (input())\na = list ... | {
"inputs": [
"3\n3 2 2\n",
"4\n2 2 2 2\n",
"7\n9 7 7 8 8 7 8\n",
"10\n13 12 10 13 13 14 10 10 12 12\n",
"10\n94 96 91 95 99 94 96 92 95 99\n",
"100\n1 555 876 444 262 234 231 598 416 261 206 165 181 988 469 123 602 592 533 97 864 716 831 156 962 341 207 377 892 51 866 96 757 317 832 476 549 4... | competition | https://codeforces.com/problemset/problem/348/A | |
2,040 | Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area.
Formally, the carrot can be viewed as an isosceles triangl... | ["n, h = map(int,input().split())\nunit = h*h/n\nfor i in range(1,n):\n print((unit*i)**0.5, end=' ')", "from math import sqrt\n\nn, h = map(int, input().split(' '))\n\nfor i in range(1, n):\n r = h*sqrt(i/n)\n print(str(r), end=\" \")", "n, h = map(int, input().split())\ns = ''\nfor i in range(1, n):\n\ts += ... | {"inputs": ["3 2\n", "2 100000\n", "2 1\n", "20 17\n", "2 5713\n", "4 31901\n", "4 23850\n", "4 72694\n", "4 21538\n", "4 70383\n", "5 1\n", "5 1\n", "5 1\n", "5 1\n", "5 1\n", "20 1\n"], "outputs": ["1.154700538379 1.632993161855\n", "70710.678118654752\n", "0.707106781187\n", "3.801315561750 5.375872022286 6.58407168... | competition | https://codeforces.com/problemset/problem/794/B | |
2,089 | Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an... | ["from operator import __or__, __and__, __xor__\nfrom sys import stdin, stdout\nn, b, c = int(stdin.readline()), 0, 1023\nm = {'|': __or__, '&': __and__, '^': __xor__}\nfor i in range(n):\n t, v = [i for i in stdin.readline().split()]\n b = m[t](b, int(v))\n c = m[t](c, int(v))\nx, o, a = 0, 0, 1023\nfor i in ... | {
"inputs": [
"3\n| 3\n^ 2\n| 1\n",
"3\n& 1\n& 3\n& 5\n",
"3\n^ 1\n^ 2\n^ 3\n",
"2\n| 999\n^ 689\n",
"3\n& 242\n^ 506\n^ 522\n",
"2\n| 56\n^ 875\n",
"3\n^ 125\n^ 377\n& 1019\n",
"1\n& 123\n",
"1\n| 123\n",
"1\n^ 123\n",
"10\n^ 218\n& 150\n| 935\n& 61\n| 588\n& 897\n| 411\n|... | competition | https://codeforces.com/problemset/problem/878/A | |
2,142 | Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation.
For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative ... | ["n=int(input())\na=[]\nfor i in range(n):\n a.append(list(map(int,input().split())))\nans = [0]*n\nfor i in range(n):\n for j in range(n):\n if j!=i:\n ans[i] |= a[i][j]\n print(ans[i],end = ' ')\n", "n = int(input())\np = [0] * n\nfor i in range(n):\n t = list(map(int, input().split()))\n t.pop(i)\n ... | {
"inputs": [
"1\n-1\n",
"3\n-1 18 0\n18 -1 0\n0 0 -1\n",
"4\n-1 128 128 128\n128 -1 148 160\n128 148 -1 128\n128 160 128 -1\n",
"5\n-1 0 0 0 0\n0 -1 1 0 0\n0 1 -1 0 0\n0 0 0 -1 0\n0 0 0 0 -1\n",
"6\n-1 1835024 1966227 34816 68550800 34832\n1835024 -1 18632728 306185992 324272924 289412624\n196622... | competition | https://codeforces.com/problemset/problem/245/D | |
2,200 | Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realiz... | ["import sys\ninput = sys.stdin.readline \n\n\nn = int(input())\na = list(map(int, input().split()))\nb = a\n\nans = 0\nfor k in range(29):\n a0 = []\n a1 = []\n a0a = a0.append\n a1a = a1.append\n \n b0 = []\n b1 = []\n b0a = b0.append\n b1a = b1.append\n for i in a:\n if i&(1<<k):... | {
"inputs": [
"2\n1 2\n",
"3\n1 2 3\n",
"2\n1 1\n",
"100\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 8... | competition | https://codeforces.com/problemset/problem/1322/B | |
2,281 | Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value a_{i}. The root of the tree is node 1.
This tree has a special property: when a value val is added to a value of node i, the value -val ... | ["class BIT():\n \"\"\"\u533a\u9593\u52a0\u7b97\u3001\u4e00\u70b9\u53d6\u5f97\u30af\u30a8\u30ea\u3092\u305d\u308c\u305e\u308cO(logN)\u3067\u5fdc\u3048\u308b\u30c7\u30fc\u30bf\u69cb\u9020\u3092\u69cb\u7bc9\u3059\u308b\n add: \u533a\u9593[begin, end)\u306bval\u3092\u52a0\u3048\u308b\n get_val: i\u756a\u76ee(0-in... | {
"inputs": [
"5 5\n1 2 1 1 2\n1 2\n1 3\n2 4\n2 5\n1 2 3\n1 1 2\n2 1\n2 2\n2 4\n",
"10 10\n137 197 856 768 825 894 86 174 218 326\n7 8\n4 7\n8 9\n7 10\n1 2\n2 4\n3 6\n3 5\n2 3\n1 9 624\n2 1\n2 4\n1 6 505\n1 8 467\n1 3 643\n2 1\n1 8 631\n2 4\n1 7 244\n",
"10 10\n418 45 865 869 745 901 177 773 854 462\n4 8\... | competition | https://codeforces.com/problemset/problem/383/C | |
2,352 | Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>]
where: <protocol> can equal either "http" (without the quotes) or "ftp" (without the quote... | ["s=\"\"\nL=[]\ns=input()\nk=0\nr=0\nc=0\nif s[0]=='h':\n L.append('http://')\n c=4\n s=s[c:]\nelif s[0]=='f':\n L.append('ftp://')\n c=3\n s=s[c:]\nr=s.find('ru',1)\nL.append(s[:r])\nL.append('.ru')\n\nk=r+2\n\nif k<len(s):\n L.append('/')\n L.append(s[k:])\n \nprint(''.join(L))\n\n", "s=\"\"... | {
"inputs": [
"httpsunrux\n",
"ftphttprururu\n",
"httpuururrururruruurururrrrrurrurrurruruuruuu\n",
"httpabuaruauabbaruru\n",
"httpuurrruurruuruuruuurrrurururuurruuuuuuruurr\n",
"httpruhhphhhpuhruruhhpruhhphruhhru\n",
"httpftprftprutprururftruruftptp\n",
"httpfttpftpfttftpftpftppfrurur... | competition | https://codeforces.com/problemset/problem/245/B | |
2,354 | As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.
Mu-mu's enemy Kashtanka wants to unlock Mu-mu's p... | ["s = input()\nn = int(input())\na = [input() for i in range(n)]\nfor i in range(n):\n for j in range(n):\n if a[i] == s or a[i][1] + a[j][0] == s:\n print(\"YES\")\n return\nprint(\"NO\")\n", "pas = input()\ncount = int(input())\nwords = [input() for i in range(count)]\n\nif pas in word... | {
"inputs": [
"ya\n4\nah\noy\nto\nha\n",
"hp\n2\nht\ntp\n",
"ah\n1\nha\n",
"bb\n4\nba\nab\naa\nbb\n",
"bc\n4\nca\nba\nbb\ncc\n",
"ba\n4\ncd\nad\ncc\ncb\n",
"pg\n4\nzl\nxs\ndi\nxn\n",
"bn\n100\ndf\nyb\nze\nml\nyr\nof\nnw\nfm\ndw\nlv\nzr\nhu\nzt\nlw\nld\nmo\nxz\ntp\nmr\nou\nme\npx\nvp\ne... | competition | https://codeforces.com/problemset/problem/868/A | |
2,661 | A marine themed rival site to Codewars has started. Codwars is advertising their website all over the internet using subdomains to hide or obfuscate their domain to trick people into clicking on their site.
Your task is to write a function that accepts a URL as a string and determines if it would result in an http req... | ["import re\n\ndef find_codwars(url):\n return bool(re.match(r''\n '^(https?://)?' # http(s)://\n '([a-z]+\\.)*' # subdomains\n 'codwars\\.com' # codwars.com\n '([/?].*)?$' # directories or querystrings\n , url))", "import re\ndef find_codwars(url):\n domain = url.... | {"fn_name": "find_codwars", "inputs": [["codwars.com"], ["http://codwars.com"], ["http://kcodwars.com"], ["https://www.codwars.com"], ["https://www.codwars.com/kata"], ["codewars.com.codwars.com"], ["https://www.codwars.com/kata?this=is&a=querystring"], ["https://this.is.an.unneccesarily.long.subdomain.codwars.com/kata... | introductory | https://www.codewars.com/kata/5967a67c8b0fc0093e000062 |
def find_codwars(url):
|
2,664 | In this Kata, you will check if it is possible to convert a string to a palindrome by changing one character.
For instance:
```Haskell
solve ("abbx") = True, because we can convert 'x' to 'a' and get a palindrome.
solve ("abba") = False, because we cannot get a palindrome by changing any character.
solve ("abcba") ... | ["def solve(s):\n v = sum(s[i] != s[-1-i] for i in range((len(s))//2) )\n return v == 1 or not v and len(s)%2", "solve=lambda s:any(s[:y]+c+s[y+1:]==(s[:y]+c+s[y+1:])[::-1]!=s for y,x in enumerate(s)for c in set(s))", "def solve(s):\n d = sum(1 for i in range(len(s) // 2) if s[i] != s[-i-1])\n return d == 1... | {"fn_name": "solve", "inputs": [["abba"], ["abbaa"], ["abbx"], ["aa"], ["ab"], ["abcba"]], "outputs": [[false], [true], [true], [false], [true], [true]]} | introductory | https://www.codewars.com/kata/5a66ea69e6be38219f000110 |
def solve(s):
|
2,669 | Consider the following series:
`1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, 108, 116, 122`
It is generated as follows:
* For single digit integers, add the number to itself to get the next element.
* For other integers, multiply all the non-zero digits and add the result to the original number to get the next elem... | ["from operator import mul\nfrom functools import reduce\n\ndef genSequence(n):\n yield n\n while True:\n n += reduce(mul, [int(d) for d in str(n) if d != '0']) if n > 9 else n\n yield n\n\ndef extract(seq, v):\n return sorted(seq).index(v)\n\ndef convergence(n):\n gen1, genN = genSequence(1),... | {"fn_name": "convergence", "inputs": [[3], [5], [10], [15], [500], [5000]], "outputs": [[5], [6], [5], [2], [29], [283]]} | introductory | https://www.codewars.com/kata/59971e64bfccc70748000068 |
def convergence(n):
|
2,670 | # Task
Get the digits sum of `n`th number from the [Look-and-Say sequence](http://en.wikipedia.org/wiki/Look-and-say_sequence)(1-based).
`1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ...`
# Input/Output
`[input]` integer `n`
`n`th number in the sequence to get where `1 <= n <= 55` and `n=1 is "1"`.
[out... | ["def look_and_say_and_sum(N):\n l=[1]\n for n in range(N-1):\n result = [1,l[0]]\n for i in range(1,len(l)):\n if l[i]==result[-1]:\n result[-2] += 1\n else:\n result += [1,l[i]] \n l=result\n return sum(l)\n", "def look_and_say_and_sum(... | {"fn_name": "look_and_say_and_sum", "inputs": [[1], [2], [3], [4], [5]], "outputs": [[1], [2], [3], [5], [8]]} | introductory | https://www.codewars.com/kata/5922828c80a27c049c000078 |
def look_and_say_and_sum(n):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.