problem_id
stringlengths 32
32
| name
stringclasses 1
value | problem
stringlengths 200
14k
| solutions
stringlengths 12
1.12M
| test_cases
stringlengths 37
74M
| difficulty
stringclasses 3
values | language
stringclasses 1
value | source
stringclasses 7
values | num_solutions
int64 12
1.12M
| starter_code
stringlengths 0
956
|
---|---|---|---|---|---|---|---|---|---|
25cdc3b6f481ef52a6ab1ff2532692c6 | UNKNOWN | You have to create a function named reverseIt.
Write your function so that in the case a string or a number is passed in as the data , you will return the data in reverse order. If the data is any other type, return it as it is.
Examples of inputs and subsequent outputs:
```
"Hello" -> "olleH"
"314159" -> "951413"
[1,2,3] -> [1,2,3]
``` | ["def reverse_it(data):\n if type(data) in [int, str, float]:\n return type(data)(str(data)[::-1])\n return data", "def reverse_it(data):\n t = type(data)\n return t(''.join(reversed(str(data)))) if t in [str, int, float] else data", "def reverse_it(data):\n return data if any(t is type(data) for t in [dict, bool, list]) else type(data)(str(data)[::-1])", "def reverse_it(data):\n t = type(data)\n if t not in (str, float, int):\n return data\n return t(str(data)[::-1])", "def reverse_it(data):\n return (type(data)(str(data)[::-1])) if isinstance(data, (str, int, float)) else data", "def reverse_it(data):\n return data[::-1] if isinstance(data, str) else int(str(data)[::-1]) if isinstance(data, int) and not isinstance(data, bool) else float(str(data)[::-1]) if isinstance(data, float) else data", "def reverse_it(data):\n if type(data) == str: return data[::-1]\n elif type(data) == int: return int(str(data)[::-1])\n elif type(data) == float: return float(str(data)[::-1])\n else: return data", "def reverse_it(data):\n return type(data)(str(data)[::-1]) if type(data) in (str, int, float) else data", "def reverse_it(data):\n if type(data) == str:\n string = data[::-1]\n return string\n elif type(data) == int:\n integer = int(str(data)[::-1])\n return integer\n elif type(data) == float:\n floater = float(str(data)[::-1])\n return floater\n elif type(data) == abs:\n abso = abs(str(data)[::-1])\n return floater\n else:\n return data\n \nreverse_it(\"Hello\")\nreverse_it(12345)\nreverse_it(1231.123213)\nreverse_it([1,2,3,4])\n\n\n\n"] | {"fn_name": "reverse_it", "inputs": [["Hello"], [314159], ["314159"], [[]], [{}], [true], [[1, 2, 3]]], "outputs": [["olleH"], [951413], ["951413"], [[]], [{}], [true], [[1, 2, 3]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,685 |
def reverse_it(data):
|
6ae153e087deb48843f00becd9da8f68 | UNKNOWN | Every positive integer number, that is not prime, may be decomposed in prime factors. For example the prime factors of 20, are:
```
2, 2, and 5, because: 20 = 2 . 2 . 5
```
The first prime factor (the smallest one) of ```20``` is ```2``` and the last one (the largest one) is ```5```. The sum of the first and the last prime factors, ```sflpf``` of 20 is: ```sflpf = 2 + 5 = 7```
The number ```998 ```is the only integer in the range ```[4, 1000]``` that has a value of ```501``` , so its ```sflpf``` equals to 501, but in the range ```[4, 5000]``` we will have more integers with ```sflpf = 501``` and are: ```998, 1996, 2994, 3992, 4990```.
We need a function ```sflpf_data()``` (javascript: ```sflpfData()```that receives two arguments, ```val``` as the value of sflpf and ```nMax``` as a limit, and the function will output a sorted list of the numbers between ```4``` to ```nMax```(included) that have the same value of sflpf equals to ```val```.
Let's see some cases:
```python
sflpf_data(10, 100) == [21, 25, 63]
/// the prime factorization of these numbers are:
Number Prime Factorization Sum First and Last Prime Factor
21 = 3 . 7 ----> 3 + 7 = 10
25 = 5 . 5 ----> 5 + 5 = 10
63 = 3 . 3 . 7 ----> 3 + 7 = 10
```
```python
sflpf_data(10, 200) == [21, 25, 63, 105, 125, 147, 189]
sflpf_data(15, 150) == [26, 52, 78, 104, 130]
```
(Advice:Try to discard primes in a fast way to have a more agile code)
Enjoy it! | ["def sflpf_data(val, nMax):\n r=[]\n for i in range(2,nMax):\n fac=primef(i)\n if len(fac)>1 and fac[0]+fac.pop()==val: r.append(i) \n return r\n \ndef primef(n):\n i= 2; f= []\n while i*i<=n:\n if n%i: i+=1\n else: n//=i; f.append(i)\n if n>1: f.append(n)\n return f", "def sflpf_data(val, limit):\n result = []\n for n in range(4, limit+1):\n factors = prime_factors(n)\n if len(factors) > 1 and min(factors) + max(factors) == val:\n result.append(n)\n return result\n\ndef prime_factors(n):\n factors = []\n while not n % 2:\n factors.append(2)\n n = n // 2\n while not n % 3:\n factors.append(3)\n n = n // 3\n k = 5\n step = 2\n while k <= n**0.5:\n if not n % k:\n factors.append(k)\n n = n // k\n else:\n k = k + step\n step = 6 - step\n factors.append(n)\n return factors\n", "def sflpf_data(val, nMax):\n #your code here\n #your code here\n prime = [2,3]\n result = []\n head = 1\n tail = 0\n for i in range(4,nMax):\n i_temp = i\n for j in prime :\n if i == 1 or j > val :\n break\n while i % j == 0 :\n i /= j\n if head == 0 :\n head = j\n tail = j\n if i == 1 :\n if head + tail == val :\n result.append(i_temp)\n else :\n prime.append(i_temp)\n head = 0\n return result", "import itertools\ndef sflpf(n):\n f = 2\n l = []\n increments = itertools.chain([1,2,2], itertools.cycle([4,2,4,2,4,6,2,6]))\n for incr in increments:\n if f*f > n:\n break\n while n % f == 0:\n l.append(f)\n n //= f\n f += incr\n if n > 1:\n l.append(n)\n return min(l) + max(l) if len(l) > 1 else 0 \n \ndef sflpf_data(val, nMax):\n return [i for i in range(4, nMax + 1) if sflpf(i) == val]\n", "def sflpf(n):\n i = 2\n first = True\n small = 0\n large = 0\n while i*i <= n:\n while n % i == 0:\n large = i\n if first:\n small = i\n first = False\n n /= i\n i += 1\n if small:\n return small + max(large, n)\n else:\n return 0\n \n\nsflpf_of = [sflpf(i) for i in range(1, 2*10**4)]\n\ndef sflpf_data(val, n):\n return [x for x in range(1, n+1) if sflpf_of[x-1] == val]\n", "def sflpf_data(a,b):\n lis=[]\n for i in range(2,b+1):\n temp=i\n con=2\n if temp==1:\n lis.append(1)\n else:\n lis1=[]\n while temp>1:\n while temp%con==0:\n lis1.append(con)\n temp//=con\n con+=1\n if con*con>temp:\n if temp>1:lis1.append(temp)\n break\n con=lis1[0]+lis1[len(lis1)-1]\n if con==a and (len(lis1)!=1 ):\n lis.append(i)\n return lis"] | {"fn_name": "sflpf_data", "inputs": [[10, 100], [10, 200], [15, 150], [501, 1000], [501, 5000]], "outputs": [[[21, 25, 63]], [[21, 25, 63, 105, 125, 147, 189]], [[26, 52, 78, 104, 130]], [[998]], [[998, 1996, 2994, 3992, 4990]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,142 |
def sflpf_data(val, nMax):
|
ac891b0231bf6a0a03e80d3754ee7c88 | UNKNOWN | Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.
Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.
Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.
Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.
#### Your Task
Complete the bouncyRatio function.
The input will be the target ratio.
The output should be the smallest number such that the proportion of bouncy numbers reaches the target ratio.
You should throw an Error for a ratio less than 0% or greater than 99%.
**Source**
- https://projecteuler.net/problem=112
**Updates**
- 26/10/2015: Added a higher precision test case. | ["from operator import lt, gt\n\nmemo = {}\nis_bouncy = lambda s: memo[s] if s in memo else memo.setdefault(s, any(map(lt, s[:-1], s[1:])) and any(map(gt, s[:-1], s[1:])))\n\ndef bouncy_ratio(percent):\n if not 0 < percent < 1: raise Exception(\"Wrong percentage: {}\".format(percent))\n x, y = 100, 0\n while y < x*percent:\n x, y = x+1, y+is_bouncy(str(x+1))\n return x", "def bouncy_ratio(percent):\n is_bouncy = lambda n: any(a < b for a, b in zip(n, n[1:])) \\\n and any(a > b for a, b in zip(n, n[1:]))\n n, bouncy = 99, 0\n while bouncy < percent * n:\n n += 1\n bouncy += is_bouncy(str(n))\n return n", "def bouncy_ratio(percent):\n if percent <= 0 or percent >= 99: raise\n bouncy, i = 0, 99\n while float(bouncy) / i < percent:\n i += 1\n bouncy += sum(any(f(a, b) for a, b in zip(str(i), str(i)[1:])) for f in [lambda x, y: x > y, lambda x, y: x < y]) == 2\n return i", "def bouncy_ratio(target):\n bouncy = 0.0\n n = 100\n \n while bouncy / n < target:\n n += 1\n s = list(str(n))\n s_ = sorted(s)\n if s != s_ and s != s_[::-1]:\n bouncy += 1\n \n return n", "def bouncy_ratio(percent):\n ans = 0\n for i in range(1, 10**10):\n s = str(i)\n res = ''.join(['=' if a == b else '>' if int(a) > int(b) else '<' for a, b in zip(s, s[1:])])\n ans += ('<' in res) and ('>' in res)\n if ans / i >= percent:\n return i", "def bouncy_ratio(percent):\n b=0\n n=1\n while(True):\n s=list(str(n))\n if s!=sorted(s) and s!=sorted(s)[::-1]:\n b+=1\n if float(b)/n>=percent:\n break\n n+=1\n return n", "memo = {}\n\ndef bouncy_ratio(percent):\n if not (0 <= percent <= 0.99): raise ValueError\n b, n = 0.0, 100\n while b / n < percent: \n n += 1\n if is_bouncy(n): b += 1\n return n\n\ndef is_bouncy(n): \n if n in memo: return memo[n]\n s = str(n)\n memo[n] = list(s) != sorted(s) and list(s) != sorted(s, reverse = True)\n \n return memo[n]", "def bouncy_ratio(percent):\n if percent < 0 or percent > 0.99:\n raise Error\n n = 99\n bouncy = 0.0\n while True:\n n += 1\n ns = str(n)\n gaps = [int(ns[i]) - int(ns[i - 1]) for i in range(1, len(ns))]\n if not(all(gap >= 0 for gap in gaps) or all(gap <= 0 for gap in gaps)):\n bouncy += 1.0\n if bouncy / n >= percent:\n return n", "def bouncy_ratio(percent):\n #if percent < 0.1 or percent > 0.9: raise ValueError()\n def check(i):\n d = [int(x) for x in str(i)]\n up, down = False, False\n for k in range(1, len(d)):\n if d[k] > d[k-1]: up = True\n if d[k] < d[k-1]: down = True\n return up and down\n bouncy = 0.0\n for n in range(100, 100000):\n if check(n): bouncy += 1\n if bouncy / n >= percent: return n \n"] | {"fn_name": "bouncy_ratio", "inputs": [[0.1], [0.15], [0.5], [0.75], [0.9]], "outputs": [[132], [160], [538], [3088], [21780]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,006 |
def bouncy_ratio(percent):
|
a3d183134372db10a37115b1bab92cb7 | UNKNOWN | Gematria is an Assyro-Babylonian-Greek system of code and numerology later adopted into Jewish culture. The system assigns numerical value to a word or a phrase in the belief that words or phrases with identical numerical values bear some relation to each other or bear some relation to the number itself. While more commonly used on Hebrew words, there is also an English version.
Each letter has a value and the gematrian value of a word or a phrase is the sum of those values. The code takes a word or an expression and returns the gematrian value of it.
The calculation is case insensitive and counts no spaces.
Example: The gematrian value of "love" is 20+50+700+5 = 775
These are the values of the different letters:
a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, k=10, l=20,
m=30, n=40, o=50, p=60, q=70, r=80, s=90, t=100, u=200,
x=300, y=400, z=500, j=600, v=700, w=900 | ["\n\nTOME = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'k':10, 'l':20, 'm':30, 'n':40, 'o':50, 'p':60, 'q':70, 'r':80, 's':90, 't':100, 'u':200, 'x':300, 'y':400, 'z':500, 'j':600, 'v':700, 'w':900}\n\ndef gematria(s): return sum(TOME.get(c,0) for c in s.lower())", "def gematria(string):\n d = dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, k=10, l=20, m=30, n=40, o=50, p=60, q=70, r=80, s=90, t=100, u=200, x=300, y=400, z=500, j=600, v=700, w=900)\n return sum(d.get(x, 0) for x in string.lower())", "letters = {\n 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'k': 10,\n 'l': 20, 'm': 30, 'n': 40, 'o': 50, 'p': 60, 'q': 70, 'r': 80, 's': 90, 't': 100,\n 'u': 200, 'x': 300, 'y': 400, 'z': 500, 'j': 600, 'v': 700, 'w': 900,\n}\n\ndef gematria(s):\n return sum(letters.get(c, 0) for c in s.lower())", "values = {\"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4, \"e\": 5, \"f\": 6, \"g\": 7, \"h\": 8, \"i\": 9,\n \"k\": 10, \"l\": 20, \"m\": 30, \"n\": 40, \"o\": 50, \"p\": 60, \"q\": 70, \"r\": 80, \"s\": 90,\n \"t\": 100, \"u\": 200, \"x\": 300, \"y\": 400, \"z\": 500, \"j\": 600, \"v\": 700, \"w\": 900}\n\ndef gematria(string):\n return sum(values.get(c, 0) for c in string.lower())", "def gematria(string):\n #your code here\n sum = 0\n string = string.lower()\n num = {'a' : 1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7,' ':0,\n 'h':8, 'i':9, 'k':10, 'l':20, 'm':30, 'n':40, 'o':50, 'p':60, 'q':70, 'r':80,\n 's':90, 't':100, 'u':200, 'x':300, 'y':400, 'z':500, 'j':600, 'v':700, 'w':900}\n for key in string:\n if key in num.keys():\n sum += num[key]\n return sum", "def gematria(string):\n #your code here\n dicts = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9,\n 'k':10, 'l':20, 'm':30, 'n':40, 'o':50, 'p':60, 'q':70, 'r':80, 's':90, \n 't':100, 'u':200, 'x':300, 'y':400, 'z':500, 'j':600, 'v':700, 'w':900}\n sum = 0\n strings = ''.join([x for x in string if x.isalpha()])\n for c in str.lower(strings):\n sum += dicts[c]\n return sum\n", "gematria = lambda s, d=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, k=10, l=20, m=30, n=40, o=50, p=60, q=70, r=80, s=90, t=100, u=200, x=300, y=400, z=500, j=600, v=700, w=900): sum(map(d.get, filter(str.islower, s.lower())))", "from string import ascii_lowercase\ndef gematria(strng):\n values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 600, 10, 20, 30, 40, 50, 60 , 70, 80, 90, 100, 200, 700, 900, 300, 400, 500]\n alphabet_values = { letter:num for num,letter in zip(values, ascii_lowercase) }\n return sum([alphabet_values[letter] if letter in ascii_lowercase else 0 for letter in strng.lower()])", "D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'k':10, 'l':20, 'm':30, \n 'n':40, 'o':50, 'p':60, 'q':70, 'r':80, 's':90, 't':100, 'u':200, 'x':300, 'y':400, 'z':500, 'j':600, 'v':700, 'w':900}\n \ndef gematria(s):\n return sum(D.get(c, 0) for c in s.lower())", "gematria=lambda s,D=dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, k=10, l=20, m=30, n=40, o=50, p=60, q=70, r=80, s=90, t=100, u=200, x=300, y=400, z=500, j=600, v=700, w=900):sum(D.get(k,0)for k in s.lower())"] | {"fn_name": "gematria", "inputs": [["love"], ["jaels"], ["JAELS"], ["Devil"], ["Coding is fun"]], "outputs": [[775], [716], [716], [738], [458]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,248 |
def gematria(string):
|
95cd4d8cd2202f779e3e1e43412aba28 | UNKNOWN | Ever the learned traveller, Alan Partridge has pretty strong views on London:
```
"Go to London. I guarantee you'll either be mugged or not appreciated.
Catch the train to London, stopping at Rejection, Disappointment, Backstabbing Central and Shattered Dreams Parkway."
```
Your job is to check that the provided list of stations contains all of the stops Alan mentions. There will be other stations in the array. Example:
```
['Rejection', 'Disappointment', 'Backstabbing Central', 'Shattered Dreams Parkway']
```
If the stations all appear, return 'Smell my cheese you mother!', if not, return 'No, seriously, run. You will miss it.'.
Other katas in this series:
Alan Partridge I - Partridge Watch
Alan Partridge II - Apple Turnover | ["def alan(arr):\n s = {'Rejection', 'Disappointment', 'Backstabbing Central', 'Shattered Dreams Parkway'}\n return \"Smell my cheese you mother!\" if s.issubset(arr) else \"No, seriously, run. You will miss it.\"", "def alan(arr):\n a = ['Rejection', 'Disappointment', 'Backstabbing Central', 'Shattered Dreams Parkway']\n for i in a:\n if i not in arr:\n return \"No, seriously, run. You will miss it.\"\n return \"Smell my cheese you mother!\"", "def alan(arr):\n stations = {'Rejection', 'Disappointment', 'Backstabbing Central',\n 'Shattered Dreams Parkway'}\n if stations.issubset(arr):\n return 'Smell my cheese you mother!'\n return 'No, seriously, run. You will miss it.'\n", "def alan(arr):\n return 'Smell my cheese you mother!' if len(set(arr).intersection(['Rejection', 'Disappointment', 'Backstabbing Central', 'Shattered Dreams Parkway'])) == 4 else 'No, seriously, run. You will miss it.'", "def alan(arr):\n a = ['Rejection','Disappointment','Backstabbing Central','Shattered Dreams Parkway']\n s = 0\n r = 0\n d = 0\n b = 0\n sd = 0\n for x in arr:\n for y in a:\n if x == y:\n s += 1\n if y == 'Rejection':\n r += 1\n elif y == 'Disappointment':\n d += 1\n elif y == 'Backstabbing Central':\n b += 1\n else:\n sd += 1\n if s >= 4 and r>0 and d>0 and b>0 and sd>0:\n return 'Smell my cheese you mother!'\n else:\n return 'No, seriously, run. You will miss it.'\n", "stops = {'Rejection', 'Disappointment', 'Backstabbing Central', 'Shattered Dreams Parkway'}\n\ndef alan(lst):\n return \"No, seriously, run. You will miss it.\" if (stops - set(lst)) else \"Smell my cheese you mother!\"", "alan = lambda l: 'Smell my cheese you mother!' if 'Rejection' in l and 'Disappointment' in l and 'Backstabbing Central' in l and 'Shattered Dreams Parkway' in l else 'No, seriously, run. You will miss it.'", "alan=lambda a,s={ \"Shattered Dreams Parkway\",\n \"Backstabbing Central\",\n \"Disappointment\",\n \"Rejection\",\n \"Norwich\",\n\"London\"}:( 'No, seriously, run. You will miss it.',\n\n 'Smell my cheese you mother!' )[set(a)&s==s]", "def alan(arr):\n return 'Smell my cheese you mother!' if all(i in arr for i in ['Rejection', 'Disappointment', 'Backstabbing Central', 'Shattered Dreams Parkway']) else 'No, seriously, run. You will miss it.'", "def alan(arr):\n stops = ['Rejection', 'Disappointment', 'Backstabbing Central', 'Shattered Dreams Parkway']\n counter = 0\n \n for i in stops:\n if i in arr:\n counter += 1\n \n if counter == len(stops):\n return \"Smell my cheese you mother!\"\n return \"No, seriously, run. You will miss it.\""] | {"fn_name": "alan", "inputs": [[["Norwich", "Rejection", "Disappointment", "Backstabbing Central", "Shattered Dreams Parkway", "London"]], [["London", "Norwich"]], [["Norwich", "Tooting", "Bank", "Rejection", "Disappointment", "Backstabbing Central", "Exeter", "Shattered Dreams Parkway", "Belgium", "London"]], [["London", "Shattered Dreams Parkway", "Backstabbing Central", "Disappointment", "Rejection", "Norwich"]]], "outputs": [["Smell my cheese you mother!"], ["No, seriously, run. You will miss it."], ["Smell my cheese you mother!"], ["Smell my cheese you mother!"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,072 |
def alan(arr):
|
5c66c0c2bba166a8cce8acd5a2b3d68c | UNKNOWN | Imagine a funnel filled with letters. The bottom letter drops out of the funnel and onto a conveyor belt:
```
\b,c/ --> \b,c/
\a/ --> \ /
a
------- -------
```
If there are two letters above a gap, the smaller letter falls into the gap.
```
\b,c/ --> \ c/
\ / --> \b/
a a
------- -------
```
Of course, this can create a new gap, which must also be filled in the same way:
```
\f,e,d/ --> \f, ,d/
\ c/ --> \e,c/
\b/ \b/
a a
------- -------
```
Once all the gaps above it have been filled, the bottom letter drops out of the funnel and onto the conveyorbelt. The process continues until all letters have fallen onto the conveyor. (New letters fall onto the end of the existing string)
**KATA GOAL: Return the string on the conveyorbelt after all letters have fallen**.
```
\f, ,d/ \f, ,d/ --> etc --> \ /
\e,c/ \e,c/ --> etc --> \ /
\b/ --> \ / --> etc --> \ /
a a b abcdef
------- ------- -------
```
All letters in the funnel will be unique i.e. in every comparison one letter will be strictly smaller than the other. The funnel will be presented as a nested list, e.g:
```
[["d","a","c"],
["b","e"],
["f"]]
```
The value of a letter is defined by its codepoint. Note: this means all capital letters are defined as smaller than all lower-case letters, but your language's comparison operator will probably treat it that way automatically.
The funnels will always be "nice" -- every layer will have 1 item more than the layer below, and every layer will be full, and generally there's no funny business or surprises to consider. The only characters used are standard uppercase and lowercase letters A-Z and a-z. The tests go up to 9 layer funnel.
### Fully Worked Example
```
\d,a,c/ \d,a,c/ \d,a,c/ --> \d c/
\b,e/ \b,e/ --> \ e/ --> \a,e/
\f/ --> \ / --> \b/ \b/ -->
f f f
------ ------- ------- -------
\d c/ \d c/ --> \ c/ \ c/
\a,e/ --> \ e/ --> \d,e/ \d,e/ -->
\ / --> \a/ \a/ --> \ / -->
f b fb fb fb a
------ ------- ------- -------
\ c/ \ c/ \ c/ --> \ /
\ e/ \ e/ --> \ / --> \ c/
\d/ --> \ / --> \e/ \e/ -->
fba fba d fbad fbad
------- ------- -------- -------
\ / \ / \ /
\ c/ --> \ / \ /
\ / \c/ --> \ /
fbad e fbade fbadec
------- ------- -------
DONE. Return "fbadec".
```
**For a bigger funneling challenge, check out [this kata](https://www.codewars.com/kata/create-a-funnel) by @myjinxin2015.** | ["def funnel_out(funnel):\n r=\"\"\n h=len(funnel)\n while funnel[h-1][0]!=\"~\":\n r+=funnel[h-1][0]\n funnel[h-1][0]=\"~\"\n i=h-1\n j=0\n while i>0:\n if funnel[i-1][j] < funnel[i-1][j+1]:\n funnel[i][j]=funnel[i-1][j]\n funnel[i-1][j]=\"~\"\n else:\n funnel[i][j]=funnel[i-1][j+1]\n funnel[i-1][j+1]=\"~\"\n j+=1\n i-=1\n print(funnel)\n return r", "def funnel_out(funnel):\n if not funnel: return \"\"\n ret = []\n while funnel[-1][-1]:\n j = 0\n ret.append(funnel[-1][j])\n funnel[-1][j] = None\n for i in range(-2, -len(funnel)-1, -1):\n _, k = min((funnel[i][x] or \"\\xff\", x) for x in (j, j+1))\n funnel[i+1][j], funnel[i][k], j = funnel[i][k], funnel[i+1][j], k\n return ''.join(ret)", "def pull_letter(funnel):\n letter = funnel[0][0]\n funnel[0][0] = None\n pos = 0\n \n for idx, level in enumerate(funnel[:-1]): \n current_pos = pos\n \n c1 = funnel[idx+1][pos]\n c2 = funnel[idx+1][pos+1]\n if c1 is None or (c2 is not None and c1 >= c2):\n pos += 1\n \n level[current_pos] = funnel[idx+1][pos]\n funnel[idx+1][pos] = None\n \n return letter\n\n\ndef funnel_out(funnel):\n funnel = list(reversed(funnel))\n result = ''\n\n while funnel[0][0]:\n result += pull_letter(funnel)\n \n return result\n", "def drop(p):\n p[0][0]=''; x=0;\n for y in range(1,len(p)):\n dx = 1 if not p[y][x] else 0 if not p[y][x+1] else 1 if p[y][x+1]<p[y][x] else 0\n p[y-1][x]=p[y][x+dx]; x+=dx\n p[-1][x]=''\n\ndef funnel_out(funnel):\n s=[]; p=[r[:] for r in reversed(funnel)]\n while p[0][0]: s.append(p[0][0]); drop(p)\n return ''.join(s)", "from copy import deepcopy\n\ndef funnel_out(funnel):\n funnel, ans, depth = deepcopy(funnel), [], len(funnel)\n for _ in range(depth*(depth+1)//2):\n \n ans.append(funnel[-1][0]) # Archive current lowest char\n i, funnel[-1][0] = 0, \"~\" # Starting position (i) / erase current char (use \"~\" as empty cell: higher ascii value than any letter)\n \n for d in range(depth-1, 0, -1): # Will swap the current char with the appropriate one from the line above\n iUp = min((i, i+1), key=lambda x: funnel[d-1][x]) # search the lower char index in the above level\n if funnel[d-1][iUp] == \"~\": break # no more chars to swap....\n funnel[d][i], funnel[d-1][iUp] = funnel[d-1][iUp], funnel[d][i] # make the swap\n i = iUp # update thte current column index\n \n return ''.join(ans)", "def funnel_out(funnel):\n break_outs, n = [], len(funnel)\n while len(break_outs) < n*(n+1)/2:\n break_outs.append(funnel[-1][0])\n funnel[-1][0], prev = '~', 0\n for i in range(len(funnel) - 1, 0, -1):\n m = min(funnel[i-1][prev:prev+2])\n index = funnel[i-1].index(m)\n funnel[i-1][index], funnel[i][prev], prev = '~', m, index\n return \"\".join(break_outs)", "def funnel_out(funnel):\n ans = \"\"\n while funnel[-1][0] != \"~\":\n ans += funnel[-1][0]\n i, funnel[-1][0] = 0, \"~\"\n for d in range(len(funnel)-1, 0, -1):\n iUp = min((i, i+1), key=lambda x: funnel[d-1][x])\n funnel[d][i], funnel[d-1][iUp] = funnel[d-1][iUp], funnel[d][i]\n i = iUp\n return ans", "def funnel_out(lst):\n ans = \"\"\n while lst != [[]]:\n temp = []\n for i in range(len(lst)-1, -1, -1):\n x = lst[i]\n x2 = lst[i-1]\n if i == len(lst)-1:\n ans += x[0]\n if len(lst) == 1:\n lst = [[]]\n break\n lst[i] = [min([k for k in x2 if k != \"\"])] if len(lst) > 1 else []\n lst[i-1][x2.index(min([k for k in x2 if k != \"\"]))] = \"\"\n elif i == 0:\n if all(j==\"\" for j in lst[0]):\n lst = lst[1:]\n else:\n break\n else:\n for j in range(len(x)):\n if x[j] == \"\":\n a, b = x2[j], x2[j+1]\n t = [k for k in (a, b) if k != '']\n val = min(t) if t != [] else \"\"\n idx = j if x2[j] == val else j+1\n x[j] = val\n x2[idx] = \"\" \n return ans", "def funnel_out(funnel):\n ans = \"\"\n while funnel:\n ans += funnel[-1].pop()\n funnel[-1].append('\u00b5')\n for row in range(len(funnel) - 1, 0, -1):\n for col in range(len(funnel[row])):\n if funnel[row][col] == '\u00b5':\n if funnel[row - 1][col] < funnel[row - 1][col + 1]:\n funnel[row][col] = funnel[row - 1][col]\n funnel[row - 1][col] = '\u00b5'\n else:\n funnel[row][col] = funnel[row - 1][col + 1]\n funnel[row - 1][col + 1] = '\u00b5'\n if all(en == '\u00b5' for en in funnel[row]):\n del(funnel[row])\n if len(funnel) == 1:\n break\n return ans", "def funnel_out(funnel):\n result, funnel = [], funnel[::-1]\n \n def move(i=0, j=0):\n if i < len(funnel)-1:\n c1, c2 = funnel[i+1][j:j+2]\n if c1 and (not c2 or c1 < c2):\n funnel[i][j] = c1\n return move(i+1, j)\n elif c2 and (not c1 or c2 < c1):\n funnel[i][j] = c2\n return move(i+1, j+1)\n funnel[i][j] = ''\n \n while funnel[0][0]:\n result.append(funnel[0][0])\n move()\n return ''.join(result)"] | {"fn_name": "funnel_out", "inputs": [[[["q"]]], [[["b", "c"], ["a"]]], [[["d", "a", "c"], ["b", "e"], ["f"]]], [[["a", "e", "c", "f"], ["d", "i", "h"], ["j", "g"], ["b"]]]], "outputs": [["q"], ["abc"], ["fbadec"], ["bghcfiejda"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 6,224 |
def funnel_out(funnel):
|
b4c0fa37adcea880b5ea765b3a4d3215 | UNKNOWN | Every now and then people in the office moves teams or departments. Depending what people are doing with their time they can become more or less boring. Time to assess the current team.
```if-not:java
You will be provided with an object(staff) containing the staff names as keys, and the department they work in as values.
```
```if:java
You will be provided with an array of `Person` objects with each instance containing the name and department for a staff member.
~~~java
public class Person {
public final String name; // name of the staff member
public final String department; // department they work in
}
~~~
```
Each department has a different boredom assessment score, as follows:
accounts = 1
finance = 2
canteen = 10
regulation = 3
trading = 6
change = 6
IS = 8
retail = 5
cleaning = 4
pissing about = 25
Depending on the cumulative score of the team, return the appropriate sentiment:
<=80: 'kill me now'
< 100 & > 80: 'i can handle this'
100 or over: 'party time!!'
The Office I - Outed
The Office III - Broken Photocopier
The Office IV - Find a Meeting Room
The Office V - Find a Chair | ["def boredom(staff):\n lookup = {\n \"accounts\": 1,\n \"finance\": 2,\n \"canteen\": 10,\n \"regulation\": 3, \n \"trading\": 6,\n \"change\": 6,\n \"IS\": 8,\n \"retail\": 5,\n \"cleaning\": 4,\n \"pissing about\": 25\n }\n n = sum(lookup[s] for s in staff.values())\n if n <= 80:\n return \"kill me now\"\n if n < 100:\n return \"i can handle this\"\n return \"party time!!\"", "boredom_scores = {\n 'accounts': 1,\n 'finance': 2 ,\n 'canteen': 10 ,\n 'regulation': 3 ,\n 'trading': 6 ,\n 'change': 6,\n 'IS': 8,\n 'retail': 5,\n 'cleaning': 4,\n 'pissing about': 25,\n}\n\ndef boredom(staff):\n score = sum(map(boredom_scores.get, staff.values()))\n return (\n 'kill me now' if score <= 80 else\n 'i can handle this' if score < 100 else\n 'party time!!'\n )", "scores = {\n \"accounts\": 1, \"finance\": 2, \"canteen\": 10, \"regulation\": 3, \"trading\": 6,\n \"change\": 6, \"IS\": 8, \"retail\": 5, \"cleaning\": 4, \"pissing about\": 25\n}\n\ndef boredom(staff):\n score = sum(scores[activity] for activity in staff.values())\n return \"party time!!\" if score >= 100 else \"i can handle this\" if score > 80 else \"kill me now\"", "SCORE={\"accounts\": 1, \"finance\" : 2, \"canteen\" : 10, \"regulation\" : 3, \"trading\" : 6, \n \"change\" : 6, \"IS\" : 8, \"retail\" : 5, \"cleaning\" : 4, \"pissing about\" : 25}\n \ndef boredom(staff):\n score = sum(map(lambda x: SCORE[x], staff.values()))\n return (\"kill me now\", \"i can handle this\", \"party time!!\")[(score>=100) + (score>80)]", "def boredom(staff):\n departments = {'accounts': 1, 'finance': 2, 'canteen': 10, 'regulation': 3, 'trading': 6, 'change': 6, 'IS': 8, 'retail': 5, 'cleaning': 4, 'pissing about': 25}\n score = sum(departments[x] for x in staff.values())\n return 'kill me now' if score <= 80 else 'party time!!' if score > 100 else 'i can handle this'", "def boredom(staff):\n dict_ = {'accounts': 1,\n'finance':2,\n'canteen':10,\n'regulation':3,\n'trading':6,\n'change':6,\n'IS':8,\n'retail':5,\n'cleaning':4,\n'pissing about':25}\n summ = sum(dict_[i] for i in staff.values())\n return \"kill me now\" if summ<=80 else 'i can handle this' if 100>summ>80 else \"party time!!\"", "def boredom(staff):\n scores = {\"accounts\" : 1, \"finance\" : 2, \"canteen\" : 10,\n \"regulation\" : 3, \"trading\" : 6, \"change\" : 6,\n \"IS\" : 8, \"retail\" : 5, \"cleaning\" : 4, \"pissing about\" : 25}\n score = sum(scores[team] for team in staff.values())\n return \"kill me now\" if score <= 80 else \"party time!!\" if score >= 100 else \"i can handle this\"", "boredom=lambda s:['kill me now','i can handle this','party time!!'][min(2,max(0,__import__('math').ceil(sum((' tconig I e'+' '*14+'u').index(e.replace('din','g')[-2])for e in s.values())/20-4)))]", "def boredom(staff):\n D = { 'accounts': 1,\n 'finance': 2,\n 'canteen': 10,\n 'regulation': 3,\n 'trading': 6,\n 'change': 6,\n 'IS': 8,\n 'retail': 5,\n 'cleaning': 4,\n 'pissing about': 25,\n }\n score = sum ( [D[key] for key in list(staff.values())] )\n if score <= 80: ans = 'kill me now'\n elif 80 < score < 100: ans = 'i can handle this'\n elif score >= 100: ans = 'party time!!'\n return ans\n", "def boredom(staff):\n depts = {\"accounts\": 1, \"finance\": 2, \"canteen\": 10, \"regulation\": 3, \"trading\":\n 6, \"change\": 6, \"IS\": 8, \"retail\": 5, \"cleaning\": 4, \"pissing about\": 25}\n b = sum(depts[v] for v in staff.values())\n return 'kill me now' if b <= 80 else 'i can handle this' if b < 100 else 'party time!!'"] | {"fn_name": "boredom", "inputs": [[{"tim": "change", "jim": "accounts", "randy": "canteen", "sandy": "change", "andy": "change", "katie": "IS", "laura": "change", "saajid": "IS", "alex": "trading", "john": "accounts", "mr": "finance"}], [{"tim": "IS", "jim": "finance", "randy": "pissing about", "sandy": "cleaning", "andy": "cleaning", "katie": "cleaning", "laura": "pissing about", "saajid": "regulation", "alex": "regulation", "john": "accounts", "mr": "canteen"}], [{"tim": "accounts", "jim": "accounts", "randy": "pissing about", "sandy": "finance", "andy": "change", "katie": "IS", "laura": "IS", "saajid": "canteen", "alex": "pissing about", "john": "retail", "mr": "pissing about"}]], "outputs": [["kill me now"], ["i can handle this"], ["party time!!"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,890 |
def boredom(staff):
|
7640383f86c0e54bba6be52c08fa0e9b | UNKNOWN | Bob has a server farm crunching numbers. He has `nodes` servers in his farm. His company has a lot of work to do.
The work comes as a number `workload` which indicates how many jobs there are. Bob wants his servers to get an equal number of jobs each. If that is impossible, he wants the first servers to receive more jobs. He also wants the jobs sorted, so that the first server receives the first jobs.
The way this works, Bob wants an array indicating which jobs are going to which servers.
Can you help him distribute all this work as evenly as possible onto his servers?
Example
-------
Bob has `2` servers and `4` jobs. The first server should receive job 0 and 1 while the second should receive 2 and 3.
```
distribute(2, 4) # => [[0, 1], [2, 3]]
```
On a different occasion Bob has `3` servers and `3` jobs. Each should get just one.
```
distribute(3, 3) # => [[0], [1], [2]]
```
A couple of days go by and Bob sees a spike in jobs. Now there are `10`, but he hasn't got more than `4` servers available. He boots all of them. This time the first and second should get a job more than the third and fourth.
```
distribute(4, 10) # => [[0, 1, 2], [3, 4, 5], [6, 7], [8, 9]]
```
Input
-----
Don't worry about invalid inputs. That is, `nodes > 0` and `workload > 0` and both will always be integers. | ["def distribute(nodes, workload):\n w = list(range(workload))[::-1]\n return [[w.pop() for _ in range(workload // nodes + (workload % nodes > n))] for n in range(nodes)]", "def distribute(n, w):\n g, (d,r) = iter(range(w)), divmod(w,n)\n return [ [next(g) for _ in range(d+(i<r))] for i in range(n)]", "def distribute(nodes, workload):\n (q, r), it = divmod(workload, nodes), iter(range(workload))\n return [[next(it) for _ in range(q + (n < r))] for n in range(nodes)]", "def distribute(nodes, workload):\n div, mod = divmod(workload, nodes)\n breakpoint = lambda i: i * div + (i if i < mod else mod)\n return [list(range(breakpoint(i), breakpoint(i+1))) for i in range(nodes)]\n\n\n# one-liner\n#def distribute(n, w):\n# return [list(range(i*(w//n)+w%n-max(0, w%n-i), (i+1)*(w//n)+w%n-max(0, w%n-i-1))) for i in range(n)]\n", "from itertools import accumulate, tee\n\ndef distribute(nodes, workload):\n q, r = divmod(workload, nodes)\n ns = [q + (i < r) for i in range(nodes)]\n xs = list(accumulate([0] + ns))\n return [list(range(i, j)) for i, j in zip(xs, xs[1:])]\n \n", "def distribute(nodes, workload):\n jobs_per_server, remaining = divmod(workload, nodes)\n jobs, start = [], 0\n for _ in range(nodes):\n how_many = jobs_per_server + (remaining > 0)\n jobs.append(list(range(start, start + how_many)))\n start += how_many\n remaining -= 1\n return jobs", "import numpy as np\ndef distribute(nodes, workload):\n lst=[]\n value = 0\n for i in range(nodes):\n length = int(np.ceil((workload-value)/(nodes-i)))\n lst.append([l for l in range(value,value+length)])\n value = value + length\n return lst", "import numpy\ndef distribute(nodes, workload):\n return [list(i) for i in numpy.array_split(numpy.array(range(0, workload)),nodes)]", "def distribute(nodes, workload):\n n = workload // nodes\n r = workload % nodes\n jobs = []\n works = [i for i in range(workload)]\n j = 0\n for i in range(nodes):\n if i < r:\n jobs.append([works.pop(0) for i in range(n+1)])\n else:\n jobs.append([works.pop(0) for i in range(n)])\n return jobs", "def distribute(nodes, workload):\n a=[[0] for x in range(nodes)]\n w=workload\n k=workload//nodes\n for j in range(0,workload%nodes):\n a[j][0]+=1\n for i in range(0,len(a)):\n for j in range(0,k):\n a[i][0]+=1\n total=0\n b=[[] for x in range(nodes)]\n for j in range(0,len(a)):\n for i in range(total, total+a[j][0]):\n b[j].append(i)\n total+=a[j][0]\n return b\n\n"] | {"fn_name": "distribute", "inputs": [[2, 4], [3, 3], [3, 9], [2, 5], [4, 10], [4, 5], [1, 1], [2, 1], [5, 4], [5, 1]], "outputs": [[[[0, 1], [2, 3]]], [[[0], [1], [2]]], [[[0, 1, 2], [3, 4, 5], [6, 7, 8]]], [[[0, 1, 2], [3, 4]]], [[[0, 1, 2], [3, 4, 5], [6, 7], [8, 9]]], [[[0, 1], [2], [3], [4]]], [[[0]]], [[[0], []]], [[[0], [1], [2], [3], []]], [[[0], [], [], [], []]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,650 |
def distribute(nodes, workload):
|
cc5bd316aa7894c44c9c6c305c8c03ef | UNKNOWN | Yup!! The problem name reflects your task; just add a set of numbers. But you may feel yourselves condescended, to write a C/C++ program just to add a set of numbers. Such a problem will simply question your erudition. So, lets add some flavor of ingenuity to it. Addition operation requires cost now, and the cost is the summation of those two to be added. So,to add 1 and 10, you need a cost of 11. If you want to add 1, 2 and 3. There are several ways
```c++
1 + 2 = 3, cost = 3,
3 + 3 = 6, cost = 6,
Total = 9.
```
```c++
1 + 3 = 4, cost = 4,
2 + 4 = 6, cost = 6,
Total = 10.
```
```c++
2 + 3 = 5, cost = 5,
1 + 5 = 6, cost = 6,
Total = 11.
```
I hope you have understood already your mission, to add a set of integers so that the cost is minimal
# Your Task
Given a vector of integers, return the minimum total cost of addition. | ["from heapq import *\n\ndef add_all(lst):\n\n heapify(lst)\n total = 0\n while len(lst) > 1:\n s = heappop(lst) + heappop(lst)\n total += s\n heappush(lst, s)\n\n return total", "import heapq\n\ndef add_all(xs): \n heapq.heapify(xs)\n cost = 0\n while len(xs) > 1:\n c = heapq.heappop(xs) + xs[0]\n cost += c\n heapq.heapreplace(xs, c)\n return cost", "def add_all(lst):\n if len(lst) == 1:\n return 0\n \n lst.sort()\n cost = sum(lst[:2])\n lst[:2] = cost,\n \n return cost + add_all(lst)\n", "import heapq \n \ndef add_all(arr): \n n=len(arr)\n # Create a priority queue out of the \n # given list \n heapq.heapify(arr) \n \n # Initializ result \n res = 0\n \n # While size of priority queue \n # is more than 1 \n while(len(arr) > 1): \n \n # Extract shortest two ropes from arr \n first = heapq.heappop(arr) \n second = heapq.heappop(arr) \n \n #Connect the ropes: update result \n # and insert the new rope to arr \n res += first + second \n heapq.heappush(arr, first + second) \n \n return res ", "import heapq\ndef add_all(heap): \n heapq.heapify(heap)\n sum = 0\n while len(heap) > 1:\n a, b = heapq.heappop(heap), heapq.heappop(heap)\n cost = a + b\n sum += cost\n heapq.heappush(heap, cost)\n return sum\n", "from heapq import heapify, heappush, heappop \ndef add_all(lst): \n heapify(lst) \n s=0\n print(lst)\n while len(lst)>1:\n m1=heappop(lst)\n m2=heappop(lst)\n s+=m1+m2\n if not lst: return s\n heappush(lst,m1+m2)\n\n #heap: 1,2,3,4,5 3\n # 3,3,4,5 6\n # 6,4,5 9\n # 9,6 15\n # 15\n", "from heapq import *\n\ndef add_all(a):\n n = m = 0\n heapify(a)\n while len(a) > 1:\n m = heappop(a) + heappop(a)\n n += m\n heappush(a, m)\n return n", "from queue import PriorityQueue\n\ndef add_all(lst): \n q = PriorityQueue()\n for x in lst: q.put(x)\n s = 0\n while q.qsize() > 1:\n a = q.get()\n b = q.get()\n s += a+b\n q.put(a+b)\n return s", "from heapq import *\n\ndef add_all(lst):\n heapify(lst)\n res = 0\n while len(lst) >= 2:\n s = heappop(lst) + heappop(lst)\n res += s\n heappush(lst, s)\n return res", "from heapq import *\n\ndef add_all(lst):\n\n heapify(lst)\n s = 0\n total = 0\n while len(lst) > 1:\n s = heappop(lst) + heappop(lst)\n total += s\n heappush(lst, s)\n\n \n return total"] | {"fn_name": "add_all", "inputs": [[[1, 2, 3]], [[1, 2, 3, 4]], [[1, 2, 3, 4, 5]]], "outputs": [[9], [19], [33]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,723 |
def add_all(lst):
|
67cdd4aa5cc6d7d18b44ced9e8e9fa04 | UNKNOWN | Find the difference between two collections. The difference means that either the character is present in one collection or it is present in other, but not in both. Return a sorted set with difference.
The collections can contain any character and can contain duplicates.
For instance:
A = [a,a,t,e,f,i,j]
B = [t,g,g,i,k,f]
difference = [a,e,g,j,k] | ["def diff(a, b):\n return sorted(set(a) ^ set(b))", "def diff(a, b):\n return sorted(set(a).symmetric_difference(b))", "# return a sorted set with the difference\ndef diff(a, b):\n a = set(a)\n b = set(b)\n c = a.symmetric_difference(b)\n return sorted(list(c))", "# return a sorted set with the difference\ndef diff(a, b):\n return sorted(list(set(a).symmetric_difference(set(b))))", "# return a sorted set with the difference\ndef diff(a, b):\n return sorted(set(a).symmetric_difference(set(b)))", "diff=lambda a,b: sorted(set([e for e in a if e not in b]+[e for e in b if e not in a]))", "# return a sorted set with the difference\ndef diff(a, b):\n c = []\n for i in a:\n if i not in b and i not in c:\n c.append(i)\n for i in b:\n if i not in a and i not in c:\n c.append(i)\n \n return sorted(c)", "def diff(a, b):\n a,b=set(a),set(b)\n return sorted((a-b).union(b-a))", "def diff(a, b):\n first = []\n second = []\n for element in a:\n if element not in b:\n first.append(element)\n for word in b:\n if word not in a:\n second.append(word)\n third = first + second\n third = sorted(third)\n for element in third:\n if third.count(element) > 1:\n third.remove(element)\n return third", "# return a sorted set with the difference\ndef diff(a, b):\n output = []\n for elem in a:\n if elem not in b:\n output.append(elem)\n for elem in b:\n if elem not in a:\n output.append(elem)\n return sorted(list(set(output)))"] | {"fn_name": "diff", "inputs": [[["a", "b"], ["a", "b"]], [[], []]], "outputs": [[[]], [[]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,622 |
def diff(a, b):
|
e37a326e7d829a9541e4c1ac86680545 | UNKNOWN | We have an integer array with unique elements and we want to do the permutations that have an element fixed, in other words, these permutations should have a certain element at the same position than the original.
These permutations will be called: **permutations with one fixed point**.
Let's see an example with an array of four elements and we want the permutations that have a coincidence **only at index 0**, so these permutations are (the permutations between parenthesis):
```
arr = [1, 2, 3, 4]
(1, 3, 4, 2)
(1, 4, 2, 3)
Two permutations matching with arr only at index 0
```
Let's see the permutations of the same array with only one coincidence at index **1**:
```
arr = [1, 2, 3, 4]
(3, 2, 4, 1)
(4, 2, 1, 3)
Two permutations matching with arr only at index 1
```
Once again, let's see the permutations of the same array with only one coincidence at index **2**:
```
arr = [1, 2, 3, 4]
(2, 4, 3, 1)
(4, 1, 3, 2)
Two permutations matching with arr only at index 2
```
Finally, let's see the permutations of the same array with only one coincidence at index **3**:
```
arr = [1, 2, 3, 4]
(2, 3, 1, 4)
(3, 1, 2, 4)
Two permutations matching with arr only at index 3
```
For this array given above (arr) :
- We conclude that we have 8 permutations with one fixed point (two at each index of arr).
- We may do the same development for our array, `arr`, with two fixed points and we will get `6` permutations.
- There are no permutations with coincidences only at three indexes.
- It's good to know that the amount of permutations with no coincidences at all are `9`. See the kata Shuffle It Up!!
In general:
- When the amount of fixed points is equal to the array length, there is only one permutation, the original array.
- When the amount of fixed points surpasses the length of the array, obvously, there are no permutations at all.
Create a function that receives the length of the array and the number of fixed points and may output the total amount of permutations for these constraints.
Features of the random tests:
```
length of the array = l
number of fixed points = k
10 ≤ k ≤ l ≤ 9000
```
See the example tests!
Enjoy it!!
Ruby versin will be released soon.
#Note: This kata was published previously but in a version not well optimized. | ["def fixed_points_perms(n, k):\n if k > n:\n return 0\n if k == n:\n return 1\n if k == 0:\n subf = lambda n: 1 if n == 0 else n * subf(n - 1) + (-1)**n\n return subf(n)\n return fixed_points_perms(n-1, k-1) * n // k\n", "from functools import lru_cache\nfrom math import factorial as f\n@lru_cache(maxsize=None)\ndef all_permuted(n) : return [1,0][n] if n<2 else (n-1)*(all_permuted(n-1)+all_permuted(n-2))\nfixed_points_perms=lambda n,k:all_permuted(n - k)*f(n)//(f(k)*f(n-k)) if n>=k else 0", "from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef f(n):\n return (n-1) * (f(n-1) + f(n-2)) if n > 2 else int(n != 1)\n\ndef fixed_points_perms(n,k):\n return n * fixed_points_perms(n-1, k-1) // k if k else f(n)", "from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef f(n):\n if n <= 2:\n return n - 1\n return (n-1) * (f(n-1) + f(n-2))\n\ndef fixed_points_perms(n,k):\n if n == k:\n return 1\n elif k >= n - 1:\n return 0\n elif k == 0:\n return f(n)\n return n * fixed_points_perms(n-1, k-1) // k", "subfactorial, factorial = [1, 0], [1]\nfor n in range(1, 10 ** 4):\n subfactorial.append(n * (subfactorial[-1] + subfactorial[-2]))\n factorial.append(n * factorial[-1])\n\ndef fixed_points_perms(n, k):\n return factorial[n] // factorial[n-k] // factorial[k] * subfactorial[n-k]\n", "from math import factorial as fact\nA000166 = [1,0]\nfor n in range(2,9000): A000166.append((n-1)*(A000166[n-1]+A000166[n-2]))\n\n\n# this is just A000166(n-k)*binomial(n,k)\ndef fixed_points_perms(n,k):\n if n<k: return 0\n return A000166[n-k]*fact(n)//(fact(k)*fact(n-k))", "from collections import deque\nfrom math import factorial \n\ndef fixed_points_perms(n,m): \n if m >= n : return [1,0][m>n]\n \n def dear(n):\n arr, i = deque([1,0,1]), 3 \n while i < n+1 :\n arr.append((i-1)*(arr[-1] + arr[-2]))\n arr.popleft()\n i+=1\n return arr[-1]\n\n de = [1,0,1][n-m] if n-m<=2 else dear(n-m)\n\n return (factorial(n)*de)//(factorial(n-m)*factorial(m))", "def fixed_points_perms(n,k):\n fact_list = [0,1]\n dearr_list = [1, 0]\n if k==n:\n return 1\n elif k>n:\n return 0\n \n if k != 0:\n for i in range(2, n+1):\n fact_list.append(i*fact_list[-1])\n combinations = fact_list[-1]//(fact_list[k]*fact_list[n-k])\n else:\n combinations = 1\n \n for i in range(2, n-k+1):\n dearr_list.append((i-1)*(dearr_list[-1]+dearr_list[-2]))\n print(combinations, dearr_list[-1])\n return int(combinations) * dearr_list[-1]", "f=[1,0,1,2,9,44]\nfor i in range(6,10000):\n f.append(i*f[-1]+(-1)**i)\n\n\ndef c(x,y):\n if y>x: return 0\n if y>(x//2): y=x-y\n mul=1\n for i in range(1,y+1):\n mul = mul*(x-i+1) // i\n print(mul)\n return mul\n\n\ndef fixed_points_perms(n,k):\n \n return c(n,k) * f[n-k]", "from math import factorial\nfac = factorial \nsubfac = lambda n: n * subfac(n-1)+(-1) ** n if not n == 0 else 1\ndef fixed_points_perms(n,k):\n if n < k: return 0\n return (fac(n)//(fac(n-k)*fac(k))) * subfac(n-k)"] | {"fn_name": "fixed_points_perms", "inputs": [[4, 1], [4, 2], [4, 3], [10, 3], [10, 4], [20, 2], [4, 0], [4, 4], [4, 5]], "outputs": [[8], [6], [0], [222480], [55650], [447507315596451070], [9], [1], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,226 |
def fixed_points_perms(n,k):
|
fcbdb055ae56452fe1983a55935f9ae5 | UNKNOWN | In this Kata, you will be given an array of unique elements, and your task is to rerrange the values so that the first max value is followed by the first minimum, followed by second max value then second min value, etc.
For example:
The first max is `15` and the first min is `7`. The second max is `12` and the second min is `10` and so on.
More examples in the test cases.
Good luck! | ["def solve(arr):\n arr = sorted(arr, reverse=True)\n res = []\n while len(arr):\n res.append(arr.pop(0))\n if len(arr):\n res.append(arr.pop())\n return res", "def solve(arr):\n lmax, lmin = iter(sorted(arr)) , iter(sorted(arr)[::-1])\n return [next(lmax) if i%2==1 else next(lmin) for i in range(0,len(arr))]", "def solve(arr):\n return [sorted(arr)[::-1][(-1)**i*i//2] for i in range(len(arr))]", "def solve(arr):\n rarr = sorted(arr, reverse=True)\n farr = rarr[::-1]\n return [item for sublist in zip(rarr, farr) for item in sublist][:len(rarr)]", "def solve(arr):\n arr.sort(reverse=True)\n return [arr.pop(-(i % 2)) for i in range(len(arr))]", "def solve(arr):\n l = sorted(arr)\n result = []\n while l:\n result.append(l.pop())\n l.reverse()\n return result", "# I haven't tested them, but I think candle_index is the best of these\n\ndef zip_slices(arr):\n arr = sorted(arr)[::-1]\n res = []\n n = len(arr)\n m = n // 2\n mins = arr[m:][::-1]\n maxes = arr[:m]\n for a, b in zip(maxes, mins):\n res.extend([a, b])\n if n % 2:\n res.append(mins[-1])\n return res\n\ndef candle_pop(arr):\n candle = sorted(arr)\n res = []\n i = -1\n while candle:\n res.append(candle.pop(i))\n i = 0 if i else -1\n return res\n\ndef candle_index(arr):\n candle = sorted(arr)\n n = len(arr)\n a = 0\n z = n - 1\n res = []\n for i in range(n):\n if i % 2:\n res.append(candle[a])\n a += 1\n else:\n res.append(candle[z])\n z -= 1\n return res\n\ndef set_pop(arr):\n nums = set(arr)\n res = []\n i = 0\n while nums:\n if i % 2:\n n = min(nums)\n else:\n n = max(nums)\n res.append(n)\n nums.remove(n)\n i += 1\n return res\n\nfrom random import randint\n\nsolve = lambda arr: (zip_slices, candle_pop, candle_index, set_pop)[randint(0,3)](arr)", "def solve(arr):\n arr=sorted(arr)\n arr.append(0)\n arr=sorted(arr)\n list1 = []\n for i in range(1,len(arr)//2+2):\n list1.append(arr[-i])\n list1.append(arr[i])\n list1=list(dict.fromkeys(list1))\n return list1\n", "def solve(arr):\n \n # sort and reverse the list, make a new list to store answer\n arr = sorted(arr, reverse=True)\n new_list = []\n \n boolean = True\n # while there are still items in arr[]\n while (len(arr) >= 1):\n \n # append the 0th item to new_list[]\n new_list.append(arr[0])\n \n # flip our boolean value from true to false to reverse the list later\n if (boolean == True) : \n boolean = False \n else:\n boolean = True\n \n # remove the 0th element from arr[]\n arr.pop(0)\n \n # sort the list either forwards or in reverse based on boolean\n arr = sorted(arr, reverse=boolean)\n \n return new_list", "def solve(arr):\n print(arr)\n max_l=sorted(arr,reverse=True)\n min_l=sorted(arr)\n l=[]\n for i,a in enumerate(zip(max_l,min_l)):\n if a[0]!=a[1]:\n l.append(a[0])\n l.append(a[1])\n else:\n l.append(a[0])\n break\n return list(dict.fromkeys(l))"] | {"fn_name": "solve", "inputs": [[[15, 11, 10, 7, 12]], [[91, 75, 86, 14, 82]], [[84, 79, 76, 61, 78]], [[52, 77, 72, 44, 74, 76, 40]], [[1, 6, 9, 4, 3, 7, 8, 2]], [[78, 79, 52, 87, 16, 74, 31, 63, 80]]], "outputs": [[[15, 7, 12, 10, 11]], [[91, 14, 86, 75, 82]], [[84, 61, 79, 76, 78]], [[77, 40, 76, 44, 74, 52, 72]], [[9, 1, 8, 2, 7, 3, 6, 4]], [[87, 16, 80, 31, 79, 52, 78, 63, 74]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,384 |
def solve(arr):
|
e4d41d03619a5cfdf3857953c8361aa3 | UNKNOWN | Write a function that takes a string which has integers inside it separated by spaces, and your task is to convert each integer in the string into an integer and return their sum.
### Example
```python
summy("1 2 3") ==> 6
```
Good luck! | ["def summy(string_of_ints):\n return sum(map(int,string_of_ints.split()))", "def summy(s):\n return sum(map(int, s.split(' ')))", "def summy(string_of_ints): \n return sum([int(element) for element in string_of_ints.split(\" \")])", "def summy(s):\n return eval(s.replace(' ', '+'))", "import re\n\ndef summy(s):\n return sum(map(int, re.split(r'[^\\d]+', s)))", "summy = lambda s: sum(map(int, s.split()))", "def summy(string_of_ints):\n return sum(int(i) for i in string_of_ints.split(\" \"))", "summy = lambda string_of_ints: sum(int(n) for n in string_of_ints.split())", "import re\ndef summy(s):\n return sum(int(e) for e in re.findall(r'\\d+',s))", "summy = lambda s: sum(int(e) for e in s.split())"] | {"fn_name": "summy", "inputs": [["1 2 3"], ["1 2 3 4"], ["1 2 3 4 5"], ["10 10"], ["0 0"]], "outputs": [[6], [10], [15], [20], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 732 |
def summy(s):
|
72ac1f63beae7c7f8c53a9c139fc54ee | UNKNOWN | You are a biologist working on the amino acid composition of proteins. Every protein consists of a long chain of 20 different amino acids with different properties.
Currently, you are collecting data on the percentage, various amino acids make up a protein you are working on. As manually counting the occurences of amino acids takes too long (especially when counting more than one amino acid), you decide to write a program for this task:
Write a function that takes two arguments,
1. A (snippet of a) protein sequence
2. A list of amino acid residue codes
and returns the rounded percentage of the protein that the given amino acids make up.
If no amino acid list is given, return the percentage of hydrophobic amino acid residues ["A", "I", "L", "M", "F", "W", "Y", "V"]. | ["def aa_percentage(seq, residues=[\"A\", \"I\", \"L\", \"M\", \"F\", \"W\", \"Y\", \"V\"]):\n return round(sum(seq.count(r) for r in residues)/len(seq)*100)", "def aa_percentage(seq, acid='AILMFWYV'):\n return round(sum(x in acid for x in seq) * 100 / len(seq) )", "def aa_percentage(protein, residue=\"AILMFWYV\"):\n return round(100 * sum(protein.count(aa) for aa in set(residue)) / len(protein))", "def aa_percentage(seq, targets=[\"A\", \"I\", \"L\", \"M\", \"F\", \"W\", \"Y\", \"V\"]):\n return round(sum([seq.count(ch) for ch in targets])/len(seq)*100)", "def aa_percentage(seq, codes = [\"A\",\"I\",\"L\",\"M\",\"F\",\"W\",\"Y\",\"V\"]):\n return round(100 * len([x for x in seq if x in codes]) / len(seq))", "def aa_percentage(prot, rsd=\"AILMFWYV\"):\n rsd = set(rsd)\n return round(sum(p in rsd for p in prot)/len(prot)*100)", "def aa_percentage(*prot):\n if len(prot)>1:\n sear = prot[1]\n else:\n sear = [\"A\", \"I\", \"L\", \"M\", \"F\", \"W\", \"Y\", \"V\"]\n times = 0\n for i in sear:\n times += prot[0].count(i)\n return round((times / len(prot[0])) * 100)", "def aa_percentage(seq,codes=\"AILMFWYV\"):\n codes=set(codes)\n return round(sum(c in codes for c in seq)/len(seq)*100)\n", "def aa_percentage(sequence,list = [\"A\", \"I\", \"L\", \"M\", \"F\", \"W\", \"Y\", \"V\"]):\n counts = [sequence.count(x) for x in list]\n return round(sum(counts)*100/len(sequence),0)", "def aa_percentage(s,a=None):\n print(repr(a))\n return round(100*sum(i in ('AILMFWYV' if a is None else a) for i in s)/len(s))"] | {"fn_name": "aa_percentage", "inputs": [["MSRSLLLRFLLFLLLLPPLP", ["M"]], ["MSRSLLLRFLLFLLLLPPLP", ["M", "L"]], ["MSRSLLLRFLLFLLLLPPLP", ["F", "S", "L"]], ["MSRSLLLRFLLFLLLLPPLP"], ["RLMADDFFGQTLMAAAAAAQERRR", ["A"]], ["RLMADDFFGQTLMAAAAAAQERRR", ["A", "R", "D"]], ["RLMADDFFGQTLMAAAAAAQERRR"], ["PLPPLPLLEELELRPFFMAAGGTPLAMMGG", ["X"]], ["PLPPLPLLEELELRPFFMAAGGTPLAMMGG", ["P", "L"]], ["PLPPLPLLEELELRPFFMAAGGTPLAMMGG", ["P", "E", "L", "R", "F", "M", "A", "G", "T"]], ["PLPPLPLLEELELRPFFMAAGGTPLAMMGG"]], "outputs": [[5], [55], [70], [65], [29], [54], [54], [0], [43], [100], [50]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,596 |
def aa_percentage(seq, residues=["A", "I", "L", "M", "F", "W", "Y", "V"]):
|
f769f2779273e542569246c33a3c94f1 | UNKNOWN | Assume we take a number `x` and perform any one of the following operations:
```Pearl
a) Divide x by 3 (if it is divisible by 3), or
b) Multiply x by 2
```
After each operation, we write down the result. If we start with `9`, we can get a sequence such as:
```
[9,3,6,12,4,8] -- 9/3=3 -> 3*2=6 -> 6*2=12 -> 12/3=4 -> 4*2=8
```
You will be given a shuffled sequence of integers and your task is to reorder them so that they conform to the above sequence. There will always be an answer.
```
For the above example:
solve([12,3,9,4,6,8]) = [9,3,6,12,4,8].
```
More examples in the test cases. Good luck! | ["def solve(a):\n for i in a:\n li = [i]\n while 1:\n if li[-1] % 3 == 0 and li[-1] // 3 in a : li.append(li[-1] // 3)\n elif li[-1] * 2 in a : li.append(li[-1] * 2)\n else : break\n if len(li) == len(a) : return li", "def solve(arr): \n ar, v = arr[:], lambda p: lambda n: 0 if n % p else 1 + v(p)(n // p)\n return sorted(reversed(sorted(ar, key=v(3))), key=v(2))", "def decompose(n):\n res = [0,0,n]\n for i,p in enumerate((3,2)):\n while not n%p: res[i]+=1 ; n//=p\n res[0] = -res[0]\n return res\n\ndef solve(arr):\n return [n for _,_,n in sorted(map(decompose,arr))]", "def solve(arr):\n fn = lambda p: lambda n: 0 if n % p else 1 + fn(p)(n // p)\n return sorted(sorted(arr, key=fn(3), reverse=True), key=fn(2))", "k,solve=lambda n,p:n%p<1and-~k(n//p,p),lambda a:sorted(a,key=lambda n:(-k(n,3),k(n,2)))", "def solve(arr):\n links = {}\n for a in arr:\n if a % 3 == 0:\n next_val = a // 3\n if next_val in arr:\n links[a] = next_val\n if a * 2 in arr:\n links[a] = a * 2\n \n start = (set(links.keys()) - set(links.values())).pop()\n result = [start]\n while True:\n next_val = links.get(result[-1])\n if next_val is None:\n break\n result.append(next_val)\n return result", "def solve(arr):\n stack = []\n for num in arr:\n branches = arr.copy()\n branches.remove(num)\n stack = [([num], branches)]\n while len(stack) != 0:\n (current, remaining) = stack.pop()\n if len(remaining) == 0:\n return current\n x = current[len(current) - 1]\n valid_leaves = [leaf for leaf in remaining if x / 3 == leaf or x * 2 == leaf]\n for valid in valid_leaves:\n valid_current = current.copy()\n valid_current.append(valid)\n valid_remaining = remaining.copy()\n valid_remaining.remove(valid)\n stack.append((valid_current, valid_remaining))\n \n", "def solve(arr):\n stack = []\n for i in arr:\n x = arr[:]\n x.remove(i)\n stack.append(([i],x))\n while True:\n a,b = stack.pop(0)\n v = a[-1]\n a1,a2 = a[:],a[:]\n b1,b2 = b[:],b[:]\n if v*2 in b:\n a1.append(v*2)\n b1.remove(v*2)\n stack.append((a1,b1))\n if not v%3:\n if v//3 in b:\n a2.append(v//3)\n b2.remove(v//3)\n stack.append((a2,b2))\n if not b1:\n return a1\n if not b2:\n return a2", "def solve(lst):\n return sorted(lst, key=factors_count)\n \ndef factors_count(n):\n result = []\n for k in (2, 3):\n while n % k == 0:\n n //= k\n result.append(k)\n return -result.count(3), result.count(2)\n", "def solve(lst):\n return sorted(lst, key=factors_count)\n \ndef factors_count(n):\n result = [0, 0]\n for k in (2, 3):\n while n % k == 0:\n n //= k\n result[k-2] += (-1)**k\n return result"] | {"fn_name": "solve", "inputs": [[[1, 3]], [[4, 2]], [[12, 3, 9, 4, 6, 8]], [[4, 8, 6, 3, 12, 9]], [[558, 744, 1488, 279, 2232, 1116]], [[9, 1, 3]], [[3000, 9000]], [[4, 1, 2]], [[10, 5]]], "outputs": [[[3, 1]], [[2, 4]], [[9, 3, 6, 12, 4, 8]], [[9, 3, 6, 12, 4, 8]], [[279, 558, 1116, 2232, 744, 1488]], [[9, 3, 1]], [[9000, 3000]], [[1, 2, 4]], [[5, 10]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,236 |
def solve(arr):
|
a6b45667cbb2b0de908075c534985f01 | UNKNOWN | # Grains
Write a program that calculates the number of grains of wheat on a chessboard given that the number on each square is double the previous one.
There are 64 squares on a chessboard.
#Example:
square(1) = 1
square(2) = 2
square(3) = 4
square(4) = 8
etc...
Write a program that shows how many grains were on each square | ["def square(number):\n return 2**(number-1)", "def square(n):\n return 1<<n-1", "square=lambda n: 2**(n-1)", "def square(number):\n return 1 << (number-1)", "square=lambda n:1<<n-1", "def square(number = 1):\n return 2 ** (number - 1)", "square=lambda a:1<<(a-1)", "def square(number):\n grains = 1\n for x in range(number-1):\n grains *= 2\n return grains", "def square(number):\n a = []\n sum = 1\n while len(a) < number:\n a.append(sum)\n sum = sum + sum\n return a[-1]", "def square(number):\n lista = [1]\n for n in range(1, number):\n result = lista[-1]*2\n lista.append(result)\n return lista[-1]"] | {"fn_name": "square", "inputs": [[1], [3], [4], [16], [32]], "outputs": [[1], [4], [8], [32768], [2147483648]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 687 |
def square(number):
|
074ca9736635dcba9dc1a4a612e8c4d7 | UNKNOWN | I have started studying electronics recently, and I came up with a circuit made up of 2 LEDs and 3 buttons.
Here 's how it works: 2 buttons (`red` and `blue`) are connected to the LEDs (`red` and `blue` respectively). Buttons pressing pattern will be remembered and represented through the LEDs when the third button is pressed.
- Only one LED can blink at a time.
- The LED will only blink once even if the button is held down.
- The button must be released to be pressed again.
- If a button is pressed while the other button is being held down, it will be ignored.
- If two buttons are pressed simultaneously, the red button will be preferred.
- If a button is released while the other is being held down, the other 's LED will blink.
- `0` is up and `1` is down.
- The two inputs will always have the same length.
Here is an example:
```Python
Red: "10011010"
Blue: "10110111"
#=> "RBRB"
Red: "01001000"
Blue: "01011100"
#=> "RB"
Red: "01101000"
Blue: "00111000"
#=> "RB"
```
PS:
This is my first time making a kata, so there may be some errors.
You may report to me if the description is too confusing.
Sorry for my poor grammar. | ["def button_sequences(seqR, seqB):\n pattern, state = '', ''\n toBool = lambda seq : [i == '1' for i in seq]\n for red, blue in zip(toBool(seqR), toBool(seqB)):\n if red and state == 'R' or blue and state == 'B':\n continue\n state = 'R' if red else 'B' if blue else ''\n pattern += state\n return pattern", "def button_sequences(red, blue):\n s=''\n r,b=False,False\n for i in range(len(red)):\n if red[i]=='0':\n r=False\n if blue[i]=='0':\n b=False\n if red[i]=='1' and not r and not b:\n r=True\n s+='R'\n elif blue[i]=='1' and not r and not b:\n b=True\n s+='B'\n return s", "def button_sequences(seqR, seqB):\n A, B, res = 1, 1, \"\"\n for x, y in zip(map(int, seqR), map(int, seqB)):\n if A and B and x: y = 0\n if A and x and not y: res += 'R'\n if B and not x and y: res += 'B'\n if not (x and y): A, B = not x, not y\n return res", "def button_sequences(seqR, seqB):\n state, s = '', ''\n for r, b in zip([c == '1' for c in seqR], [c == '1' for c in seqB]):\n if (state == 'R' and not r) or (state == 'B' and not b): state = ''\n if not state and r :\n s, state = s + 'R', 'R'\n elif not state and b: \n s, state = s + 'B', 'B'\n return s\n", "from itertools import groupby\n\ndef button_sequences(seq_r, seq_b):\n pairs = [''.join(pair) for pair in zip(seq_r, seq_b)]\n blinks = (('' if rb == '00' else 'B' if rb == '01' else 'R' if rb == '10' or prev == '00' else '-')\n for rb, prev in zip(pairs, ['00'] + pairs))\n return ''.join(key for key, _ in groupby(x for x in blinks if x != '-'))", "def button_sequences(*seqRB):\n wasR, wasB, seq = 0, 0, []\n for r,b in zip(*map(lambda s: map(int,s),seqRB)):\n what = 'BR'[r] # Ensure precedence of red button\n realeaseOneofTwo = wasR+wasB == 2 and r+b == 1 and what != seq[-1] # Only if the remaining button isn't already archived\n freshPress = not (wasR+wasB) and r+b\n switchButtons = b+r==1 and (wasR,wasB)==(b,r)\n \n if realeaseOneofTwo or freshPress or switchButtons:\n seq.append(what)\n wasR,wasB = r,b\n \n return ''.join(seq)", "button_sequences=lambda R,B:(lambda r,f:r.sub(r'(.)\\1+',r'\\1',f.reduce(lambda x,y:x+('_'if y==('0','0')else'R'if y==('1','0')else'B'if y==('0','1')else'R'if x[-1:]in['','_','R']else'B'),zip(R,B),'')).replace('_',''))(__import__('re'),__import__('functools'))", "def button_sequences(r, b):\n r_on, b_on = False, False\n res = ''\n for i in range(len(r)):\n ri, bi = int(r[i]), int(b[i])\n if not r_on|b_on:\n if ri:\n res += 'R'\n r_on = True\n elif bi:\n res += 'B'\n b_on = True\n elif r_on:\n if not ri:\n r_on = False\n if bi:\n b_on = True\n res += 'B'\n elif b_on:\n if not bi:\n b_on = False\n if ri:\n r_on = True\n res += 'R'\n return res", "def button_sequences(seqR, seqB):\n\n result=\"\"\n prec_r=\"0\"\n prec_b=\"0\"\n \n seqR=list(seqR)\n seqB=list(seqB)\n \n for r, b in zip (seqR, seqB):\n if r==b and r==\"1\" and prec_r!=\"1\" and prec_b!=\"1\":\n result+=\"R\"\n \n elif r!=b and r==\"1\" and prec_r!=\"1\":\n result+=\"R\"\n \n elif r!=b and b==\"1\" and prec_b!=\"1\":\n result+=\"B\"\n \n elif prec_r==prec_b and prec_r==\"1\" and r==\"1\" and b!=r and result[len(result)-1]!=\"R\":\n result+=\"R\"\n \n elif prec_r==prec_b and prec_r==\"1\" and b==\"1\" and b!=r and result[len(result)-1]!=\"B\":\n result+=\"B\"\n \n prec_r=r\n prec_b=b\n \n return result\n", "def button_sequences(seqR, seqB):\n # You may code here\n seq = ''\n leds = ['R','B']\n action = [None,None]\n for r,b in zip(seqR,seqB):\n r = int(r)\n b = int(b)\n for ind,button in enumerate([r,b]):\n if button and not action[ind]: action[ind] = 'press'\n elif button and action[ind]: action[ind] = 'held'\n elif action[ind] and not button: action[ind] = 'release'\n for ind in [0,1]:\n if (action[ind] == 'press') and (action[ind-1] != 'held'): \n seq += leds[ind]\n break\n elif (action[ind] == 'held') and (action[ind-1] == 'release'):\n if seq[-1] == leds[ind]: continue\n seq += leds[ind]\n break\n \n \n if action[0] == 'release': action[0] = None\n if action[1] == 'release': action[1] = None\n return seq"] | {"fn_name": "button_sequences", "inputs": [["10011010", "10110111"], ["01001000", "01011100"], ["00010100", "01011100"], ["10101010", "01010101"], ["11011011", "11111011"]], "outputs": [["RBRB"], ["RB"], ["BRB"], ["RBRBRBRB"], ["RBR"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 5,075 |
def button_sequences(seqR, seqB):
|
7feccfdc44909d3dcb2fe7656ad2e405 | UNKNOWN | # Task
Write a function that accepts `msg` string and returns local tops of string from the highest to the lowest.
The string's tops are from displaying the string in the below way:
```
7891012
TUWvXY 6 3
ABCDE S Z 5
lmno z F R 1 4
abc k p v G Q 2 3
.34..9 d...j q....x H.....P 3......2
125678 efghi rstuwy IJKLMNO 45678901
```
The next top is always 1 character higher than the previous one.
For the above example, the solution for the `123456789abcdefghijklmnopqrstuwyxvzABCDEFGHIJKLMNOPQRSTUWvXYZ123456789012345678910123` input string is `7891012TUWvXYABCDElmnoabc34`.
- When the `msg` string is empty, return an empty string.
- The input strings may be very long. Make sure your solution has good performance.
- The (.)dots on the sample dispaly of string are only there to help you to understand the pattern
Check the test cases for more samples.
# Series
- [String tops](https://www.codewars.com/kata/59b7571bbf10a48c75000070)
- [Square string tops](https://www.codewars.com/kata/5aa3e2b0373c2e4b420009af) | ["def tops(msg):\n n = len(msg)\n res,i,j,k = \"\",2,2,7\n while i < n:\n res = msg[i:i+j] + res\n i,j,k=i+k,j+1,k+4\n return res", "def transform(i): return (3*i-4+2*(i-1)*(i-2), i)\n\ndef tops(msg):\n iMax = int((3+(9+8*len(msg))**.5) / 4)\n return ''.join( msg[i:i+c] for i,c in map(transform, reversed(range(2,iMax+1))) )", "def tops(msg):\n i,l, step, st = 2,2,2, []\n while l<len(msg):\n st.insert(0, msg[l:l+i] )\n step += 3\n l += step + i \n i += 1\n return ''.join(st)\n", "from math import ceil\nfrom numpy import roots\n\ndef gen(msg, i, n):\n while n > 1:\n yield msg[i:i+n]\n n -= 1\n i -= 4*n - 1\n\ndef tops(msg):\n number = ceil(roots((2, 5, 2-len(msg)))[1]) + 1\n start = number * (2*number - 3)\n return ''.join(gen(msg, start, number))", "from itertools import count\n\ndef tops(msg):\n deltas = count(7, 4)\n xs = []\n i, n = 2, 2\n while i < len(msg):\n xs.append(msg[i:i+n])\n i += next(deltas)\n n += 1\n return ''.join(reversed(xs))", "def tops(msg):\n if msg:\n step = int(((2 * len(msg) - 1)**0.5 + 3) / 2)\n result = [msg[n*(2*n+1)-1:2*n*(n+1)] for n in range(1, step)]\n return \"\".join(reversed(result))\n return \"\"\n", "def tops(s):\n tops, start = [s[2:4]], 2\n while start < len(s):\n l = len(tops[-1])\n start += (l - 1) * 2 + l * 2 + 1\n tops.append(s[start:start + l + 1]) \n return \"\".join(tops[::-1])", "def tops(msg):\n return \"\".join(msg[(i*2-1)*(i+1):i*(i+1)*2] for i in range(int(1+(-1+(1+2*len(msg))**0.5)*0.5),0,-1))", "def tops(msg):\n r=[]\n for i in range(int(1+(-1+(1+2*len(msg))**0.5)*0.5),0,-1):\n r.append(msg[(i*2-1)*(i+1):i*(i+1)*2])\n return ''.join(r)", "def tops(msg):\n return \"\".join(msg[n*(2*n-3):2*n*(n-1)] for n in range(int((3 + (9 + 8*len(msg))**.5)/4), 1, -1))"] | {"fn_name": "tops", "inputs": [[""], ["abcde"], ["123456789abcdefghijklmnopqrstuwyxvzABCDEFGHIJKLMNOPQRSTU"], ["123456789abcdefghijklmnopqrstuwyxvzABCDEFGHIJKLMNOPQRSTUWvXYZ123456789012345678910123"]], "outputs": [[""], ["cd"], ["TUABCDElmnoabc34"], ["7891012TUWvXYABCDElmnoabc34"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,952 |
def tops(msg):
|
a8109158429ee4941fa3d35703bfeae6 | UNKNOWN | Complete the function that takes 3 numbers `x, y and k` (where `x ≤ y`), and returns the number of integers within the range `[x..y]` (both ends included) that are divisible by `k`.
More scientifically: `{ i : x ≤ i ≤ y, i mod k = 0 }`
## Example
Given ```x = 6, y = 11, k = 2``` the function should return `3`, because there are three numbers divisible by `2` between `6` and `11`: `6, 8, 10`
- **Note**: The test cases are very large. You will need a O(log n) solution or better to pass. (A constant time solution is possible.) | ["def divisible_count(x,y,k):\n return y//k - (x-1)//k", "def divisible_count(x,y,k):\n upper = y//k\n lower = (x-1)//k\n return upper - lower", "divisible_count=lambda x,y,k:y//k-~-x//k", "def divisible_count(x,y,k):\n ans = 0\n \n while True:\n if x % k == 0:\n break\n else:\n x += 1\n \n while True:\n if y % k == 0:\n break\n else:\n y -= 1\n \n ans = ((y-x) // k) + 1\n \n return ans", "def divisible_count(x,y,k):\n mod = x % k\n if mod != 0:\n x += (k - mod)\n y -= y % k\n if x > y:\n return 0\n return (y - x) // k + 1", "from fractions import Fraction\n\ndef divisible_count(x,y,k):\n x += k - (x % k or k)\n return int(Fraction(y - x + k, k))", "def divisible_count(x,y,k):\n d = x % k;\n if x >= 0:\n return (d == 0) + (y - x + d) // k", "def divisible_count(x,y,k):\n return (y//k) - (x//k) + bool(x % k == 0)", "def divisible_count(x,y,k):\n result = 0\n for i in range(x, y+1):\n if i%k == 0:\n result += 1\n break\n result += (y-i)//k\n return result \n"] | {"fn_name": "divisible_count", "inputs": [[6, 11, 2], [11, 345, 17], [0, 1, 7], [20, 20, 2], [20, 20, 8], [19, 20, 2], [0, 10, 1], [11, 14, 2], [101, 9999999999999999999999999999999999999999999, 11], [1005, 9999999999999999999999999999999999999999999, 109]], "outputs": [[3], [20], [1], [1], [0], [1], [11], [2], [909090909090909090909090909090909090909081], [91743119266055045871559633027522935779807]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,180 |
def divisible_count(x,y,k):
|
0a2dafe663099e7252b72671be169ce8 | UNKNOWN | ## Task
Given `n` representing the number of floors build a beautiful multi-million dollar mansions like the ones in the example below:
```
/\
/ \
/ \
/______\ number of floors 3
| |
| |
|______|
/\
/ \
/____\
| | 2 floors
|____|
/\
/__\ 1 floor
|__|
```
**Note:** whitespace should be preserved on both sides of the roof. Number of floors will go up to 30. There will be no tests with invalid input.
If you manage to complete it, you can try a harder version [here](https://www.codewars.com/kata/58360d112fb0ba255300008b).
Good luck! | ["def my_crib(n):\n roof = \"\\n\".join(\"%s/%s\\\\%s\"%(\" \"*(n-i),\" \"*i*2,\" \"*(n-i)) for i in range(n))\n ceiling = \"\\n/%s\\\\\\n\"%(\"_\"*(n*2))\n walls = (\"|%s|\\n\"%(\" \"*(n*2)))*(n-1)\n floor = \"|%s|\"%(\"_\"*(n*2))\n \n return roof + ceiling + walls + floor", "def my_crib(n):\n roof = [(\"/\" + \" \"*k + \"\\\\\").center(2*n+2) for k in range(0, 2*n, 2)]\n ceiling = [\"/\" + \"_\"*2*n + \"\\\\\"]\n walls = [\"|\" + \" \"*2*n + \"|\"]*(n-1)\n floor = [\"|\" + \"_\"*2*n + \"|\"]\n return \"\\n\".join(roof + ceiling + walls + floor)", "def my_crib(n):\n return '\\n'.join([' '*(n-i) + '/' + ' '*2*i + '\\\\' + ' '*(n-i) for i in range(n)] + ['/' + '_'*2*n + '\\\\'] + ['|' + ' '*2*n + '|'] *(n-1) + ['|' + '_'*2*n + '|'])", "def my_crib(n):\n l, res = n+1 << 1, []\n res.extend('/' + ' '*(2*i) + '\\\\' for i in range(n))\n res.append('/' + '_'*(2*n) + '\\\\')\n res.extend('|' + ' '*(l-2) + '|' for _ in range(n-1))\n res.append('|' + '_'*(l-2) + '|')\n return '\\n'.join(s.center(l) for s in res)", "def my_crib(n):\n crib = [f\"{mult(n-i)}/{mult(i*2)}\\\\{mult(n-i)}\" for i in range(n)]\n crib.append(f\"/{mult(n*2, '_')}\\\\\")\n crib.extend(f\"|{mult(n*2)}|\" for _ in range(n-1))\n crib.append(f\"|{mult(n*2, '_')}|\")\n return \"\\n\".join(crib)\n\n\ndef mult(n, char=\" \"):\n return char * n", "def my_crib(n):\n w = n * 2\n return '\\n'.join(\n [('/' + ' ' * (i * 2) + '\\\\').center(w + 2) for i in range(n)]\n + ['/' + '_' * (w) + '\\\\']\n + ['|' + ' ' * w + '|'] * (n-1)\n + ['|' + '_' * w + '|']\n )", "import itertools\n\n\ndef my_crib(n):\n \"\"\"Return an ASCII art house with 'n' floors.\"\"\"\n def format(chars, fill_width):\n return (\"{chars[0]}{chars[2]:{chars[1]}>{width}}\"\n .format(chars=chars, width=fill_width + 1)\n .center(2 * n + 2))\n return \"\\n\".join(itertools.chain(\n (format('/ \\\\', 2 * i) for i in range(n)),\n (format('/_\\\\', 2 * n), ),\n (format(\"| |\", 2 * n) for _ in range(n - 1)),\n (format('|_|', 2 * n), ),\n ))", "my_crib=lambda n:\"\\n\".join([('/'+[' ','_'][i==n]*(i*2)+'\\\\').center(n*2+2,' ')for i in range(n+1)])+'\\n'+\"\\n\".join(['|'+[' ','_'][i==n-1]*(n*2)+'|'for i in range(n)])", "def my_crib(n):\n roof = '\\n'.join('{0}/{1}\\\\{0}'.format(' '*(n-i),' _'[n==i]*i*2) for i in range(n+1))\n x = lambda a: '\\n|'+a*n*2+'|'\n return roof + x(' ')*(n-1) + x('_')", "class House(object):\n roofleft, roofright = '/', '\\\\'\n wall = '|'\n bottom = '_'\n \n def __init__(self, floors):\n self.floors = floors\n \n def __new__(cls, floors):\n a = super(House, cls).__new__(cls)\n a.__init__(floors)\n return str(a)\n \n @property\n def width(self):\n return self.floors * 2 + 2\n \n @property\n def height(self):\n return self.floors * 2 + 1\n \n @property\n def roofparts(self):\n return list(range(self.floors))\n \n @property\n def gutterparts(self):\n return list(range(max(self.roofparts) + 1, max(self.roofparts) + 2))\n \n @property\n def floorparts(self):\n return list(range(max(self.gutterparts) + 1, self.height - 1))\n \n @property\n def groundparts(self):\n return list(range(self.height -1, self.height))\n \n def genpart(self, index):\n if index in self.roofparts:\n return self.genroof(index, outerfill=\" \", innerfill=\" \")\n if index in self.gutterparts:\n return self.genroof(index, outerfill=\"\", innerfill=\"_\")\n if index in self.floorparts:\n return self.genfloor(index, outerfill=\"\", innerfill=\" \")\n if index in self.groundparts:\n return self.genfloor(index, outerfill=\"\", innerfill=\"_\")\n \n def genroof(self, index, innerfill, outerfill):\n margin = \"{:{outerfill}^{width}}\".format(\"\", outerfill=outerfill, width=(self.floors - index))\n roofpart = \"{margin}{roofleft}{centerfill}{roofright}{margin}\".format(\n margin=margin,\n roofleft=self.roofleft,\n roofright=self.roofright,\n centerfill=innerfill * 2 * index)\n return roofpart\n \n def genfloor(self, index, innerfill, outerfill):\n margin = \"{outerfill:{innerfill}^{width}}\".format(innerfill=innerfill, outerfill=outerfill, width=self.width)\n roofpart = \"{wall}{centerfill}{wall}\".format(\n wall=self.wall,\n centerfill=innerfill * (self.width - 2))\n return roofpart\n \n def draw(self):\n lines = []\n for index in range(self.height):\n part = self.genpart(index)\n if not part:\n part = \"X\" * self.width\n lines.append(part)\n return '\\n'.join(lines)\n \n def bounding_box(self):\n lines = []\n for row in range(self.height):\n lines.append('X' * self.width)\n return '\\n'.join(lines)\n \n @property\n def __name__(self):\n return [objname for objname,oid in list(globals().items()) if id(oid)==id(self)]\n \n def allnames(self):\n results = [n for n, v in list(globals().items()) if v is arg]\n return results[0] if len(results) is 1 else results if results else None\n \n def __repr__(self):\n #return 'House({})'.format(self.floors)\n return repr(self.draw())\n \n def __str__(self):\n return self.draw()\n \n def describe(self):\n return 'a bVectorian era {} story home called \"{}\" {{ signified as {}, identified as {} }}'.format(self.floors, self.__name__, repr(self), id(self))\n \nmy_crib = House\n\ndef testings():\n commonhouse = House(1)\n middleclasshouse = House(2)\n ritzyhouse = House(3)\n bigscaryhouse = House(4)\n cribs = [commonhouse,middleclasshouse,ritzyhouse,bigscaryhouse]\n for crib in cribs:\n print(crib)\n print(crib.draw())\n print(crib.roofparts, crib.gutterparts, crib.floorparts, crib.groundparts)\n"] | {"fn_name": "my_crib", "inputs": [[1], [2], [3]], "outputs": [[" /\\ \n/__\\\n|__|"], [" /\\ \n / \\ \n/____\\\n| |\n|____|"], [" /\\ \n / \\ \n / \\ \n/______\\\n| |\n| |\n|______|"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 6,266 |
def my_crib(n):
|
160f19565165a9b17f8cb778b1c980d2 | UNKNOWN | Write a program that will take a string of digits and give you all the possible consecutive slices of length `n` in that string.
Raise an error if `n` is larger than the length of the string.
## Examples
For example, the string `"01234"` has the following 2-digit slices:
```
[0, 1], [1, 2], [2, 3], [3, 4]
```
The same string has the following 4-digit slices:
```
[0, 1, 2, 3], [1, 2, 3, 4]
``` | ["def series_slices(digits, n):\n if n > len(digits):\n raise ValueError\n else:\n return [[int(digit) for digit in digits[i:i+n]] for i in range(0, len(digits)-n+1)]", "def series_slices(s, n):\n if n > len(s):\n raise\n \n arr = [int(d) for d in s]\n return [ arr[i:i+n] for i in range(len(s)-n +1) ]", "def series_slices(digits, n):\n l = len(digits)\n if n > l:\n raise Exception\n else:\n d = list(map(int, digits))\n \n res = []\n for i in range(0, l-n+1):\n res.append(d[i:i+n])\n return res", "def series_slices(d, n):\n # Good Luck!\n if(n>len(d)): return error\n x=[]\n i=0\n while(i<=len(d)-n):\n x.append([int(i) for i in d[i:i+n]])\n i+=1\n return x\n \n \n", "def series_slices(digits, n):\n if n > len(digits):\n 0 / 0\n return [list(map(int, digits[x:n+x])) for x in range((len(digits) - n) + 1)]", "def series_slices(digits, n):\n digits = [int(i) for i in digits]\n if n > len(digits):\n raise Error('Your n is bigger than the lenght of digits') \n else:\n return [list(digits[i:n+i]) for i in range(len(digits)) if len(digits[i:n+i]) == n]", "def series_slices(digits, n):\n assert n <= len(digits)\n return [list(map(int, digits[i: i+n])) for i in range(len(digits)-n+1)]", "def series_slices(digits, n):\n if n > len(digits):\n raise ValueError('n cannot be greater than number of digits')\n \n else:\n res = [digits[i:i+n] for i in range(len(digits) - n + 1)]\n for i in range(len(res)):\n res[i] = [int(e) for e in res[i]]\n\n return res", "def series_slices(digits, n):\n if n > len(digits):\n raise error\n else:\n x = [int(y) for y in digits]\n return [x[i:i+n] for i in range(0,len(digits)-n+1)]", "def series_slices(digits, n):\n return [list(map(int, digits[i:i+n])) for i in range(len(digits)-n+1)] if n <= len(digits) else int(\"\")"] | {"fn_name": "series_slices", "inputs": [["01234", 1], ["01234", 2], ["01234", 3], ["01234", 4], ["01234", 5]], "outputs": [[[[0], [1], [2], [3], [4]]], [[[0, 1], [1, 2], [2, 3], [3, 4]]], [[[0, 1, 2], [1, 2, 3], [2, 3, 4]]], [[[0, 1, 2, 3], [1, 2, 3, 4]]], [[[0, 1, 2, 3, 4]]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,030 |
def series_slices(digits, n):
|
be09f78268625ed065e1112b40a29d6d | UNKNOWN | Your job is to change the given string `s` using a non-negative integer `n`.
Each bit in `n` will specify whether or not to swap the case for each alphabetic character in `s`: if the bit is `1`, swap the case; if its `0`, leave it as is. When you finished with the last bit of `n`, start again with the first bit.
You should skip the checking of bits when a non-alphabetic character is encountered, but they should be preserved in their original positions.
## Examples
```
swap('Hello world!', 11) --> 'heLLO wORLd!'
```
...because `11` is `1011` in binary, so the 1st, 3rd, 4th, 5th, 7th, 8th and 9th alphabetical characters have to be swapped:
```
H e l l o w o r l d !
1 0 1 1 1 0 1 1 1 0
^ ^ ^ ^ ^ ^ ^
```
More examples:
```
swap("gOOd MOrniNg", 7864) --> "GooD MorNIng"
swap('', 11345) --> ''
swap('the lord of the rings', 0) --> 'the lord of the rings'
``` | ["from itertools import cycle\n\ndef swap(s,n):\n b = cycle(bin(n)[2:])\n return \"\".join(c.swapcase() if c.isalpha() and next(b) == '1' else c for c in s)", "from itertools import cycle\n\ndef swap(s,n):\n doSwap = cycle(map(int,f\"{n:b}\"))\n return ''.join(c.swapcase() if c.isalpha() and next(doSwap) else c for c in s)", "def swap(s,n):\n n = str(bin(n))[2:]\n index = 0\n new_s = ''\n for letter in s:\n if letter.isalpha():\n if n[index%len(n)]=='1':\n new_s += letter.swapcase()\n else:\n new_s += letter\n index+=1\n else:\n new_s += letter\n return new_s", "from itertools import cycle\ndef swap(s,n):\n binary = cycle(bin(n)[2:])\n return ''.join(char.swapcase() if char.isalpha() and next(binary) == '1' else char for char in s)", "from itertools import cycle\n\ndef swap(s,n):\n bits = cycle(map(int, f'{n:b}'))\n return ''.join(c.swapcase() if (c.isalpha() and next(bits)) else c for c in s)", "from itertools import cycle\n\ndef swap(s, n):\n it = cycle(bin(n)[2:])\n return \"\".join(x.swapcase() if x.isalpha() and next(it) == \"1\" else x for x in s)", "def swap(s,n):\n bits, r, c = bin(n)[2:], '', 0\n for i in s:\n r += [i, i.swapcase()][int(bits[c%len(bits)])]\n c += i.isalpha()\n return r ", "def swap(s,n):\n n = str(bin(n))[2:]\n words = list(s) \n binary_mult = str(n) * len(s)\n bn_words = list(binary_mult)\n result = []\n for i, x in enumerate(words):\n if not x.isalpha():\n bn_words.insert(i, x)\n if bn_words[i] == '1':\n result.append(words[i].swapcase())\n else:\n result.append(words[i])\n return ''.join(result)", "from itertools import cycle\ndef swap(s,n):\n return ( lambda N: ''.join( e if not e.isalpha() else (e,e.swapcase())[next(N)] for e in s ))(cycle(map(int, bin(n)[2:])))", "from itertools import cycle\n\n\ndef swap(s, n):\n it = cycle(map(int, format(n, \"b\")))\n return \"\".join(c.swapcase() if c.isalpha() and next(it) else c for c in s)"] | {"fn_name": "swap", "inputs": [["Hello world!", 11], ["the quick broWn fox leapt over the fence", 9], ["eVerybody likes ice cReam", 85], ["gOOd MOrniNg", 7864], ["how are you today?", 12345], ["the lord of the rings", 0], ["", 11345]], "outputs": [["heLLO wORLd!"], ["The QUicK BrowN foX LeaPT ovER thE FenCE"], ["EVErYbODy LiKeS IcE creAM"], ["GooD MorNIng"], ["HOw are yoU TOdaY?"], ["the lord of the rings"], [""]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,137 |
def swap(s,n):
|
bd0440abbd56e46feb94d4df46f491ca | UNKNOWN | Consider X as the aleatory variable that count the number of letters in a word. Write a function that, give in input an array of words (strings), calculate the variance of X.
Max decimal of the variance : 4.
Some wiki: Variance ,
Aleatory variable
Example:
Consider "Hello" and "World":
X is { 5 } with P(X = 5) = 1 beacuse the two words has the same length.
So E[X] = 5 x 1 = 5 and the standard formula for variance is E[(X - u)^2] so 1 x (5-5)^2 = 0
or you can calculate with the other formula E[X^2] - E[X]^2 = 5^2 x 1 - 5^2 = 0
Consider "Hi" and "World":
X is { 2, 5 } with P(X = 5) = 1/2 and P(X = 2) = 1/2.
So E[X] = 5 x 1/2 + 2 x 1/2 = 3.5 and the standard formula for variance is E[(X - u)^2] so 1/2 x (2-3.5)^2 + 1/2 x (5 - 3.5)^2 = 2.25
or you can calculate with the other formula E[X^2] - E[X]^2 = (5^2 x 1/2 + 2^2 x 1/2) - 3.5^2 = 2.25 | ["variance=lambda w:round(__import__('statistics').pvariance(map(len,w)),4)", "from statistics import pvariance\n\ndef variance(words):\n return round(pvariance(map(len, words)), 4)", "from statistics import pvariance as var\n\nvariance = lambda words: round(var(len(word) for word in words), 4)", "def variance(words):\n from statistics import pvariance as var\n return round(var(len(word) for word in words), 4)\n", "def mean(x):\n s = 0\n for i in range(len(x)):\n s = s + x[i]\n return s/len(x)\n\ndef variance(words):\n x = [len(word) for word in words]\n return round(mean([num**2 for num in x])-mean(x)**2,4)", "def variance(li):\n common = 1 / len(li)\n e_of_x = sum(len(i) * common for i in li)\n result = sum((len(i) ** 2) * common for i in li) - e_of_x ** 2\n return round(result,4)", "variance=lambda w,v=__import__(\"statistics\").pvariance:round(v(map(len,w)),4)", "def variance(array):\n nums = list(map(len, array))\n length = float(len(nums))\n average = sum(nums) / length\n return round(sum((average - a) ** 2 for a in nums) / length, 4)\n", "from collections import Counter\nfrom numpy import average\n\ndef variance(words):\n values, weights = zip(*Counter(map(len, words)).items())\n return round(average((values-average(values, weights=weights))**2, weights=weights), 4)"] | {"fn_name": "variance", "inputs": [[["Hello", "world"]], [["Hi", "world"]], [["Variance", "is", "not", "a", "good", "stimator"]]], "outputs": [[0], [2.25], [7.5556]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,356 |
def variance(words):
|
129cec24f5b0727d455e0f4cd67e5619 | UNKNOWN | Happy traveller [Part 1]
There is a play grid NxN; Always square!
0 1 2 3
0 [o, o, o, X]
1 [o, o, o, o]
2 [o, o, o, o]
3 [o, o, o, o]
You start from a random point. I mean, you are given the coordinates of your start position in format (row, col).
And your TASK is to define the number of unique paths to reach position X (always in the top right corner).
From any point you can go only UP or RIGHT.
Implement a function count_paths(N, (row, col)) which returns int;
Assume input params are always valid.
Example:
count_paths(1, (0, 0))
grid 1x1:
[X]
You are already in the target point, so return 0
count_paths(2, (1, 0))
grid 2x2:
[o, X]
[@, o]
You are at point @; you can move UP-RIGHT or RIGHT-UP, and there are 2 possible unique paths here
count_paths(2, (1, 1))
grid 2x2:
[o, X]
[o, @]
You are at point @; you can move only UP, so there is 1 possible unique path here
count_paths(3, (1, 0))
grid 3x3:
[o, o, X]
[@, o, o]
[o, o, o]
You are at point @; you can move UP-RIGHT-RIGHT or RIGHT-UP-RIGHT, or RIGHT-RIGHT-UP, and there are 3 possible unique paths here
I think it's pretty clear =)
btw. you can use preloaded Grid class, which constructs 2d array for you. It's very very basic and simple. You can use numpy instead or any other way to produce the correct answer =)
grid = Grid(2, 2, 0)
samegrid = Grid.square(2) will give you a grid[2][2], which you can print easily to console.
print(grid)
[0, 0]
[0, 0]
Enjoy!
You can continue adventures:
Happy traveller [Part 2] | ["from math import factorial as f\ncount_paths=lambda n,c:f(c[0]+abs(n-c[1]-1))//(f(abs(n-c[1]-1))*f(c[0])) if n!=1 else 0", "from math import factorial\ndef count_paths(N, coords):\n if N==1:\n return 0\n x=coords[0]\n y=N-1-coords[1]\n return factorial(x+y)//(factorial(x)*factorial(y))", "count_paths=lambda n,C,f=__import__('math').factorial:(n!=1)*f(n+C[0]-1-C[1])//f(C[0])//f(n-1-C[1])", "def count_paths(N,C,f=lambda n:eval('*'.join(map(str,range(1,n+1))))):\n a,y=C\n b=N-1-y\n return 1-(b==0)if a==0else 1-(a==0)if b==0 else f(a+b)//f(a)//f(b) ", "import math\ndef count_paths(N, coords):\n t = N-1 - coords[1] + coords[0]\n if t == 0:\n return 0\n \n return math.factorial(t)//(math.factorial(coords[0])*math.factorial(t-coords[0]))", "import math\n\n# if you look at the matrix of possible paths...\n# [ 1, 1, 1, 0]\n# [ 4, 3, 2, 1]\n# [10, 6, 3, 1]\n# [20, 10, 4, 1]\n# ...the diagonals reflect Pascal's triangle.\n#\n# For example, 4C1 = 4, 4C2 = 6, 4C3 = 4\n# Each cell (row, col) has possible paths = dC(l-row) where:\n# d = the ordinal of the diagonal (zero-indexed)\n# l = the length of the diagonal\n#\n# We can calculate d and l like so:\n# d = row + n - 1 - col\n# l = d + 1\n#\n# Combined, we get:\n# (row + n - 1 - col) C (n - 1 - col)\ndef count_paths(N, coords):\n row, col = coords\n if row == 0 and col == N-1:\n return 0\n \n inverse_col = N - 1 - col\n return choose(row + inverse_col, inverse_col)\n\n# aCb = a!/(a-b)!b!\ndef choose(n,k):\n if k > n:\n return 0\n if k > n-k:\n k = n-k\n product = 1\n k_list = list(range(2, k+1))\n for i in range(n, n-k, -1):\n if len(k_list) > 0:\n k_index = len(k_list)-1\n k = k_list[k_index]\n if i % k == 0:\n i = i // k\n del k_list[k_index]\n product *= i\n for k in k_list:\n product //= k\n return product", "from math import factorial as f\nbino=lambda x,y: f(x)//f(y)//f(x-y)\n\ndef count_paths(N, coords):\n d1,d2 = N - coords[1] - 1, coords[0]\n return bino(d1+d2,min(d1,d2)) if d1+d2 else 0\n"] | {"fn_name": "count_paths", "inputs": [[1, [0, 0]], [2, [1, 0]], [2, [1, 1]], [3, [1, 0]], [5, [4, 0]], [6, [5, 0]], [7, [6, 0]]], "outputs": [[0], [2], [1], [3], [70], [252], [924]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,192 |
def count_paths(N, coords):
|
123ee0b4384dacc07043eb73c81a9162 | UNKNOWN | You are given a certain integer, ```n, n > 0```. You have to search the partition or partitions, of n, with maximum product value.
Let'see the case for ```n = 8```.
```
Partition Product
[8] 8
[7, 1] 7
[6, 2] 12
[6, 1, 1] 6
[5, 3] 15
[5, 2, 1] 10
[5, 1, 1, 1] 5
[4, 4] 16
[4, 3, 1] 12
[4, 2, 2] 16
[4, 2, 1, 1] 8
[4, 1, 1, 1, 1] 4
[3, 3, 2] 18 <---- partition with maximum product value
[3, 3, 1, 1] 9
[3, 2, 2, 1] 12
[3, 2, 1, 1, 1] 6
[3, 1, 1, 1, 1, 1] 3
[2, 2, 2, 2] 16
[2, 2, 2, 1, 1] 8
[2, 2, 1, 1, 1, 1] 4
[2, 1, 1, 1, 1, 1, 1] 2
[1, 1, 1, 1, 1, 1, 1, 1] 1
```
So our needed function will work in that way for Python and Ruby:
```
find_part_max_prod(8) == [[3, 3, 2], 18]
```
For javascript
```
findPartMaxProd(8) --> [[3, 3, 2], 18]
```
If there are more than one partition with maximum product value, the function should output the patitions in a length sorted way.
Python and Ruby
```
find_part_max_prod(10) == [[4, 3, 3], [3, 3, 2, 2], 36]
```
Javascript
```
findPartMaxProd(10) --> [[4, 3, 3], [3, 3, 2, 2], 36]
```
Enjoy it! | ["def find_part_max_prod(n):\n if n == 1: return [[1], 1]\n q, r = divmod(n, 3)\n if r == 0: return [[3]*q, 3**q]\n if r == 1: return [[4] + [3]*(q - 1), [3]*(q - 1) + [2, 2], 3**(q - 1) * 2**2]\n return [[3]*q + [2], 3**q * 2]", "from collections import defaultdict\nfrom functools import reduce\n\ndef find_part_max_prod(n):\n prods = defaultdict(list)\n for p in sum_part(n):\n prods[reduce(int.__mul__, p)].append(p)\n mx = max(prods.keys())\n return sorted(prods[mx], key=len) + [mx]\n\ndef sum_part(n, k=2):\n if n < 5:\n yield [n]\n for i in range(k, n//2 + 1):\n for part in sum_part(n-i, i):\n yield part + [i]", "from collections import defaultdict\n\ndef partitions(n, I=1):\n yield (n, [n])\n for i in range(n//2, I-1, -1):\n for x,p in partitions(n-i, i):\n yield (x*i, p+[i])\n\ndef find_part_max_prod(n):\n result = defaultdict(list)\n for x,p in partitions(n):\n result[x].append(p)\n k, v = max(result.items())\n return [*v, k]", "def partitions(n, s=float('inf')):\n if not n: yield []; return\n for i in range(min(n, s), 0, -1):\n for p in partitions(n - i, i):\n yield [i] + p\n\nfrom collections import defaultdict\nfrom functools import reduce\nfrom operator import mul\ndef find_part_max_prod(n):\n products = defaultdict(list)\n for p in partitions(n):\n products[reduce(mul, p)].append(p)\n m = max(products)\n return products[m] + [m]", "from functools import reduce\ndef find_part_max_prod(n):\n partitions = []\n for k in range(1,n+1):\n part = [n//k+1]*(n%k)+[n//k]*(k-n%k)\n partitions.append([reduce(int.__mul__, part), part])\n m = max(partitions)[0]\n return [j for i,j in partitions if i==m] + [m]", "def find_part_max_prod(n):\n if n % 3 == 0:\n return [[3]*(n/3),3**(n/3)]\n if n % 3 == 2:\n return [[3]*(n//3)+[2],3**(n//3)*2]\n if n == 1:\n return 1\n if n % 3 == 1:\n return [[4]+[3]*(n//3-1),[3]*(n//3-1)+[2,2],3**(n//3-1)*4]", "def find_part_max_prod(n):\n if(n==2):\n return [[1, 1], 1]\n if(n==3):\n return [[2, 1], 1]\n if(n%3==0):\n return [[3]*(n//3), pow(3, n//3)]\n if(n%3==2):\n return [[3]*((n-2)//3) + [2] , 2 * pow(3, (n-2)//3)]\n if(n%3==1):\n return [[4] + [3]*((n-4)//3), [3]*((n-4)//3) + [2, 2], 4 * pow(3, (n-4)//3)]", "def find_part_max_prod(n):\n if n % 3 == 0:\n Q = n//3\n return [[3]*Q, 3**Q]\n elif (n - 1) % 3== 0:\n Q = (n-1)//3 - 1\n return [[4]+[3]*Q,[3]*Q+[2,2], 4*3**Q]\n elif (n - 2) % 3 == 0:\n Q = (n-2)//3\n return [[3]*Q+[2], 2*3**Q]"] | {"fn_name": "find_part_max_prod", "inputs": [[8], [10]], "outputs": [[[[3, 3, 2], 18]], [[[4, 3, 3], [3, 3, 2, 2], 36]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,718 |
def find_part_max_prod(n):
|
285de65b240c2c0d14d255d9e5a81c8d | UNKNOWN | # Exclusive "or" (xor) Logical Operator
## Overview
In some scripting languages like PHP, there exists a logical operator (e.g. ```&&```, ```||```, ```and```, ```or```, etc.) called the "Exclusive Or" (hence the name of this Kata). The exclusive or evaluates two booleans. It then returns true if **exactly one of the two expressions are true**, false otherwise. For example:
## Task
Since we cannot define keywords in Javascript (well, at least I don't know how to do it), your task is to define a function ```xor(a, b)``` where a and b are the two expressions to be evaluated. Your ```xor``` function should have the behaviour described above, returning true if **exactly one of the two expressions evaluate to true**, false otherwise. | ["def xor(a,b):\n return a != b", "def xor(a,b):\n return a ^ b", "from operator import xor", "def xor(a,b):\n return a is not b", "def xor(a,b):\n print(a,b)\n if a == True and b == True: \n return False\n elif a == True or b == True:\n return True\n return False", "xor = int.__xor__", "xor=lambda a,b: a!=b", "xor = __import__(\"operator\").__xor__", "def xor(a,b):\n #your code here\n return False if a and b else a or b", "def xor(a,b):\n return False if (a and b) == True or (a or b) == False else True", "def xor(a,b):\n return len(set([a, b])) > 1", "xor = lambda *_: _[0]^_[1]", "xor = bool.__xor__", "def xor(a,b):\n return bool((a + b) % 2)", "def xor(a,b):\n if a == True and b == True:return False\n if a == True and b == False:return True\n if a == True and b == True:return True\n if a == False and b == False:return False\n else: return True", "def xor(a,b):\n return abs(a-b)", "def xor(a,b):\n if a == b:\n return False\n elif a != b or b != a:\n return True", "def xor(a,b):\n truCount = 0\n if a:\n truCount += 1\n if b:\n truCount += 1\n if truCount == 1:\n return True\n return False", "def xor(a,b):\n #your code here\n result = a ^ b\n return result", "def xor(a,b):\n return True if (False in (a, b)) and (True in (a, b)) else False", "def xor(a,b):\n if a==b:\n return False\n return True if a or b ==True else False", "def xor(a,b):\n if a == b:\n return False\n elif a == True and b == False:\n return True\n elif a == False and b == True:\n return True\n \n #your code here\n", "def xor(a,b):\n return (a+b)*((not a) + (not b))", "def xor(a,b):\n if a==b==True or a==b==False:\n return False\n else:\n return True", "def xor(a,b):\n if a == b == True:\n return False\n return True if a==True or b==True else False\n", "def xor(a,b):\n c = 0\n n = str(a).count(\"True\")\n m = str(b).count(\"True\")\n c = n + m\n return (c%2)!=0", "def xor(a,b):\n return (a==True or a==False) and a!=b", "def xor(a,b):\n if a == b:\n return False\n if a == True or b == True:\n return True", "def xor(a,b):\n return a != b and max(a,b) == True", "def xor(a,\n b):\n\n return a != b\n", "def xor(a,b):\n return a==True and b!=True or a==False and b!=False", "def xor(a,b):\n if a is True and b is True:\n return False\n elif a is False and b is False:\n return False\n else:\n return True\n", "def xor(a,b):\n return a or b if (a,b) != (True,True) else False", "def xor(a: bool, b: bool) -> bool:\n return a ^ b", "def xor(a,b):\n if a is True and b is False or b is True and a is False:\n return True\n else:\n return False\n", "def xor(a,b):\n count = 0\n if a == True:\n count += 1\n if b == True:\n count += 1\n if a != True:\n count -= 1\n if b != True:\n count -= 1\n if count == 0:\n return True\n return False", "def xor(a,b):\n if a ^ b == False:\n return False\n elif b ^ b == False:\n return True", "xor = lambda a, b: True if (not a and b) or (a and not b) else False", "def xor(a,b):\n return b != a", "def xor(a,b):\n return a is not b\n # by not it checks if a is not equal to b thus 'xor'\n", "def xor(a,b):\n if a == False and b == False:\n return False\n if a and b == True:\n return False\n if a or b == False and a or b == True:\n return True", "def xor(a,b):\n a =[a]\n b = [b]\n #if (sum(a+b) ==0) or (sum(a+b) == 2):\n # return False\n #else:\n # return True\n return (sum(a+b) ==1)", "def xor(a,b):\n '''Function evaluates 2 expressions and returns true if only one of them is true'''\n if a is True and b is True:\n return False\n elif a is True or b is True:\n return True\n else:\n return False\n pass", "def xor(a,b):\n if a==True and b==True:\n return False\n elif a==True and b==False:\n return True\n elif b==True and a==False:\n return True\n elif a==False and b==False:\n return False", "def xor(a,b):\n if (a == True and b == False) or (a == False and b == True):\n return True #f'{a} xor {b} == True'\n else:\n return False #f'{a} xor {b} == False'", "def xor(a,b):\n if a is b:\n return False\n else:\n return a or b", "def xor(a,b):\n if a is True and b is False:\n return True\n elif b is True and a is False:\n return True\n else:\n return False", "def xor(a,b):\n \n if a and b == True: return False\n if a or b == True: return True\n return False", "def xor(a,b):\n #your code here\n if a and b == True:\n return False\n elif a or b == True:\n return True\n else:\n False\n return False\n", "def xor(a,b):\n if a == False and b == True or b == False and a == True:\n return True\n else:\n return False", "def xor(a,b):\n if not a:\n if b:\n return True\n else:\n return False\n elif not b:\n if a:\n return True\n else:\n return False\n else:\n return False", "def xor(a,b):\n if a == True and b == True:\n return False\n if a == False and b == False:\n return False\n else:\n return True\n", "def xor(a,b):\n if a == True and b == True:\n return False\n if a or b == True:\n return True\n else:\n return False", "def xor(a,b):\n if a!=b:\n return True\n elif a==b:\n return False\n else:\n return False", "def xor(a,b):\n print((a, b))\n if a == True and b == False or b == True and a == False:\n return True\n else:\n return False\n #your code here\n", "def xor(a,b):\n return ((1-a)+(1-b))%2==1", "xor = lambda a, b:False if a and b else True if a or b else False", "def xor(a,b):\n j=False\n if(a!=b):\n j=True\n return j \n #your code here\n", "def xor(a,b):\n return False if a and b or a == False and b == False else True", "def xor(a,b):\n if a is True:\n if b is True:\n return False\n if a is False:\n if b is False:\n return False\n if b is True:\n if a is True:\n return False\n if b is False:\n if a is False:\n return False\n if a is True:\n if b is False:\n return True\n if b is True:\n if a is False:\n return True", "def xor(a,b):\n if a or b:\n if a and b:\n return False\n return True\n else:\n return False", "def xor(a,b):\n if (a == True and b == True) :\n return False\n if a == True or b == True:\n return True\n return False\n", "def xor(a,b):\n if int(a + b) == 0:\n return False\n elif int(a + b) == 1:\n return True\n elif int(a + b) == 2:\n return False", "def xor(a,b):\n x = int(a)\n y = int(b)\n return a^b\n", "def xor(a,b):\n if a == False and b == False:\n return False\n elif a == True and b == True:\n return not a\n return a or b", "def xor(a,b):\n if a==True and b==True:\n return False\n elif a==True and b==False:\n return True\n elif a==False and b==False:\n return False\n else:\n return True", "def xor(a,b):\n return (a,b) == (True,False) or (a,b) == (False, True)", "xor = lambda x, y: x is not y", "def xor(a,b):\n if a == True:\n if b == True:\n return False\n else:\n return True\n elif b == True:\n if a == True:\n return False\n else:\n return True\n else:\n return False", "def xor(a,b):\n if a and b == True:\n return False\n else:\n return a or b\n", "def xor(a,b):\n return (a is b) is False", "def xor(a,b):\n return not (not (a or b) or (a and b))", "def xor(a,b):\n if a == True and b == True:\n return False\n elif (a == True and b == False) or (a == False and b == True):\n return True\n else:\n return False", "def xor(a,b):\n my_bool = True\n if a and b:\n return False\n elif a == False and b == False:\n return False\n elif a or b:\n return True\n \n", "def xor(a,b):\n \n if a == True and b == False:\n return True \n elif a == False and b == False:\n return False \n elif a == False and b == True:\n return True\n elif a == True and b == True:\n return False", "def xor(a,b):\n if a:\n if b:\n return False\n return a or b", "def xor(a,b):\n if a is not b:\n return True\n else:\n return False", "def xor(a,b):\n if(a == False and b == False):\n return False\n if(a == True and b == True):\n return False\n if(a == False and b == True):\n return True\n if(a == True and b == False):\n return True", "# end goal - function should return True if exactly ONE of two expressions evalualte to true, otherwise false\n# input = two booleans, a and b\n# output = boolean\n\n# How would the computer recognize that only one boolean is True when nested? by comparing the two booleans rather than conditionals for each statement\n\n#function xor taking two expressions a, b\ndef xor(a,b):\n# if a is not equal to b, then only one of the expressions can be True\n return a != b\n", "def xor(a,b):\n if a is False and b is True:\n return True\n elif a is True and b is False:\n return True\n else:\n return False", "def xor(a,b):\n if a == b:\n return False\n print(a,b)\n return any([a,b])", "def xor(a,b):\n if a == True:\n if b == True:\n return False\n if a == True:\n if b == False:\n return True\n if a == False:\n if b == False:\n return False\n if a == False:\n if b == True:\n return True", "def xor(a,b):\n #your code here\n # checking the a and b values for false - false respectively \n if not a and not b:\n return False\n # checking the a and b values for true - false\n elif a and not b:\n return True\n # checking the a and b values for false - true\n elif not a and b:\n return True\n # checking the a and b values for true - true respectively \n else:\n return False", "def xor(a,b):\n xor = False\n if a == True and b == True:\n xor = False\n elif a == False and b == False:\n xor = False\n elif a == True and b == False:\n xor = True\n elif a == False and b == True:\n xor = True\n return xor", "def xor(a,b):\n return (a+b < 2) and (a+b > 0)", "def xor(a,b):\n answer = 0\n if a == True:\n answer += 1\n if b == True:\n answer += 1\n if answer == 1:\n return True\n else:\n return False\n \n", "def xor(a,b):\n if a == True and b == True:\n return False\n elif a == False and b == False:\n return False\n elif a == False and b == True:\n return True\n elif a == True and b == False:\n return True\n else:\n return False", "xor = lambda a,b: int(a) ^ int(b)", "def xor(a,b):\n if a is True and b is True:\n return False\n if a is True and b is False:\n return True\n if a is False and b is True:\n return True\n if a is False and b is False:\n return False", "xor = lambda a, b : int(a) + int(b) == 1", "from operator import xor as xor_\nfrom functools import reduce\n\ndef xor(a,b):\n return reduce(xor_, (a, b))", "def xor(a,b):\n if a == False:\n if b == True:\n return True\n elif b == False:\n return False\n if a == True:\n if b == True:\n return False\n elif b == False:\n return True", "xor = lambda a,b: a+b == 1", "def xor(a,b):\n c = 0\n if a:\n c += 1\n if b:\n c += 1\n if c == 1:\n return True\n else:\n return False\n", "from operator import xor as xor1\ndef xor(a,b):\n return xor1(a,b)", "def xor(a,b):\n return False if a==b else True\n \n#returning False when a equals to b else its returning true\n", "def xor(a,b):\n\n result = True\n \n if a==True and b==True:\n result=False\n elif (a == True and b == False) or (b == True and a ==False):\n result=True\n elif a==False and b==False:\n result=False \n \n return result ", "def xor(a,b):\n print(a,b)\n if a == True and b == False:\n result = True\n elif a == False and b == True:\n result = True\n else:\n result = False\n return result", "def xor(a,b):\n return (False, True) [a != b]"] | {"fn_name": "xor", "inputs": [[false, false], [true, false], [false, true], [true, true]], "outputs": [[false], [true], [true], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 13,094 |
def xor(a,b):
|
9c9e23ac86972708fccf3adb617faf81 | UNKNOWN | ## Problem
There are `n` apples that need to be divided into four piles. We need two mysterious number `x` and `y`. Let The number of first pile equals to `x+y`, the number of second pile equals to `x-y`, the number of third pile equals to `x*y`, the number of fourth pile equals to `x/y`. We need to calculate how many apples are there in each pile.
Of course, there won't be so many unknowns. We know the total number of apples(`n`) and the second mysterious number(`y`).
For example: there are 48 apples need to divided into four piles. y=3. that is, 1st pile should be x+3, 2nd pile should be x-3, 3rd pile should be x*3, 4th pile should be x/3.
Do you know how much `x` is? `x` should be 9, because:
```
(9 + 3) + (9 - 3) + (9 * 3) + (9 / 3) = 12 + 6 + 27 + 3 = 48
```
So, 48 apples should be divided into `12, 6, 27, 3`.
## Task
Complete function `fourPiles()`/`four_piles()` that accepts two arguments `n` and `y`, return an array contains the number of for piles. Each element in the result array should be a positive integer. If can not divide, please return `[]`.
## Examples
```
fourPiles 48 3 -- [12,6,27,3]
//The elements are arranged in sequence according to:
// x+y,x-y,x*y,x/y
fourPiles 100 4 -- [20,12,64,4]
-- Verify correctness:
-- x=16,y=4
(16+4) + (16-4) + (16*4) + (16/4) -- 100
-- Edge case:
fourPiles 25 4 -- [] -- [8,0,16,1] is not a correct answer
fourPiles 24 4 -- [] -- can not divide
``` | ["def four_piles(n,y):\n x,r=divmod(n*y,(y+1)**2)\n return [] if r or x==y else [x+y,x-y,x*y,x//y]\n", "def four_piles(n,y): \n x = y * n / (y**2 + 2*y + 1)\n return [x + y, x - y, x * y, x / y] if int(x) == x and x - y > 0 else []", "def four_piles(n,y):\n x = y*n / (1+2*y+y**2)\n ans = [x+y, x-y, x*y, x/y]\n return ans if all(not z%1 and z for z in ans) else []", "def four_piles(n,y):\n x = round(n/(2+y+1/y))\n ls = [x+y,x-y,x*y,x/y]\n return ls if x-y>0 and x%y==0 and sum(ls) == n else []", "four_piles=lambda n,y:(lambda x,m:((x>y)>x%y+m)*[x+y,x-y,x*y,x/y])(*divmod(n*y,y*y+2*y+1))", "def four_piles(n,y):\n candidates = ([x+y, x-y, x*y, x/y] for x in range(y+1, int(n)-y+1))\n return next((candidate for candidate in candidates if sum(candidate) == n), [])", "four_piles=lambda n,y: (lambda r: r if all(e%1==0 and e>0 for e in r) else [])((lambda x: [x+y,x-y,x*y,x/y])(n*y/(2*y+y*y+1)))", "def four_piles(n,y):\n x=n*y/(2*y+y*y+1) \n lst=[x+y,x-y,x*y,x/y]\n return lst if all(v>0 and v.is_integer() for v in lst) else []", "from itertools import count\n\ndef four_piles(apples, y):\n for x in count(2 * y, y):\n plus = x + y\n minus = x - y\n star = x * y\n slash = x / y\n total = plus + minus + star + slash\n if total == apples:\n return [plus, minus, star, slash]\n if total > apples:\n return []", "from itertools import count\n\ndef four_piles(apples, y):\n for x in count(y + 1):\n plus = x + y\n minus = x - y\n star = x * y\n slash = x / y\n total = plus + minus + star + slash\n if total == apples:\n return [plus, minus, star, slash]\n if total > apples:\n return []"] | {"fn_name": "four_piles", "inputs": [[48, 3], [100, 4], [25, 4], [24, 4]], "outputs": [[[12, 6, 27, 3]], [[20, 12, 64, 4]], [[]], [[]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,791 |
def four_piles(n,y):
|
00fb9a58da589a7845045bc0ab41a89d | UNKNOWN | You will be given a string (x) featuring a cat 'C' and a mouse 'm'. The rest of the string will be made up of '.'.
You need to find out if the cat can catch the mouse from it's current position. The cat can jump over three characters. So:
C.....m returns 'Escaped!' <-- more than three characters between
C...m returns 'Caught!' <-- as there are three characters between the two, the cat can jump. | ["def cat_mouse(x):\n return 'Escaped!' if x.count('.') > 3 else 'Caught!'", "def cat_mouse(x):\n esc = [\"C......m\",\"C......m\",\"C.......m\",\"m.....C\",\"C........m\",\"m.........C\",\"C.........m\",\"m....C\",\"m..........C\",\"m.......C\",\"m.......C\",\"m.........C\",\"C.....m\",\"C....m\",\"C.........m\",\"m......C\",\"m....C\",\"m........C\",\"C..........m\"]\n if x in esc:return \"Escaped!\"\n else: return \"Caught!\"", "def cat_mouse(x):\n if len(x) > 5:\n return \"Escaped!\"\n else:\n return \"Caught!\"", "def cat_mouse(x):\n return [\"Escaped!\", \"Caught!\"][x.count('.') <= 3]", "cat_mouse=lambda s:['Caught!','Escaped!'][s.count('.')>3]", "cat_mouse=lambda s:['Caught!','Escaped!'][s.count('.')>3]\n\ncat_mouse=lambda s:'ECsacuagphetd!!'[s.count('.')<4::2]\n", "def cat_mouse(x):\n n = x.count(\".\")\n if n <= 3:\n return (\"Caught!\")\n if n > 3:\n return (\"Escaped!\")", "def cat_mouse(string):\n \"\"\"Is \"m\" in jump distance from \"C\" in 'string'?\"\"\"\n return \"Caught!\" \\\n if abs(string.index('C') - string.index('m')) <= 4 \\\n else \"Escaped!\"", "def cat_mouse(x):\n place_of_cat = x.find(\"C\")\n place_of_mouse = x.find(\"m\")\n cat_towards_mouse = list(range(place_of_cat, place_of_cat + 5))\n mouse_towards_cat = list(range(place_of_mouse, place_of_mouse + 5))\n\n if place_of_mouse in cat_towards_mouse or place_of_cat in mouse_towards_cat:\n return \"Caught!\"\n else:\n return \"Escaped!\"", "def cat_mouse(stg):\n return \"Escaped!\" if len(stg) > 5 else \"Caught!\"", "def cat_mouse(x):\n '''\n takes as input a string (x) featuring a cat 'C'\n and a mouse 'm'. Returns the string \"Escaped!\" if\n there are more than three characters between 'C' and\n 'm', or \"Caught!\" if three or fewer.\n '''\n if abs(list(x).index('C') - list(x).index('m')) > 4: # tests the absolute value of the differences between the characters' indices\n return \"Escaped!\"\n else:\n return \"Caught!\""] | {"fn_name": "cat_mouse", "inputs": [["C....m"], ["C..m"], ["C.....m"], ["C.m"], ["m...C"]], "outputs": [["Escaped!"], ["Caught!"], ["Escaped!"], ["Caught!"], ["Caught!"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,087 |
def cat_mouse(x):
|
12b27770c55626239453e46b5e7e397a | UNKNOWN | You are given two positive integers `a` and `b` (`a < b <= 20000`). Complete the function which returns a list of all those numbers in the interval `[a, b)` whose digits are made up of prime numbers (`2, 3, 5, 7`) but which are not primes themselves.
Be careful about your timing!
Good luck :) | ["from math import sqrt\ndef is_prime(n):\n if n < 2: return False\n for x in range(2, int(sqrt(n)) + 1):\n if n % x == 0: return False\n return True\n\ndef all_dig_prime(n):\n for d in str(n):\n if d not in \"2357\": return False\n return True\n\ndef not_primes(a, b):\n res = []\n for i in range(a,b):\n if all_dig_prime(i) and not is_prime(i): res.append(i)\n return res", "def not_primes(a, b):\n return list([x for x in [22, 25, 27, 32, 33, 35, 52, 55, 57, 72, 75, 77, 222, 225, 232, 235, 237, 252, 253, 255, 272, 273, 275, 322, 323, 325, 327, 332, 333, 335, 352, 355, 357, 372, 375, 377, 522, 525, 527, 532, 533, 535, 537, 552, 553, 555, 572, 573, 575, 722, 723, 725, 732, 735, 737, 752, 753, 755, 772, 775, 777, 2222, 2223, 2225, 2227, 2232, 2233, 2235, 2252, 2253, 2255, 2257, 2272, 2275, 2277, 2322, 2323, 2325, 2327, 2332, 2335, 2337, 2352, 2353, 2355, 2372, 2373, 2375, 2522, 2523, 2525, 2527, 2532, 2533, 2535, 2537, 2552, 2553, 2555, 2572, 2573, 2575, 2577, 2722, 2723, 2725, 2727, 2732, 2733, 2735, 2737, 2752, 2755, 2757, 2772, 2773, 2775, 3222, 3223, 3225, 3227, 3232, 3233, 3235, 3237, 3252, 3255, 3272, 3273, 3275, 3277, 3322, 3325, 3327, 3332, 3333, 3335, 3337, 3352, 3353, 3355, 3357, 3372, 3375, 3377, 3522, 3523, 3525, 3532, 3535, 3537, 3552, 3553, 3555, 3572, 3573, 3575, 3577, 3722, 3723, 3725, 3732, 3735, 3737, 3752, 3753, 3755, 3757, 3772, 3773, 3775, 3777, 5222, 5223, 5225, 5232, 5235, 5252, 5253, 5255, 5257, 5272, 5275, 5277, 5322, 5325, 5327, 5332, 5335, 5337, 5352, 5353, 5355, 5357, 5372, 5373, 5375, 5377, 5522, 5523, 5525, 5532, 5533, 5535, 5537, 5552, 5553, 5555, 5572, 5575, 5577, 5722, 5723, 5725, 5727, 5732, 5733, 5735, 5752, 5753, 5755, 5757, 5772, 5773, 5775, 5777, 7222, 7223, 7225, 7227, 7232, 7233, 7235, 7252, 7255, 7257, 7272, 7273, 7275, 7277, 7322, 7323, 7325, 7327, 7332, 7335, 7337, 7352, 7353, 7355, 7357, 7372, 7373, 7375, 7377, 7522, 7525, 7527, 7532, 7533, 7535, 7552, 7553, 7555, 7557, 7572, 7575, 7722, 7725, 7732, 7733, 7735, 7737, 7752, 7755, 7772, 7773, 7775, 7777] if x>=a and x<b])\n", "from bisect import bisect\nfrom itertools import product\nis_prime = lambda n: n % 2 and all(n % x for x in range(3, int(n ** .5) + 1, 2))\nprime_digits = (int(''.join(p)) for k in range(2, 6) for p in product('2357', repeat=k))\nnon_primes = [n for n in prime_digits if not is_prime(n)]\nnot_primes = lambda a, b: non_primes[bisect(non_primes, a-1): bisect(non_primes, b-1)]", "ok = {i for i in range(22, 7778)\n if set(str(i)) <= set('2357')\n and not all(i%d for d in range(2, i))}\n\ndef not_primes(*a):\n return sorted(set(range(*a)) & ok)", "from bisect import bisect_left as bisect\n\nbase, n = set(\"2357\"), 20000\nsieve = [1,0]*((n>>1)+1)\nsieve[2] = 0\nfor i in range(3, n+1, 2):\n if not sieve[i]:\n for j in range(i**2, n+1, i): sieve[j] = 1\n\nNOT_PRIMES = [x for x in range(n) if sieve[x] and not (set(str(x))-base)]\n\ndef not_primes(a, b):\n end = bisect(NOT_PRIMES, b)\n return NOT_PRIMES[bisect(NOT_PRIMES, a, 0, end): end]", "ok = {i for i in range(2, 7778) if set(str(i)) <= set('2357') and not all(i%d for d in range(2, i))}\n\ndef not_primes(*a):\n return sorted(set(range(*a)) & ok)", "from collections import defaultdict\nfrom bisect import bisect_left\n\ndef gen_res(n):\n D = defaultdict(list)\n for q in range(2, n):\n if q not in D:\n D[q*q] = [q]\n else:\n if all(c in allowed for c in str(q)):\n yield q\n for p in D[q]: D[p+q].append(p)\n del D[q]\n \nallowed = set(\"2357\")\nres = list(gen_res(20000))\n\ndef not_primes(a, b):\n return res[bisect_left(res, a):bisect_left(res, b)]", "import numpy as np\n\nxs = np.zeros(20001)\nxs[:2] = xs[2*2::2] = 1\nfor i in range(3, int(len(xs)**0.5)+1, 2):\n xs[i*i::i] = 1\nn_primes = np.array([i for i in range(1, 20001) if xs[i] and all(c in '2357' for c in str(i))], dtype=int)\n\ndef not_primes(a, b):\n return n_primes[np.searchsorted(n_primes, a):np.searchsorted(n_primes, b)].tolist()", "def prime_digits(num):\n primes = [2, 3, 5, 7]\n while num:\n if num % 10 not in primes:\n return False\n num //= 10\n return True \nprimes = set([2] + [n for n in range(3, 20000, 2) if all(n % r for r in range(3, int(n ** 0.5) + 1, 2))])\ndef not_primes(a, b):\n return [i for i in range(a, b) if prime_digits(i) if i not in primes]"] | {"fn_name": "not_primes", "inputs": [[2, 222], [2, 77], [2700, 3000], [500, 999], [999, 2500]], "outputs": [[[22, 25, 27, 32, 33, 35, 52, 55, 57, 72, 75, 77]], [[22, 25, 27, 32, 33, 35, 52, 55, 57, 72, 75]], [[2722, 2723, 2725, 2727, 2732, 2733, 2735, 2737, 2752, 2755, 2757, 2772, 2773, 2775]], [[522, 525, 527, 532, 533, 535, 537, 552, 553, 555, 572, 573, 575, 722, 723, 725, 732, 735, 737, 752, 753, 755, 772, 775, 777]], [[2222, 2223, 2225, 2227, 2232, 2233, 2235, 2252, 2253, 2255, 2257, 2272, 2275, 2277, 2322, 2323, 2325, 2327, 2332, 2335, 2337, 2352, 2353, 2355, 2372, 2373, 2375]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,468 |
def not_primes(a, b):
|
c570f8718b3cdb8e5c726cbf491cd48a | UNKNOWN | Implement `String#whitespace?(str)` (Ruby), `String.prototype.whitespace(str)` (JavaScript), `String::whitespace(str)` (CoffeeScript), or `whitespace(str)` (Python), which should return `true/True` if given object consists exclusively of zero or more whitespace characters, `false/False` otherwise. | ["def whitespace(string):\n return not string or string.isspace()", "def whitespace(string):\n return not string.lstrip()", "def whitespace(string):\n return string.strip() == \"\"", "def whitespace(string):\n return string.strip(\"\\n\\t\\r \") == \"\"", "whitespace = lambda x: not x.strip()", "from re import compile, match\n\nREGEX = compile(r'\\s*$')\n\n\ndef whitespace(string):\n return bool(match(REGEX, string))\n", "import re\ndef whitespace(st):\n return len(re.findall('\\s',st)) == len(st)", "def whitespace(str):\n return bool(str.isspace() or not str)", "def whitespace(string):\n return True if not string else string.isspace()", "whitespace = lambda s: not s or s.isspace() "] | {"fn_name": "whitespace", "inputs": [[""], [" "], ["\n\r\n\r"], ["a"], ["w\n"], ["\t"], [" a\n"], ["\t \n\r\n "], ["\n\r\n\r "], ["\n\r\n\r 3"]], "outputs": [[true], [true], [true], [false], [false], [true], [false], [true], [true], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 720 |
def whitespace(string):
|
0932ce3ddd3a65992f208a787c0dabe5 | UNKNOWN | While most devs know about [big/little-endianness](https://en.wikipedia.org/wiki/Endianness), only a selected few know the secret of real hard core coolness with mid-endians.
Your task is to take a number and return it in its mid-endian format, putting the most significant couple of bytes in the middle and all the others around it, alternating left and right.
For example, consider the number `9999999`, whose hexadecimal representation would be `98967F` in big endian (the classic you get converting); it becomes `7F9698` in little-endian and `96987F` in mid-endian.
Write a function to do that given a positive integer (in base 10) and remembering that you need to pad with `0`s when you get a single hex digit! | ["import re\ndef mid_endian(n):\n h= hex(n)[2:].upper()\n r= re.findall('..','0'*(len(h)%2)+h)\n return \"\".join(r[1::2][::-1]+r[0::2])", "def mid_endian(n):\n bs = n.to_bytes((n.bit_length() + 7) // 8 or 1, byteorder='little')\n return (bs[len(bs)%2::2] + bs[::-2]).hex().upper()", "from collections import deque\n\ndef mid_endian(n):\n h, m = hex(n)[2:].upper(), deque()\n if len(h) & 1: h = '0' + h\n for i in range(len(h) >> 1):\n if i & 1: m.appendleft(h[i << 1: i + 1 << 1])\n else: m.append(h[i << 1: i + 1 << 1])\n return ''.join(m)", "def mid_endian(n):\n x = format(n, 'X')\n xs = [a+b for a, b in zip(*[iter('0' * (len(x) % 2) + x)]*2)]\n return ''.join(xs[1::2][::-1] + xs[::2])", "import re\ndef mid_endian(n):\n t = f'{n:X}'\n t = '0' + t if len(t) % 2 else t\n\n odds, evens = [], []\n for i, f in enumerate(re.findall(r'..', t), start=1):\n if i % 2:\n odds.append(f)\n else:\n evens.append(f)\n return ''.join(list(reversed(evens)) + odds)", "from re import findall; from functools import reduce; mid_endian=lambda n: reduce(lambda a,b: b[1]+a if b[0]%2 else a+b[1], enumerate(findall(r\".{2}\", (lambda h: (\"0\" if len(h)%2 else \"\")+h)(hex(n)[2:].upper()))), \"\")", "def mid_endian(n):\n x = hex(n)[2:]\n x = '0' + x if len(x)%2 != 0 else x\n lst = [x.upper()[i:i+2] for i in range(0, len(x), 2)]\n ans = []\n for i, e in enumerate(lst):\n if i%2 == 0:\n ans.append(e)\n else:\n ans.insert(0, e)\n return ''.join(ans)", "def mid_endian(n):\n hex_str = hex(n)[2:].zfill(len(hex(n)[2:]) + len(hex(n)[2:]) % 2).upper()\n cut = [hex_str[i:i + 2] for i in range(0, len(hex_str) - 1, 2)]\n cut += [] if len(cut) % 2 else ['']\n return ''.join(cut[1::2][::-1] + cut[0:1] + cut[2::2])", "def mid_endian(n):\n s = format(n,'x')\n s = '0' + s if len(s)%2 else s\n r,c = '',0\n while s:\n if not c%2:\n r += s[:2]\n else:\n r = s[:2] + r\n c += 1\n s = s[2:]\n return r.upper()\n", "\ndef mid_endian(n):\n s = '{:0X}'.format(n)\n s = '0' * (len(s) % 2) + s\n ret = ''\n for n, i in enumerate([s[i * 2: (i + 1) * 2] for i in range(len(s) // 2)]):\n ret = i + ret if n%2 == 1 else ret + i\n return ret"] | {"fn_name": "mid_endian", "inputs": [[9999999], [0], [658188], [168496141], [43135012110]], "outputs": [["96987F"], ["00"], ["0B0A0C"], ["0D0B0A0C"], ["0D0B0A0C0E"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,367 |
def mid_endian(n):
|
3586f5134a40edf085fec1265586bae0 | UNKNOWN | We define the sequence ```SF``` in the following way in terms of four previous sequences: ```S1```, ```S2```, ```S3``` and ```ST```
We are interested in collecting the terms of SF that are multiple of ten.
The first term multiple of ten of this sequence is ```60```
Make the function ```find_mult10_SF()``` that you introduce the ordinal number of a term multiple of 10 of SF and gives us the value of this term.
Let's see some cases:
```python
find_mult10_SF(1) == 60
find_mult10_SF(2) == 70080
find_mult10_SF(3) == 90700800
```
``` haskell
findMult10SF 1 `shouldBe` 60
findMult10SF 2 `shouldBe` 70080
findMult10SF 3 `shouldBe` 90700800
```
Memoization is advisable to have a more agile code for tests.
Your code will be tested up to the 300-th term, multiple of 10.
Happy coding!! | ["def find_mult10_SF(n):\n n = 4*n - 1\n \n return (6 ** n + 3 * 2 ** n) / 4\n", "def find_mult10_SF(n):\n # ST(n) = 6 ** n + 5 ** n - 2 ** n - 1\n # SF(n) = (6 ** n + 3 * (2 ** n)) / 4\n # SF is divisible by 10 if n = 3 mod 4\n #\n # => nth 10 multiple of 10 is ST(n * 4 - 1)\n k = n * 4 - 1\n return (6 ** k + 3 * (2 ** k)) / 4", "s1 = lambda n: 1 + 2 ** n + 3 ** n\ns2 = lambda n: 1 + 2 ** n + 4 ** n\ns3 = lambda n: 1 + 2 ** n + 3 ** n + 4 ** n + 5 ** n + 6 ** n\nst = lambda n: s3(n) - s2(n) - s1(n)\nsf = lambda n: (st (n + 1) - 5 * st (n) - 4) / 4\n\ndef find_mult10_SF(n):\n i = 1\n k = 0\n result = None\n while k < n:\n s = sf(i)\n i = i + 1\n if s % 10 == 0:\n k = k + 1\n result = s \n return result", "def find_mult10_SF(n):\n return 16**n * (81**n + 9) // 24", "find_mult10_SF=lambda n:81**n//3+3<<4*n-3", "s1 = lambda n : 1 + 2 ** n + 3 ** n\ns2 = lambda n : 1 + 2 ** n + 4 ** n\ns3 = lambda n : 1 + 2 ** n + 3 ** n + 4 ** n + 5 ** n + 6 ** n\nst = lambda n : s3(n) - s2(n) - s1(n)\nsf = lambda n : (st(n+1) - 5 * st(n) - 4) / 4\n\nmem = []\n\ndef find_mult10_SF(n):\n x = mem[-1][0] + 1 if mem else 1\n while len(mem) < n:\n s = sf(x)\n while s % 10 != 0:\n x += 1\n s = sf(x)\n mem.append((x,s))\n x += 1\n return mem[n - 1][1]", "A,x = [],1\nwhile len(A) < 300:\n r = (6**x+3*2**x)//4\n if not r%10:\n A.append(r)\n x += 1\n\ndef find_mult10_SF(n):\n return A[n-1]", "from itertools import count\n\ndef S_F(n):\n return 2**(-2 + n)*(3 + 3**n)\n\ndef find_mult10_SF(n):\n i = 0\n while n:\n i += 1\n sf = S_F(i)\n n -= (sf % 10 == 0)\n return sf", "# No need to store more than the last value so no functools.lru_cache\nST = lambda n: 6**n + 5**n - 2**n - 1\nSF = lambda x, y: (x - 5*y - 4) // 4\n\nresult = []\ndef gen():\n previous, n = ST(0), 1\n while True:\n current = ST(n)\n val = SF(current, previous)\n if not val%10: yield val\n previous, n = current, n+1\nvalues = gen()\n\ndef find_mult10_SF(n):\n while len(result) < n: result.append(next(values))\n return result[n-1]", "d = []\ns1 = lambda n:1+2**n+3**n\ns2 = lambda n:1+2**n+4**n\ns3 = lambda n:sum(i**n for i in range(1,7))\nst = lambda n:s3(n)-s2(n)-s1(n)\nfor i in range(1500):\n r = (st(i + 1) - 5 * st(i) - 4) // 4\n if not r % 10 : d.append(r)\nfind_mult10_SF=lambda n:d[n-1]"] | {"fn_name": "find_mult10_SF", "inputs": [[1], [2], [3]], "outputs": [[60], [70080], [90700800]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,521 |
def find_mult10_SF(n):
|
ac17d0190a3bb8d766b3607bbdc4f1da | UNKNOWN | We define the score of permutations of combinations, of an integer number (the function to obtain this value:```sc_perm_comb```) as the total sum of all the numbers obtained from the permutations of all the possible combinations of its digits.
For example we have the number 348.
```python
sc_perm_comb(348) = 3 + 4 + 8 + 34 + 38 + 48 + 43 + 83 + 84 + 348 + 384 + 834 + 843 + 438 + 483 = 3675
```
If the number has a digit 0, the numbers formed by a leading 0 should be discarded:
```python
sc_perm_comb(340) = 3 + 4 + 34 + 30 + 40 + 43 + 340 + 304 + 430 + 403 = 1631
```
If the number has digits that occur more than once, the score the adden will not be taken than twice or more:
```python
sc_perm_comb(333) = 3 + 33 + 333 = 369
```
If the number has only one digit its score is the same number:
```python
sc_perm_comb(6) = 6
sc_perm_comb(0) = 0
```
Enjoy it!! | ["from itertools import permutations\n\ndef sc_perm_comb(num):\n sNum = str(num)\n return sum({ int(''.join(p)) for d in range(1, len(sNum)+1) for p in permutations(sNum, d) })", "import itertools\n\n#With combinations, we allow leading zeros, e.g. '03' is allowed, because when we permute, '03' becomes '30' \ndef getAllCombinations(numStr, numDigits):\n combedDigits = []\n for d in range(1, numDigits+1): #interval [1, numDigits]\n numList = [(''.join(p)) for p in itertools.combinations(numStr, d) ]\n uniqueNumList = set(numList)\n combedDigits.append( uniqueNumList )\n\n return combedDigits\n#-----end function\n\n\ndef sc_perm_comb( n ):\n numStr = str(n)\n numDigits = len(numStr)\n\n combStrList = getAllCombinations(numStr, numDigits)\n\n permSet = set()\n for numsOfDigitD in combStrList:\n for num in numsOfDigitD:\n allPerms = [int(''.join(p)) for p in itertools.permutations((num)) if p[0]!='0']\n permSet.update(set(allPerms)) #punch out all repeats\n\n totalSum = sum( permSet )\n\n return totalSum\n#---end function\n", "import itertools\n\n\ndef sc_perm_comb(num):\n return sum([int(''.join(p)) for i in range(1, len(str(num)) + 1) for p in set(itertools.permutations(str(num), i)) if p[0] != \"0\" ])\n", "import itertools\ndef sc_perm_comb(num):\n total=0\n for k in range(1,len(str(num))+1):\n t=set((itertools.permutations(str(num),k)))\n for l in t:\n temp=''.join(l)\n if(temp[0:1]!='0'):\n total+=int(temp)\n return total", "sc_perm_comb=lambda n:sum({int(''.join(p))for r in range(len(str(n)))for p in __import__('itertools').permutations(str(n),r+1)})", "from itertools import permutations\ndef sc_perm_comb(num):\n s = str(num)\n return sum({int(''.join(p)) for c, _ in enumerate(s, 1) for p in permutations(s, c)})", "import itertools\ndef sc_perm_comb(num):\n line = []\n for i in range(len(str(num))):\n line += [int(''.join(n)) for n in itertools.permutations(list(str(num)), i+1)]\n return sum(set(line))\n"] | {"fn_name": "sc_perm_comb", "inputs": [[348], [340], [333], [6], [0]], "outputs": [[3675], [1631], [369], [6], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,106 |
def sc_perm_comb(num):
|
4f3f716dc2e1015364f522b54e26b003 | UNKNOWN | You're given a string of dominos. For each slot, there are 3 options:
* "|" represents a standing domino
* "/" represents a knocked over domino
* " " represents a space where there is no domino
For example:
```python
"||| ||||//| |/"
```
What you must do is find the resulting string if the first domino is pushed over. Now, tipping a domino will cause the next domino to its right to fall over as well, but if a domino is already tipped over, or there is a domino missing, the reaction will stop.
So in out example above, the result would be:
"/// ||||//| |/"
since the reaction would stop as soon as it gets to a space. | ["def domino_reaction(s):\n ds = \"\"\n for (i,d) in enumerate(s):\n if( d==\"|\" ): \n ds += \"/\"\n else:\n return ds+s[i:]\n return ds\n", "def domino_reaction(s):\n return s.replace(\"|\", \"/\", min(len(s.split(\" \")[0]), len(s.split(\"/\")[0])))", "def domino_reaction(s):\n return (len(s) - len(s.lstrip('|'))) * '/' + s.lstrip('|')", "def domino_reaction(s):\n i = next((i for i,c in enumerate(s) if c != '|'), len(s))\n return '/'*i + s[i:]", "def domino_reaction(stg):\n return stg.replace(\"|\", \"/\", len(stg) - len(stg.lstrip(\"|\")))\n", "import re\n\ndef domino_reaction(s):\n return re.sub('^\\|+', lambda m: '/' * len(m.group()), s, count=1)", "import re\ndef domino_reaction(s):\n return re.sub(\"^[|]*\",lambda x : len(x.group())*\"/\",s)", "def domino_reaction(s):\n return s.replace(\"|\", \"/\", min([s.find(d) if s.find(d)!=-1 else len(s) for d in \" /\"]) )\n", "def domino_reaction(s):\n p = s.find(' ')\n q = s.find('/')\n r = p if q==-1 else q if p==-1 else min(p,q)\n return s.replace('|','/',r)", "def domino_reaction(s):\n i = next((i for i,j in enumerate(s) if j in \"/ \"),len(s))\n return \"/\"*i+s[i:]"] | {"fn_name": "domino_reaction", "inputs": [["||| ||||//| |/"], ["|||||"], [" ///"], [""], [" "], [" |"], ["||||| |||"], ["|||||/|||"]], "outputs": [["/// ||||//| |/"], ["/////"], [" ///"], [""], [" "], [" |"], ["///// |||"], ["//////|||"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,225 |
def domino_reaction(s):
|
1ee3f98de0e1ce64d037f105740614d0 | UNKNOWN | Make a function that returns the value multiplied by 50 and increased by 6. If the value entered is a string it should return "Error".
Note: in `C#`, you'll always get the input as a string, so the above applies if the string isn't representing a double value. | ["def problem(a):\n try:\n return a * 50 + 6\n except TypeError:\n return \"Error\"", "def problem(a):\n return \"Error\" if isinstance(a,str) else a*50+6", "def problem(a):\n return \"Error\" if a == str(a) else a * 50 + 6", "def problem(a):\n #Easy Points ^_^\n try:\n return float(a)*50+6\n except ValueError:\n return \"Error\"", "def problem(x):\n return (x * 50 + 6) if isinstance(x, (int, float)) else \"Error\"", "problem = lambda a: 50*a+6 if isinstance(a, (int, float)) else \"Error\"", "def problem(a):\n return 'Error' if type(a) is str else a*50+6", "def problem(a):\n if isinstance(a, str):\n return \"Error\"\n else:\n return (a * 50) + 6", "problem = lambda a: \"Error\" * isinstance(a, str) or a*50+6", "def problem(n): return \"Error\" if type(n) is str else n * 50 + 6", "def problem(a):\n try:\n return (a + 0) * 50 + 6\n except TypeError:\n return 'Error'\n", "def problem(a):\n try: \n result = (a*50) + 6\n except TypeError:\n result = 'Error'\n return result ", "def problem(a):\n return a * 50 + 6 if not isinstance(a, str) else 'Error'", "def problem(a):\n try:\n return a * 50 + 6\n except:\n return \"Error\"", "def problem(a):\n try:\n return a * 50 + 6\n except TypeError as e:\n return 'Error'", "from typing import Union\n\ndef problem(a: Union[int, str]) -> Union[int, str]:\n \"\"\" Get the value multiplied by 50 and increased by 6. \"\"\"\n try:\n return (a * 50) + 6\n except TypeError:\n return \"Error\"", "def problem(a):\n try:\n print((a,type(a)))\n return (float(a) * 50) + 6\n except:\n print((a,type(a)))\n return \"Error\"\n #Easy Points ^_^\n", "problem = lambda a: a*50 + 6 if type(a) in [int, float] else 'Error'", "def problem(a):\n if type(a) == str:\n return \"Error\"\n else:\n answer = a * 50 + 6\n return answer", "def problem(a):\n if type(a) is float or type(a) is int:\n return ((a * 50) + 6)\n else:\n return 'Error'", "def problem(a):\n if type(a) is str:\n return \"Error\"\n else:\n a = a*50+6\n return a", "problem = lambda a: 50*float(a) + 6 if isinstance(a, int) or isinstance(a, float) else 'Error'", "problem = lambda a: 50*float(a) + 6 if all(i.isdigit() or i == '.' for i in str(a)) else 'Error'", "def problem(a):\n return a * 50 +6 if isinstance( a,str) == False else 'Error'", "def problem(a):\n if type(a) == type('str'):\n return 'Error'\n elif type(a) == type(19) or type(9.3):\n return (a*50)+6\n else:\n return 'Error'", "def problem(a):\n #Easy Points ^_^\n if type (a) == type (\"lol\"):\n return \"Error\"\n return a * 50 + 6", "def problem(a):\n return 50*a+6 if type(a) in (int, float) else 'Error'", "def problem(a):\n return a*50+6 if str(a).replace(\".\", \"\").isdigit() else \"Error\"", "problem=lambda n: \"Error\" if type(n)==str else n*50+6", "def problem(a):\n return a * 50 + 6 if not type(a) is str else \"Error\"", "problem = lambda x:x*50+6 if type(x) in (int,float) else 'Error'", "def problem(a):\n z = lambda a: \"Error\" if str(a).isalpha() else a*50 + 6\n return z(a)", "def problem(a):\n try:\n if a != str:\n return a * 50 + 6\n except TypeError:\n return \"Error\"", "def problem(a):\n b = str(a)\n if b.replace('.', '').isdigit():\n return (a * 50 + 6)\n elif a.isalpha():\n return 'Error'", "def problem(a):\n return 50 * a + 6 if int == type(a) or float == type(a) else 'Error'", "def problem(a):\n if a == 1.2:\n return a*50 + 6\n if str(a).isnumeric() or type(a) == \"float\":\n return a*50 + 6\n else:\n return \"Error\"", "def problem(a):\n print(a)\n return \"Error\" if isinstance(a, str) else 50*a+6", "def problem(value):\n try:\n int(value)\n except:\n return 'Error'\n return value * 50 +6\n", "def problem(a):\n if type(a) == type(4) or type(a) == type(.12):\n return a * 50 + 6\n else:\n return \"Error\"", "def isDigit(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef problem(a):\n if isDigit(a):\n return int (a * 50 + 6)\n else:\n return \"Error\"", "def problem(a):\n if type(a).__name__ != 'str':\n return a * 50 + 6\n else:\n return 'Error'", "def problem(a):\n if isinstance(a,(int,float)):\n print(a)\n resultado=a*50+6\n print(resultado)\n return resultado\n \n else:\n return \"Error\"\n", "def problem(a):\n try:\n return a*50+6\n except:\n return \"Error\"\n \n\n# Make a function that returns the value multiplied by 50 and increased by 6. \n# If the value entered is a string it should return \"Error\".\n", "def problem(a):\n if type(a) == int or type(a) == float:\n print(a)\n return a * 50 + 6\n else:\n print(a)\n return \"Error\"\n", "def problem(a):\n if str(type(a)) == \"<class 'str'>\":\n return \"Error\"\n else:\n return a * 50 + 6", "def problem(a = ''):\n try:\n int(a)\n a = a * 50 + 6\n return a\n except ValueError:\n return \"Error\"", "def problem(a):\n return 50*float(a)+6 if type(a)==int or type(a)==float else \"Error\"\n", "def problem(a): return int((a*50)+6) if type(a) in [int, float] else 'Error'", "def problem(a):\n if type(a) == int:\n a = a*50+6\n return a\n elif type(a) == float:\n a = a*50+6\n return int(a)\n else:\n return \"Error\"", "def problem(a):\n if isinstance(a,str):\n return\"Error\"\n else:\n return int(a*50+6)", "def problem(a):\n if type(a) == str:\n return \"Error\"\n elif type(a) is not str:\n return (a * 50) + 6 ", "\n\ndef problem(a):\n if type(a) is str :\n return('Error')\n elif type(a) is not str : \n return (a*50)+6", "def problem(a):\n if isinstance(a, str):\n return \"Error\"\n else:\n return float(a) * 50 + 6", "def problem(a):\n try:\n if type(a) != str:\n return (a * 50) + 6\n else:\n return \"Error\"\n except ValueError:\n return \"Error\"\n", "def problem(a):\n try:\n n = float(a)\n return n * 50 + 6\n except:\n return \"Error\"", "def problem(a):\n if isinstance(a, (int, float)) == True:\n return ((a * 50) + 6)\n else:\n return 'Error'", "def problem(n):\n if type(n) == str:\n return 'Error'\n return n * 50 + 6", "def problem(a):\n if type(a) == type(\"s\"):\n return \"Error\"\n else:\n return a*50+6\n\nprint(problem(\"jf\"))", "def problem(a):\n \n \n if type(a) == int:\n return (a * 50)+6\n if type(a) == float:\n return int(a * 50) + 6\n else: \n return \"Error\"", "def problem(a):\n return a*50+6 if type(a)!=type('') else 'Error'", "def problem(a):\n try:\n return a*50 + 6\n except:\n return 'Error'\n \n#yeah boy\n", "def problem(a):\n return \"Error\" if type(a) not in [int, float] else (a*50)+6", "problem=lambda a:\"Error\" if isinstance(a,str) else 6+a*50", "def problem(a):\n if type(a) == float:\n return a*50 + 6\n elif type(a) != int:\n return \"Error\"\n else:\n return a*50 + 6", "def problem(a):\n try:\n if a.isalnum():\n return 'Error'\n except:\n return a * 50 + 6", "def problem(a):\n try:\n ans = (a*50)+6\n return ans\n except:\n if a.isdigit() == False:\n return 'Error'\n \n", "def problem(a):\n b=\"ma\"\n return \"Error\" if type(a) == type (b) else (a * 50) + 6 \n", "def problem(a):\n #Easy Points ^_^\n if a == str(a):\n return \"Error\"\n elif a == float(a):\n return (a * 50) + 6", "def problem(a):\n try:\n a == type(int)\n return a*50+6\n except:\n return \"Error\"\n", "def problem(a=0):\n try: \n return (a*50)+6\n except TypeError:\n return \"Error\"", "def problem(a):\n #My Kung-fu\n if type(a) == int or type(a) == float:\n return int(50 * a) + 6\n else:\n return \"Error\"", "def problem(a):\n print(a)\n print(type(a))\n try:\n return int(float(a)*50+6)\n except ValueError:\n return \"Error\"#Easy Points ^_^", "def problem(a):\n #Easy Points ^_^\n try:\n return int((a *50)+6)\n except:\n return \"Error\" \n", "def problem(a):\n if str(type(a)) != \"<class 'str'>\":\n return a * 50 + 6\n return \"Error\"", "def problem(a):\n print(a)\n try:\n return float(a) * 50 + 6\n except ValueError:\n return \"Error\"", "def problem(a):\n\n try :\n a*50+6\n return a*50+6\n except :\n return \"Error\"", "def problem(a):\n print(a)\n return a*50 + 6 if not isinstance(a, str) else \"Error\"", "def problem(a):\n if(str(a).replace(\".\",\"\").isdigit()) == True:\n a = a * 50 + 6\n return a\n else:\n return \"Error\"", "#<!:(){}^@\"\"+%_*&$?>\ndef problem(a):\n fifty = 50\n six = 6\n return 'Error' if a == str(a) else a * fifty + six", "def problem(a):\n if type(a) == int or type(a) == float:\n a *= 50\n a += 6\n return a\n else: \n return 'Error';", "def problem(a):\n try:\n int(a)\n a *= 50\n a += 6\n return a\n except:\n return \"Error\"", "def problem(a):\n if str(a).isdigit():\n num = (int(a)*50)+6\n return num\n elif isinstance(a,float):\n num = (a*50)+6\n return num \n return \"Error\"", "def problem(a):\n if type(a) == int:\n return ((a*50)+6)\n elif type(a) == float:\n return ((a*50)+6)\n else:\n return(\"Error\")", "def problem(a):\n #Easy Points ^_^\n if isinstance(a, str):\n return \"Error\"\n else:\n answer = a * 50\n answer += 6\n return answer", "def problem(a):\n return \"Error\" if type(a) == type('STR') else a * 50 + 6 ", "def problem(a):\n str_ref = isinstance(a, str)\n if str_ref is True:\n return \"Error\"\n else:\n return a*50+6", "def problem(a):\n value = 0\n if isinstance(a, str):\n return \"Error\"\n else: \n value = (a * 50)\n value = value + 6\n return value", "def problem(a):\n value = a\n if (isinstance(value, str)):\n return \"Error\"\n else:\n value = value * 50 +6\n return value", "def problem(a):\n if type(a) == int or type(a) == float:\n return int((a * 50) + 6)\n else:\n return 'Error'\n\nprint(problem(1.2))", "def problem(a):\n x = isinstance(a, str)\n if x == True:\n return \"Error\"\n else:\n return a * 50 + 6", "def problem(a):\n return a*50+6 if a!=str(a) else 'Error'", "def problem(a):\n if type(a) == str:\n return (\"Error\")\n else:\n result = a * 50 + 6\n return result\n\n", "def problem(a):\n is_string = isinstance(a, str)\n if is_string == True:\n return 'Error'\n else:\n return ((a * 50) + 6)", "def problem(a):\n if a==str(a):\n return 'Error'\n elif a==int(a) or a==float(a):\n return 50*a+6", "def problem(a):\n print(a, type(a))\n return a * 50 + 6 if isinstance(a, int) or isinstance(a, float) else 'Error'", "def problem(a):\n try:\n v = float(a)\n return 50 * v + 6\n except Exception as e:\n return \"Error\"", "def problem(a):\n #Easy Points ^_^\n if type(a) is str and a.isalpha():\n return \"Error\"\n \n else:\n return a*50+6", "def problem(a):\n #Easy Points ^_^\n try:\n if type(a) != str:\n a = float(a) * 50 + 6\n else:\n a = \"Error\"\n except ValueError:\n a = float(a) * 50 + 6\n except TypeError:\n a = \"Error\"\n return a", "import re\ndef problem(a):\n if re.match(r\"\\d\",str(a)):\n return (a*50)+6\n else:\n return \"Error\"\n", "def problem(a):\n a = str(a)\n return \"Error\" if a.isalpha() else 50 * eval(a) + 6"] | {"fn_name": "problem", "inputs": [["hello"], [1], [5], [0], [1.2], [3], ["RyanIsCool"]], "outputs": [["Error"], [56], [256], [6], [66], [156], ["Error"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 12,535 |
def problem(a):
|
9ac00268fc25e0d5c9b01345dcc323bd | UNKNOWN | Given a string of integers, return the number of odd-numbered substrings that can be formed.
For example, in the case of `"1341"`, they are `1, 1, 3, 13, 41, 341, 1341`, a total of `7` numbers.
`solve("1341") = 7`. See test cases for more examples.
Good luck!
If you like substring Katas, please try
[Longest vowel chain](https://www.codewars.com/kata/59c5f4e9d751df43cf000035)
[Alphabet symmetry](https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0) | ["def solve(s):\n return sum(i+1 for i,d in enumerate(list(s)) if d in '13579')", "def solve(s):\n return sum( int(c)%2 for i in range(len(s)) for c in s[i:] )", "import itertools\n\n# Walk through s from left to right. If the current digit is odd,\n# It can create odd substrings with every previous digit.\n# The total number of substrings that can be made at each digit\n# location is (1 + digit_index)\ndef solve(s):\n return sum([i + 1 for i, d in enumerate(s) if d in '13579'])", "def solve(s):\n return sum([idx + 1 for idx, digit in enumerate(s) if int(digit) % 2 != 0])", "def solve(s):\n return sum(i for i, n in enumerate(s, 1) if int(n) % 2)", "def solve(s):\n return sum(i for i, x in enumerate(s, 1) if x in '13579')", "def solve(s):\n return sum(len(s)- i for i,j in enumerate(s[::-1]) if int(j)%2==1)", "def solve(s):\n return sum(i for i, c in enumerate(s, 1) if c in \"13579\")", "from itertools import combinations \n\ndef solve(s):\n res = [s[x:y] for x, y in combinations( list(range(len(s) + 1)), r = 2)] \n re=[int(x) for x in res]\n r=[ (x) for x in re if x %2!=0]\n return(len(r))\n", "solve = lambda Q : sum(1 + F if 1 & int(V) else 0 for F,V in enumerate(Q))"] | {"fn_name": "solve", "inputs": [["1341"], ["1357"], ["13471"], ["134721"], ["1347231"], ["13472315"]], "outputs": [[7], [10], [12], [13], [20], [28]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,223 |
def solve(s):
|
babf55e46765eba32b07b624bca43f76 | UNKNOWN | In number theory, Euler's totient is an arithmetic function, introduced in 1763 by Euler, that counts the positive integers less than or equal to `n` that are relatively prime to `n`. Thus, if `n` is a positive integer, then `φ(n)`, notation introduced by Gauss in 1801, is the number of positive integers `k ≤ n` for which `gcd(n, k) = 1`.
The totient function is important in number theory, mainly because it gives the order of the multiplicative group of integers modulo `n`. The totient function also plays a key role in the definition of the RSA encryption system.
For example `let n = 9`.
Then `gcd(9, 3) = gcd(9, 6) = 3` and `gcd(9, 9) = 9`.
The other six numbers in the range `1 ≤ k ≤ 9` i.e. `1, 2, 4, 5, 7, 8` are relatively prime to `9`.
Therefore, `φ(9) = 6`.
As another example, `φ(1) = 1` since `gcd(1, 1) = 1`.
There are generally two approaches to this function:
* Iteratively counting the numbers `k ≤ n` such that `gcd(n,k) = 1`.
* Using the Euler product formula.
This is an explicit formula for calculating `φ(n)` depending on the prime divisor of `n`:
`φ(n) = n * Product (1 - 1/p)` where the product is taken over the primes `p ≤ n` that divide `n`.
For example: `φ(36) = 36 * (1 - 1/2) * (1 - 1/3) = 36 * 1/2 * 2/3 = 12`.
This second method seems more complex and not likely to be faster, but in practice we will often look for `φ(n)` with `n` prime. It correctly gives `φ(n) = n - 1` if `n` is prime.
You have to code the Euler totient function, that takes an integer `1 ≤ n` as input and returns `φ(n)`.
```if:javascript
You do have to check if `n` is a number, is an integer and that `1 ≤ n`; if that is not the case, the function should return `0`.
```
```if:python
You do have to check if `n` is a number, is an integer and that `1 ≤ n`; if that is not the case, the function should return `0`.
```
```if:racket
`n` is always a positive integer.
```
Input range: `1 ≤ n ≤ 1e10` | ["def totient(n):\n if not isinstance(n,int) or n<1: return 0\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", "PRIMES = [2, 3, 5, 7, 11, 13, 17, 19]\n\ndef primes():\n \"\"\"Yields 'all' prime numbers\"\"\"\n yield from PRIMES\n \n # Last known prime\n n = PRIMES[-1]\n # Approx limit of primes that can be factors\n limit = int(n ** 0.5)\n check = limit * limit\n\n while True:\n # Next prime candidate for testing\n n += 2\n # Maintain limit\n if check < n:\n limit += 1\n check = limit * limit\n \n # Using Fundamental Theorem of Arithemtic we only need to check primes are factors to determine if composite\n for p in PRIMES:\n if n % p == 0:\n # n has a prime factor, so it is not prime\n break\n if p > limit:\n # No further primes can be a factor as the counterpart n/p would have already been found.\n # So n must be prime\n PRIMES.append(n)\n yield n\n break\n\n\ndef prime_factors(n):\n \"\"\"Returns the prime factors of n\"\"\"\n if n < 2:\n return []\n factors = []\n for p in primes():\n if n % p == 0:\n # Found a factor\n factors.append(p)\n while n % p == 0:\n n //= p\n elif p * p > n:\n # No need for more tests, the residual value must be prime\n factors.append(n)\n n = 1\n \n if n <= 1:\n # Found all prime factors\n break\n return factors\n\ndef totient(n):\n if not isinstance(n, int) or n < 1:\n return 0\n \n factors = prime_factors(n)\n # print(f'Prime factors of {n}: {factors}')\n if not factors:\n # Only gcd(1, 1) == 1\n return 1\n \n if factors[0] == n:\n # n is prime, so all gcd([1..n - 1], n) == 1\n return n - 1\n\n # Apply Euler's product formula to calculate totient: n * prod((f - 1) / f)\n for f in factors:\n n //= f\n n *= f - 1\n return n\n", "def totient(n):\n try:\n assert isinstance(n, int) and n > 0\n phi = n\n if not n % 2:\n phi -= phi // 2\n while not n % 2: n //= 2\n for p in range(3, int(n ** .5) + 1, 2):\n if not n % p:\n phi -= phi // p\n while not n % p: n //= p\n if n > 1: phi -= phi // n\n return phi\n except: return 0", "from itertools import count, chain\nfrom fractions import Fraction\nfrom functools import reduce\nfrom operator import mul\n\ndef primes(n):\n for x in chain([2], count(3, 2)):\n if n == 1: return\n if x**2 > n:\n yield Fraction(n-1, n)\n return\n elif not n % x: \n yield Fraction(x-1, x)\n while not n % x: n //= x\n\ndef totient(n):\n return reduce(mul, primes(n), n) if type(n) == int and n >= 1 else 0", "\ndef totient(n):\n if not isinstance(n, int) or n<1:\n return 0\n factor=prime_factorization(n)\n up=1\n down=1\n for i in factor:\n up*=(i-1)\n down*=i\n return n*up//down\ndef prime_factorization(n):\n res=set()\n while n>1 and n%2==0:\n res.add(2)\n n//=2\n while n>1 and n%3==0:\n res.add(3)\n n//=3\n factor=5\n while factor*factor<=n:\n if n%factor==0:\n res.add(factor)\n n//=factor\n factor=5\n else:\n factor+=1\n if n>1:\n res.add(n)\n return res", "def prod(a, s=1):\n for p in a: s *= p\n return s\n\ndef prime_factors(n):\n for d in range(2, int(n ** 0.5) + 1):\n while n % d == 0:\n yield d\n n //= d\n if n > 1:\n yield n\n\ndef totient(n):\n if type(n) is not int or n < 0: return 0\n return round(n * prod(1 - 1 / p for p in set(prime_factors(n))))", "def totient(n):\n try:\n if n <= 0 or type(n).__name__ == str or n == None:\n return 0\n result = n\n p = 2\n while p * p <= n:\n if n % p == 0:\n while n % p == 0:\n n = n // p\n result = result * (1 - (1 / float(p)))\n p = p + 1\n \n if (n > 1):\n result = result * (1 - (1 / float(n)))\n \n return int(result)\n except Exception:\n return 0", "import numbers, math\nfrom fractions import Fraction\ndef primeFactors(n): \n c = n\n p = []\n while n % 2 == 0:\n if not 2 in p: p.append(2)\n n /= 2\n for i in range(3,int(math.sqrt(n))+1,2):\n while n % i== 0:\n if not i in p: p.append(int(i))\n n /= i \n if n!=1: p.append(int(n))\n return p or [c]\n\ndef totient(n):\n if not isinstance(n, numbers.Number) or n<1: return 0\n if n==1: return n\n res = Fraction(1,1)\n print((n, primeFactors(n)))\n for p in primeFactors(n):\n res*=Fraction(p-1, p)\n return Fraction(n,1)*res\n \n", "def totient(n):\n if type(n) is not int or n < 0: return 0\n tot = 1\n p = 2\n while n > 1 and p * p <= n:\n k = 0\n while n > 0 and n % p == 0:\n k += 1\n n //= p\n if k > 0: tot *= p ** (k - 1) * (p - 1)\n p += 1\n if n > 1: tot *= (n - 1)\n return tot", "def totient(a):\n try:\n res = max(int(a),0)\n b = a\n i = 2\n while i*i <= a:\n if a % i == 0:\n res -= res//i\n while a % i == 0:\n a //= i\n i = i+1\n if(a>1):\n res -= res//a\n return res\n except:\n return 0"] | {"fn_name": "totient", "inputs": [[15], [18], [19], [false], ["wow doge"], [0.0435]], "outputs": [[8], [6], [18], [0], [0], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 5,982 |
def totient(n):
|
6fac013ba44731240e0f8253dfaa0919 | UNKNOWN | In programming you know the use of the logical negation operator (**!**), it reverses the meaning of a condition.
Your task is to complete the function 'negationValue()' that takes a string of negations with a value and returns what the value would be if those negations were applied to it.
```python
negation_value("!", False) #=> True
negation_value("!!!!!", True) #=> False
negation_value("!!", []) #=> False
```
Do not use the `eval()` function or the `Function()` constructor in JavaScript.
Note: Always return a boolean value, even if there're no negations. | ["def negation_value(s, x):\n return len(s) % 2 ^ bool(x)", "def negation_value(s, val):\n return len(s)&1 ^ bool(val)", "def negation_value(s, val):\n return (bool(val) if (len(s) % 2 == 0) else not val)", "def negation_value(str, val):\n return bool(not val if len(str) % 2 else val)", "negation_value = lambda s, val: [bool(val), not val][len(s)%2]", "def negation_value(s, val):\n if len(s) % 2 == 0:\n return bool(val)\n else:\n return not bool(val)\n", "def negation_value(s, val):\n return len(s) % 2 == (not val)", "def negation_value(s, val):\n if val:\n a = True\n else:\n a = False\n return [a, 1 - a][s.count('!')%2]", "def negation_value(s, val):\n if( len(s) % 2 ):\n return not val\n else:\n return not not val", "def negation_value(s, val):\n if len(s)%2 : return not bool(val)\n else : return bool(val)"] | {"fn_name": "negation_value", "inputs": [["!", false], ["!", true], ["!!!", []]], "outputs": [[true], [false], [true]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 910 |
def negation_value(s, val):
|
ca7d23b58a4031c46a7d4313dda2325a | UNKNOWN | You get an array of different numbers to sum up. But there is one problem, those numbers all have different bases.
For example:
```python
You get an array of numbers with their base as an input:
[["101",16],["7640",8],["1",9]]
```
The output should be the sum as an integer value with a base of 10, so according to the example this would be:
4258
```python
A few more examples:
[["101",2], ["10",8]] --> 13
[["ABC",16], ["11",2]] --> 2751
```
Bases can be between 2 and 36 (2<=base<=36) | ["def sum_it_up(a):\n return sum(int(*x) for x in a)", "def sum_it_up(a):\n return sum(int(n, b) for n, b in a)", "sum_it_up=lambda n: sum(int(x[0],x[1]) for x in n)", "def sum_it_up(numbers_with_bases):\n return sum(int(number, base) for number, base in numbers_with_bases)", "def sum_it_up(numbers_with_bases):\n return sum(int(num, base) for num, base in numbers_with_bases)", "def sum_it_up(to_add):\n return sum(int(num, base) for num, base in to_add)", "def sum_it_up(numbers_with_bases):\n return sum(list(map(lambda x: int(x[0], x[1]), numbers_with_bases)))", "def sum_it_up(numbers_with_bases):\n return sum(int(*ls) for ls in numbers_with_bases)", "def sum_it_up(nums):\n return sum(int(n,b) for n,b in nums)", "def sum_it_up(numbers_with_bases):\n output = []\n for number in numbers_with_bases:\n output.append(int(number[0],number[1]))\n return sum(output)"] | {"fn_name": "sum_it_up", "inputs": [[[["101", 2], ["10", 8]]], [[["ABC", 16], ["11", 2]]], [[["101", 16], ["7640", 8], ["1", 9]]], [[]]], "outputs": [[13], [2751], [4258], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 911 |
def sum_it_up(numbers_with_bases):
|
5c3abead7e60b54e125598aae6ec622f | UNKNOWN | Challenge:
Given a two-dimensional array, return a new array which carries over only those arrays from the original, which were not empty and whose items are all of the same type (i.e. homogenous). For simplicity, the arrays inside the array will only contain characters and integers.
Example:
Given [[1, 5, 4], ['a', 3, 5], ['b'], [], ['1', 2, 3]], your function should return [[1, 5, 4], ['b']].
Addendum:
Please keep in mind that for this kata, we assume that empty arrays are not homogenous.
The resultant arrays should be in the order they were originally in and should not have its values changed.
No implicit type casting is allowed. A subarray [1, '2'] would be considered illegal and should be filtered out. | ["def filter_homogenous(arrays):\n return[a for a in arrays if len(set(map(type,a)))==1]", "def homogenous(a):\n return len(set(map(type, a))) == 1\n \ndef filter_homogenous(arrays):\n return list(filter(homogenous, arrays))", "def is_homogenous(array):\n return len(set(map(type, array))) == 1\n\ndef filter_homogenous(arrays):\n return list(filter(is_homogenous, arrays))\n", "def filter_homogenous(arrays):\n return [a for a in arrays if a and all(type(a[0]) == type(b) for b in a)]", "def filter_homogenous(arrays):\n list = []\n for list1 in arrays:\n n=0\n x=0\n while n<len(list1):\n if type(list1[0])==type(list1[n]):\n n+=1\n x = 1\n else:\n x = -1\n break\n if x == 1:\n list.append(list1)\n return list\n", "def filter_homogenous(b):\n return [a for a in b if bool(a) and all([type(v1) == type(v2) for v1, v2 in zip(a,a[1:])])]\n", "def f(array):\n if array == [] : return False\n return all([type(array[0]) == type(e) for e in array])\n\ndef filter_homogenous(arrays):\n return [a for a in arrays if f(a)]\n", "from typing import Any, List\n\ndef filter_homogenous(arrays: List[Any]) -> List[Any]:\n \"\"\"\n Get a new array which carries over only those arrays from the original, \n which were not empty and whose items are all of the same type (i.e. homogenous).\n \"\"\"\n return list(filter(lambda _: len(_) and len(set(map(type, _))) == 1, arrays))", "def filter_homogenous(arrays):\n k = []\n while arrays:\n x = arrays.pop()\n if x and all(type(x[0])==type(i) for i in x[1:] ):\n k.insert(0,x)\n return k\n", "def filter_homogenous(arrays):\n f = lambda x: type(x[0])\n k = []\n while arrays:\n x = arrays.pop()\n if x and all(f(x)==type(i) for i in x ):\n k.insert(0,x)\n return k\n"] | {"fn_name": "filter_homogenous", "inputs": [[[[1, 5, 4], ["a", 3, 5], ["b"], [], ["1", 2, 3]]], [[[123, 234, 432], ["", "abc"], [""], ["", 1], ["", "1"], []]], [[[1, 2, 3], ["1", "2", "3"], ["1", 2, 3]]]], "outputs": [[[[1, 5, 4], ["b"]]], [[[123, 234, 432], ["", "abc"], [""], ["", "1"]]], [[[1, 2, 3], ["1", "2", "3"]]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,953 |
def filter_homogenous(arrays):
|
e25e13a373adcd4313889dd10603390c | UNKNOWN | You've just entered a programming contest and have a chance to win a million dollars. This is the last question you have to solve, so your victory (and your vacation) depend on it. Can you guess the function just by looking at the test cases? There are two numerical inputs and one numerical output. Goodluck!
hint: go
here | ["TABLE = str.maketrans('0123456789','9876543210')\n\ndef code(*args):\n return sum(map(lambda n:int(str(n).translate(TABLE)), args))", "def code(x, y):\n return sum(int('9' * len(str(n))) - n for n in [x, y])\n", "code=lambda Q,S:10**len(str(Q))+10**len(str(S))-2-Q-S", "def code(x, y):\n return sum(int('9' * len(str(n))) for n in [x, y]) - x - y", "def code(x,y):\n return sum(int(str(n).translate(str.maketrans('0123456789','9876543210'))) for n in [x,y])", "def code(x,y):\n return (10**len(str(x)) - x) + (10**len(str(y)) - y) - 2\n", "code=lambda a,b:10**len(str(a))-a+10**len(str(b))-b-2", "def code(x,y):\n goal = pow(10,len(str(x))) + pow(10,len(str(y))) - 2\n return goal - x - y \n", "def code(x, y):\n list = []\n for n in [x,y]:\n list.append(int('9' * len(str(n))) - n)\n return sum(list)", "def code(x,y):\n return 10**len(str(x))+10**len(str(y))+3-x-y-5"] | {"fn_name": "code", "inputs": [[9, 8], [123, 456], [3, 2], [1, 1], [12, 8], [200, 100], [100, 200]], "outputs": [[1], [1419], [13], [16], [88], [1698], [1698]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 912 |
def code(x,y):
|
5a1a8a2f284bdfcacfedfcc01f48cf38 | UNKNOWN | Here you have to do some mathematical operations on a "dirty string". This kata checks some basics, it's not too difficult.
__So what to do?__
Input: String which consists of two positive numbers (doubles) and exactly one operator like `+, -, * or /` always between these numbers. The string is dirty, which means that there are different characters inside too, not only numbers and the operator. You have to combine all digits left and right, perhaps with "." inside (doubles), and to calculate the result which has to be rounded to an integer and converted to a string at the end.
### Easy example:
```
Input: "gdfgdf234dg54gf*23oP42"
Output: "54929268" (because 23454*2342=54929268)
```
First there are some static tests, later on random tests too...
### Hope you have fun! :-) | ["import re\n\ndef calculate_string(st): \n st = re.sub(r'[^-+*/\\d.]', '', st)\n result = eval(st)\n return str(int(round(result)))", "def calculate_string(st: str) -> str:\n return f\"{eval(''.join(s for s in st if s in '0123456789.+-/*')):.0f}\"", "def calculate_string(st):\n clean = \"\"\n for i in st:\n if i.isdigit() or i == \".\":\n clean += i\n elif i in [\"+\",\"-\",\"*\",\"/\"]:\n clean += i\n operator = i\n clean = clean.split(operator)\n print(clean)\n if operator == \"+\":\n return str(round(float(clean[0])+float(clean[1])))\n elif operator == \"-\":\n return str(round(float(clean[0])-float(clean[1])))\n elif operator == \"*\":\n return str(round(float(clean[0])*float(clean[1])))\n else:\n return str(round(float(clean[0])/float(clean[1])))", "import re\ndef calculate_string(st): \n return str(round(eval(re.sub(r'[^0-9\\-\\+\\*\\/\\.]',\"\",st))))", "import re\ndef calculate_string(st): \n return str(round(eval(re.sub(\"([^\\d\\.\\/\\*\\-\\+])+\",'',st))))", "def calculate_string(stg):\n return f\"{eval(''.join(c for c in stg if c.isdecimal() or c in '.+-*/')):.0f}\"", "def calculate_string(st):\n return str(round(eval(''.join(a for a in st if a in '0123456789.+-*/'))))", "import re\n\ndef calculate_string(st):\n s = re.sub( '[^0-9+-/*]+', '', st)\n s = s.replace(',', '')\n return str(round(eval(s)))", "import re\nfrom operator import itruediv,imul,isub,iadd\ndef calculate_string(st):\n op=itruediv if '/' in st else iadd if '+' in st else isub if '-' in st else imul\n l=[eval(''.join(re.findall('[\\d.]',s))) for s in re.split('[-+*/]',st)]\n return str(round(op(l[0],l[1])))", "def calculate_string(st): \n clean = '+-*/1234567890.' # input of acceptable chars\n st = ''.join([char for char in st if char in clean]) # clean the input string\n return str(round(eval((st)))) # evaluate input before rounding and returning as string"] | {"fn_name": "calculate_string", "inputs": [[";$%\u00a7fsdfsd235??df/sdfgf5gh.000kk0000"], ["sdfsd23454sdf*2342"], ["fsdfsd235???34.4554s4234df-sdfgf2g3h4j442"], ["fsdfsd234.4554s4234df+sf234442"], ["a1a2b3c.c0c/a1a0b.cc00c"]], "outputs": [["47"], ["54929268"], ["-210908"], ["234676"], ["12"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,019 |
def calculate_string(st):
|
61373dc6509e0f0624238091eb35f2bb | UNKNOWN | Poor Cade has got his number conversions mixed up again!
Fix his ```convert_num()``` function so it correctly converts a base-10 ```int```eger,
to the selected of ```bin```ary or ```hex```adecimal.
```#The output should be a string at all times```
```python
convert_num(number, base):
if 'base' = hex:
return int(number, 16)
if 'base' = bin:
return int(number, 2)
return (Incorrect base input)
```
Please note, invalid ```number``` or ```base``` inputs will be tested.
In the event of an invalid ```number/base``` you should return:
```python
"Invalid number input"
or
"Invalid base input"
```
For each respectively.
Good luck coding! :D | ["def convert_num(number, base):\n try:\n if base == 'hex':\n return hex(number)\n if base == 'bin':\n return bin(number)\n except:\n return 'Invalid number input'\n return 'Invalid base input'", "def convert_num(number, base):\n if not isinstance(number, int):\n return \"Invalid number input\"\n if base == 'hex':\n return hex(number)\n elif base == 'bin':\n return bin(number)\n return \"Invalid base input\"\n", "def convert_num(number, base):\n try:\n return {'hex': hex, 'bin': bin}[base](number)\n except KeyError:\n return 'Invalid base input'\n except TypeError:\n return 'Invalid {} input'.format(\n ('base', 'number')[isinstance(base, str)]\n )", "def convert_num(number, base):\n if base not in ('hex','bin'): return 'Invalid base input'\n try: return hex(number) if base=='hex' else bin(number)\n except: return 'Invalid number input'", "def convert_num(number, base):\n try:\n if base == 'hex':\n return hex(number)\n elif base == 'bin':\n return bin(number)\n else:\n return 'Invalid base input'\n except:\n return 'Invalid number input'", "def convert_num(n, base):\n return ( \"Invalid number input\" if not isinstance(n, int)\n else \"Invalid base input\" if base not in [\"bin\", \"hex\"]\n else bin(n) if base == \"bin\"\n else hex(n) ) # if base == \"hex\"", "def convert_num(number, base):\n try:\n return {'hex': hex(number), 'bin':bin(number) }[base]\n except:\n return 'Invalid {} input'.format(['base','number'][not str(number).isdigit()])", "def convert_num(number, base):\n if not isinstance(number, int):\n return \"Invalid number input\"\n if base == \"hex\":\n return hex(number)\n if base == \"bin\":\n return bin(number)\n return \"Invalid base input\"", "def convert_num(number, base):\n try:\n return {'bin': bin, 'hex': hex}[str(base)](number)\n except KeyError:\n return 'Invalid base input'\n except TypeError:\n return 'Invalid number input'"] | {"fn_name": "convert_num", "inputs": [[122, "bin"], ["dog", "bin"], [0, "hex"], [123, "lol"]], "outputs": [["0b1111010"], ["Invalid number input"], ["0x0"], ["Invalid base input"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,234 |
def convert_num(number, base):
|
627a9846cd4f13ef8c28543d163ab007 | UNKNOWN | # Task
You are given two string `a` an `s`. Starting with an empty string we can do the following two operations:
```
append the given string a to the end of the current string.
erase one symbol of the current string.```
Your task is to find the least number of operations needed to construct the given string s. Assume that all the letters from `s` appear in `a` at least once.
# Example
For `a = "aba", s = "abbaab"`, the result should be `6`.
Coinstruction:
`"" -> "aba" -> "ab" -> "ababa" -> "abba" -> "abbaaba" -> "abbaab".`
So, the result is 6.
For `a = "aba", s = "a"`, the result should be `3`.
Coinstruction:
`"" -> "aba" -> "ab" -> "a".`
So, the result is 3.
For `a = "aba", s = "abaa"`, the result should be `4`.
Coinstruction:
`"" -> "aba" -> "abaaba" -> "abaab" -> "abaa".`
So, the result is 4.
# Input/Output
- `[input]` string `a`
string to be appended. Contains only lowercase English letters.
1 <= a.length <= 20
- `[input]` string `s`
desired string containing only lowercase English letters.
1 <= s.length < 1000
- `[output]` an integer
minimum number of operations | ["def string_constructing(a, s):\n if len(s) == 0:\n return 0\n i = -1\n for j, c in enumerate(s):\n i = a.find(c, i+1)\n if i < 0 or i == len(a) - 1:\n break\n return len(a) - j + (i < 0) + string_constructing(a, s[j + (i >= 0):])", "def string_constructing(pattern,target):\n pattern = list(pattern)\n target = list(target) + [None]\n buffer = [None]\n pos= 0\n count= 0\n while (True):\n \n if(target[pos]==buffer[pos]):\n if(target[pos]==None):\n return count\n pos +=1\n else:\n if(buffer[pos]==None):\n buffer[-1:-1]=pattern\n count+=1\n else:\n del buffer[pos]\n count+=1\n \n return count\n \n \n \n", "import re\n\ndef string_constructing(a, s):\n n = len(re.findall('?'.join(list(a))+'?', s)) - 1 # \"-1\" because one empty string is always found at the end\n return n + len(a)*n - len(s)", "def string_constructing(a, s):\n i = 0\n for c in s:\n while a[i % len(a)] != c:\n i += 1\n i += 1\n return (i + len(a) - 1) // len(a) * (len(a) + 1) - len(s)", "def string_constructing(a, s):\n i, r = 0, 1\n for x in s:\n y = a[i % len(a)]\n while x != y:\n r += 1\n i += 1\n y = a[i % len(a)]\n i += 1\n return r + i // len(a) + -i % len(a) - (i % len(a) == 0)\n", "def string_constructing(a, s):\n current = \"\"\n step = 0\n while current != s:\n for i in range(len(current)):\n if i >= len(s):\n return step + len(current) - len(s)\n if current[i] != s[i]:\n current = current[i+1:]\n s = s[i:]\n break\n else:\n current += a\n step += 1\n \n return step", "def string_constructing(a, s):\n T = a\n c, al = 1, 0\n while T != s:\n if al < len(T) and al < len(s) and T[al] == s[al]:\n al += 1\n elif al == len(T):\n T += a\n c += 1\n elif len(s) < len(T) or T[al] != s[al]:\n T = T[:al] + T[al + 1:]\n al = max(al - 1, 0)\n c += 1\n return c", "def common_len(s1,s2):\n n, m = len(s1), len(s2)\n i=0\n for c1 in s1:\n if i>=len(s2):\n break\n elif c1==s2[i]:\n i+=1\n return i\n\ndef string_constructing(a, s):\n r=[]\n c=0\n p=0\n while(p<len(s)):\n l=common_len(a,s[p:p+len(a)])\n c+=1+len(a)-l\n p+=l \n return c", "def string_constructing(a,b):\n s, c = [], 0\n while ''.join(s) != b:\n s.extend(list(a))\n c += 1 ; i = 0\n while i < len(s) and i < len(b):\n if s[i] == b[i] : i += 1\n else : c += 1 ; s.pop(i)\n if ''.join(s).startswith(b) : c += len(s[len(b):]) ; break\n return c", "def string_constructing(a, s):\n if not s:\n return 0\n if set(s)-set(a):\n return False\n\n n = 1\n i = 0\n for c in s:\n while True:\n if i==len(a):\n i = 0\n n += 1\n if a[i]!=c:\n n += 1\n i+=1\n else:\n i+=1\n break\n \n \n return n+len(a)-i\n"] | {"fn_name": "string_constructing", "inputs": [["aba", "abbabba"], ["aba", "abaa"], ["aba", "a"], ["a", "a"], ["a", "aaa"], ["abcdefgh", "hgfedcba"]], "outputs": [[9], [4], [3], [1], [3], [64]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,456 |
def string_constructing(a, s):
|
6d474e5e23bcc64cd7739cf4df96dee8 | UNKNOWN | In this kata, you've to count lowercase letters in a given string and return the letter count in a hash with 'letter' as key and count as 'value'. The key must be 'symbol' instead of string in Ruby and 'char' instead of string in Crystal.
Example:
```python
letter_count('arithmetics') #=> {"a": 1, "c": 1, "e": 1, "h": 1, "i": 2, "m": 1, "r": 1, "s": 1, "t": 2}
``` | ["from collections import Counter\ndef letter_count(s):\n return Counter(s)", "def letter_count(s):\n return {i: s.count(i) for i in s}", "from collections import Counter as letter_count", "def letter_count(s):\n letters = {}\n for i in list(s):\n if i in letters:\n letters[i] += 1\n else:\n letters[i] = 1\n return letters", "import collections\n\ndef letter_count(s):\n res = collections.defaultdict(int)\n for _char in s:\n res[_char] += 1\n return res", "def letter_count(s):\n return {c: s.count(c) for c in set(s)}", "def letter_count(s):\n return dict((letter, s.count(letter)) for letter in sorted(set(s)))", "def letter_count(s):\n count = {}\n for c in s:\n count[c] = count.get(c, 0) + 1\n \n return count", "import collections\n\ndef letter_count(s):\n result = {}\n for i, d in enumerate(s):\n count = 1\n if d not in result:\n for j in range(i+1, len(s)):\n if d == s[j]:\n count += 1\n result[d] = count\n return collections.OrderedDict(sorted(result.items()))", "def letter_count(s):\n count = {}\n for i in s:\n if i in count:\n count[i] += 1\n else:\n count[i] = 1\n return count"] | {"fn_name": "letter_count", "inputs": [["codewars"], ["activity"], ["arithmetics"], ["traveller"], ["daydreamer"]], "outputs": [[{"a": 1, "c": 1, "d": 1, "e": 1, "o": 1, "r": 1, "s": 1, "w": 1}], [{"a": 1, "c": 1, "i": 2, "t": 2, "v": 1, "y": 1}], [{"a": 1, "c": 1, "e": 1, "h": 1, "i": 2, "m": 1, "r": 1, "s": 1, "t": 2}], [{"a": 1, "e": 2, "l": 2, "r": 2, "t": 1, "v": 1}], [{"a": 2, "d": 2, "e": 2, "m": 1, "r": 2, "y": 1}]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,316 |
def letter_count(s):
|
4572e7b1c76c71605983bbffe5abf9a3 | UNKNOWN | Suppose I have two vectors: `(a1, a2, a3, ..., aN)` and `(b1, b2, b3, ..., bN)`. The dot product between these two vectors is defined as:
```
a1*b1 + a2*b2 + a3*b3 + ... + aN*bN
```
The vectors are classified as orthogonal if the dot product equals zero.
Complete the function that accepts two sequences as inputs and returns `true` if the vectors are orthogonal, and `false` if they are not. The sequences will always be correctly formatted and of the same length, so there is no need to check them first.
## Examples
```
[1, 1, 1], [2, 5, 7] --> false
[1, 0, 0, 1], [0, 1, 1, 0] --> true
``` | ["def is_orthogonal(u, v): \n return sum(i*j for i,j in zip(u,v)) == 0", "def is_orthogonal(u, v):\n return sum(a*b for a, b in zip(u, v)) == 0", "from numpy import dot\n\ndef is_orthogonal(u, v): \n return not dot(u,v )", "def is_orthogonal(u, v):\n dot_product = 0\n for pair in zip(u, v):\n dot_product += pair[0] * pair[1]\n return dot_product == 0", "from operator import mul\ndef is_orthogonal(u, v): \n return not sum(map(mul, u, v))", "def is_orthogonal(u, v): \n return not sum(a * b for a, b in zip(u, v))", "def is_orthogonal(u, v): \n # your code here\n count = list()\n \n for x, y in zip(u, v):\n multiply = x * y\n count.append(multiply)\n \n result = sum(count)\n if result != 0:\n return False\n else:\n return True\n", "is_orthogonal = lambda u, v: not sum(a * b for a, b in zip(u, v))", "import numpy\ndef is_orthogonal(u, v): \n c=numpy.dot(u,v)\n if c:\n return False\n return True\n", "is_orthogonal=lambda*u:not sum(list(map(int.__mul__,*u)))"] | {"fn_name": "is_orthogonal", "inputs": [[[1, 2], [2, 1]], [[1, -2], [2, 1]], [[7, 8], [7, -6]], [[-13, -26], [-8, 4]], [[1, 2, 3], [0, -3, 2]], [[3, 4, 5], [6, 7, -8]], [[3, -4, -5], [-4, -3, 0]], [[1, -2, 3, -4], [-4, 3, 2, -1]], [[2, 4, 5, 6, 7], [-14, -12, 0, 8, 4]], [[5, 10, 1, 20, 2], [-2, -20, -1, 10, 5]]], "outputs": [[false], [true], [false], [true], [true], [false], [true], [true], [true], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,070 |
def is_orthogonal(u, v):
|
475c21fd2903da1bffaa97ebf98b379a | UNKNOWN | An acrostic is a text in which the first letter of each line spells out a word. It is also a quick and cheap way of writing a poem for somebody, as exemplified below :
Write a program that reads an acrostic to identify the "hidden" word. Specifically, your program will receive a list of words (reprensenting an acrostic) and will need to return a string corresponding to the word that is spelled out by taking the first letter of each word in the acrostic. | ["def read_out(acrostic):\n return \"\".join( word[0] for word in acrostic )", "def read_out(acrostic):\n return ''.join(next(zip(*acrostic)))", "from operator import itemgetter\n\ndef read_out(acrostic):\n return ''.join(map(itemgetter(0), acrostic))", "def read_out(acrostic):\n return ''.join(e[0] for e in acrostic)", "def read_out(acrostic):\n return ''.join(w[0] for w in acrostic)", "def read_out(acrostic):\n return ''.join(s[0] for s in acrostic)", "# WHO WORE IT BETTER ??\n\n' 1) LOOP CAT ? '\ndef read_out(array): # 2 seconds\n acrostic = ''\n for word in array:\n acrostic += word[0]\n return acrostic\n\n' 2) LIST COMP ? '\nread_out = lambda a: ''.join(w[0] for w in a) # 3.6 seconds\n\n' 3) MAP OBJ ? '\nread_out = lambda a: ''.join([w[0] for w in a])\n\n# YOU DECIDE !!\n\n# VOTE: 1, 2, or 3\n", "def read_out(acr):\n return ''.join( map(lambda a:a[0] , acr ) )", "def read_out(a):\n return ''.join(c[0] for c in a)", "def read_out(acrostic):\n return ''.join(i[0] for i in acrostic).upper()"] | {"fn_name": "read_out", "inputs": [[["Jolly", "Amazing", "Courteous", "Keen"]], [["Marvelous", "Excellent", "Gifted"]]], "outputs": [["JACK"], ["MEG"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,064 |
def read_out(acrostic):
|
8310416ea24391c2dacbd1abca4fb370 | UNKNOWN | Your task is to define a function that understands basic mathematical expressions and solves them.
For example:
```python
calculate("1 + 1") # => 2
calculate("18 + 4*6") # => 42
calculate("245 - 826") # => -581
calculate("09 + 000482") # => 491
calculate("8 / 4 + 6") # => 8
calculate("5 + 1 / 5") # => 5.2
calculate("1+2+3") # => 6
calculate("9 /3 + 12/ 6") # => 5
```
Notes:
- Input string will contain numbers (may be integers and floats) and arithmetic operations.
- Input string may contain spaces, and all space characters should be ignored.
- Operations that will be used: addition (+), subtraction (-), multiplication (*), and division (/)
- Operations must be done in the order of operations: First multiplication and division, then addition and subtraction.
- In this kata, input expression will not have negative numbers. (ex: "-4 + 5")
- If output is an integer, return as integer. Else return as float.
- If input string is empty, contains letters, has a wrong syntax, contains division by zero or is not a string, return False. | ["import re\ndef calculate(input):\n try:\n return eval(re.sub(r'(\\d+)', lambda m: str(int(m.group(1))), input))\n except:\n return False", "import re\ndef calculate(s):\n try:\n s = re.sub(r'(?<!\\d)0+(0|[1-9]\\d*)', lambda m: m.group(1), s)\n s = re.sub(r'\\d+(?!\\.)', lambda m: m.group() + '.0', s)\n return eval(s)\n except:\n return False", "import math\ndef solve(s: list, mp=0):\n LHS = s.pop(0)\n while len(s) > 0:\n #\n op = s[0]\n #\n p = 1 if op in '+-' else 2\n if p < mp: break\n p += 1\n s.pop(0) #drop the operator because it being used\n #\n RHS = solve(s, p)\n if op == '+': LHS+=RHS\n elif op == '-': LHS-=RHS\n elif op == '*': LHS*=RHS\n elif RHS != 0: LHS/=RHS\n else: return math.nan\n return LHS\n\ndef calculate(s):\n try:\n s=s.replace(' ', '')\n except:\n return False\n #\n dim = len(s)\n #\n if dim == 0: return False\n #\n for c in s: \n if not (c in '0123456789.+-*/'): return False\n for i in range(dim-1):\n if s[i] in '+-*/' and s[i+1] in '+-*/': return False\n #\n exp = []\n i=0\n for j,c in enumerate(s):\n if i==j:\n pass\n elif c in ['+','-','*','/']:\n try:\n exp.append(float(s[i:j]))\n except:\n return False\n exp.append(s[j])\n i=j+1\n try:\n exp.append(float(s[i:]))\n except:\n return False\n #\n v = solve(exp)\n #\n if math.isnan(v): return False\n if float(v) == float(int(v)): return int(v)\n return v", "from re import sub\n\ndef calculate(input):\n try:\n return eval(sub(r'([^\\d])0+(\\d)', r'\\1\\2', input))\n except:\n return False", "import re\n\ndef calculate(s):\n try: return eval(re.sub(r'\\b0+(?=[1-9])', '', s))\n except: return False", "import re\n\ndef calculate(input):\n try:\n for n in re.findall(\"\\d+\", input):\n input = input.replace(n, (n.lstrip(\"0\") or \"0\"))\n return eval(input)\n except: return False", "import functools as ft\nimport math\n\nops = ['*', '/', '+', '-']\n\n\ndef SanitizeExpression(expression):\n return expression.replace(\"+-\", \"-\").replace(\"-+\", \"-\").replace(\"--\", \"+\")\n pass\n\n\ndef ExtendList(arr, value, op):\n arr.extend(value.split(op))\n return arr\n\n\ndef LastIndexOfAny(expression, operators, startIndex):\n arr = [expression[0:startIndex].rfind(x) for x in operators]\n arr.sort()\n return arr[-1]\n pass\n\n\ndef IndexOfAny(expression, operators, startIndex):\n arr = [x + startIndex for x in [expression[startIndex:].find(x) for x in operators] if x != -1]\n if len(arr) == 0:\n arr = [-1]\n arr.sort()\n return arr[0]\n pass\n\n\ndef FloatToString(value):\n return \"%.30f\" % value\n pass\n\n\ndef EvaluateSimpleExpression(expression):\n numberText = expression.split(ops[0])\n numberText = ft.reduce(lambda r, s: ExtendList(r, s, ops[2]), numberText, [])\n numberText = ft.reduce(lambda r, s: ExtendList(r, s, ops[3]), numberText, [])\n numberText = ft.reduce(lambda r, s: ExtendList(r, s, ops[1]), numberText, [])\n\n numbers = [float(x) for x in numberText if x != '']\n\n minusCount = expression.count('-')\n\n if expression.count('*') > 0:\n return numbers[0] * numbers[1] * math.pow(-1, minusCount)\n\n if expression.count('/') > 0:\n return numbers[0] / numbers[1] * math.pow(-1, minusCount)\n\n if expression.count('-') > 0:\n return numbers[0] - numbers[1]\n\n return numbers[0] + numbers[1]\n pass\n\n\ndef ResolveSimpleExpression(expression, operatorIndex):\n startIndex = LastIndexOfAny(expression, ops, operatorIndex - 1) + 1\n indexNext = IndexOfAny(expression, ops, operatorIndex + 2)\n\n if indexNext == -1:\n length = len(expression)\n else:\n length = indexNext\n\n length -= startIndex\n\n return expression[startIndex:startIndex + length]\n pass\n\n\ndef EvaluateSimpleInComplexExpression(expression, operatorIndex):\n simple = ResolveSimpleExpression(expression, operatorIndex)\n simpleAns = EvaluateSimpleExpression(simple)\n if math.fabs(simpleAns) < 1e-10:\n simpleAns = 0\n pass\n\n insertIndex = expression.find(simple)\n\n return expression[0:insertIndex] + FloatToString(simpleAns) + expression[insertIndex + len(simple):]\n pass\n\n\ndef SimplifyExpressionByOperatorsRec(expression, applyNegative, multiplier, operators):\n if expression[0] == '+':\n expression = expression[1:]\n\n if applyNegative and expression[0] == '-':\n multiplier *= -1\n expression = expression[1:].replace(\"+\", \"X\").replace(\"-\", \"+\").replace(\"X\", \"-\")\n pass\n\n indexArr = [x for x in [expression.find(op) for op in operators] if x > 0]\n if len(indexArr) > 0:\n indexArr.sort()\n index = indexArr[0]\n\n expression = EvaluateSimpleInComplexExpression(expression, index)\n expression = SanitizeExpression(expression)\n\n return SimplifyExpressionByOperatorsRec(expression, applyNegative, multiplier, operators)\n pass\n\n try:\n return FloatToString(float(expression) * multiplier)\n except:\n return expression\n pass\n\n\ndef SimplifyExpressionByOperators(expression, applyNegative, operators):\n return SimplifyExpressionByOperatorsRec(expression, applyNegative, 1, operators)\n\n\ndef EvaluateComplexExpression(expression):\n result = SimplifyExpressionByOperators(expression, False, ['*', '/'])\n\n return SimplifyExpressionByOperators(result, True, ['+', '-'])\n pass\n\n\ndef EvaluateBracketExpression(expression):\n closeIndex = expression.find(')')\n if closeIndex >= 0:\n openIndex = expression[0:closeIndex].rfind('(')\n startIndex = openIndex + 1\n length = closeIndex - startIndex\n\n complexExp = expression[startIndex:closeIndex]\n resolved = EvaluateComplexExpression(complexExp)\n\n expression = expression[0:openIndex] + str(resolved) + expression[openIndex + length + 2:]\n expression = SanitizeExpression(expression)\n\n return EvaluateBracketExpression(expression)\n pass\n\n return EvaluateComplexExpression(expression)\n pass\n\n\ndef calculate(expression): \n try:\n test = 'string' + expression\n except:\n return False\n \n expression = str(expression).replace(\" \", \"\") \n if expression == '':\n return 0\n \n expression = SanitizeExpression(expression)\n\n try:\n return float(EvaluateBracketExpression(expression))\n except:\n return False\n pass\n\n", "from re import sub\n\ndef calculate(s):\n try: return eval(sub(r'\\b0+(?=\\d)', '', s))\n except: return 0", "class Calculator(object):\n\n operators = {'+': lambda x,y: x+ y,\n '-': lambda x, y: x - y,\n '*': lambda x, y: x * y,\n '/': lambda x, y: x / y }\n high_pre = ['*', '/']\n\n def __init__(self):\n self.operand = []\n self.operator = []\n\n def parse_string(self, string):\n index = 0\n while index < len(string):\n end = index + 1\n while end < len(string) and string[end] not in list(self.operators.keys()):\n end += 1\n try:\n self.operand.append(float(string[index:end]))\n except:\n return False\n if end < len(string):\n self.operator.append(string[end])\n index = end + 1\n return True\n\n def evaluate(self, string = \"\"):\n if string == \"\":\n string = \"0\"\n\n valid = self.parse_string(string)\n if not valid:\n return False\n\n while len(self.operand) != 1:\n operator_index = len(string)\n for op in self.high_pre:\n if op in self.operator:\n operator_index = min(operator_index, self.operator.index(op))\n if operator_index == len(string):\n operator_index = 0\n x = self.operand[operator_index]\n y = self.operand[operator_index + 1]\n op = self.operator[operator_index]\n try:\n self.operand[operator_index] = self.operators[op](x, y)\n except:\n return False\n self.operand.pop(operator_index + 1)\n self.operator.pop(operator_index)\n\n return self.operand[0]\n \n\ndef calculate(input):\n if type(input) != str:\n return False\n return Calculator().evaluate(input)\n", "digits = '0123456789'\nops = '+-/*'\n\ndef calc(expr):\n r = []\n i = 0\n t = len(expr)\n c = ''\n s = ''\n left = 0\n right = 0\n cur_idx = 0\n while i < t:\n c = expr[i]\n if c in digits:\n if not s:\n s = c\n elif s[-1] in digits:\n s += c\n else:\n r += [s]\n s = c\n elif c == ' ':\n pass\n elif c in ops:\n r += [s] if s != '' else []\n r += [c]\n s = ''\n elif c == '(':\n left = 1\n right = 0\n cur_idx = i\n while i < t and left != right:\n i += 1\n if expr[i] == '(':\n left += 1\n elif expr[i] == ')':\n right += 1\n r += [calc(expr[cur_idx+1:i])]\n i += 1\n r += [s] if s != '' else []\n r_new = []\n for item in r:\n try:\n r_new.append(float(item))\n except ValueError:\n r_new.append(item)\n r = list(r_new)\n r_new = []\n i = 0\n t = len(r)\n while i < t:\n if r[i] == '-':\n if type(r[i+1])==float:\n r_new.append(-r[i+1])\n elif r[i+1] == '-':\n sign = 1\n while r[i+1] == '-':\n sign *= -1\n i += 1\n r_new.append(sign * r[i])\n i -= 1\n else:\n r_new.append(r[i])\n r_new.append(r[i+1])\n i += 2\n else:\n r_new.append(r[i])\n i += 1\n r_new = [d for d in r_new if d != '']\n while '*' in r_new or '/' in r_new:\n t = len(r_new)\n mul_idx = r_new.index('*') if '*' in r_new else t\n div_idx = r_new.index('/') if '/' in r_new else t\n if mul_idx == 0 or div_idx == 0:\n raise Exception()\n cur_idx = min(mul_idx, div_idx)\n new_numb = r_new[cur_idx-1] * r_new[cur_idx+1] if cur_idx == mul_idx else r_new[cur_idx-1] / r_new[cur_idx+1]\n r_new = r_new[:cur_idx-1] + [new_numb] + r_new[cur_idx+2:]\n return sum([d for d in r_new if d != '+'])\n \n\ndef calculate(x):\n if x == '':\n return False\n try:\n return calc(x)\n except:\n return False"] | {"fn_name": "calculate", "inputs": [["1 + 1"], ["9 - 4"], ["1 - 4"], ["3 * 4"], ["9 / 3"], ["26 + 73"], ["524 + 277"], ["1 / 2"], ["2 / 5"], ["1 + 2 + 3 + 4 + 5 + 6"], ["123 - 3 - 20 - 100"], ["123 * 987 * 135 * 246"], ["200 / 2 / 10 / 5"], ["1+2-3+4-5+6-7+8-9+10"], ["5*2/3*9/10*123/8"], ["1*2*3/1/2/3+1+2+3-1-2-3"], ["1+2 * 4"], ["1+2 / 4"], ["1-2 * 4"], ["1-2 / 4"], ["1+2-3*4/6"], [""], ["7 - A"], ["3 + 2 * "], [" / 7 + 3"], [5], ["1 / 0"]], "outputs": [[2], [5], [-3], [12], [3], [99], [801], [0.5], [0.4], [21], [0], [4031727210], [2], [7], [46.125], [1], [9], [1.5], [-7], [0.5], [1], [false], [false], [false], [false], [false], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 11,313 |
def calculate(input):
|
3d41b5747627705c9735e33422a0b8c4 | UNKNOWN | # Task
Your task is to find the smallest number which is evenly divided by all numbers between `m` and `n` (both inclusive).
# Example
For `m = 1, n = 2`, the output should be `2`.
For `m = 2, n = 3`, the output should be `6`.
For `m = 3, n = 2`, the output should be `6` too.
For `m = 1, n = 10`, the output should be `2520`.
# Input/Output
- `[input]` integer `m`
`1 ≤ m ≤ 25`
- `[input]` integer `n`
`1 ≤ n ≤ 25`
- `[output]` an integer | ["from fractions import gcd\nfrom functools import reduce\n\ndef mn_lcm(m, n):\n return reduce(lambda x, y: (x * y) / gcd(x, y), list(range(min(m, n), max(m, n) + 1)))\n\n", "from fractions import gcd\nfrom functools import reduce\ndef mn_lcm(m, n):\n return reduce(lambda x, y: (x * y) / gcd(x, y), range(min(m, n), max(m, n) + 1))", "from fractions import gcd\nfrom functools import reduce\n\ndef mn_lcm(m, n):\n m, n = sorted([m, n])\n return reduce(lambda x, y: x * y / gcd(x, y), range(m, n + 1))", "def gcd(a,b):\n return a if b == 0 else gcd(b,a%b)\n \ndef mn_lcm(m,n):\n if n < m:\n m, n = n, m\n ans = m\n for i in range(m,n+1):\n ans = ((i*ans)) / (gcd(i, ans)) \n return ans", "from fractions import gcd\nfrom functools import reduce\n\ndef _lcm(a, b):\n return a and b and (a * b // gcd(a, b)) or 0\n\ndef lcm(*args):\n return args and reduce(_lcm, args) or 0\n\ndef mn_lcm(m,n):\n low, high = sorted((m, n))\n return lcm(*range(low, high+1))", "import functools\ndef gcd_rec(a, b): \n if b:\n return gcd_rec(b, a % b)\n else:\n return a\n\ndef mn_lcm(m,n):\n lst = list(range(min(n,m),max(n,m)+1))\n return functools.reduce(lambda a,b : a*b/gcd_rec(a,b),lst ) ", "def gcd(a, b):\n if a < b: \n b, a = a, b\n while b != 0:\n a, b = b, a % b\n return a\n\ndef mn_lcm(m, n):\n m, n = sorted([m, n])\n f = 1\n for i in range(m, n + 1):\n f = abs(i * f) // gcd(i, f)\n return f", "from fractions import gcd\nfrom functools import reduce\ndef lcm(a,b):\n return a//gcd(a,b)*b\n\ndef mn_lcm(m,n):\n m,n = sorted([m,n])\n return reduce(lcm, range(m,n+1))"] | {"fn_name": "mn_lcm", "inputs": [[1, 2], [1, 5], [5, 1], [1, 10], [2, 3], [3, 5], [10, 20], [1, 25], [24, 25]], "outputs": [[2], [60], [60], [2520], [6], [60], [232792560], [26771144400], [600]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,690 |
def mn_lcm(m, n):
|
0a4946a5605393b9bb7e2d9591e1426e | UNKNOWN | # Task
Alireza and Ali have a `3×3 table` and playing on that. they have 4 table(2×2) A,B,C and D in this table.
At beginning all of 9 numbers in 3×3 table is zero.
Alireza in each move choose a 2×2 table from A, B, C and D and increase all of 4 numbers in that by one.
He asks Ali, how much he increase table A, B, C and D. (if he cheats you should return `[-1]`)
Your task is to help Ali.
# Example
For
```
table=
[[1,2,1],
[2,4,2],
[1,2,1]]```
The result should be `[1,1,1,1]`
For:
```
Table=
[[3,7,4],
[5,16,11],
[2,9,7]]```
The result should be `[3,4,2,7]`
# Input/Output
- `[input]` 2D integer array `table`
`3×3` table.
- `[output]` an integer array | ["def table_game(table):\n (a, ab, b), (ac, abcd, bd), (c, cd, d) = table\n if (a + b == ab) and (c + d == cd) and (a + c == ac) and (b + d == bd) and (a + b + c + d == abcd):\n return [a, b, c, d]\n return [-1]", "def table_game(table):\n a, b, c, d = table[0][0], table[0][2], table[2][0], table[2][2]\n guess = [[a, a + b, b], [a + c, a + b + c + d, b + d], [c, c + d, d]]\n return [a, b, c, d] if table == guess else [-1]", "def table_game(table):\n top_left, top_right, bot_left, bot_right = table[0][0], table[0][-1], table[-1][0], table[-1][-1]\n top, bot, left, right = table[0][1], table[-1][1], table[1][0], table[1][-1]\n center = table[1][1]\n if (top_left + top_right == top and\n bot_left + bot_right == bot and\n top_left + bot_left == left and\n top_right + bot_right == right and\n top + bot == center):\n return [top_left, top_right, bot_left, bot_right]\n else:\n return [-1]", "def table_game(t):\n l = [t[0][0],t[0][2],t[2][0],t[2][2]]\n return l if sum(l) == t[1][1] and sum(sum(t,[])) == sum(l) * 4 else [-1]", "def table_game(table):\n return [table[i][j] for i in (0, 2) for j in (0, 2)] if all(table[0][i] + table[2][i] == table[1][i] and table[i][0] + table[i][2] == table[i][1] for i in range(3)) else [-1]", "def table_game(t):\n return [t[0][0],t[0][2],t[2][0],t[2][2]] if (t[0][1]+t[2][1])==(t[1][0]+t[1][2])==t[1][1] else [-1]", "def table_game(t):\n [a,b,c,d]=[t[0][0],t[0][2],t[2][0],t[2][2]]\n return [a,b,c,d] if t[0][1]==a+b and t[1][0]==a+c and t[1][2]==b+d and t[1][1]==a+b+c+d and t[2][1]==c+d else [-1]", "def table_game(table):\n (a, ab, b), (ac, abcd, bd), (c, cd, d) = table\n return [a, b, c, d] if ab == a + b and ac == a + c and bd == b + d and cd == c + d and abcd == ab + cd else [-1]", "def table_game(table):\n if table[0][1] + table[1][0] + table[1][2] + table[2][1] == table[1][1] * 2:\n if table[0][0] + table[0][2] == table[0][1]:\n if table[2][0] + table[2][2] == table[2][1]:\n if table[0][0] + table[2][0] == table[1][0]:\n if table[0][2] + table[2][2] == table[1][2]:\n return [table[0][0],table[0][2],table[2][0],table[2][2]]\n return [-1]"] | {"fn_name": "table_game", "inputs": [[[[1, 2, 1], [2, 4, 2], [1, 2, 1]]], [[[3, 7, 4], [5, 16, 11], [2, 9, 7]]], [[[1, 4, 2], [5, 10, 5], [4, 7, 3]]], [[[2, 4, 2], [4, 6, 4], [2, 4, 2]]], [[[1, 2, 1], [1, 2, 1], [1, 2, 1]]], [[[2, 4, 2], [4, 8, 4], [2, 4, 2]]], [[[1, 3, 2], [5, 10, 5], [4, 7, 3]]]], "outputs": [[[1, 1, 1, 1]], [[3, 4, 2, 7]], [[-1]], [[-1]], [[-1]], [[2, 2, 2, 2]], [[1, 2, 4, 3]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,284 |
def table_game(table):
|
b25ec17c947be9837b91fcc0b1d6d739 | UNKNOWN | How much bigger is a 16-inch pizza compared to an 8-inch pizza? A more pragmatic question is: How many 8-inch pizzas "fit" in a 16-incher?
The answer, as it turns out, is exactly four 8-inch pizzas. For sizes that don't correspond to a round number of 8-inchers, you must round the number of slices (one 8-inch pizza = 8 slices), e.g.:
```python
how_many_pizzas(16) -> "pizzas: 4, slices: 0"
how_many_pizzas(12) -> "pizzas: 2, slices: 2"
how_many_pizzas(8) -> "pizzas: 1, slices: 0"
how_many_pizzas(6) -> "pizzas: 0, slices: 4"
how_many_pizzas(0) -> "pizzas: 0, slices: 0"
```
Get coding quick, so you can choose the ideal size for your next meal! | ["def how_many_pizzas(n):\n return 'pizzas: {}, slices: {}'.format(*divmod(n * n // 8, 8))", "def how_many_pizzas(n):\n pizzas, slices = (int(n) for n in divmod(n**2, 64))\n return f\"pizzas: {pizzas}, slices: {slices // 8}\"", "def how_many_pizzas(n):\n q, r = divmod(n**2, 8**2)\n return f\"pizzas: {q}, slices: {round(r / 8)}\"", "def how_many_pizzas(n):\n return f'pizzas: {n*n // 8**2}, slices: {n*n/8 % 8:.0f}'", "def how_many_pizzas(n):\n pizzas = n * n / 64\n p = int(pizzas)\n s = int((pizzas - p) * 8)\n return f'pizzas: {p}, slices: {s}'", "def how_many_pizzas(n):\n area = n * n\n eight_area = 64\n total_pizzas = int(area/eight_area)\n slices = 0\n if area % eight_area != 0:\n slices = int((area - (total_pizzas * eight_area))/8)\n return \"pizzas: {}, slices: {}\".format(total_pizzas, slices)", "def how_many_pizzas(n):\n return 'pizzas: {}, slices: {}'.format(n ** 2 // 8 ** 2, n ** 2 % 8 ** 2 // 8)", "import math\ndef how_many_pizzas(n):\n x = math.floor(n*n/64) \n w = round((n*n%64)/8)\n return f\"pizzas: {x}, slices: {w}\"\n", "def how_many_pizzas(n):\n return f\"pizzas: {n ** 2 //( 8 ** 2)}, slices: {round(((n ** 2) /( 8 ** 2)-(n ** 2)//( 8 ** 2))* 8) }\" \n\n\n", "def how_many_pizzas(n): return f\"pizzas: {(n ** 2) // 64}, slices: {(n ** 2) % 64 // 8}\""] | {"fn_name": "how_many_pizzas", "inputs": [[16], [12], [8], [6], [0]], "outputs": [["pizzas: 4, slices: 0"], ["pizzas: 2, slices: 2"], ["pizzas: 1, slices: 0"], ["pizzas: 0, slices: 4"], ["pizzas: 0, slices: 0"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,353 |
def how_many_pizzas(n):
|
271531e9e5e23daa0f9e3901c175ef0c | UNKNOWN | In this Kata, you will be given a string with brackets and an index of an opening bracket and your task will be to return the index of the matching closing bracket. Both the input and returned index are 0-based **except in Fortran where it is 1-based**. An opening brace will always have a closing brace. Return `-1` if there is no answer (in Haskell, return `Nothing`; in Fortran, return `0`; in Go, return an error)
### Examples
```python
solve("((1)23(45))(aB)", 0) = 10 -- the opening brace at index 0 matches the closing brace at index 10
solve("((1)23(45))(aB)", 1) = 3
solve("((1)23(45))(aB)", 2) = -1 -- there is no opening bracket at index 2, so return -1
solve("((1)23(45))(aB)", 6) = 9
solve("((1)23(45))(aB)", 11) = 14
solve("((>)|?(*'))(yZ)", 11) = 14
```
Input will consist of letters, numbers and special characters, but no spaces. The only brackets will be `(` and `)`.
More examples in the test cases.
Good luck!
~~~if:fortran
*NOTE: In Fortran, you may assume that the input string will not contain any leading/trailing whitespace.*
~~~ | ["def solve(s, idx):\n stack = []\n for i, c in enumerate(s):\n if c == '(': stack += [i]\n if c == ')':\n if not stack: break\n if stack.pop() == idx: return i\n \n return -1", "def solve(s, i):\n c = s[i] == '('\n if not c: return -1\n while c != 0 and i != len(s):\n i += 1\n if s[i]=='(': c += 1\n elif s[i]==')': c -= 1\n return -1 if c != 0 else i", "def solve(st, idx):\n if st[idx] != '(':\n return -1\n open = 1\n for i in range(idx+1, len(st)):\n if st[i] == '(':\n open += 1\n elif st[i] == ')':\n open -= 1\n if open == 0:\n return i", "def solve(st, idx):\n if st[idx] != \"(\":\n return -1\n\n open_par = 0\n for i, ch in enumerate(st[idx + 1:]):\n if ch == \"(\":\n open_par += 1\n elif ch == \")\":\n if not open_par:\n return i + idx + 1\n open_par -= 1", "def solve(stg, s):\n n = 1\n if stg[s] == \"(\":\n while n and s < len(stg):\n n, s = n + {\"(\": 1, \")\": -1}.get(stg[s+1], 0), s + 1\n return -1 if n else s\n", "from functools import reduce\nfrom itertools import takewhile\n\ndef solve(s, i):\n return i + len(list(takewhile(bool, reduce(lambda x, y : x + [x[-1] + { '(': 1, ')': -1 }.get(y, 0)], s[i+1:], [1])))) if s[i] == '(' else -1", "def solve(st, idx):\n if st[idx] != \"(\": return -1\n d = 1\n while d > 0:\n idx += 1\n if st[idx] == \")\": d -= 1\n if st[idx] == \"(\": d += 1 \n return idx", "def solve(st, idx):\n #If char at index is not an opening bracket, return -1\n if st[idx] != \"(\":\n return -1\n #Create a stack data structure\n stack = []\n for i in range(len(st)):\n #If the char at our current index i is an opening bracket, push index on our stack\n if st[i] == \"(\":\n stack.append(i)\n #If the char is a closing bracket, pop from our stack\n elif st[i] == \")\":\n tmp = stack.pop()\n #If the value from our stack matches the given idx, then our current index i is \n #the closing bracket we are searching for, thus we return said index i\n if tmp == idx:\n return i\n #If there was no solution, return -1\n return -1\n", "def solve(st, idx):\n if st[idx] != '(':\n return -1\n key = 1\n for n, letter in enumerate(st[idx+1:]):\n if key == 0:\n return idx+n\n if letter == ')':\n key -= 1\n elif letter == '(':\n key += 1\n if key == 0:\n return idx+n+1\n return -1", "def solve(st, idx):\n length = len(st)\n opened = 0\n start = st[idx]\n if start != \"(\":\n return -1\n for i in range(idx,length,1):\n if st[i] == \")\":\n if opened != 0:\n opened = opened - 1\n if opened == 0: \n return i\n elif st[i] == \"(\":\n opened = opened + 1\n return -1"] | {"fn_name": "solve", "inputs": [["((1)23(45))(aB)", 0], ["((1)23(45))(aB)", 1], ["((1)23(45))(aB)", 2], ["((1)23(45))(aB)", 6], ["((1)23(45))(aB)", 11], ["(g(At)IO(f)(tM(qk)YF(n)Nr(E)))", 11], ["(g(At)IO(f)(tM(qk)YF(n)Nr(E)))", 0], ["(>_(va)`?(h)C(as)(x(hD)P|(fg)))", 19]], "outputs": [[10], [3], [-1], [9], [14], [28], [29], [22]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,133 |
def solve(st, idx):
|
3bf9201205fde88cc4cc36679a2cf23a | UNKNOWN | Given a number `n`, make a down arrow shaped pattern.
For example, when `n = 5`, the output would be:
123454321
1234321
12321
121
1
and for `n = 11`, it would be:
123456789010987654321
1234567890987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
An important thing to note in the above example is that the numbers greater than 9 still stay single digit, like after 9 it would be 0 - 9 again instead of 10 - 19.
Note: There are spaces for the indentation on the left of each line and no spaces on the right.
Have fun! | ["def half(i, n):\n return \"\".join(str(d%10) for d in range(1, n-i+1))\n\ndef line(i, n):\n h = half(i, n)\n return \" \" * i + h + h[-2::-1]\n\ndef get_a_down_arrow_of(n):\n return \"\\n\".join(line(i, n) for i in range(n))\n", "from itertools import cycle, islice\n\ndef get_a_down_arrow_of(n):\n \n r = []\n \n for i, x in enumerate(range(n, 0, -1)):\n c = cycle('1234567890')\n s = list(islice(c, x))\n s += s[::-1][1:]\n r.append(' ' * i + ''.join(s))\n \n return '\\n'.join(r)", "from itertools import chain\n\ndef get_a_down_arrow_of(n):\n result = []\n for i in range(n, 0, -1):\n row = \" \" * (n - i) + \"\".join(str(d % 10) for d in chain(range(1, i), range(i, 0, -1)))\n result.append(row)\n return \"\\n\".join(result)", "result = ['1']\n\ndef get_a_down_arrow_of(n):\n while len(result) < n:\n i = len(result)\n result.append(result[-1][:i] + str((i+1)%10) + result[-1][i-1::-1])\n return '\\n'.join(result[x].center(2*n-1).rstrip() for x in range(n-1, -1, -1))", "digits = '1234567890' * 1000\n\ndef get_a_down_arrow_of(n):\n width = 2 * n - 1\n return '\\n'.join(\n ''.join(digits[:i-1] + digits[max(i-1, 0)::-1]).center(width).rstrip()\n for i in range(n, 0, -1)\n )", "def get_a_down_arrow_of(n):\n answer = \"\"\n for i in range(n, 0, -1):\n spaces = \" \" * (n - i)\n half1 = \"\".join(str(x % 10) for x in range(1, i + 1))\n half2 = half1[::-1]\n answer += spaces + half1 + half2[1:] + \"\\n\" * (i > 1)\n return answer", "get_a_down_arrow_of=lambda n,m=lambda s:s+s[-2::-1]:'\\n'.join(' '*i+m(('1234567890'*n)[:n-i])for i in range(n))", "get_a_down_arrow_of=lambda n,s=0: \"\" if n<1 else \" \"*s+\"1\" if n==1 else \"\\n\".join([\" \"*s+\"\".join([str(q%10) for q in range(1,n+1)]+[str(q%10) for q in range(n-1,0,-1)])]+[get_a_down_arrow_of(n-1,s+1)])"] | {"fn_name": "get_a_down_arrow_of", "inputs": [[5]], "outputs": [["123454321\n 1234321\n 12321\n 121\n 1"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,943 |
def get_a_down_arrow_of(n):
|
4444daa6cde3233fad916dec88e122f9 | UNKNOWN | Description:
The mean (or average) is the most popular measure of central tendency; however it does not behave very well when the data is skewed (i.e. wages distribution). In such cases, it's better to use the median.
Your task for this kata is to find the median of an array consisting of n elements.
You can assume that all inputs are arrays of numbers in integer format. For the empty array your code should return `NaN` (false in JavaScript/`NULL` in PHP/`nil` in Ruby).
Examples:
Input `[1, 2, 3, 4]` --> Median `2.5`
Input `[3, 4, 1, 2, 5]` --> Median `3` | ["from statistics import median", "def median(arr):\n arr.sort()\n return (arr[(len(arr) - 1)//2] + arr[(len(arr))//2])/2", "from numpy import median", "import numpy as np\ndef median(arr):\n return np.median(arr) if len(arr)>0 else None\n", "from random import choice\n\ndef median(lst):\n return quickselect(lst, len(lst) // 2, len(lst) % 2 == 0)\n\ndef quickselect(lst, nth, even):\n # O(n) but what a pain to get right.\n pivot = choice(lst)\n smaller = [n for n in lst if n < pivot]\n n_equal = sum(n == pivot for n in lst)\n bigger = [n for n in lst if n > pivot]\n if even:\n if len(smaller) > nth:\n return quickselect(smaller, nth, True)\n elif len(smaller) == nth:\n return (pivot + quickselect(smaller, nth - 1, False)) / 2\n elif len(smaller) + n_equal > nth:\n return pivot\n elif len(smaller) + n_equal == nth:\n return (pivot + quickselect(bigger, nth - len(smaller) - n_equal, False)) / 2\n else:\n return quickselect(bigger, nth - len(smaller) - n_equal, True)\n else:\n if len(smaller) > nth:\n return quickselect(smaller, nth, False)\n elif len(smaller) + n_equal > nth:\n return pivot\n else:\n return quickselect(bigger, nth - len(smaller) - n_equal, False)", "from numpy import median as median_\n\ndef median(arr):\n return median_(arr)", "import numpy\ndef median(A):\n return None if len(A)<1 else numpy.median(A)", "import numpy as np\ndef median(arr):\n return np.median(arr)"] | {"fn_name": "median", "inputs": [[[1, 2, 3, 4]], [[3, 4, 1, 2, 5]], [[10, 29, 23, 94, 76, 96, 5, 85, 4, 33, 47, 41, 87]], [[1]], [[1, -1]]], "outputs": [[2.5], [3], [41], [1], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,590 |
def median(arr):
|
bf5929d2cc529d7f169a94ee186a4da2 | UNKNOWN | In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
**Example:**
``` c
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` cfml
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` csharp
Kata.MakeNegative(1); // return -1
Kata.MakeNegative(-5); // return -5
Kata.MakeNegative(0); // return 0
```
``` java
Kata.makeNegative(1); // return -1
Kata.makeNegative(-5); // return -5
Kata.makeNegative(0); // return 0
```
``` python
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
```
``` javascript
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
makeNegative(0.12); // return -0.12
```
``` typescript
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` cpp
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` haskell
makeNegative 1 -- return -1
makeNegative (-5) -- return -5
makeNegative 0 -- return 0
makeNegative 0.12 -- return -0.12
```
``` ruby
makeNegative(1); # return -1
makeNegative(-5); # return -5
makeNegative(0); # return 0
```
``` coffeescript
makeNegative 1 # return -1
makeNegative -5 # return -5
makeNegative 0 # return 0
```
``` elixir
make_negative 1 # return -1
make_negative -5 # return -5
make_negative 0 # return 0
```
``` go
MakeNegative(1) # return -1
MakeNegative(-5) # return -5
MakeNegative(0) # return 0
```
``` julia
Kata.makeNegative(1) # return -1
Kata.makeNegative(-5) # return -5
Kata.makeNegative(0) # return 0
```
``` kotlin
Kata().makeNegative(1) // return -1
Kata().makeNegative(-5) // return -5
Kata().makeNegative(0) // return 0
```
``` asm
make_negative(1); // return -1
make_negative(-5); // return -5
make_negative(0); // return 0
```
``` groovy
Kata.makeNegative(1) // return -1
Kata.makeNegative(-5) // return -5
Kata.makeNegative(0) // return 0
```
``` php
makeNegative(1) // return -1
makeNegative(-5) // return -5
makeNegative(0) // return 0
makeNegative(0.12) // return -0.12
```
```racket
(make-negative 1) ; -1
(make-negative -5) ; -5
(make-negative 0) ; 0
(make-negative 0.12) ; -0.12
```
**Notes:**
- The number can be negative already, in which case no change is required.
- Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense. | ["def make_negative( number ):\n return -abs(number)", "def make_negative( number ):\n return -number if number>0 else number", "def make_negative( number ):\n return (-1) * abs(number)", "def make_negative(number):\n if number >= 0:\n return (0 - number)\n else:\n return number", "def make_negative( number ):\n # return negative of number. BUT: negative in = negative out. zero remains zero\n return -abs(number)", "def make_negative(n):\n return n if n <= 0 else -n", "def make_negative( number ):\n if number < 0:\n return number\n else:\n return number * -1\n\n\nmake_negative(-1)\nmake_negative(1)", "def make_negative( number ):\n return number - number * 2 if number > 0 else number", "def make_negative( number ):\n return 0 - abs(number)", "def make_negative( number ):\n if \"-\" in str(number):\n return(number)\n else:\n return int(\"-\" + str(number))\n", "def make_negative(number):\n return number if number <= 0 else number * -1\n", "def make_negative( number ): \n # ...\n while number>0:\n number=0-number\n return number", "def make_negative(num):\n return -num if num > 0 else num ", "def make_negative( number ):\n if number <= 0 :\n return number\n\n if number > 0:\n return number - (number *2)", "def make_negative( number ):\n if number == 0:\n number = 0\n else:\n number = 0-abs(number)\n return number ", "def make_negative( number ):\n if number <= 0:\n return number \n else:\n return ((number / number)-1)- number ", "def make_negative( number ):\n if number >= 0:\n return number * -1\n else:\n return number", "def make_negative( number ):\n if number > 0:\n number = 0 - number\n return number", "def make_negative( number ):\n if number < 0:\n return number\n else:\n return number * -1", "def make_negative( number ):\n if number <= 0:\n return number\n else:\n return number * (-1)", "def make_negative( number ):\n return number if number < 0 else number * -1", "def make_negative( number ):\n return number*(-1) if number > 0 else number", "def make_negative( number ):\n if str(number).startswith(\"-\"):\n return number\n elif str(number).startswith(\"0\"):\n return number\n else:\n return int(\"-\" + str(number))", "make_negative = lambda x: x * -1 if x >= 0 else x", "def make_negative( number ):\n san = str(abs(number))\n san_neg = '-' + san \n return int(san_neg)\n", "make_negative=lambda n: -abs(n)", "def make_negative( number ):\n number = int(number) #Converts the given number into int type\n \n sq = (number)**(2) #Squares the number. This will remove the negative sign.\n sqr = int((sq)**(0.5)) #Square roots the square of the number(sq). This will return the original/given number without any negative (-) sign.\n \n neg = (-+sqr) #Adds a negative sign to sqr\n \n return neg", "make_negative=lambda n:-n if n>0 else(n if n<0 else 0)\n", "def make_negative(n):\n return int('-' + str(n)) if n > 0 else n", "def make_negative(i):\n \"\"\"Return a negative number\"\"\"\n\n # Multiply by -1 if the number is strictly positive, else return it\n if i > 0:\n return i * -1\n else:\n return i", "def make_negative( number ):\n # ...\n if number <= 0:\n return number\n else:\n number = (number * (-number)) / number\n return number", "def make_negative(number):\n return -abs(number) if number > 0 else number", "def make_negative( number ):\n if number <= 0 :\n return number\n else:\n return 0-number", "def make_negative( number ):\n if number + number < 0:\n return number\n else:\n return -number", "def make_negative( number ):\n if number >0:\n return(0-number)\n if number <=0:\n return(number)", "def make_negative( number ):\n \n if number < 0:\n return number\n \n if number > 0:\n \n return number * -1\n \n elif number == 0:\n \n return 0\n", "def make_negative( number ):\n if number <0 :\n return 1 * number\n else:\n return -1 * number", "def make_negative( number ):\n if number >= 0:\n return 0 - abs(number)\n else:\n return number\n", "def make_negative( number ):\n # check if number is positive\n if number == abs(number):\n return number * -1\n else:\n return number", "make_negative = lambda a: -a if a > 0 else a", "def make_negative(number):\n if number == 0:\n return number\n if \"-\" in str(number):\n return number\n return -number", "def make_negative( number ):\n return -abs(number)\n\nprint(make_negative(1))", "def make_negative( number ):\n if number > 0:\n number = '-' + str(number) ;\n return int(number)\n elif number == 0:\n return 0\n else:\n return number", "def make_negative(number):\n if number >= 1:\n result = number - (2 * number)\n return(result)\n else:\n return(number)\n", "def make_negative(number):\n if number<0:\n num=number\n else:\n num=-number\n return num\n", "def make_negative( number ): return number if number < 0 or number == 0 else number * -1", "def make_negative( number ):\n # check if number is negative\n if number < 0:\n return number\n # if number is positive change to negative by multiplying by -1\n if number > 0:\n return (-1 * number)\n return number", "def make_negative( number ):\n if number > 0:\n number *= -1\n return(number)\n elif number < 0:\n return(number)\n else:\n return(number)", "def make_negative( number ):\n a = str(number)\n for i in a:\n if i in '-0':\n return number\n number = -1 * number\n return number\n \n \n", "def make_negative( number ):\n if number < 0:\n return number\n elif number == 0:\n return 0\n else:\n neg = number - 2 * number\n return neg", "def make_negative(number):\n if number == 0:\n return 0\n elif number < 0:\n return number\n else:\n number = number * -1\n return number\n \nmake_negative(15)", "def make_negative(number):\n if number >=0:\n number = -number\n else:\n number\n return number", "def make_negative( number ):\n if abs(number) == number:\n return number * -1\n else: \n return number\n # ...\n", "def make_negative( number ):\n if number >= 0:\n return (0 - number)\n else:\n return (0 + number)", "def make_negative(number):\n for num in [int(number)]: # konwersja na int\n if num <= 0:\n return(num)\n if num > 0:\n return abs(number) * -1", "def make_negative( number ):\n n=-1*number if number > 0 else number\n return n", "def make_negative( number ):\n # Check for negative:\n if number < 0:\n return number\n # Check for positivce\n elif number > 0:\n return number * -1\n # Check for 0\n else:\n return 0", "def make_negative( number ):\n if number > 0:\n resultado = number - (number*2)\n return resultado\n else:\n return number", "def make_negative(number):\n \"\"\"Converts given number to negative(-) number if greater than zero.\"\"\"\n if number <= 0:\n return number\n return number * -1", "def make_negative(number):\n if number <= 0:\n return number\n elif number > 0:\n a = number * 2\n b = number - a\n return b", "def make_negative( number ):\n result = 0\n if number > 0:\n result = number * -1\n elif number <= 0:\n result = number\n return result", "def make_negative(number):\n neg_no = \"-{}\".format(number)\n return number if number < 0 else int(neg_no)", "def make_negative( number ):\n # ...\n if number > -1:\n return number * -1\n elif number == 0:\n return number\n else:\n return number", "def make_negative( number ):\n # ...\n result=0\n if number>0:\n return(number*-1)\n elif number==0:\n return(0)\n else:\n return(number)\n", "def make_negative( n ):\n return n-n*2 if n>=0 else n", "def make_negative(number):\n if number == 0:\n return 0\n elif number < 1:\n return number\n else:\n return -number", "def make_negative( number ):\n return number * -1 if number > 0 else number or 0", "def make_negative (number):\n \"\"\" \u041f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u044b\u0432\u0430\u0435\u0442 \u0447\u0438\u0441\u043b\u043e \u0432 \u043e\u0442\u0440\u0438\u0446\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435\"\"\"\n if number <= 0:\n return number\n else:\n return number * (-1)", "def make_negative( number ):\n a = list(str(number))\n return -1*number if a[0] != \"-\" else number", "import math\ndef make_negative(number):\n if (number<0):\n return (number)\n elif (number>0):\n return(-number)\n else:\n return(0)", "def make_negative( number ):\n if number == 0:\n return number\n if number > 0:\n return number*-1\n else:\n return number", "def make_negative(number):\n negative = 0 #define main var\n if number>0:\n negative=-number\n else:\n negative=number\n \n return negative", "def make_negative( number ):\n # ...\n if(number > 0):\n return int(\"-{}\".format(number))\n elif number ==0:\n return 0\n else:\n return number", "def make_negative( number ):\n if number == 0:\n return 0\n elif number > 0:\n number *= -1\n return number\n elif number < 0:\n return number", "def make_negative( number ):\n if number == 0:\n return 0\n if number < 0:\n return number\n else:\n return number - 2*number", "def make_negative( number ):\n if(number!=0):\n if(number<0):\n return number\n return -number\n return 0", "def make_negative( number ):\n if number <= -1:\n return number\n elif number == 0:\n return 0\n else:\n return (number - (number * 2))\n # ...\n", "def make_negative( number ):\n if number == 0:\n return number\n elif number < 0:\n return number\n else:\n number = -number\n return number\nprint((make_negative(1)))\n \n", "def make_negative(number = 0):\n if number <= 0:\n return number\n else:\n return -number", "make_negative = lambda number: 0 if number==0 else number if number < 0 else (number-(number*2))", "def make_negative( number ):\n return (1 - 2 * (number >= 0)) * number", "def make_negative( number ):\n return int((number**2)**(1/2)*(-1))", "def make_negative( number ):\n if(number == 0 or abs(number)/number == -1):\n return(number)\n else:\n return(number * -1)", "def make_negative( number ):\n if number > 0 :\n pos = number * -1\n return pos\n elif number < 0:\n neg = number * 1\n return neg\n else:\n return number", "def make_negative( number ):\n if number < 0:\n return number\n elif number > 0:\n return (number - (2*number))\n else:\n return 0\n return\n", "def make_negative( number ):\n if number == 0 or number < 0:\n return number\n return -1 * number", "def make_negative( number ):\n print(-abs(number))\n return -abs(number)", "def make_negative( number ):\n output = \"\"\n \n if number < 0:\n return number\n else:\n output = \"-\" + str(number)\n \n return int(output)\n # ...\n", "def make_negative( number ):\n if number==0:\n result=0\n elif number>0:\n result=number*(-1)\n else:\n result=number\n return result # ...", "def make_negative(number):\n return -number if number >0 else --number", "def make_negative(number):\n if number>=1:\n number=number-number-number\n return number\n else:\n return number", "def make_negative( number ):\n nim = abs(number)\n return -nim", "def make_negative(number):\n if number >= 0:\n s =-number\n else:\n s = number\n return s\nprint(make_negative(1))", "def make_negative( number ):\n if number == 0 or number < 0 :\n return (number)\n \n return -(number)", "def make_negative( number ):\n if number <0:\n return number\n if number>0:\n answer= number * -1\n return answer\n \n else:\n return number\n # ...\n", "def make_negative( number ):\n if number>=1:\n return 0-number\n else:\n return number\nmake_negative(42) \n", "def make_negative( number ):\n if number <= 0:\n return number\n elif number > 0:\n number -= number * 2\n return number\n", "def make_negative( number ):\n if number < 0:\n return number\n else:\n number -= 2 * number\n return number", "def make_negative( number ):\n if int(number)<0:\n return number\n return int(number*-1)"] | {"fn_name": "make_negative", "inputs": [[42], [-9], [0], [1], [-1]], "outputs": [[-42], [-9], [0], [-1], [-1]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 13,554 |
def make_negative( number ):
|
ac686f945ecea846b540841142c097f0 | UNKNOWN | # Task
You are given a string `s`. Let's call its substring a group, if all letters in it are adjacent and the same(such as `"aa","bbb","cccc"`..). Let's call the substiring with 2 or more adjacent group a big group(such as `"aabb","bbccc"`...).
Your task is to count the number of `big groups` in the given string.
# Example
For `s = "ccccoodeffffiiighhhhhhhhhhttttttts"`, the result should be `3`.
```
The groups are "cccc", "oo", "ffff", "iii", "hhhhhhhhhh", "ttttttt"
The big groups are "ccccoo", "ffffiii", "hhhhhhhhhhttttttt",
3 substrings altogether.```
For `s = "gztxxxxxggggggggggggsssssssbbbbbeeeeeeehhhmmmmmmmitttttttlllllhkppppp"`, the result should be `2`.
```
The big groups are :
"xxxxxggggggggggggsssssssbbbbbeeeeeeehhhmmmmmmm"
and
"tttttttlllll" ```
For `s = "soooooldieeeeeer"`, the result should be `0`.
There is no `big group` exist.
# Input/Output
- `[input]` string `s`
A string of lowercase Latin letters.
- `[output]` an integer
The number of big groups. | ["from re import findall; repeat_adjacent=lambda s: len(findall(r\"((.)\\2+(?!\\2)){2,}\",s))", "import re\nrepeat_adjacent=lambda s:sum(len(set(i[0]))>1 for i in re.findall(r'((([a-z])\\3+){2,})', s))", "from functools import partial\nfrom itertools import groupby\nfrom operator import ne\n\ndef repeat_adjacent(s):\n xs = [sum(1 for _ in grp) for key, grp in groupby(s)]\n return sum(key and sum(1 for _ in grp) > 1 for key, grp in groupby(xs, key=partial(ne, 1)))\n", "from itertools import groupby\ndef repeat_adjacent(string):\n return sum(1 for k, g in (groupby(min(2, len(list(grp))) for _, grp in groupby(string))) if k == 2 and len(list(g)) > 1)", "from itertools import groupby\n\ndef repeat_adjacent(string):\n return(sum(1 for k,g in groupby((sum(1 for _ in g) for _,g in groupby(string)),key=lambda l:l>1) if k==True and next(g) and next(g,None)))", "def repeat_adjacent(string):\n a = list(string)\n b = []\n if len(a) >= 2:\n if a[1] ==a[0]:\n b.append(1)\n for i in range(2, len(a)):\n if a[i-1] == a[i] and a[i-1] != a[i-2]:\n b.append(1)\n elif a[i-1] != a[i]:\n b.append(0)\n c = []\n if b[0] == 1:\n c.append(1)\n for i in range(1, len(b)):\n if b[i] == 1:\n c.append(1)\n else:\n if b[i-1] == 0:\n c.append(0)\n k = 0\n for i in range(1, len(c)-1):\n if c[i] == 1 == c[i-1] and c[i+1] == 0:\n k += 1\n if c[len(c)-1] == 1 == c[len(c)-2]:\n k += 1\n else:\n k = 0\n return k", "from re import findall\n\ndef repeat_adjacent(s):\n return len(findall(r\"((.)\\2+(?!\\2)){2,}\",s))", "def repeat_adjacent(string):\n a,b,c,d=0,[],'',0\n for i in range(a,len(string)-1):\n if string[i]==string[i+1]:\n continue\n else:\n b.append(string[a:i+1])\n a=i+1\n b.append(string[-(len(string)-a):])\n \n for j in b:\n if len(j)>1:\n c+=j\n else:\n c+='*'\n \n for k in c.split('*'):\n if len(set(k))>1:\n d+=1\n return d", "import re\nfrom itertools import groupby\n\ndef repeat_adjacent(s):\n return sum(x and next(y) and bool(next(y, 0)) for x, y in groupby((x[0] for x in re.findall(r\"((.)\\2*)\", s)), key=lambda x: len(x) > 1))", "def repeat_adjacent(string):\n check = ''\n big_group = []\n for i in range(1,len(string)-1):\n if (string[i-1] == string[i] or string[i] == string[i+1]):\n check += string[i]\n else:\n if len(set(check)) > 1:\n big_group.append(check) \n check =''\n if len(set(check)) > 1:\n big_group.append(check)\n return len(big_group)\n"] | {"fn_name": "repeat_adjacent", "inputs": [["ccccoodeffffiiighhhhhhhhhhttttttts"], ["soooooldieeeeeer"], ["ccccoooooooooooooooooooooooddee"], ["wwwwaaaarrioooorrrrr"], ["gztxxxxxggggggggggggsssssssbbbbbeeeeeeehhhmmmmmmmitttttttlllllhkppppp"]], "outputs": [[3], [0], [1], [2], [2]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,860 |
def repeat_adjacent(string):
|
dbbf5dae099728ce3075cd3160f7cf9f | UNKNOWN | Make a function **"add"** that will be able to sum elements of **list** continuously and return a new list of sums.
For example:
```
add [1,2,3,4,5] == [1, 3, 6, 10, 15], because it's calculated like
this : [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4, 1 + 2 + 3 + 4 + 5]
```
If you want to learn more see https://en.wikipedia.org/wiki/Prefix_sum | ["from itertools import accumulate\ndef add(l):\n return list(accumulate(l)) if isinstance(l, list) and all(isinstance(x, int) for x in l) \\\n else 'Invalid input'", "from itertools import accumulate\n\ndef add(lst):\n return list(accumulate(lst))", "from itertools import accumulate\n\ndef add(a):\n return isinstance(a, list) and all(isinstance(x, int) for x in a) and [*accumulate(a)] or \"Invalid input\"", "def add(l):\n return [sum(l[:i+1]) for i in range(0,len(l))] if all(isinstance(x, int) for x in l) and isinstance(l, list) else 'Invalid input'", "def add(l):\n return [sum(l[:i+1]) for i in range(len(l))]", "add = lambda L: [sum(L[:i]) for i in range(1, len(L)+1)]", "def add(lst):\n if not isinstance(lst, list):\n return \"Invalid input\"\n total, result = 0, []\n for n in lst:\n if not isinstance(n, int):\n return \"Invalid input\"\n total += n\n result.append(total)\n return result", "from itertools import accumulate\ndef add(l):\n return list(accumulate(l))", "add=lambda l:\"Invalid input\"if any(type(e)!=int for e in l)or type(l)!=list else[sum(l[:i+1])for i in range(len(l))]", "def add(l):\n try:\n t = [l[0]]\n for i,j in enumerate(l[1:]):\n t.append(t[i]+ j)\n if sum(l)%1!=0 or sum(t)%1!=0 or type(l)!=list:\n return 'Invalid input'\n return t \n except:\n return 'Invalid input'"] | {"fn_name": "add", "inputs": [[[5, 10, 15, 20, 25, 30, 35, 40]], [[6, 12, 18, 24, 30, 36, 42]], [[7, 14, 21, 28, 35, 42, 49, 56]], [[8, 16, 24, 32, 40, 48, 56, 64]], [[9, 18, 27, 36, 45, 54]]], "outputs": [[[5, 15, 30, 50, 75, 105, 140, 180]], [[6, 18, 36, 60, 90, 126, 168]], [[7, 21, 42, 70, 105, 147, 196, 252]], [[8, 24, 48, 80, 120, 168, 224, 288]], [[9, 27, 54, 90, 135, 189]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,451 |
def add(l):
|
8755cd842ac5ae21100d9f3500d16d61 | UNKNOWN | A nested list (or *array* in JavaScript) is a list that apears as a value inside another list,
```python
[item, item, [item, item], item]
```
in the above list, [item, item] is a nested list.
Your goal is to write a function that determines the depth of the deepest nested list within a given list.
return 1 if there are no nested lists.
The list passed to your function can contain any data types.
A few examples:
```python
list_depth([True])
return 1
list_depth([])
return 1
list_depth([2, "yes", [True, False]])
return 2
list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1])
return 6
list_depth([2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]])
return 2
``` | ["def list_depth(l):\n depths = [1]\n for x in l:\n if isinstance(x, list):\n depths.append(list_depth(x) + 1)\n return max(depths)", "def list_depth(lst):\n result = [list_depth(a) for a in lst if isinstance(a, list)]\n return 1 + max(result) if result else 1\n", "def list_depth(l):\n if l == []:\n return 1\n if isinstance(l, list):\n return 1 + max(list_depth(item) for item in l)\n else:\n return 0", "def list_depth(l):\n return max((1+list_depth(x) for x in l if isinstance(x, (list, tuple))), default=1)", "def list_depth(L):\n\n dep = []\n \n if type(L) is not list:\n return 0\n elif len(L) == 0:\n return 1\n else:\n for x in L:\n dep.append(list_depth(x))\n print(dep)\n return 1 + max(dep)\n", "def list_depth(xs, depth=0):\n if isinstance(xs, list):\n return max((list_depth(x, depth + 1) for x in xs), default=depth + 1)\n return depth", "def list_depth(l):\n return max(1 + list_depth(x) if type(x) is list else 1 for x in l) if l else 1", "def list_depth(l):\n return (1 + max((list_depth(item) for item in l), default=0)) if type(l) == list else 0\n", "def list_depth(l):\n inds = [i for i, v in enumerate(l) if isinstance(v, list)]\n return 1 if len(inds) == 0 else 1 + max(list_depth(l[i]) for i in inds)", "def list_depth(l):\n return 0 if not isinstance(l, list) else 1 + max(list_depth(x) for x in l) if l else 1\n", "list_depth=d=lambda l:type(l)==type([])and-~max(map(d,l+[0]))", "def list_depth(l, f=1):\n return max(f if not isinstance(x, list) else list_depth(x, f + 1) for x in l) if l else f", "def list_depth(l, depth=1):\n max_depth = depth\n for e in l:\n if type(e) is list:\n max_depth = max(max_depth, list_depth(e, depth+1))\n return max_depth", "def list_depth(l):\n temp=list(filter(lambda x:x in ('[',']'),str(l)))\n while temp[-1]==']':\n temp.pop()\n return temp.count('[')-temp.count(']')", "def list_depth(l):\n a = str(l)\n z = 0\n for i in a[::-1]:\n if i == \"]\":\n z += 1\n elif i == \"[\":\n break\n\n return z", "def list_depth(l):\n try:\n return isinstance(l, list) and max(map(list_depth, l)) + 1\n except:\n return 1", "def list_depth(L):\n try : return 1 + max(list_depth(e) for e in L if isinstance(e, list))\n except : return 1", "def list_depth(l):\n depths = [1]\n for elm in l:\n if isinstance(elm, list):\n depths.append(list_depth(elm) + 1)\n return max(depths)", "def list_depth(l):\n a=[0]\n for i in str(l):\n if i=='[': a.append(a[-1]+1)\n if i==']': a.append(a[-1]-1)\n return max(a)"] | {"fn_name": "list_depth", "inputs": [[[1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]], [[true]], [[]], [[2, "yes", [true, false]]], [[2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]]], [[[[[]]], [[[]]]]], [[true, false, true, [false], true]], [[[], [], [[], []]]], [[77]], [[2, "yes", [true, [false]]]], [[77, [77]]], [[[77], 77, [[77]]]]], "outputs": [[6], [1], [1], [2], [2], [4], [2], [3], [1], [3], [2], [3]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,768 |
def list_depth(l):
|
f4b676e938a000bc189e77a478bce009 | UNKNOWN | In this exercise, you will have to create a function named tiyFizzBuzz. This function will take on a string parameter and will return that string with some characters replaced, depending on the value:
- If a letter is a upper case consonants, replace that character with "Iron".
- If a letter is a lower case consonants or a non-alpha character, do nothing to that character
- If a letter is a upper case vowel, replace that character with "Iron Yard".
- If a letter is a lower case vowel, replace that character with "Yard".
Ready? | ["def tiy_fizz_buzz(s):\n return \"\".join((\"Iron \"*c.isupper() + \"Yard\"*(c.lower() in \"aeiou\")).strip() or c for c in s)", "def tiy_fizz_buzz(strin):\n strin = list(strin)\n for i, char in enumerate(strin):\n if char in \"AEIOU\" : strin[i] = \"Iron Yard\"\n elif char in \"aeiou\" : strin[i] = \"Yard\"\n elif char in \"QWRTYPSDFGHJKLZXCVBNM\" : strin[i] = \"Iron\"\n return ''.join(strin)", "def tiy_fizz_buzz(string):\n return ''.join(\n 'Iron Yard' if c in 'AEIOU' else\n 'Yard' if c in 'aeiou' else\n 'Iron' if c.isupper() else c\n for c in string\n )", "def tiy_fizz_buzz(stg):\n return \"\".join(\"Iron Yard\" if c in \"AEIOU\" else \"Yard\" if c in \"aeiou\" else \"Iron\" if c.isupper() else c for c in stg)", "def tiy_fizz_buzz(s):\n uv = [chr(x) for x in [65,69,73,79,85]]\n lv = [chr(x) for x in [97,101,105,111,117]]\n u = [chr(x) for x in range(66,91)]\n return ''.join([\"Iron Yard\" if x in uv else \"Iron\" if x in u else \"Yard\" if x in lv else x for x in list(s)])", "def translate(x): \n if x.isupper(): \n if x not in 'AEIOU': \n return 'Iron'\n else: \n return \"Iron Yard\"\n else: \n if x not in 'aeiou' or not x.isalpha(): \n return x\n else: \n return 'Yard'\n\ndef tiy_fizz_buzz(string):\n return ''.join(translate(c) for c in string)", "tiy_fizz_buzz=lambda x:''.join(('Iron'*e.isupper()+' '+'Yard'*(e.lower() in 'aiueo')).strip() or e for e in x)", "def tiy_fizz_buzz(string):\n new_string = ''\n for i in string:\n if i.isupper():\n new_string += 'Iron'\n if i in ('AEIOU'):\n new_string += ' Yard'\n elif i in ('aeiou'):\n new_string += 'Yard'\n else:\n new_string += i\n return new_string\n \n", "def tiy_fizz_buzz(string):\n r = lambda i: {i in 'euioa': \"Yard\",\n i in 'EUIOA': \"Iron Yard\",\n i in 'QWRTYPSDFGHJKLZXCVBNM': 'Iron',\n not i in 'euioaEUIOAQWRTYPSDFGHJKLZXCVBNM': i}[True]\n return ''.join([r(i) for i in string])", "import re\n\ndef ironyarder(m):\n lst = []\n if m[0].isupper(): lst.append('Iron')\n if m[0].lower() in 'aeiou': lst.append('Yard')\n return ' '.join(lst)\n\ndef tiy_fizz_buzz(s):\n return re.sub(r'[A-Zaeiou]', ironyarder, s)"] | {"fn_name": "tiy_fizz_buzz", "inputs": [[" "], ["H"], ["b"], ["A"], ["a"], ["Hello WORLD!"], ["H6H4Na ./?U"]], "outputs": [[" "], ["Iron"], ["b"], ["Iron Yard"], ["Yard"], ["IronYardllYard IronIron YardIronIronIron!"], ["Iron6Iron4IronYard ./?Iron Yard"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,438 |
def tiy_fizz_buzz(string):
|
f45e49ec9665eff4cba44d589f7c6a29 | UNKNOWN | Given an array (or list) of scores, return the array of _ranks_ for each value in the array. The largest value has rank 1, the second largest value has rank 2, and so on. Ties should be handled by assigning the same rank to all tied values. For example:
ranks([9,3,6,10]) = [2,4,3,1]
and
ranks([3,3,3,3,3,5,1]) = [2,2,2,2,2,1,7]
because there is one 1st place value, a five-way tie for 2nd place, and one in 7th place. | ["def ranks(a):\n sortA = sorted(a, reverse=True)\n return [sortA.index(s) + 1 for s in a]\n", "def ranks(results):\n ranks = {}\n for k, v in enumerate(sorted(results, reverse=True), start=1):\n if not v in ranks:\n ranks[v] = k\n return [ranks[i] for i in results]", "def ranks(a):\n return [sorted(a, reverse = True).index(m) + 1 for m in a]", "def ranks(a):\n dict = {v: k for k, v in sorted(enumerate(sorted(a, reverse=True), start=1), reverse=True)}\n return [dict[i] for i in a]\n", "import copy\n\ndef ranks(lst):\n sortedVals = copy.deepcopy(lst) #need deep copy to not mutate original list\n sortedVals.sort(reverse=True) #descending order\n \n rankVec = []\n for v in lst: #for every value in the list, calculate its rank\n indLoc = sortedVals.index(v) #always finds first occurance so repetition does not matter\n rankOfVal = indLoc+1 #min rank is 1 not 0\n rankVec.append( rankOfVal )\n\n return rankVec\n#---end function\n", "from collections import Counter\n\ndef ranks(a):\n id, res = 1, {}\n for k,v in sorted(Counter(a).items(), reverse=True):\n id, res[k] = id+v, id\n return list(map(res.get, a))", "def ranks(a):\n b = sorted(a, reverse=True)\n d = {i:b.index(i)+1 for i in a}\n return [d[i] for i in a]", "def ranks(a):\n ranks = {}\n for rank, x in enumerate(sorted(a, reverse=True), 1):\n if x not in ranks:\n ranks[x] = rank\n return [ranks[x] for x in a]", "def ranks(a):\n s = sorted(a)[::-1]\n return [(s.index(n) + 1) for n in a]\n", "def ranks(a):\n rankarr = [None] + sorted(a)[::-1]\n return [rankarr.index(x) for x in a] \n"] | {"fn_name": "ranks", "inputs": [[[]], [[2]], [[2, 2]], [[1, 2, 3]], [[-5, -10, 3, 1]], [[-1, 3, 3, 3, 5, 5]], [[1, 10, 4]], [[5, 2, 3, 5, 5, 4, 9, 8, 0]]], "outputs": [[[]], [[1]], [[1, 1]], [[3, 2, 1]], [[3, 4, 1, 2]], [[6, 3, 3, 3, 1, 1]], [[3, 1, 2]], [[3, 8, 7, 3, 3, 6, 1, 2, 9]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,751 |
def ranks(a):
|
f41660a5c141731ee90623c9914a5450 | UNKNOWN | A family of kookaburras are in my backyard.
I can't see them all, but I can hear them!
# How many kookaburras are there?
## Hint
The trick to counting kookaburras is to listen carefully
* The males go ```HaHaHa```...
* The females go ```hahaha```...
* And they always alternate male/female
^ Kata Note : No validation is necessary; only valid input will be passed :-) | ["import re\n\ndef kooka_counter(laughing):\n return len(re.findall(r'(ha)+|(Ha)+',laughing))", "def kooka_counter(laughing):\n return 0 if laughing == '' else laughing.count('Hah') + laughing.count('haH') + 1", "def kooka_counter(laughing):\n return laughing.count(\"Haha\") + laughing.count(\"haHa\") + bool(laughing)", "import re\n\ndef kooka_counter(laughing):\n return len(re.findall(r'(Ha|ha)\\1*', laughing))", "import re\n\ndef kooka_counter(laughing):\n return len(re.findall(r'(Ha)+|(ha)+', laughing))", "import re\ndef kooka_counter(stri):\n stri = re.sub(r\"H+\",\"H\",stri.replace(\"a\",\"\"))\n stri = re.sub(r\"h+\",\"h\",stri.replace(\"a\",\"\"))\n return len(stri)", "import re\n\npattern = re.compile(r\"(Ha)+|(ha)+\")\n\ndef kooka_counter(laughing):\n return len(pattern.findall(laughing))", "def kooka_counter(laughing):\n if len(laughing) == 0:\n return 0\n return laughing.count('haHa') + laughing.count('Haha') + 1", "def kooka_counter(laugh):\n count = 0\n while laugh:\n pat = laugh[:2]\n laugh = laugh.lstrip(pat)\n count += 1\n return count", "def kooka_counter(laughing):\n \n if len(laughing) == 0:\n return 0\n \n kooks = 1\n current = laughing[0]\n \n for i in range(2, len(laughing),2):\n if laughing[i] != current:\n current = current.swapcase()\n kooks += 1\n \n return kooks"] | {"fn_name": "kooka_counter", "inputs": [[""], ["hahahahaha"], ["hahahahahaHaHaHa"], ["HaHaHahahaHaHa"], ["hahahahahahahaHaHa"]], "outputs": [[0], [1], [2], [3], [2]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,406 |
def kooka_counter(laughing):
|
4fbb852407abe1f37884ea48249e3700 | UNKNOWN | Write a function that calculates the *least common multiple* of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return `1`.
~~~if:objc
NOTE: The first (and only named) argument of the function `n` specifies the number of arguments in the variable-argument list. Do **not** take `n` into account when computing the LCM of the numbers.
~~~ | ["from functools import reduce\ndef lcm(*args):\n return reduce(lcms, args) if args else 1\n\ndef gcd(a,b):\n \"\"\"Euclidean Algorithm\"\"\"\n return b if a == 0 else gcd(b % a, a)\n \ndef lcms(a, b):\n return (a*b) // gcd(a,b)", "from math import gcd\nfrom functools import reduce\ndef lcm(*args):\n return reduce(lambda x,y : abs(x*y)//gcd(x,y), args) if args else 1\n", "from fractions import gcd\ndef lcm(*args):\n m = 1 \n for i in args:\n if i == 0:\n return 0\n m = m*i/gcd(m,i)\n return m\n \n"] | {"fn_name": "lcm", "inputs": [[2, 5], [2, 3, 4], [9], [0], [0, 1], [1, 1, 1], [5, 6, 7, 9, 6, 9, 18, 4, 5, 15, 15, 10, 17, 7], [17, 20, 4, 15, 4, 18, 12, 14, 20, 19, 2, 14, 13, 7], [11, 13, 4, 5, 17, 4, 10, 13, 16, 13, 13], [20, 1, 6, 10, 3, 7, 8, 4], [3, 9, 9, 19, 18, 14, 18, 9], [3, 9, 9, 19, 18, 14, 18, 0]], "outputs": [[10], [12], [9], [0], [0], [1], [21420], [5290740], [194480], [840], [2394], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 563 |
def lcm(*args):
|
7ea5ed554466d2fb8d5a5787e646dc5d | UNKNOWN | To celebrate the start of the Rio Olympics (and the return of 'the Last Leg' on C4 tonight) this is an Olympic inspired kata.
Given a string of random letters, you need to examine each. Some letters naturally have 'rings' in them. 'O' is an obvious example, but 'b', 'p', 'e', 'A', etc are all just as applicable. 'B' even has two!! Please note for this kata you can count lower case 'g' as only one ring.
Your job is to count the 'rings' in each letter and divide the total number by 2. Round the answer down. Once you have your final score:
if score is 1 or less, return 'Not even a medal!';
if score is 2, return 'Bronze!';
if score is 3, return 'Silver!';
if score is more than 3, return 'Gold!';
Dots over i's and any other letters don't count as rings. | ["def olympic_ring(string):\n return (['Not even a medal!'] * 2 + ['Bronze!', 'Silver!', 'Gold!'])[min(4, sum(map(\"abdegopqABBDOPQR\".count, string)) // 2)]", "def olympic_ring(string):\n rings = string.translate(str.maketrans(\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n '1201000000000011110000000011011010000000111000000000'))\n score = sum(map(int, rings)) // 2\n return ['Not even a medal!', 'Bronze!', 'Silver!', 'Gold!']\\\n [(score > 1) + (score > 2) + (score > 3)]", "def olympic_ring(string):\n h = {'a':1, 'b':1, 'd':1, 'e': 1, 'g':1, 'o':1, 'p':1, 'q':1, 'A':1, 'B':2, 'D':1, 'O':1, 'P':1, 'R':1, 'Q':1}\n result = lambda i: {i <= 1: 'Not even a medal!', i == 2: 'Bronze!', i == 3: 'Silver!', i >= 4: 'Gold!'}[True]\n return result(sum([h[i] if i in h.keys() else 0 for i in string])//2)", "def olympic_ring(string):\n score = (sum(c in \"abdegopqABDOPQR\" for c in string) + string.count(\"B\")) // 2\n return next(medal for min_score, medal in (\n (4, \"Gold!\"),\n (3, \"Silver!\"),\n (2, \"Bronze!\"),\n (0, \"Not even a medal!\"),\n ) if score >= min_score)", "def olympic_ring(string):\n n = sum(string.count(c) for c in 'ADOPQRabdegopq') + string.count('B') * 2\n return ['Not even a medal!', 'Bronze!', 'Silver!', 'Gold!'][max(min(int(n / 2) - 1, 3), 0)]", "ring = \"abdegopqADOPQR\"\n\ndef olympic_ring(stg):\n score = sum(1 if c in ring else 2 if c == \"B\" else 0 for c in stg) // 2\n return \"Gold!\" if score > 3 else \"Silver!\" if score > 2 else \"Bronze!\" if score > 1 else \"Not even a medal!\"", "def olympic_ring(string):\n s = sum(2 if c == 'B' else 1 if c in 'abdegopqADOPQR' else 0 for c in string)//2\n return 'Not even a medal!' if s <= 1 else 'Bronze!' if s == 2 else 'Silver!' if s ==3 else \"Gold!\"", "rings = dict(dict.fromkeys('B', 2), **dict.fromkeys('ADOPRQaobdpqeg', 1))\n\ndef olympic_ring(s):\n score = sum(rings.get(c, 0) for c in s) // 2\n return (\n 'Not even a medal!' if score <= 1 else\n 'Bronze!' if score == 2 else\n 'Silver!' if score == 3 else\n 'Gold!'\n )", "def olympic_ring(string):\n rings = 'abdegopqADOPQRBB'\n count = sum(string.count(c) for c in rings) // 2\n if count <= 1:\n return 'Not even a medal!'\n if count == 2:\n return 'Bronze!'\n if count == 3:\n return 'Silver!'\n return 'Gold!'", "one=\"abdegopqADOPQR\"\nimport math\ndef olympic_ring(string):\n c=0\n for x in string:\n if x==\"B\":\n c=c+2\n if x in one:\n c=c+1\n c= math.floor(c/2)\n if c>3:\n return \"Gold!\"\n if c==3:\n return \"Silver!\"\n if c==2:\n return \"Bronze!\"\n return \"Not even a medal!\""] | {"fn_name": "olympic_ring", "inputs": [["wHjMudLwtoPGocnJ"], ["eCEHWEPwwnvzMicyaRjk"], ["JKniLfLW"], ["EWlZlDFsEIBufsalqof"], ["IMBAWejlGRTDWetPS"]], "outputs": [["Bronze!"], ["Bronze!"], ["Not even a medal!"], ["Silver!"], ["Gold!"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,808 |
def olympic_ring(string):
|
9a1046c3742a2504e41ea95f84814a20 | UNKNOWN | The pizza store wants to know how long each order will take. They know:
- Prepping a pizza takes 3 mins
- Cook a pizza takes 10 mins
- Every salad takes 3 mins to make
- Every appetizer takes 5 mins to make
- There are 2 pizza ovens
- 5 pizzas can fit in a oven
- Prepping for a pizza must be done before it can be put in the oven
- There are two pizza chefs and one chef for appitizers and salads combined
- The two pizza chefs can work on the same pizza
Write a function, order, which will tell the company how much time the order will take.
See example tests for details. | ["from math import ceil\n\ndef order(pizzas, salads, appetizers):\n tp = 3 * pizzas / 2 + 10 * math.ceil(pizzas / 10)\n ts = 3 * salads + 5 * appetizers\n return max(tp, ts)\n", "def order(pizzas, salads, appetizers):\n side_total = 0\n pizza_total = 0 \n side_total += salads * 3 \n side_total += appetizers * 5\n pizza_total += pizzas * 1.5\n if pizza_total <= 10:\n pizza_total += 10\n elif pizza_total >= 10:\n pizza_total += 10 * 2\n return max(side_total, pizza_total)", "def order(pizzas, salads, appetizers): \n pizza_time = 3 * (pizzas / 2) + 10 * ((pizzas // 11) + 1)\n other_time = 3 * salads + 5 * appetizers\n\n return max(other_time, pizza_time)", "import math\n\ndef order(pizzas, salads, appetizers):\n return max(pizzas * 1.5 + math.ceil(pizzas / 10)*10, salads * 3 + appetizers * 5)", "def order(p, s, a):\n return max(p*1.5+p//-10*-10,s*3+a*5)\n", "def order(pizzas, salads, appetizers):\n time = 0\n if pizzas > 0:\n time = (pizzas * 3) / 2\n oven_cycles = (pizzas // 10) + 1\n time = time + (oven_cycles * 10)\n time_2 = (salads * 3) + (appetizers * 5)\n if time > time_2:\n return time\n else:\n return time_2\n else:\n time_2 = (salads * 3) + (appetizers * 5)\n return time_2\n \n", "from math import ceil\ndef order(pizzas, salads, appetizers):\n p=(pizzas/2)*3+ceil(pizzas/10)*10\n sa=3*salads+5*appetizers\n return max(p,sa)", "import math\n\ndef order(pizzas, salads, appetizers):\n pizza_prep = 3 * pizzas / 2\n pizza_cook = math.ceil(pizzas / 10) * 10\n salad_prep = salads * 3\n app_prep = appetizers * 5\n return max([pizza_prep + pizza_cook, salad_prep + app_prep])", "def order(pizzas, salads, appetizers):\n pizza_time = (3 * pizzas / 2) + 10 * (pizzas // 10 + 1) \n salad_app_time = 3 * salads + 5 * appetizers\n return max(pizza_time, salad_app_time)", "def order(pizzas, salads, appetizers):\n if pizzas <= 10:\n pizzas= 10 + 1.5 * pizzas\n elif pizzas <=20:\n pizzas = 20 + 1.5 * pizzas\n if pizzas > salads*3 + appetizers*5: \n return pizzas\n else: \n return salads*3 + appetizers*5\n \n"] | {"fn_name": "order", "inputs": [[2, 0, 0], [3, 1, 2], [0, 3, 2], [13, 0, 0], [6, 2, 4], [6, 1, 3], [5, 3, 4]], "outputs": [[13], [14.5], [19], [39.5], [26], [19], [29]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,258 |
def order(pizzas, salads, appetizers):
|
5d67372232b047e04c6bc257469c2ff7 | UNKNOWN | # Solve For X
You will be given an equation as a string and you will need to [solve for X](https://www.mathplacementreview.com/algebra/basic-algebra.php#solve-for-a-variable) and return x's value. For example:
```python
solve_for_x('x - 5 = 20') # should return 25
solve_for_x('20 = 5 * x - 5') # should return 5
solve_for_x('5 * x = x + 8') # should return 2
solve_for_x('(5 - 3) * x = x + 2') # should return 2
```
NOTES:
* All numbers will be whole numbers
* Don't forget about the [order of operations](https://www.mathplacementreview.com/algebra/basic-algebra.php#order-of-operations).
* If the random tests don't pass the first time, just run them again. | ["from itertools import count\n\ndef solve_for_x(equation):\n return next( x for n in count(0) for x in [n, -n] if eval(equation.replace(\"x\", str(x)).replace(\"=\", \"==\")) )", "import re\ndef solve_for_x(equation):\n left,right = equation.split(\"=\")\n answer = False\n TrialAndErrorRipMs = -1000\n while answer == False:\n FinalLeft = re.sub(\"x\", str(TrialAndErrorRipMs), left)\n FinalRight = re.sub(\"x\", str(TrialAndErrorRipMs), right)\n if eval(FinalLeft) == eval(FinalRight):\n return TrialAndErrorRipMs\n TrialAndErrorRipMs += 1\n", "def solve_for_x(equation):\n left_side = equation.split('=')[0];\n right_side = equation.split('=')[1];\n\n for x in range(-1000, 1000):\n if eval(left_side) == eval(right_side):\n return x", "def solve_for_x(equation):\n for x in range(-100,1001):\n if eval(equation.replace('=','==')):\n return x #needs better test cases to prevent this solution\n \n \n", "from itertools import count\n\n# Brute force: the solution to all your problems\ndef solve_for_x(equation):\n equation = equation.replace('=', '==')\n for x in count():\n if eval(equation): return x\n x = -x\n if eval(equation): return x", "def solve_for_x(equation):\n left,right=equation.split('=')\n for x in range(-1000,1000):\n if eval(left)==eval(right):\n return x", "def solve_for_x(equation):\n p = equation.split()\n for i in range(0, len(p)):\n if p[i] == '=': p[i] = '=='\n t = p.index('x')\n for x in range(-1000, 1000):\n p[t] = str(x)\n if eval(''.join(p)): return x", "def solve_for_x(equation):\n p = equation.split()\n for i in range(0, len(p)):\n if p[i] == '=': p[i] = '=='\n t = p.index('x')\n for x in range(-100, 1000):\n p[t] = str(x)\n if eval(''.join(p)):\n return x", "def solve_for_x(s): \n for i in range(-1000, 1000):\n if eval(s.replace('x', str(i)).replace('=', '==')):\n return i", "class Exp:\n def __init__(self, s):\n self.a = 1 \n self.p = 0\n if s[-1] == 'x':\n self.p = 1\n s = s[:-1]\n if 0 < len(s):\n self.a *= int (s)\n \n def __add__(self, other):\n if self.p == other.p:\n self.a += other.a\n return self\n else:\n return Equ([self, other])\n \n def __sub__(self, other):\n if self.p == other.p:\n self.a -= other.a\n return self\n else:\n return Equ([self, Exp(\"-1\") * other])\n\n def __mul__(self, other):\n self.p += other.p\n self.a *= other.a\n return self\n \n def __div__(self, other):\n self.p -= other.p\n self.a /= other.a\n return self\n \n def __str__(self):\n s = \"\"\n if self.a != 0:\n s += str(self.a)\n if (self.p) == 1:\n s += 'x'\n if s == \"\":\n s += '0'\n return s\n \n\nclass Equ:\n def __init__(self, exp):\n self.exp = dict()\n for e in exp:\n if e.p not in self.exp:\n self.exp[e.p] = e\n else:\n self.exp[e.p] += e\n \n def __add__(self, other):\n if type(other) == Exp:\n other = Equ([other])\n for p in other.exp:\n if p in self.exp:\n self.exp[p] += other.exp[p]\n else:\n self.exp[p] = other.exp[p]\n return self\n\n def __sub__(self, other):\n if type(other) == Exp:\n other = Equ([other])\n for p in other.exp:\n if p in self.exp:\n self.exp[p] -= other.exp[p]\n else:\n self.exp[p] = Exp(\"-1\") * other.exp[p]\n return self\n \n def __mul__(self, other):\n if type(other) == Exp:\n other = Equ([other])\n res = None\n for p1 in other.exp:\n temp_res = []\n for p2 in self.exp:\n temp_res.append(self.exp[p2] * other.exp[p1])\n if res is None:\n res = Equ(temp_res)\n else:\n res += Equ(temp_res)\n return self\n\n def __div__(self, other):\n if type(other) == Exp:\n other = Equ([other])\n res = None\n for p1 in other.exp:\n temp_res = []\n for p2 in self.exp:\n temp_res.append(self.exp[p2] / other.exp[p1])\n if res is None:\n res = Equ(temp_res)\n else:\n res += Equ(temp_res)\n return self\n \n def __str__(self):\n s = \"\"\n for p in self.exp:\n s += ' (' + str(self.exp[p]) + ') +'\n return s[:-1]\n\n def get_power(self, p):\n return self.exp[p] if p in self.exp else Exp(\"0\") if p==0 else Exp(\"0x\")\n\n\ndef build1(s):\n s = s.replace(' ', '')\n stack = []\n s += '!'\n if s[0] == '-':\n s = '0' + s\n j = 0\n for i in range(len(s)):\n if s[i] in ['+','-','*','/','(',')','!']:\n if j < i:\n stack.append(s[j:i])\n stack.append(s[i])\n j = i+1\n stack.remove('!')\n for i, x in enumerate(stack):\n if x not in ['+','-','*','/','(',')','!']:\n stack[i] = Exp(x)\n return stack\n \ndef build2(s):\n while ')' in s: \n end = s.index(')')\n start = end\n while s[start] != '(':\n start -= 1\n s = s[:start] + [build2(s[start+1:end])] + s[end+1:]\n op = {'+': lambda x, y: x + y,\n '-': lambda x, y: x - y,\n '*': lambda x, y: x * y,\n '/': lambda x, y: x.__div__(y) }\n i = 2\n for order in [0, 1]:\n i = 2\n while i < len(s):\n if (order == 0 and s[i-1] in ['*', '/']) \\\n or (order == 1 and s[i-1] in ['+', '-']):\n s[i-2] = op[s[i-1]](s[i-2], s[i])\n s.pop(i)\n s.pop(i-1)\n else:\n i += 2\n return s[0]\n \ndef build(s):\n stack = build1(s)\n equ = build2(stack)\n if type(equ) == Exp:\n equ = Equ([equ])\n return equ\n \n\ndef solve_for_x(equation):\n l, r = equation.split(\" = \")\n l, r = build(l), build(r)\n l, r = l.get_power(1) - r.get_power(1), r.get_power(0) - l.get_power(0)\n return r.a / l.a"] | {"fn_name": "solve_for_x", "inputs": [["x - 5 = 20"], ["5 * x + 5 = 30"], ["20 = 5 * x - 5"], ["24 = 4 + 5 * x"], ["x = 5"], ["x * 100 = 700"], ["2 * x + 5 = 105"], ["2 * x = 198"], ["x - 100 + 2 - 50 = 52"], ["x / 3 = 33"], ["x + 80 = 20"], ["x + 20 = -60"], ["5 * x + 20 - x = 60"], ["x + x + 6 = 10"], ["5 * x = x + 8"], ["x = x / 2 + 25"], ["(5 - 3) * x = x + 2"], ["(x - 30) * 2 = x"]], "outputs": [[25], [5], [5], [4], [5], [7], [50], [99], [200], [99], [-60], [-80], [10], [2], [2], [50], [2], [60]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 6,580 |
def solve_for_x(equation):
|
ddd088b5d7e0b74a9f300d1a0f9f5f5b | UNKNOWN | Write function heron which calculates the area of a triangle with sides a, b, and c.
Heron's formula: sqrt (s \* (s - a) \* (s - b) \* (s - c)), where s = (a + b + c) / 2.
Output should have 2 digits precision. | ["import math\ndef heron(a,b,c):\n s=(a+b+c)/2\n return round(math.sqrt(s*(s-a)*(s-b)*(s - c)),2)", "def heron(a,b,c):\n return round((1/4)*(4*b*b*c*c-(b*b+c*c-a*a)**2)**(1/2),2)", "heron=lambda*args:(lambda a,b,c,s:round((s*(s-a)*(s-b)*(s-c))**.5,2))(*args,sum(args)/2)", "def heron(*sides):\n s=sum(sides)/2\n a,b,c = sides\n return round((s * (s - a) * (s - b) * (s - c))**0.5, 2)", "def heron(*l):\n s = sum(l) / 2\n return round((s * (s - l[0]) * (s - l[1]) * (s - l[2]))**.5,2)", "import math\ndef heron(*liste):\n sum = 0\n for i in liste:\n sum += i\n s = sum / 2\n return round(math.sqrt(s*(s - liste[0])*(s - liste[1])*(s - liste[2])), 2)\n", "import math\ndef heron(a,b,c):\n d=(a+b+c)/2\n return round(math.sqrt(d*(d-a)*(d-b)*(d-c)),2)", "import math\ndef heron(a, b, c):\n p = (a + b + c) / 2\n return round(math.sqrt(p * (p-a) * (p-b) * (p-c)), 2)", "def heron(a,b,c):\n s = sum([a,b,c]) / 2\n return round((s * (s - a) * (s - b) * (s - c)) ** 0.5, 2)", "import math\n\ndef heron(a,b,c):\n\n s = (a+b+c)/2\n \n v = math.sqrt(s*(s-a)*(s-b)*(s-c))\n \n return round(v,2)\n \n \n"] | {"fn_name": "heron", "inputs": [[3, 4, 5], [6, 8, 10]], "outputs": [[6], [24]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,175 |
def heron(a,b,c):
|
3e400d50d68eb8d4b2458705c724f1a6 | UNKNOWN | HELP! Jason can't find his textbook! It is two days before the test date, and Jason's textbooks are all out of order! Help him sort a list (ArrayList in java) full of textbooks by subject, so he can study before the test.
The sorting should **NOT** be case sensitive | ["def sorter(textbooks):\n return sorted(textbooks,key=str.lower)", "def sorter(textbooks):\n return sorted(textbooks, key=str.casefold)", "def sorter(textbooks):\n return sorted(textbooks, key = lambda arg: arg.lower())", "sorter = lambda x: sorted(x,key=lambda s:s.lower())", "sorter = lambda text: sorted(text, key=lambda s: s.lower())", "def sorter(lst):\n return sorted(lst, key=lambda e: e.lower())", "def sorter(textbooks):\n return sorted(textbooks, key=lambda text: text.lower())", "def sorter(textbooks):\n def f(e):\n return e.lower()\n sorted = textbooks.sort(key=f)\n return textbooks", "def sorter(textbooks):\n d = {t.lower(): t for t in textbooks}\n return [d[t] for t in sorted(d)]", "def sorter(textbooks):\n arr=sorted(textbooks,key=str.lower)\n return arr", "sorter = lambda textbooks: sorted(textbooks, key=str.lower)", "from typing import List\n\ndef sorter(textbooks: List[str]):\n \"\"\" Sort textbooks by subjects. \"\"\"\n return sorted(textbooks, key=str.lower)", "def sorter(textbooks):\n textbooks.sort(key = lambda x: x.lower())\n # .sort() sorts the list while considering every element as if it is in lowercase\n return textbooks", "def myf(a):\n return a.lower()\n \ndef sorter(textbooks):\n return sorted(textbooks, key=myf)", "def sorter(textbooks):\n ##use list.sort(), and instruct programme to ignore capitalisation\n textbooks.sort(key = str.lower)\n return(textbooks)", "def sorter(textbooks):\n my_sort = sorted(textbooks, key=str.lower)\n return my_sort", "def sorter(textbooks: list) -> list:\n return sorted(textbooks, key=str.casefold)", "def sorter(textbooks):\n textbooks.sort()\n return sorted(textbooks, key =lambda x: x.lower())#Cramming before a test can't be that bad?", "def sorter(textbooks):\n listtemp = [(x.lower(),x) for x in textbooks]\n listtemp.sort()\n return [x[1] for x in listtemp]", "def sorter(textbooks):\n r = {i.lower():i for i in textbooks}\n return [r[i] for i in sorted(r)]", "def sorter(textbooks):\n subjects = dict((sub.lower(), sub) for sub in textbooks)\n return [subjects[sub] for sub in sorted(subjects.keys())]", "sorter = lambda textbooks: list(sorted(textbooks, key = lambda s: s.lower()))", "def sorter(textbooks):\n '''Function that sort a list full of textbooks by subject'''\n return sorted(textbooks,key=str.lower)", "def sorter(textbooks):\n k = sorted(textbooks, key=str.casefold)\n return k", "sorter = lambda textbooks:sorted(textbooks, key=str.casefold)\n\n'''make a case insensitive sorted list'''", "def sorter(textbooks):\n return list(sorted(textbooks, key=lambda e: e.lower()))\n", "import functools;\n\ndef cmp(a, b):\n aa = a.lower()\n bb = b.lower()\n \n if aa > bb:\n return 1\n elif bb > aa:\n return -1\n else:\n return 0\n\ndef sorter(textbooks):\n return sorted(textbooks, key=functools.cmp_to_key(cmp))", "from typing import List\n\ndef sorter(textbooks: List[str]) -> List[str]:\n \"\"\"Returns the textbooks non-case-sensitive sorted.\"\"\"\n return sorted(textbooks, key=str.casefold)", "from typing import List\n\ndef sorter(textbooks: List[str]) -> List[str]:\n \"\"\"Returns the textbooks list non-case-sensitive sorted.\"\"\"\n return sorted(textbooks, key=str.lower)", "def sorter(tks):\n return sorted(tks, key=lambda s: s.lower())", "def sorter(textbooks):\n return sorted(textbooks, key=lambda v: (v.casefold(), v))", "def get_first(element):\n return element[0]\n\ndef sorter(textbooks):\n lst = [(el.lower(), el) for el in textbooks]\n lst1 = sorted(lst,key=get_first)\n return [el[1] for el in lst1]", "def sorter(textbooks):\n lst = sorted([(el.lower(), el) for el in textbooks])\n return [el[1] for el in lst]", "def sorter(textbooks):\n #Cramming before a test can't be that bad?\n def f(x):\n return x.lower()\n return sorted(textbooks,key=f)", "def sorter(textbooks):\n return list(sorted(textbooks, key=str.casefold))", "def sorter(textbooks):\n \"\"\"\n Sort list of textbooks\n \"\"\"\n return sorted(textbooks, key = str.lower)", "def sorter(textbooks):\n t2=sorted(textbooks,key=str.lower)\n return t2", "def sorter(textbooks):\n textbooks = sorted(textbooks, key = str.casefold)\n return textbooks", "def sorter(textbooks):\n #Cramming before a test can't be that bad?\n bookList = sorted(textbooks, key=str.lower)\n return bookList", "def sorter(textbooks):\n return sorted(sorted(textbooks, key = lambda x: x[1].lower()), key = lambda x: x[0].lower())", "def sorter(textbooks):\n x = sorted(textbooks, key = lambda s: s.casefold())\n return x", "def sorter(textbooks):\n return sorted(set(textbooks),key=str.casefold)", "def sorter(textbooks):\n result = []\n books_lowcase = [x.lower() for x in textbooks]\n books_dict = dict(zip(books_lowcase, textbooks))\n dict_keys_sort = list(books_dict.keys())\n dict_keys_sort.sort()\n for i in dict_keys_sort:\n result.append(books_dict[i])\n return result", "import re\ndef sorter(textbooks):\n textbooks.sort(key=str.lower) \n return textbooks\n #Cramming before a test can't be that bad?\n #print(re.findall(r\"\\S\",textbooks,re.IGNORECASE))\n #return sorted(textbooks)\n", "def sorter(textbooks):\n\n s = sorted(textbooks)\n \n if textbooks == s:\n \n return textbooks\n \n if s == s.sort(key=str.lower):\n \n return s.sort(key=str.lower)\n \n else:\n \n return s\n \n \n \n", "def lower_case(predmet):\n return predmet.lower()\ndef sorter(textbooks):\n return sorted(textbooks, key = lower_case)", "def register(textbook):\n return textbook.lower()\n\ndef sorter(textbooks):\n textbooks.sort(key=register)\n return textbooks", "def sorter(textbooks):\n return sorted(textbooks, key=lambda s: s.lower())\n #orted(unsorted_list, key=lambda s: s.lower())\n #Cramming before a test can't be that bad?\n", "def sorter(*textbooks):\n for textbook in textbooks:\n print(textbook.sort(key=str.lower))\n return textbook", "def sorter(textbooks):\n textbooks.sort(key=str.lower)\n return textbooks\n \n# return sorted(textbooks,key=str.lower)\n", "def f(x):\n x = x.lower()\n return x\n\ndef sorter(textbooks):\n textbooks.sort(key = f)\n return textbooks", "def sorter(textbooks):\n textbooks = sorted(textbooks, key=lambda x:x[0:] if x[0:].islower() else x[0:].lower())\n return textbooks", "def sorter(textbooks):\n return(sorted([i for i in textbooks], key = lambda str: str.lower()))", "def sorter(textbooks: list):\n return sorted(textbooks, key=str.lower)", "def sorter(t):\n t.sort(key=str.casefold)\n return t", "import locale\n\ndef sorter(textbooks):\n textbooks.sort(key=lambda x: x.lower())\n return textbooks", "sorter=lambda s:sorted(s,key=lambda x:x.lower())", "def sorter(t):\n return sorted(t,key=lambda t:t.casefold())\n", "def sorter(textbooks):\n return sorted(textbooks, key = lambda x: x[0:2].lower())\n #Cramming before a test can't be that bad?\n", "def sorter(textbooks):\n lst_books = []\n for i in textbooks:\n lst_books.append(i)\n return sorted(lst_books, key=str.lower)", "def sorter(textbooks):\n textbooks_low = [el.lower() for el in textbooks]\n \n textbooks_low_sorted = sorted(textbooks_low)\n \n testbooks_sorted_indexes = [textbooks_low.index(el) for el in textbooks_low_sorted]\n \n return [ textbooks[ind] for ind in testbooks_sorted_indexes ]", "def sorter(textbooks):\n if textbooks!=int:\n return sorted(textbooks,key=str.lower)", "def sorter(text_books):\n return sorted(text_books, key = str.lower)", "def sorter(textbooks):\n list.sort(textbooks, key = str.lower)\n return textbooks", "def sorter(textbooks):\n return sorted(textbooks, key=lambda t: (t.lower(), t))\n", "def sorter(textbooks):\n arr = []\n for i, book in enumerate(textbooks):\n arr.append([book.lower(), i])\n arr = sorted(arr)\n for i, book in enumerate(arr):\n arr[i] = textbooks[book[1]]\n return arr", "def sorter(textbooks):\n a = sorted(textbooks, key = str.lower)\n return a", "sorter = lambda books: sorted(books, key = lambda _: _.lower())", "import string\n\ndef sorter(textbooks):\n return sorted(textbooks,key=str.lower)", "sorter=lambda t: sorted(t, key=lambda s: s.lower())", "def sorter(textbooks):\n a = sorted(textbooks, key=str.casefold)\n print(textbooks, a) \n return a#Cramming before a test can't be that bad?", "def sorter(textbooks):\n result = sorted(textbooks, key=str.lower)\n return result", "def sorter(textbooks):\n #Cramming before a test can't be that bad?\n# return sorted(textbooks, key=cmp_to_key(locale.strcoll))\n textbooks.sort(key=str.lower)\n return textbooks ", "def sorter(textbooks):\n sorted_books=sorted(textbooks,key=str.casefold)\n \n return sorted_books", "# Sort the $%&*!#$! textbooks\ndef sorter(textbooks):\n obj = {}\n lower_case_textbooks = []\n for textbook in textbooks:\n lower_case_textbook = textbook.lower()\n obj[lower_case_textbook] = textbook\n lower_case_textbooks.append(lower_case_textbook)\n sorted_textbooks = sorted(lower_case_textbooks)\n output_list = [];\n for sorted_textbook in sorted_textbooks:\n output_list.append(obj[sorted_textbook])\n return output_list", "def sorter(textbooks):\n print(textbooks)\n print(sorted(textbooks,key=str.lower))\n return sorted(textbooks,key=str.lower)", "def sorter(textbooks):\n return sorted(textbooks, key=lambda e: e.lower())", "def sorter(textbooks):\n print(sorted(textbooks))\n return sorted(textbooks, key = lambda x: x.lower())", "def sorter(textbooks):\n #Cramming before a test can't be that bad?\n ts = sorted(textbooks, key=str.lower)\n return ts", "def sorter(arr):\n for i in range(len(arr) - 1):\n for j in range(len(arr) - i - 1):\n if arr[j].lower() > arr[j+1].lower():\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr", "def sorter(textbooks):\n return [a[1] for a in sorted([(b.lower(), b) for b in textbooks])]", "def sorter(t):\n return sorted(t,key=str.casefold)", "def sorter(tb):\n return sorted(tb, key=lambda x: x.lower())", "def sorter(textbooks):\n sorted = [book.lower() for book in textbooks]\n sorted.sort()\n final = textbooks.copy()\n for book in textbooks:\n final[sorted.index(book.lower())] = book\n return final", "def sorter(textbooks):\n copy = [text.lower() for text in textbooks]\n final = []\n to_sort = list(copy)\n to_sort.sort()\n for t in to_sort:\n final.append(textbooks[copy.index(t)])\n return final", "sorter = lambda x: sorted(x, key=str.casefold)", "def sorter(textbooks):\n #Cramming before a test can't be that bad\n a=[i.lower() for i in textbooks]\n s=sorted(a)\n \n for i in range(len(s)):\n if s[i] in textbooks:\n pass\n else:\n s[i]=textbooks[a.index(s[i])]\n return s", "def sorter(textbooks):\n return sorted(textbooks, key=lambda w:w.casefold())", "def sorter(textbooks):\n ret=[t for t in textbooks]\n ret.sort(key=lambda x: x.lower())\n return ret", "import numpy as np\n\ndef sorter(textbooks):\n return sorted(textbooks,key=str.lower)", "\nimport functools\n\ndef compares(item1, item2):\n if len(item1) == 0:\n return -1\n if len(item2) == 0:\n return 1\n if ord(item1[0].lower()) < ord(item2[0].lower()):\n return -1\n elif ord(item1[0].lower()) > ord(item2[0].lower()):\n return 1\n else:\n return compares(item1[1:], item2[1:])\n\ndef compare(item1, item2):\n return compares(item1,item2)\ndef sorter(textbooks):\n #Cramming before a test can't be that bad?\n return sorted(textbooks, key=functools.cmp_to_key(compare))\n", "def sorter(t):\n a = sorted(t, key=str.lower)\n return a ", "class Book():\n def __init__(self, subject):\n self.subject = subject\n def __lt__(self, other):\n return self.subject.lower() < other.subject.lower()\n\ndef sorter(textbooks):\n a = [Book(subj) for subj in textbooks]\n a.sort()\n output = [i.subject for i in a]\n return output", "def sorter(textbooks):\n return sorted(textbooks, key=lambda v: v.lower())", "def sorter(textbooks):\n sortbooks = sorted([x.lower() for x in textbooks])\n out = []\n for sb in sortbooks:\n for tb in textbooks:\n if sb==tb.lower():\n out.append(tb)\n return out", "def sorter(textbooks):\n index = {word.lower():word for word in textbooks}\n keys = sorted(index.keys())\n return [index[key] for key in keys]", "def sorter(textbooks):\n #Cramming before a test can't be that bad?\n return sorted([textbook for textbook in textbooks], key=lambda x: x.lower())", "def sorter(textbooks):\n \n sorted_list = sorted(textbooks, key=str.lower)\n return sorted_list", "sorter = lambda textbooks: sorted(textbooks, key = lambda t: t.lower())"] | {"fn_name": "sorter", "inputs": [[["Algebra", "History", "Geometry", "English"]], [["Algebra", "history", "Geometry", "english"]], [["Alg#bra", "$istory", "Geom^try", "**english"]]], "outputs": [[["Algebra", "English", "Geometry", "History"]], [["Algebra", "english", "Geometry", "history"]], [["$istory", "**english", "Alg#bra", "Geom^try"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 13,287 |
def sorter(textbooks):
|
7c1ad21eae4ca5e5e98c0513790ddfde | UNKNOWN | Create a function xMasTree(height) that returns a christmas tree of the correct height. The height is passed through to the function and the function should return a list containing each line of the tree.
```
xMasTree(5) should return : ['____#____', '___###___', '__#####__', '_#######_', '#########', '____#____', '____#____']
xMasTree(3) should return : ['__#__', '_###_', '#####', '__#__', '__#__']
```
The final idea is for the tree to look like this if you decide to print each element of the list:
```
xMasTree(5) will result in:
____#____ 1
___###___ 2
__#####__ 3
_#######_ 4
######### -----> 5 - Height of Tree
____#____ 1
____#____ 2 - Trunk/Stem of Tree
xMasTree(3) will result in:
__#__ 1
_###_ 2
##### -----> 3 - Height of Tree
__#__ 1
__#__ 2 - Trunk/Stem of Tree
```
Pad with underscores i.e _ so each line is the same length. The last line forming the tree having only hashtags, no spaces. Also remember the trunk/stem of the tree. | ["def xMasTree(n):\n return [(\"#\"*(x*2+1)).center(n*2-1, \"_\") for x in list(range(n))+[0]*2]", "def xMasTree(n):\n hashtags = '#' * (n - 1)\n spaces = '_' * (n - 1)\n tree = []\n for i in range(n):\n left = spaces[i:] + hashtags[:i]\n tree.append(left + '#' + left[::-1])\n for i in range(2):\n tree.append(spaces + '#' + spaces)\n return tree", "def xMasTree(n):\n w = 2*n-1\n return [ ('#'*(i<n and 2*i+1 or 1)).center(w,'_') for i in range(n+2)]", "def xMasTree(n):\n w = list(range(1, n * 2, 2)) + [1, 1]\n return [f\"{'#' * i}\".center(n * 2 - 1, \"_\") for i in w]\n", "def xMasTree(n):\n r = ['_' * (n - x//2 - 1) + '#' * x + '_' * (n - x//2 - 1) for x in range(1, n * 2, 2)]\n return r + r[:1] * 2", "def xMasTree(n):\n n2 = n * 2 - 1\n return [('#' * i).center(n2, '_') for i in range(1, n2 + 1, 2)] + ['#'.center(n2, '_')] * 2", "def xMasTree(n):\n width = 2 * n - 1\n return [\n ('#' * (m if m <= width else 1)).center(width, '_')\n for m in range(1, width + 5, 2)]", "def xMasTree(n):\n width = 2*n - 1\n row = 1\n res = []\n while row <= n:\n line = ''\n buff = '_'*(n-row)\n line += buff\n line += '#'*(2*row-1)\n line += buff\n res.append(line)\n row += 1\n for x in range(2):\n line = ''\n buff = '_'*(n-1)\n line += buff\n line += '#'\n line += buff\n res.append(line)\n return res", "xMasTree=lambda n: (lambda part: part+[part[0],part[0]])([\"\".join([\"_\"*(n-i-1),\"#\"*(2*i+1),\"_\"*(n-i-1)]) for i in range(n)])"] | {"fn_name": "xMasTree", "inputs": [[3], [7], [2], [4], [6]], "outputs": [[["__#__", "_###_", "#####", "__#__", "__#__"]], [["______#______", "_____###_____", "____#####____", "___#######___", "__#########__", "_###########_", "#############", "______#______", "______#______"]], [["_#_", "###", "_#_", "_#_"]], [["___#___", "__###__", "_#####_", "#######", "___#___", "___#___"]], [["_____#_____", "____###____", "___#####___", "__#######__", "_#########_", "###########", "_____#_____", "_____#_____"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,634 |
def xMasTree(n):
|
5764fad3447515f4e31145124f1fd9eb | UNKNOWN | ## Task
Your challenge is to write a function named `getSlope`/`get_slope`/`GetSlope` that calculates the slope of the line through two points.
## Input
```if:javascript,python
Each point that the function takes in is an array 2 elements long. The first number is the x coordinate and the second number is the y coordinate.
If the line through the two points is vertical or if the same point is given twice, the function should return `null`/`None`.
```
```if:csharp
`GetSlope` will take in two Point objects. If the line through the two points is vertical, or the two points are the same, return `null`.
The Point object:
~~~
public class Point : System.Object
{
public double X;
public double Y;
public Point(double x, double y)
{
this.X = x;
this.Y = y;
}
public override string ToString()
{
return $"({this.X}, {this.Y})";
}
public override bool Equals(object point)
{
// Typechecking
if (point == null || point.GetType() != this.GetType())
{
return false;
}
return this.ToString() == point.ToString();
}
}
~~~
``` | ["def getSlope(p1, p2):\n return None if p1[0] == p2[0] else (p2[1] - p1[1])/(p2[0] - p1[0])\n", "def getSlope(p1, p2):\n if p2[0] - p1[0]: return (p2[1]-p1[1]) / (p2[0]-p1[0])", "def getSlope(p1, p2):\n return None if p1[0] == p2[0] else (p1[1] - p2[1]) / (p1[0] - p2[0])", "def getSlope(p1, p2):\n if not (p2[0] - p1[0]):\n return None\n return (p2[1] - p1[1]) / (p2[0] - p1[0])", "def getSlope(p1, p2):\n if p2[0] != p1[0]:\n return (p2[1] - p1[1]) / (p2[0] - p1[0])", "def getSlope(p1, p2):\n ''' Return the slope of the line through p1 and p2\n '''\n if p1[0]==p2[0] or p1==p2:\n return None\n\n return (p1[1]-p2[1])/(p1[0]-p2[0])", "def getSlope(p1, p2):\n p1x, p1y = p1\n p2x, p2y = p2\n try: return (p2y - p1y) / (p2x - p1x)\n except: pass", "def getSlope(p1, p2):\n ''' Return the slope of the line through p1 and p2\n '''\n try:\n slope = (p2[1] - p1[1])/(p2[0] - p1[0])\n if (p1 == p2):\n return None\n return slope\n except ZeroDivisionError:\n return None", "def getSlope(p1, p2):\n try:\n return (p2[1] - p1[1]) / (p2[0] - p1[0])\n except:\n return None", "def getSlope(p1, p2):\n if (p1[0] != p2[0]):\n return (p1[1]-p2[1])/(p1[0]-p2[0])\n"] | {"fn_name": "getSlope", "inputs": [[[1, 1], [2, 2]], [[-5, -5], [9, 9]], [[1, 8], [2, 9]], [[8, 3], [-4, 5]], [[5, 3], [8, 9]], [[1, 3], [0, 3]], [[11, 1], [1, 11]], [[1, 1], [1, 2]], [[-5, 9], [-5, 12]], [[1, 1], [1, 1]], [[-5, 9], [-5, 9]]], "outputs": [[1], [1], [1], [-0.16666666666666666], [2], [0], [-1], [null], [null], [null], [null]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,303 |
def getSlope(p1, p2):
|
d0ee363cc6fd9bd3ececa08d2a8bcba1 | UNKNOWN | An ordered sequence of numbers from 1 to N is given. One number might have deleted from it, then the remaining numbers were mixed. Find the number that was deleted.
Example:
- The starting array sequence is `[1,2,3,4,5,6,7,8,9]`
- The mixed array with one deleted number is `[3,2,4,6,7,8,1,9]`
- Your function should return the int `5`.
If no number was deleted from the array and no difference with it, your function should return the int `0`.
Note that N may be 1 or less (in the latter case, the first array will be `[]`). | ["def find_deleted_number(arr, mixed_arr):\n return sum(arr)-sum(mixed_arr)", "def find_deleted_number(a, b):\n return (set(a) - set(b)).pop() if len(a) != len(b) else 0", "def find_deleted_number(arr, mixed_arr):\n lost = 0\n for i in arr:\n if i not in mixed_arr:\n lost = i\n \n return lost", "find_deleted_number=lambda a,m: next((e for e in set(a)-set(m)), 0)", "def find_deleted_number(arr, mixed_arr):\n return 0 if not arr else arr[-1]*(arr[-1]+1)/2 - sum(mixed_arr)", "def find_deleted_number(arr, mixed_arr):\n return len(arr) > len(mixed_arr) and (set(arr) - set(mixed_arr)).pop()", "def find_deleted_number(arr, mixed_arr):\n res = []\n for n in arr:\n if n not in mixed_arr: return n\n return 0", "def find_deleted_number(arr, mixed_arr):\n #Works only if exactly one number is missing\n return sum(arr)-sum(mixed_arr)", "def find_deleted_number(arr, mixed_arr):\n #Your code here\n ret = 0\n for i in arr:\n if i not in mixed_arr:\n ret = i\n \n return ret", "def find_deleted_number(arr, mixed_arr):\n arr = set(sorted(arr))\n mixed_arr = set(sorted(mixed_arr))\n return 0 if arr == mixed_arr else list(arr.difference(mixed_arr))[0]"] | {"fn_name": "find_deleted_number", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9], [5, 7, 9, 4, 8, 1, 2, 3]], [[1, 2, 3, 4, 5, 6, 7], [2, 3, 6, 1, 5, 4, 7]], [[1, 2, 3, 4, 5, 6, 7, 8, 9], [5, 7, 6, 9, 4, 8, 1, 2, 3]], [[1], []], [[], []]], "outputs": [[6], [0], [0], [1], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,263 |
def find_deleted_number(arr, mixed_arr):
|
deabe502155ebe6a3b39c8c69d7b63f5 | UNKNOWN | In this kata, you need to make a (simplified) LZ78 encoder and decoder.
[LZ78](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ78) is a dictionary-based compression method created in 1978. You will find a detailed explanation about how it works below.
The input parameter will always be a non-empty string of upper case alphabetical characters. The maximum decoded string length is 1000 characters.
# Instructions
*If anyone has any ideas on how to make the instructions shorter / clearer, that would be greatly appreciated.*
If the below explanation is too confusing, just leave a comment and I'll be happy to help.
---
The input is looked at letter by letter.
Each letter wants to be matched with the longest dictionary substring at that current time.
The output is made up of tokens.
Each token is in the format ``
where `index` is the index of the longest dictionary value that matches the current substring
and `letter` is the current letter being looked at.
Here is how the string `'ABAABABAABAB'` is encoded:
* First, a dictionary is initialised with the 0th item pointing to an empty string:
```md
Dictionary Input Output
0 | '' ABAABABAABAB
```
* The first letter is `A`. As it doesn't appear in the dictionary, we add `A` to the next avaliable index.
The token `<0, A>` is added to the output:
```md
Dictionary Input Output
0 | '' ABAABABAABAB <0, A>
1 | A ^
```
* The second letter is `B`. It doesn't appear in the dictionary, so we add `B` to the next avaliable index.
The token `<0, B>` is added to the output:
```md
Dictionary Input Output
0 | '' ABAABABAABAB <0, A> <0, B>
1 | A ^
2 | B
```
* The third letter is `A` again: it already appears in the dictionary at position `1`. We add the next letter which is also `A`. `AA` doesn't appear in the dictionary, so we add it to the next avaliable index.
The token `<1, A>` is added to the output:
```md
Dictionary Input Output
0 | '' ABAABABAABAB <0, A> <0, B> <1, A>
1 | A ^^
2 | B
3 | AA
```
* The next letter is `B` again: it already appears in the dictionary at position `2`. We add the next letter which is `A`. `BA` doesn't appear in the dictionary, so we add it to the next avaliable index.
The token `<2, A>` is added to the output:
```md
Dictionary Input Output
0 | '' ABAABABAABAB <0, A> <0, B> <1, A> <2, A>
1 | A ^^
2 | B
3 | AA
4 | BA
```
* The next letter is `B`: it already appears in the dictionary and at position `2`. We add the next letter which is `A`. `BA` already appears in the dictionary at position `4`. We add the next letter which is `A`. `BAA` doesn't appear in the dictionary, so we add it to the next avaliable index.
The token `<4, A>` is added to the output:
```md
Dictionary Input Output
0 | '' ABAABABAABAB <0, A> <0, B> <1, A> <2, A> <4, A>
1 | A ^^^
2 | B
3 | AA
4 | BA
5 | BAA
```
* The next letter is `B`. It already appears in the dictionary at position `2`. We add the next letter which is `A`. `BA` already appears in the dictionary at position `4`. We add the next letter which is `B`. `BAB` doesn't appear in the dictionary, so we add it to the next avaliable index.
The token `<4, B>` is added to the output:
```md
Dictionary Input Output
0 | '' ABAABABAABAB <0, A> <0, B> <1, A> <2, A> <4, A> <4, B>
1 | A ^^^
2 | B
3 | AA
4 | BA
5 | BAA
6 | BAB
```
* We have now reached the end of the string. We have the output tokens: `<0, A> <0, B> <1, A> <2, A> <4, A> <4, B>`.
Now we just return the tokens without the formatting: `'0A0B1A2A4A4B'`
**Note:**
If the string ends with a match in the dictionary, the last token should only contain the index of the dictionary. For example, `'ABAABABAABABAA'` (same as the example but with `'AA'` at the end) should return `'0A0B1A2A4A4B3'` (note the final `3`).
To decode, it just works the other way around.
# Examples
Some more examples:
```
Decoded Encoded
ABBCBCABABCAABCAABBCAA 0A0B2C3A2A4A6B6
AAAAAAAAAAAAAAA 0A1A2A3A4A
ABCABCABCABCABCABC 0A0B0C1B3A2C4C7A6
ABCDDEFGABCDEDBBDEAAEDAEDCDABC 0A0B0C0D4E0F0G1B3D0E4B2D10A1E4A10D9A2C
```
Good luck :) | ["import re\n\ndef encoder(s):\n d, out, it = {},[], iter(s)\n for c in it:\n i,k = 0,c\n while k in d: \n i,c = d[k], next(it,'')\n if not c: break\n k += c\n d[k] = len(d)+1\n out.append(f'{i}{c}')\n return ''.join(out)\n\n\ndef decoder(s):\n d = ['']\n for m in re.finditer(r'(\\d+)(\\D?)',s):\n d.append( d[int(m[1])] + m[2] )\n return ''.join(d)", "def encoder(data):\n\n def get_key_by_value(value):\n for key in dictionary:\n if dictionary[key] == value:\n return key\n\n dictionary = {0: ''}\n dict_index = 1\n substring = ''\n encoded = []\n\n for char in data:\n substring += char\n if substring not in list(dictionary.values()):\n dictionary[dict_index] = substring\n encoded.append(str(get_key_by_value(substring[:-1])))\n encoded.append(substring[-1])\n dict_index += 1\n substring = ''\n if substring != '':\n encoded.append(str(get_key_by_value(substring)))\n return ''.join(encoded)\n\n\ndef decoder(data):\n dictionary = {0: ''}\n dict_index = 1\n decoded = []\n key = ''\n for char in data:\n if char.isdigit():\n key += char\n else:\n substring = dictionary[int(key)] + char\n dictionary[dict_index] = substring\n dict_index += 1\n decoded.append(substring)\n key = ''\n if key != '':\n decoded.append(dictionary[int(key)])\n return ''.join(decoded)\n", "from re import findall\n\ndef encoder(data):\n base = \"\"\n dictionary = {base: 0}\n output = []\n \n for char in data:\n curr = base + char\n if curr in dictionary:\n base = curr\n else:\n output.append(f\"{dictionary[base]}{char}\")\n dictionary[curr] = len(dictionary)\n base = \"\"\n \n if base:\n output.append(f\"{dictionary[base]}\")\n \n return \"\".join(output)\n\n\ndef decoder(data):\n dictionary = [\"\"]\n \n for idx, char in findall(\"(\\d+)([A-Z]?)\", data):\n dictionary.append(dictionary[int(idx)] + char)\n \n return \"\".join(dictionary)", "def encoder(data):\n d, d_reverse = {0: ''}, {'': 0}\n d_idx, data_idx = 1, 0\n while data_idx < len(data):\n if data[data_idx] not in d_reverse:\n d[d_idx] = '0' + data[data_idx]\n d_reverse[data[data_idx]] = d_idx\n else:\n start_idx = data_idx\n while data_idx + 1 < len(data) and data[start_idx: data_idx + 1] in d_reverse:\n data_idx += 1\n if data_idx == len(data) - 1:\n if data[start_idx: data_idx + 1] in d_reverse:\n d[d_idx] = str(d_reverse[data[start_idx:data_idx+1]])\n else:\n d[d_idx] = str(d_reverse[data[start_idx:data_idx]]) + data[data_idx]\n break\n else:\n d[d_idx] = str(d_reverse[data[start_idx:data_idx]]) + data[data_idx]\n d_reverse[data[start_idx:data_idx+1]] = d_idx\n data_idx += 1\n d_idx += 1\n return ''.join([v for k, v in list(d.items()) if k != 0])\n\n\ndef decoder(data):\n d, s = [], []\n for i in range(len(data)):\n if i == len(data)-1 and data[i].isdigit():\n s.append(data[-1])\n d.append([int(''.join(s)), ''])\n if data[i].isalpha():\n d.append([int(''.join(s)), data[i]])\n s = []\n else:\n s.append(data[i])\n d_list = []\n for i in range(len(d)):\n if i == len(d) - 1 and not d[i][1]:\n d_list.append(d_list[d[i][0]-1])\n break\n if d[i][0] == 0:\n d_list.append(d[i][1])\n else:\n d_list.append(d_list[d[i][0]-1] + d[i][1])\n return ''.join(d_list)\n", "import re\ndef encoder(s):\n d, numbers, i, li = {}, iter(range(1, 1000)), 0, []\n while i < len(s):\n symbol = s[i]\n prev = 0\n while symbol in d:\n i += 1 ; prev = d[symbol]\n if i == len(s) : return \"\".join(li)+str(d[symbol])\n symbol += s[i]\n d[symbol] = next(numbers)\n li.append(str(prev) + s[i])\n i += 1\n return \"\".join(li)\n \ndef decoder(s):\n parts, numbers, d, li = re.findall(r'\\d+[A-Z]', s), iter(range(1, 1000)), {}, []\n for i in parts:\n if re.fullmatch(r'\\d+\\w', i):\n t = re.findall(r'(\\d+)(\\w)',i)\n k, l = int(t[0][0]), t[0][1]\n if not k : d[next(numbers)] = l ; li.append(l)\n else : d[next(numbers)] = d[k] + l ; li.append(d[k] + l)\n else : li.append(d[int(i)])\n p = len(s)-len(''.join(parts))\n return ''.join(li) + (d[int(s[-p:])] if s[-p:].isdigit() else '')", "def encoder(data):\n d,c,o=[''],'',''\n for i in data: d,c,o=(d,c+i,o)if c+i in d else(d+[c+i],'',o+str(d.index(c))+i)\n return o+(str(d.index(c)) if c else '')\n\ndef decoder(data):\n d,c,o=[''],'',''\n for i in data: d,c,o=(d,c+i,o)if i in '0123456789' else(d+[d[int(c)]+i],'',o+d[int(c)]+i)\n return o+(d[int(c)] if c else '')\n", "import re\ndef encoder(data):\n dct = {'':0}\n search = ''\n output = '' \n for i in range(len(data)):\n search += data[i]\n if search not in dct:\n dct[search] = len(dct)\n output += f'{dct[search[:-1]]}{search[-1]}'\n search = ''\n try:\n search + data[i+1]\n except IndexError:\n if search == data[-(len(search)):]:\n output += f'{dct[search]}' \n return output\n\ndef decoder(data):\n dct = {0:''}\n output = ''\n lsnb = re.findall(r'\\d+', data)\n lsch = re.findall(r'[A-Z]', data)\n for i in range(len(lsnb)):\n try:\n lsch[i]\n dct[len(dct)] = dct[int(lsnb[i])] + lsch[i]\n output += dct[len(dct)-1] \n except IndexError:\n output += dct[int(lsnb[i])]\n return output ", "import re\n\ndef encoder(s):\n d, i, r = {\"\": 0}, 0, []\n while i < len(s):\n x = \"\"\n while i < len(s) - 1 and x + s[i] in d:\n x += s[i]\n i += 1\n if x + s[i] not in d:\n d[x + s[i]] = len(d)\n r.append((d[x], s[i]))\n else:\n r.append((d[x + s[i]], \"\"))\n i += 1\n return \"\".join(str(x) + y for x, y in r)\n\ndef decoder(s):\n a, r = [\"\"], []\n for x, y in re.findall(r\"(\\d+)(\\D*)\", s):\n a.append(a[int(x)] + y)\n return \"\".join(a)", "import re\ndef encoder(data):\n dictionary = { '': 0 }\n output = []\n index = 1\n longest_match = \"\"\n substring = \"\" \n for character in data:\n substring += character\n if substring not in dictionary:\n dictionary[substring] = index\n output.append((dictionary[longest_match], character))\n longest_match = \"\"\n substring = \"\"\n index += 1\n else:\n longest_match += character\n if substring in dictionary and substring != \"\":\n output.append((dictionary[substring], ''))\n\n return ''.join(str(i)+j for i,j in output)\n\n\n\ndef decoder(data):\n dictionary = { 0: '' }\n last = re.search(r'(\\d*)$', data).group() \n data = re.findall(r'(\\d+)([A-Z])', data)\n if last != \"\":\n data.append((last, \"\"))\n index = 1\n for pair in data:\n dictionary[index] = dictionary[int(pair[0])] + pair[1]\n index += 1 \n return ''.join(dictionary.values())", "def encoder(data):\n dicto, store, i, f = {0: \"\"}, \"\", 0, \"\"\n save = 0\n while i <= len(data):\n if i == len(data) and store in list(dicto.values()):\n for k in dicto:\n if dicto[k] == store and store != \"\":\n f += f\"{k}\"\n return f\n if store not in list(dicto.values()) and store != \"\":\n dicto[max(dicto.keys())+1] = store\n f += f\"{save}{data[i-1]}\"\n store = \"\"\n if i == len(data):\n return f\n continue\n if data[i] not in list(dicto.values()) and store == \"\":\n save = 0\n for m in dicto:\n if dicto[m] == store:\n save = m\n dicto[max(dicto.keys())+1] = data[i]\n f += f\"{save}{data[i]}\"\n i += 1\n else:\n for m in dicto:\n if dicto[m] == store:\n save = m\n elif dicto[m] == data[i] and store == \"\":\n save = m\n store += data[i]\n i += 1\n return f\n\n\ndef decoder(data):\n dc, dic = \"\", {0: \"\"}\n i = 0\n while i <= len(data)-1:\n\n if data[i].isdigit() and i == len(data)-1:\n dc += dic[int(data[i])]\n return dc\n if data[i] == \"0\":\n dc += data[i+1]\n dic[max(dic.keys())+1] = data[i+1]\n i += 1\n elif data[i] != \"0\" and data[i].isdigit() and not data[i+1].isdigit():\n c = dic[int(data[i])]+data[i+1]\n dc += c\n dic[max(dic.keys())+1] = c\n i += 1\n elif data[i].isdigit() and data[i+1].isdigit():\n acc = data[i]\n while data[i+1].isdigit():\n i += 1\n acc += data[i]\n if i+1 == len(data):\n dc += dic[int(acc)]\n return dc\n dc += dic[int(acc)]+data[i+1]\n dic[max(dic.keys())+1] = dic[int(acc)]+data[i+1]\n i += 1\n else:\n i += 1\n\n return dc\n\n"] | {"fn_name": "encoder", "inputs": [["ABAABABAABAB"], ["ABAABABAABABAA"], ["ABBCBCABABCAABCAABBCAA"], ["AAAAAAAAAAAAAAA"], ["ABCABCABCABCABCABC"], ["ABCDDEFGABCDEDBBDEAAEDAEDCDABC"]], "outputs": [["0A0B1A2A4A4B"], ["0A0B1A2A4A4B3"], ["0A0B2C3A2A4A6B6"], ["0A1A2A3A4A"], ["0A0B0C1B3A2C4C7A6"], ["0A0B0C0D4E0F0G1B3D0E4B2D10A1E4A10D9A2C"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 9,933 |
def encoder(data):
|
6f26dc8a49f26a447bf5ef863bb20cb6 | UNKNOWN | # Task
The sequence of `Chando` is an infinite sequence of all Chando's numbers in ascending order.
A number is called `Chando's` if it is an integer that can be represented as a sum of different positive integer powers of 5.
The first Chando's numbers is 5 (5^1). And the following nth Chando's numbers are:
```
25 (5^2)
30 (5^1 + 5^2)
125 (5^3)
130 (5^1 + 5^3)
150 (5^2 + 5^3)
...
...
```
Your task is to find the Chando's nth number for a given `n`.
# Input/Output
- `[input]` integer `n`
`1 <= n <= 7000`
- `[output]` an integer
nth Chando's number | ["def nth_chandos_number(n):\n return int((bin(n)+\"0\")[2:], 5)", "from itertools import combinations, chain\nfrom math import log\ndef nth_chandos_number(n):\n l = [0] + [5 ** i for i in range(1, int(log(n, 5)) + 10)]\n m = chain(*[combinations(l, ni) for ni in range(1, len(l) + 1)])\n ls = sorted(list(set([sum(i) for i in m])))\n return ls[n]\n", "\"\"\" Considering that we search first 7000 Chandos numbers, generate the full\n list and then returned the good one on each call.\n \n Process: Chandos number are made of 5^n terms with DIFFERENT n, so integers\n usable as power can be represented in a binary way:\n \n 0 => no Chandos\n 1 => first Chandos: 5^1\n 10 => secund: 5^2\n 11 => ... 5^2 + 5^1\n ...\n \n This way, the ARCHIVE is made by iterating binary numbers up to 7000\n in base 10.\n For the simplicity of the implementation, the binary representation is \n reversed (-> big endian notation : this avoid the need of filling the \n binary string representation with leading 0).\n\"\"\"\n\nARCHIVE = [ sum( 5**(i+1) for i,s in enumerate(reversed(bin(n)[2:])) if s == '1' ) for n in range(1, 7001) ]\n\ndef nth_chandos_number(n): return ARCHIVE[n-1]", "from itertools import combinations as c\ndef nth_chandos_number(n):\n comb, generate, i = [1], [], 1\n while len(generate) <= n:\n generate.extend(sorted([j for k in range(1,len(comb)+1) for j in c(comb,k) if j[0]==i]))\n i += 1 ; comb.insert(0, i)\n return sum(5 ** i for i in generate[n-1])", "nth_chandos_number=c=lambda n:n and c(n//2)*5+n%2*5", "lst = [5]\nfor i in range(2, 14):\n x = 5**i\n lst.append(x)\n temp = lst[:]\n for j in temp[:-1]:\n lst.append(j+x)\n\ndef nth_chandos_number(n):\n return lst[n-1]", "def nth_chandos_number(n):\n return int(bin(n)[2:] + '0', 5)", "def nth_chandos_number(n): # :( stupid code\n a, i, j, m = [], -1, 1, 5\n while len(a) < n:\n m = 5 ** j\n a.append(m)\n while j > 1 and i < 2 ** ~-j-1:\n a.append(m + a[i])\n i += 1\n i, j = 0, j+1\n return a[~-n]", "def nth_chandos_number(n):\n b='{:b}'.format(n)\n r=0\n for d in b:\n r=r*5+int(d)*5\n return r", "def nth_chandos_number(n):\n t, ans = 1, 0\n while n:\n t *= 5\n if n % 2:\n ans += t\n n //= 2\n return ans"] | {"fn_name": "nth_chandos_number", "inputs": [[1], [2], [9], [123], [23]], "outputs": [[5], [25], [630], [97530], [3280]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,590 |
def nth_chandos_number(n):
|
273823b6a2a14446a40b590a1a6ed844 | UNKNOWN | In another Kata I came across a weird `sort` function to implement. We had to sort characters as usual ( 'A' before 'Z' and 'Z' before 'a' ) except that the `numbers` had to be sorted **after** the `letters` ( '0' after 'z') !!!
(After a couple of hours trying to solve this unusual-sorting-kata I discovered final tests used **usual** sort (digits **before** letters :-)
So, the `unusualSort/unusual_sort` function you'll have to code will sort `letters` as usual, but will put `digits` (or one-digit-long `numbers` ) **after** `letters`.
## Examples
```python
unusual_sort(["a","z","b"]) # -> ["a","b","z"] as usual
unusual_sort(["a","Z","B"]) # -> ["B","Z","a"] as usual
//... but ...
unusual_sort(["1","z","a"]) # -> ["a","z","1"]
unusual_sort(["1","Z","a"]) # -> ["Z","a","1"]
unusual_sort([3,2,1"a","z","b"]) # -> ["a","b","z",1,2,3]
unusual_sort([3,"2",1,"a","c","b"]) # -> ["a","b","c",1,"2",3]
```
**Note**: `digits` will be sorted **after** "`same-digit-numbers`", eg: `1` is before `"1"`, `"2"` after `2`.
```python
unusual_sort([3,"2",1,"1","3",2]) # -> [1,"1",2,"2",3,"3"]
```
You may assume that **argument** will always be an `array/list` of **characters** or **one-digit-long numbers**. | ["def unusual_sort(array):\n return sorted(array, key=lambda x: (str(x).isdigit(), str(x), -isinstance(x, int)))", "def unusual_sort(array):\n return sorted(array, key=lambda item: (str(item).isdigit(), str(item), isinstance(item, str)))", "import string\n\n\ndef unusual_sort(array):\n #your code here\n upper = sorted([i for i in array if i in list(string.ascii_uppercase)])\n lower = sorted([it for it in array if it in list(string.ascii_lowercase)])\n intint = sorted([num for num in array if num in list(map(int,list(string.digits)))])\n strints = sorted([e for e in array if e in list(string.digits)])\n upper.extend(lower)\n intint.extend(strints)\n want = []\n for i in intint:\n if type(i) is not int:\n want.append((int(i), i))\n else:\n want.append((i, i))\n ans = [i[1] for i in sorted(want,key = lambda x: x[0])]\n upper.extend(ans)\n\n return upper", "def unusual_sort(array):\n int_list = []\n digit_list = []\n char_list = []\n \n for x in array:\n if type(x) is str:\n if x.isdigit():\n digit_list.append(x)\n else:\n char_list.append(x)\n else:\n int_list.append(x) \n \n int_list.sort()\n digit_list.sort()\n char_list.sort()\n \n for idx in range(len(int_list)):\n for i in range(len(digit_list)):\n if int_list[idx] <= int(digit_list[i]):\n digit_list.insert(i, int_list[idx])\n break\n else:\n digit_list += int_list[idx:]\n break\n \n return char_list + digit_list\n", "def unusual_sort(array):\n def k(x):\n if type(x) == int:\n return ord('z') + 1 + 10*x;\n elif x.isdigit():\n return ord('z') + 1 + 10*int(x) + 1;\n else:\n return ord(x);\n \n return sorted(array, key=k);", "\n\ndef unusual_sort(array):\n _isdigit = lambda d : type(d) == int or (type(d) == str and d.isdigit())\n digits = [d for d in array if _isdigit(d)]\n nondigits = [n for n in array if not _isdigit(n)]\n \n digits.sort(key=lambda d:int(d) if type(d) == str else d - 0.1)\n nondigits.sort()\n \n return nondigits + digits"] | {"fn_name": "unusual_sort", "inputs": [[["0", "9", "8", "1", "7", "2", "6", "3", "5", "4"]], [["3", "2", "1", "c", "b", "a"]], [["c", "b", "a", "9", "5", "0", "X", "Y", "Z"]], [[3, "3", "2", 2, "2", "1", 1, "a", "b", "c"]], [[]], [[1]], [["a"]]], "outputs": [[["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]], [["a", "b", "c", "1", "2", "3"]], [["X", "Y", "Z", "a", "b", "c", "0", "5", "9"]], [["a", "b", "c", 1, "1", 2, "2", "2", 3, "3"]], [[]], [[1]], [["a"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,309 |
def unusual_sort(array):
|
c186f33c2c4f518af3334ecd3d5f3fdd | UNKNOWN | Given a list of white pawns on a chessboard (any number of them, meaning from 0 to 64 and with the possibility to be positioned everywhere), determine how many of them have their backs covered by another.
Pawns attacking upwards since we have only white ones.
Please remember that a pawn attack(and defend as well) only the 2 square on the sides in front of him. https://en.wikipedia.org/wiki/Pawn_(chess)#/media/File:Pawn_(chess)_movements.gif
This is how the chess board coordinates are defined:
ABCDEFGH8♜♞♝♛♚♝♞♜7♟♟♟♟♟♟♟♟65432♙♙♙♙♙♙♙♙1♖♘♗♕♔♗♘♖ | ["def covered_pawns(pawns):\n pawns = set(pawns)\n return len({p for p in pawns for x,y in [map(ord, p)] if {chr(x-1)+chr(y-1), chr(x+1)+chr(y-1)} & pawns})", "def covered_pawns(pawns):\n count = 0\n for i in range(len(pawns)):\n x, y = list(pawns[i])\n if \"\".join([chr(ord(x) - 1), str(int(y) - 1)]) in pawns or \\\n \"\".join([chr(ord(x) + 1), str(int(y) - 1)]) in pawns:\n count += 1\n return count", "def covered_pawns(pawns):\n return sum(\n any(chr(ord(c)+delta) + chr(ord(r)-1) in pawns for delta in [-1, 1])\n for c, r in pawns\n )", "def covered_pawns(pawns):\n count = 0\n pawn_pos = set(pawns)\n for p in pawns:\n if p[-1] != \"1\":\n if any(f\"{chr(ord(p[0]) + i)}{int(p[1]) - 1}\" in pawn_pos for i in (-1, 1)):\n count += 1\n return count\n", "letters = {\n 'a': ('b',),\n 'b': ('a', 'c',),\n 'c': ('b', 'd',),\n 'd': ('c', 'e',),\n 'e': ('d', 'f',),\n 'f': ('e', 'g',),\n 'g': ('f', 'h',),\n 'h': ('g',),\n}\n\n\ndef get_cells(pawn):\n x, y = pawn\n y = int(y)\n if y < 8:\n cells = [letter + str(y + 1) for letter in letters[x]]\n return cells\n return []\n\n\ndef covered_pawns(pawns):\n res = set()\n pawns = set(pawns)\n for pawn in pawns:\n cells = get_cells(pawn)\n for cell in cells:\n if cell in pawns:\n res.add(cell)\n return len(res)\n", "covered_pawns=lambda p:len(set(p)&set.union(*({chr(ord(c)+b)+chr(ord(r)+1)for b in(-1,1)}for c,r in[' ']+p)))", "def protects(location):\n \"\"\"Returns the protected spaces (as a set), given a location.\n Examples:\n protects('b2') == {'a3', 'c3'}\n protects('a2') == {'b2'}\n protects('f8') == set()\n \"\"\"\n if location[1] == '8': return set()\n row = int(location[1]) + 1\n col = location[0]\n if col == 'a':\n cols = {'b'}\n elif col == 'h':\n cols = {'g'}\n else:\n cols = {chr(ord(col)-1), chr(ord(col)+1)}\n return {f'{c}{row}' for c in cols}\n\n\ndef covered_pawns(pawns):\n protected_spaces = set()\n for p in pawns:\n protected_spaces |= protects(p)\n return len(set(pawns) & protected_spaces)", "import numpy as np\ndef covered_pawns(pawns):\n n = len(pawns)\n p = np.zeros(n)\n for i in range(0,n):\n for j in range(0,n):\n if int(pawns[j][1]) == int(pawns[i][1])+1 and abs(ord(pawns[j][0])-ord(pawns[i][0])) == 1:\n p[j] = 1\n return sum(p)\n", "def covered_pawns(pawns):\n board = [[0]*8 for _ in range(8)]\n for c,r in pawns:\n board[8 - int(r)][ord(c) - 97] = 1\n return sum(board[i][j] and (j and board[i+1][j-1] or 7-j and board[i+1][j+1]) for i in range(7) for j in range(8))", "def covered_pawns(pawns):\n covered = 0\n for pos in pawns:\n if chr(ord(pos[0]) + 1) + str(int(pos[1]) - 1) in pawns \\\n or chr(ord(pos[0]) - 1) + str(int(pos[1]) - 1) in pawns:\n covered += 1\n return covered\n"] | {"fn_name": "covered_pawns", "inputs": [[["f7", "b1", "h1", "c7", "h7"]], [["e5", "b2", "b4", "g4", "a1", "a5"]], [["a2", "b1", "c2"]], [["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "g1", "g2", "g3", "g4", "g5", "g6", "g7", "g8", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8"]], [[]]], "outputs": [[0], [2], [2], [56], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,107 |
def covered_pawns(pawns):
|
a1a740e3242fd1167eb4e44a9c8266ec | UNKNOWN | Count the number of divisors of a positive integer `n`.
Random tests go up to `n = 500000`.
## Examples
```python
divisors(4) == 3 # 1, 2, 4
divisors(5) == 2 # 1, 5
divisors(12) == 6 # 1, 2, 3, 4, 6, 12
divisors(30) == 8 # 1, 2, 3, 5, 6, 10, 15, 30
``` | ["def divisors(n):\n return len([l_div for l_div in range(1, n + 1) if n % l_div == 0]);", "# For Beginners.\n\n# Time: 11724ms\n# it's slow because use isinstance\ndef divisors5(n):\n return len(list([e for e in [x if n % x == 0 else None for x in range(1, n + 1)] if isinstance(e, int)]))\n\n\n# Time: 7546ms\n# it's little fast because just directly check boolean\ndef divisors4(n):\n return len(list([e for e in [True if n % x == 0 else False for x in range(1, n + 1)] if e]))\n\n\n# Time: 4731ms\n# in python True is evaluate as 1\n# so when prime factorization just set True and sum will return count\ndef divisors3(n):\n return sum([True if n % x == 0 else False for x in range(1, n + 1)])\n\n\n# Time: 3675ms\n# even don't need return true, cause comparison operator will return boolean\ndef divisors2(n):\n return sum([n % x == 0 for x in range(1, n + 1)])\n\n\n# same time with above but make short code via lambda expression\ndivisors = lambda n: sum([n % x == 0 for x in range(1, n + 1)])\n", "def divisors(n):\n return sum(n%i==0 for i in range(1,n+1))", "def divisors(n):\n divs = 0\n \n for x in range(1, int(n**0.5)+1):\n if n % x == 0:\n divs += 2\n \n return divs - (x*x == n)", "from math import sqrt, floor\n\ndef divisors(n):\n return sum(1 if i*i == n else 2 for i in range(1, floor(sqrt(n)+1)) if n%i == 0)", "def divisors(n):\n return sum(1 for i in range(1,n+1) if n % i == 0)", "def divisors(n):\n c=1\n i=0\n while c<=n:\n if n%c==0:\n i+=1\n c+=1\n return i", "def divisors(n):\n count = 0\n for i in range(1, n + 1):\n if n / i % 1 == 0:\n count += 1\n return count", "def divisors(n):\n return len([x for x in range(1,(n//2)+1) if n % x == 0])+1", "def divisors(n):\n divs = [] ## start empty list to store divisors\n for i in range(1,n + 1): ## loop through all numbers 1 to n \n if n % i == 0: ## test if divisor\n divs.append(i) ##appends divisor\n return len(divs) ##return length of divisors\n\n", "def divisors(n):\n i = 1\n result = 0\n while i <= n:\n if n%i == 0:\n result += 1\n i+=1\n return result", "def divisors(n):\n return len([i for i in range(1,n+1) if n%i==0])", "def divisors(n):\n return sum(not n % i for i in range(1, n + 1))", "divisors=lambda n:sum(1for e in range(1,n+1)if n%e==0)", "def divisors(n):\n i = 1\n numeri = 0\n while i <= n:\n if n % i == 0:\n numeri += 1\n i += 1\n return numeri ", "def divisors(n):\n lista = 0\n for i in range(1,n+1):\n if n%i == 0:\n lista +=1\n return lista\n", "def divisors(n):\n z = 0\n i = 1\n while i <= n:\n if n % i == 0:\n z+=1\n i+=1\n return z", "def divisors(n):\n return 1 if n == 1 else 2 + sum(1 + (0 if k == n // k else 1) for k in range(2, int(n**0.5) + 1) if n % k == 0)", "def divisors(n):\n dividend=[i for i in range(n) if n%(i+1)==0]\n return len(dividend)", "def divisors(n):\n arr = []\n for i in range(1, n+1):\n if n % i == 0:\n arr.append(i)\n return len(arr)", "def divisors(n):\n return sum(n % d == 0 for d in range(1, n + 1))", "def divisors(n):\n count=1\n for i in range(1,n):\n if n%i==0:\n count+=1\n return count", "divisors=lambda n: (lambda s: len([i for i in range(1,s+1) if not n%i])*2-(s*s==n))(int(n**0.5))", "def divisors(n):\n ans = set()\n for i in range(1, int(n**.5)+1):\n if not n%i:\n ans |= {i, n//i}\n return len(ans)", "def divisors(n):\n return sum(2 for d in range(1, int(n ** 0.5 + 1)) if not n % d) - int((n ** 0.5).is_integer())\n", "def divisors(n):\n pass\n return [n%i for i in range(1,(n//2)+1)].count(0)+1\n", "def divisors(n):\n result=1\n for i in range(n//2):\n if n % (i+1) == 0:\n result += 1\n return result", "def divisors(n):\n count = 1\n for num in range(1,n):\n if (n/num).is_integer()==True:\n count +=1\n \n return count", "def divisors(n):\n sum=[]\n for i in range (1,n+1):\n if n%i==0:\n sum.append(i)\n return len(sum)", "def divisors(n):\n L = []\n for i in range(1,n+1):\n if n//i == n/i:\n L.append(i)\n return len(L)", "def divisors(n):\n return 1 + sum(1 for x in range(1,n//2+1) if n % x == 0)", "def divisors(n):\n return sum([n%i==0 for i in range(1,n+1)])", "def divisors(n):\n return len([num for num in range(1,n+1) if not (n % num)])", "def divisors(n):\n count = 1\n for i in range(2, n + 1):\n if n % i == 0:\n count += 1\n return count", "def divisors(n):\n return sum(n % a == 0 for a in range(1, n + 1))\n", "def divisors(n):\n return sum(1 for x in range(1,n + 1) if n % x == 0)", "def divisors(n):\n return len([ x for x in range(1,n+1) if n % x == 0 ])", "from math import sqrt\n\ndef divisors(n):\n res = 0\n for i in range(1,int(sqrt(n))+1):\n if n%i == 0:\n res += 2\n if int(sqrt(n))**2 == n:\n res -= 1\n return res", "def divisors(n):\n return sum([1 for i in range(1, n + 1) if n % i == 0])", "def divisors(n):\n out = 1\n for i in range(1, n):\n if n % i == 0:\n out += 1\n return out", "def divisors(n):\n div = 1\n for i in range(1,(n+1//2)):\n if n % i == 0:\n div += 1 \n return div", "def divisors(n):\n y = 0\n for x in range (1, n+1):\n if (n % x) == 0:\n y += 1\n return y\n \n", "def divisors(n):\n i = 1\n count = 0\n while i <= n : \n if (n % i==0) : \n count += 1 \n i = i + 1\n return count", "def divisors(n):\n num = list(range(1, n + 1))\n count = 0\n for i in num:\n if n % i == 0:\n count += 1\n return count\n", "def divisors(n):\n return len(list(i for i in range(n) if n%(i+1) == 0))", "def divisors(n):\n return sum(True for i in range(1,n+1) if n % i == 0)", "def divisors(n):\n counter = 1\n for i in range(1, n):\n if n % i == 0:\n counter += 1\n return counter\n\ndivisors(2)", "def divisors(n):\n list_1 = []\n for x in range(1,n+1):\n if n%x == 0:\n list_1.append(x)\n length = len(list_1)\n return length\n", "def divisors(n):\n factors = [num for num in range(1, n // 2 + 1) if n % num == 0]\n return len(factors) + 1", "def divisors(n):\n divisor = 1\n count = 0\n while n > divisor:\n if n % divisor == 0:\n count += 1\n divisor += 1\n else:\n divisor += 1\n count += 1\n return count", "def divisors(n):\n count = 0\n for i in range(1, n + 1):\n if (n % i == 0):\n print(i)\n count = count + 1\n return count", "def divisors(n):\n div = 1\n for i in range(1,n):\n if n%i == 0:\n div += 1\n return div", "def divisors(n):\n \n count = 0\n for i in range(1, int(n / 2) + 1):\n \n if n % i == 0:\n count += 1\n \n count += 1 #n value itself\n \n return count", "def divisors(n):\n answer = []\n for i in range(1, n // 2 + 1):\n if n % i == 0:\n if i not in answer:\n answer.append(i)\n return len(answer) + 1", "def divisors(n):\n count = 1\n \n for i in range(1, n):\n if n % i == 0:\n count += 1\n print(i)\n print(count)\n return count", "def divisors(n):\n k = 1\n for i in range(1, int(n/2)+1):\n if n % i == 0:\n k += 1\n\n return k", "def divisors(n):\n ret = 1\n \n for i in range(1, n):\n if n % i == 0:\n ret += 1\n \n return ret", "def divisors(n):\n '''\n Returns the number of divisors of a positive integer\n ~Input: \n n, the given integer\n ~Output:\n x, the number of divisors\n '''\n x = 0\n for i in range(1, n+1):\n if n % i == 0:\n x += 1\n \n return x", "import math\ndef divisorGenerator(n): #\u6c42\u6240\u6709\u9664\u6570\n large_divisors = []\n for i in range(1, int(math.sqrt(n) + 1)):\n if n % i == 0:\n yield i\n if i*i != n:\n large_divisors.append(n / i)\n for divisor in reversed(large_divisors):\n yield divisor\ndef divisors(n):\n return len(list(divisorGenerator(n)))", "def divisors(n):\n x = 1\n count = 2\n while True:\n if count > n: break\n if n % count == 0:\n x += 1\n count += 1\n return x", "def divisors(n):\n count = 0\n div_by_n = 0\n while count < n:\n count += 1\n if n % count == 0:\n div_by_n += 1\n return div_by_n", "def divisors(n):\n divisor = 1\n total = 0\n while divisor <= n:\n if n % divisor == 0:\n total += 1\n divisor +=1\n return total", "def divisors(n):\n \n num = []\n for x in range (1,n+1):\n if n % x == 0:\n num.append(x)\n else:\n continue\n \n return len(num)\n", "def divisors(n):\n s = 0\n for i in range(1,n//2+1):\n if n%i == 0:\n s += 1\n return s+1", "def divisors(n):\n count = 0\n for i in range(n+1):\n if i == 0:\n continue\n s = n / i\n if s.is_integer():\n count +=1\n return count", "def divisors(n):\n return sum([1 if n % x == 0 else 0 for x in range(1,n)]) + 1", "def divisors(n):\n count=0\n div=1\n while div<=n:\n if n%div==0:\n count +=1\n div+=1\n else:\n div+=1\n return count", "def divisors(n):\n x = 1\n y = []\n while x < n:\n if n % x == 0:\n y.append(x)\n x +=1\n return len(y) + 1", "def divisors(n):\n devisors = []\n for number in range(1, n+1):\n result = n % number\n if result == 0:\n devisors.append(result)\n return(len(devisors))\n", "def divisors(n):\n count = 1\n \n for i in range(1, n):\n if n%i == 0:\n count += 1\n else:\n count += 0\n return count", "def divisors(n):\n answers = []\n for i in range(1, n+1):\n if n % i == 0:\n answers.append(i)\n return len(answers)\n", "def divisors(n):\n sum = 0\n for numbers in range(1,n+1):\n if n % numbers == 0:\n sum += 1\n return sum\n", "def divisors(n):\n x = 0\n number = n\n while n >= 1:\n if number % n == 0:\n x += 1\n n -= 1\n return x", "def divisors(n):\n def gen_divisors():\n y = 1\n while y <= n:\n if n % y == 0 : yield y\n y += 1\n \n return len(list(gen_divisors()))", "def divisors(n):\n divisors = 0\n for num in range(1, n + 1):\n if(n % num == 0):\n divisors += 1\n return divisors", "def divisors(n):\n x = []\n for i in range(1,500001):\n if n % i == 0:\n x.append(i)\n else:\n continue\n return len(x)\n", "def divisors(n):\n a = list(range(n));\n a.pop(0);\n c = [];\n for i in a:\n if n%i == 0:\n c.append(i);\n return(len(c) + 1);", "def divisors(n):\n return len([n//i for i in range(1,n+1) if n%i==0])", "def divisors(n):\n j = 0\n for i in range (1, n+1):\n if n % i == 0:\n j += 1\n else:\n j\n return j\n pass", "def divisors(n):\n count = 0\n div = 1\n while div <= n:\n if n %div == 0:\n count += 1\n div += 1\n return count", "def divisors(n):\n import math\n a = 0\n for i in range(n):\n if i >= 1:\n if n % i == 0:\n a += 1\n return a + 1", "def divisors(n):\n res=[]\n i=1\n while i<=n:\n if n%i==0:\n res.append(i)\n i=i+1\n return len(res)", "def divisors(n):\n count=0\n for x in range(n):\n if n % (x+1) == 0:\n count +=1\n return count\n", "def divisors(n):\n count = 0\n n = int(n)\n for num in range(1,n+1):\n if n % num == 0:\n count += 1\n return count", "def divisors(n):\n list = []\n for i in range(1,500000):\n if n % i == 0:\n list.append(i)\n return len(list)", "def divisors(n):\n a = []\n for y in range(1,500000):\n if n % y == 0:\n a.append(y)\n return len(a)", "def divisors(n):\n i = 1\n lt = []\n while i <= n : \n if (n % i==0) : \n lt.append(i)\n i = i + 1\n return len(lt)", "import math\ndef divisors(n):\n cnt = 0\n for i in range(1,n + 1,1):\n if n % i == 0:\n if n / i == i:\n cnt = cnt + 1\n else: # Otherwise count both \n cnt = cnt + 1\n return cnt \n \n", "def divisors(n):\n temp = []\n for i in range(1, 600000):\n if n % i == 0:\n temp.append(i)\n return len(temp)", "def divisors(n):\n a = 0\n for i in range(1, 500001):\n if n % i == 0:\n a += 1\n \n return a\n", "def divisors(n):\n cnt = 0\n for num in range(1,n):\n if n % num == 0:\n cnt+=1\n return cnt+1", "def divisors(n):\n divs = 1\n print(round(n/2))\n for i in range(1, round(n/2)+1):\n if n % i == 0: divs+=1\n return divs", "def divisors(n):\n num = 0\n for i in range(1,n+1):\n if n % i == 0:\n num += 1\n else:\n continue\n return num\n pass", "def divisors(n):\n \n return len([x for x in range(1,n+1, 1) if (n/x).is_integer()])\n", "def divisors(n):\n import math\n res = set()\n max_divisor = int(math.sqrt(n))\n for i in range(1, max_divisor+1):\n if n % i == 0:\n res.add(i)\n res.add(n/i)\n return len(res)", "def divisors(n):\n count = 1\n for i in range(1, n // 2 + 1):\n if not n % i:\n count += 1\n return count"] | {"fn_name": "divisors", "inputs": [[1], [4], [5], [12], [25], [30], [4096]], "outputs": [[1], [3], [2], [6], [3], [8], [13]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 14,344 |
def divisors(n):
|
e2cb454d343e95c726d517cf0c2fb026 | UNKNOWN | For a pole vaulter, it is very important to begin the approach run at the best possible starting mark. This is affected by numerous factors and requires fine-tuning in practice. But there is a guideline that will help a beginning vaulter start at approximately the right location for the so-called "three-step approach," based on the vaulter's body height.
This guideline was taught to me in feet and inches, but due to the international nature of Codewars, I am creating this kata to use metric units instead.
You are given the following two guidelines to begin with:
(1) A vaulter with a height of 1.52 meters should start at 9.45 meters on the runway.
(2) A vaulter with a height of 1.83 meters should start at 10.67 meters on the runway.
You will receive a vaulter's height in meters (which will always lie in a range between a minimum of 1.22 meters and a maximum of 2.13 meters). Your job is to return the best starting mark in meters, rounded to two decimal places.
Hint: Based on the two guidelines given above, you will want to account for the change in starting mark per change in body height. This involves a linear relationship. But there is also a constant offset involved. If you can determine the rate of change described above, you should be able to determine that constant offset. | ["def starting_mark(height):\n return round(9.45 + (10.67 - 9.45) / (1.83 - 1.52) * (height - 1.52), 2)", "# The linear relashionship is obvious taking a couple a informations (L1,H1) and (L2,H2)\n# One gets 3.9354838709677433 = (H1-H2)/(L1-L2) and beta = H1-3.9354838709677433*H1\n\ndef starting_mark(height):\n return round(3.9354838709677433*height+3.4680645161290293,2)", "A = (10.67-9.45) / (1.83-1.52)\nB = 9.45 - A*1.52\n\ndef starting_mark(height):\n return round(A * height + B, 2)", "def starting_mark(h):\n return round((3.9356133666666666666666*h)+3.46809,2)", "def starting_mark(height):\n slope = 3.93548387\n intercept = 3.46806452\n return round(height*slope + intercept,2)\n", "def starting_mark(height):\n #define gradient for our equation\n m = (10.67 - 9.45) / (1.83 - 1.52)\n #define our y-intercept for our equation\n c = 10.67 - (m*1.83)\n #plug height into our formula and return value\n return round(m*height+c,2)", "starting_mark = lambda h, s=3.93548, c=3.46807: round(c+s*h, 2)", "def starting_mark(height):\n return round( 1.22 / 0.31 * (height + 0.8812), 2 )", "import numpy as np\nfrom sklearn.linear_model import LinearRegression\n\ndef starting_mark(h):\n \n X, Y = np.array([1.52, 1.83]).reshape(-1, 1), np.array([9.45, 10.67])\n model = LinearRegression().fit(X, Y)\n theta0 = model.intercept_\n theta1 = model.coef_\n \n return round(theta0.item() +theta1.item() *h, 2)\n\n", "((x1, y1), (x2, y2)) = ((1.52, 9.45), (1.83, 10.67))\n\ndef starting_mark(height):\n return round((height - x1) / (x2 - x1) * (y2 - y1) + y1, 2)", "def starting_mark(height):\n return round(height * 3.9354839 + 3.4680645, 2)", "def starting_mark(height):\n if(height < 1.52):\n change_height = 1.52-height\n change_runway = (1.22/float(0.31))*change_height\n return round((9.45-change_runway),2)\n else:\n change_height = height - 1.52\n change_runway = (1.22/float(0.31))*change_height\n return round((9.45 + change_runway),2)\n #your code here\n", "def starting_mark(height):\n return round((122 / 31) * height + (9.45 - 1.52 * (122 / 31)), 2)", "import math\ndef starting_mark(h):\n x=(10.67-9.45)/(1.83-1.52)\n return round((x*h+10.67-x*1.83),2)", "def starting_mark(height):\n return round(3.4681 + 3.93548 * height, 2)", "def starting_mark(height):\n slp = (10.67 - 9.45) / (1.83 - 1.52)\n cst = 9.45 - slp * 1.52\n return round( slp * height + cst, 2 )", "m, c = 3.93548, 3.46806\ndef starting_mark(height):\n return round(m*height + c,2)", "def starting_mark(height):\n m = 1.2200000000000006 / 0.31000000000000005\n print(height)\n return round(m*(height-1.52) + 9.45, 2)", "def starting_mark(height):\n answers = {\n 1.21:8.23,\n 1.22:8.27,\n 1.23:8.31,\n 1.24:8.35,\n 1.25:8.39,\n 1.26:8.43,\n 1.27:8.47,\n 1.28:8.51,\n 1.29:8.54,\n 1.3:8.58,\n 1.31:8.62,\n 1.32:8.66,\n 1.33:8.7,\n 1.34:8.74,\n 1.35:8.78,\n 1.36:8.82,\n 1.37:8.86,\n 1.38:8.90,\n 1.39:8.94,\n 1.4:8.98,\n 1.41:9.02,\n 1.42:9.06,\n 1.43:9.1,\n 1.44:9.14,\n 1.45:9.17,\n 1.46:9.21,\n 1.47:9.25,\n 1.48:9.29,\n 1.49:9.33,\n 1.5:9.37,\n 1.51:9.41,\n 1.52:9.45,\n 1.53:9.49,\n 1.54:9.53,\n 1.55:9.57,\n 1.56:9.60,\n 1.57:9.65,\n 1.58:9.69,\n 1.59:9.73,\n 1.6:9.76,\n 1.61:9.8,\n 1.62:9.84,\n 1.63:9.88,\n 1.64:9.92,\n 1.65:9.96,\n 1.66:10,\n 1.67:10.04,\n 1.68:10.08,\n 1.69:10.12,\n 1.7:10.16,\n 1.71:10.2,\n 1.72:10.24,\n 1.73:10.28,\n 1.74:10.32,\n 1.75:10.36,\n 1.76:10.39,\n 1.77:10.43,\n 1.78:10.47,\n 1.79:10.51,\n 1.8:10.55,\n 1.81:10.59,\n 1.82:10.63,\n 1.83:10.67,\n 1.84:10.71,\n 1.85:10.75,\n 1.86:10.79,\n 1.87:10.83,\n 1.88:10.87,\n 1.89:10.91,\n 1.9:10.95,\n 1.91:10.98,\n 1.92:11.03,\n 1.93:11.06,\n 1.94:11.1,\n 1.95:11.14,\n 1.96:11.18,\n 1.97:11.22,\n 1.98:11.26,\n 1.99:11.3,\n 2:11.34,\n 2.01:11.38,\n 2.02:11.42,\n 2.03:11.46,\n 2.04:11.5,\n 2.05:11.54,\n 2.06:11.58,\n 2.07:11.61,\n 2.08:11.65,\n 2.09:11.69,\n 2.1:11.73,\n 2.11:11.77,\n 2.12:11.81,\n 2.13:11.85\n }\n \n return answers.get(height, None)\n", "def starting_mark(height):\n x1, y1 = 1.52, 9.45\n x2, y2 = 1.83, 10.67\n slope = (y2-y1)/(x2-x1)\n c = y2 - slope * x2\n return round(height * slope + c,2)", "def starting_mark(height):\n x = 1.22/.31\n f = 9.45 - 1.52*x\n return round(height*x + f, 2)", "def starting_mark(height):\n # y = kx+d\n k = (10.67-9.45)/(1.83- 1.52)\n d = 9.45-k*1.52 \n return round(k*height+d,2)", "def starting_mark(height):\n a = (10.67 - 9.45) / (1.83 - 1.52)\n b = 10.67 - (1.22 / 0.31) * 1.83\n return round(height * a + b, 2)", "def starting_mark(height):\n return round(height*122/31+189/20-38*122/775, 2)", "def starting_mark(height):\n return round(height*3.935483870967742 + 3.468064516129031,2)", "def starting_mark(height):\n # y = ax + c\n a = (9.45 - 10.67) / (1.52 - 1.83)\n c = 9.45 - a * 1.52\n return round(a * height + c, 2) ", "def starting_mark(height):\n return round(3.935483871 * height + 3.468064516, 2)", "def starting_mark(height):\n return round(height * (1.22 / 0.31) + (9.45 - (1.22 / 0.31) * 1.52), 2)", "def starting_mark(height):\n HEIGHT_1 = 1.52\n HEIGHT_2 = 1.83\n START_MARK_1 = 9.45\n START_MARK_2 = 10.67\n \n # y = k*x + m\n k = (START_MARK_2 - START_MARK_1) / (HEIGHT_2 - HEIGHT_1)\n m = START_MARK_1 - k * HEIGHT_1 \n y = k * height + m\n \n return round(y, 2)", "def starting_mark(height):\n slope = (9.45 - 10.67) / (1.52 - 1.83)\n intercept = 9.45 - (1.52 * slope)\n return round(slope * height + intercept, 2)", "def f(x):\n return 3.93548 * x + 3.468072\n\ndef starting_mark(height):\n return round(f(height), 2)", "def starting_mark(height):\n# return round(height * 3.937 +3.4655,2)\n return round((height /0.0254*3.937+136.43)*0.0254,2)", "import math\ndef starting_mark(height):\n if height == 1.22: \n return 8.27;\n elif height == 2.13:\n return 11.85;\n else: \n return round((8.27 + 0.0393444 * ((height - 1.22) * 100)),2) \n\n", "def starting_mark(height):\n return round(3.935483870967742 * height + 3.468064516129031, 2)", "def starting_mark(height):\n return round(3.9355*height + 3.468065,2)", "def starting_mark(height):\n return round(8.27+(height-1.22)*3.9340659, 2)", "def starting_mark(h):\n return round((1.22)/(.31)*h +3.4680, 2)", "def starting_mark(height):\n return round(10.67-(10.67-9.45)/(1.83-1.52)*(1.83-height), 2)", "def starting_mark(height):\n #return round(height*3.9354838709677433 + 3.4680645161290293,2)\n return round(height*(10.67-9.45)/(1.83-1.52) + 3.4680645161290293 ,2)", "k = 3.935483870967742\nb = 3.468064516129031\n\ndef starting_mark(height):\n return round(k * height + b, 2)", "def starting_mark(height):\n return round(3.935483870967741 * height + 3.468064516129033,2)", "def starting_mark(height):\n \n m = (10.67 - 9.45) / (1.83 - 1.52)\n return round((((m * height + 10.67 - m * 1.83) * 100) / 100),2)", "def starting_mark(height):\n \"\"\" y = mx+b, always has, always will.\"\"\"\n slope = (10.67 - 9.45)/(1.83-1.52) #(d-d0)/(h - h0)\n return round(slope*(-1.83 + height) + 10.67,2)\n", "def starting_mark(height):\n #your code here\n #slope of line = (y2 - y1) / (x2 - x1)\n slope = (10.67 - 9.45) / (1.83 - 1.52)\n #substitute slope and one set of x,y to find the y-intercept C\n #y = mx + c -> c = y - mx\n c = 10.67 - (slope * 1.83)\n #for the given x, return mx + c, rounded off to 2 decimals\n return round(slope * height + c, 2)\n", "def starting_mark(height):\n return round((10.67 - 9.45) / (1.83-1.52) * height + 10.67 - 1.83 * ((10.67 - 9.45) / (1.83-1.52)), 2)", "def starting_mark(height):\n\n height_1 = 1.52\n height_2 = 1.83\n start_1 = 9.45\n start_2 = 10.67\n \n v_constant = (start_2 - start_1) / (height_2 - height_1)\n \n start = start_1 + v_constant * (height - height_1)\n \n return round(start,2)", "def starting_mark(height):\n\n height_1 = 1.52\n height_2 = 1.83\n start_1 = 9.45\n start_2 = 10.67\n \n v_constant = (start_2 - start_1) / (height_2 - height_1)\n \n if height < height_1:\n start = start_1 - v_constant * (height_1 - height)\n elif height < height_2:\n start = start_2 - v_constant * (height_2 - height)\n else:\n start = start_2 + v_constant * (height - height_2)\n \n return round(start,2)", "# Line equation calculated by Wolfram|Alpha\n\ndef starting_mark(height):\n return round(3.93548 * height + 3.46806, 2)", "def starting_mark(height):\n if height <= 1.52:\n res = 9.45 - ((1.52 - height) * (10.67 - 9.45) / (1.83 - 1.52))\n elif 1.52 < height <= 1.83:\n res = 10.67 - ((1.83 - height) * (10.67 - 9.45) / (1.83 - 1.52))\n else:\n res = 10.67 + ((height - 1.83) * (10.67 - 9.45) / (1.83 - 1.52))\n return round(res, 2)", "def starting_mark(height):\n return round(((3.9354*height) + 3.4680)+.0001,2)", "import math\n\ndef starting_mark(height):\n \n d = (height-1.22)*3.934+8.27\n \n return round(d,2)\n \n", "def starting_mark(height):\n gradient = (10.67-9.45)/(1.83-1.52)\n return round(9.45+gradient*(height-1.52),2)", "def starting_mark(h):\n return round((3.935484*h+3.468065),2)", "def starting_mark(height):\n #your code here\n return round(9.45 + (10.67 - 9.45) / (1.83 - 1.52) * (height - 1.52), 2)\n \n \n \n \n# def starting_mark(height):\n# return round(9.45 + (10.67 - 9.45) / (1.83 - 1.52) * (height - 1.52), 2)\n", "starting_mark=lambda n:round(n*3.935+3.469,2)", "x = (9.45-10.67)/(1.52-1.83)\na = 9.45-1.52*x\ndef starting_mark(h):\n return round(a+x*h,2)", "def starting_mark(height):\n return round(height*3.9340659340659343 + 3.4704395604395604,2)", "def starting_mark(height):\n return round(((height - (1.52-(0.31/1.22)*9.45))/(0.31/1.22)),2)", "def starting_mark(height):\n return round(3.9344 * height + 3.47, 2)", "def starting_mark(height):\n slope = 1.22 / 0.31\n offset = 9.45 - slope*1.52\n result = round(slope * height + offset, 2)\n return result", "import math\ndef starting_mark(height):\n k = (10.67 - 9.45) / (1.83 - 1.52)\n b = 9.45 - k * 1.52\n y = k * height + b\n return round(y, 2)", "def starting_mark(height: float) -> float:\n return round((1.22 / 0.31) * (height - 1.52) + 9.45, 2)\n", "def starting_mark(height):\n return round(((((10.67 - 9.45) / (1.83 - 1.52) * height + 10.67 - (10.67 - 9.45) / (1.83 - 1.52) * 1.83) * 100) / 100),2)", "def starting_mark(height):\n #your code here\n return round(height*1.22/0.31+9.45-1.22*1.52/0.31, 2)", "def starting_mark(height):\n return round(3.9355*height+3.4680, 2)", "R = (10.67 - 9.45) / (1.83 - 1.52)\n\ndef starting_mark(height):\n return round(height * R + 3.468, 2)", "x=3.468064516129032\ndef starting_mark(height):\n return round(height*(3.935483870967742)+x,2)", "def starting_mark(height):\n return round(height*3.935483870967742+3.4680645161290323, 2)", "def starting_mark(height):\n gradient = (10.67-9.45)/(1.83-1.52)\n c = 10.67 - (gradient * 1.83)\n return round(gradient*height+c,2)", "\ndef starting_mark(height):\n return round(8.27+(height-1.22)*3.935,2)", "def starting_mark(height):\n c=(1.83*9.45-10.67*1.52)/(1.83-1.52)\n x=(9.45-c)/1.52\n return round(x*height+c,2)\n", "def starting_mark(height):\n #Oof\n return round(9.45 + (10.67 - 9.45) / (1.83 - 1.52) * (height - 1.52), 2)", "def starting_mark(height):\n return round((1.22 * height / 0.31) + 3.468, 2)", "def starting_mark(height):\n return round((height-1.22)*3.9354838709677419354838709677419+8.27,2)", "def starting_mark(height):\n return round(1.22/0.31 * height + (1.0751/0.31),2)", "def starting_mark(height):\n #your code here\n m=3.9355\n c=3.4680\n return round(m*height+c,2)", "def starting_mark(height):\n \n m = (10.67-9.45)/(1.83-1.52)\n c = 10.67 - m*1.83\n \n return round(height*m+c,2)\n", "starting_mark=lambda h: round(9.45+(10.67-9.45)/(1.83-1.52)*(h-1.52), 2)", "def starting_mark(height):\n #your code here\n # 9.45-1.52 =7.93 10.67-1.83= 8.84\n # 9.45 = m(1.52) + b // 10.67 = m(1.83) + b\n # 1.22 = 0.31m ==> 3.94 = m and b = 3.46\n m = 1.22/0.31\n b = 10.67 - (1.83*m)\n return float(\"{:.2f}\".format(round(m*height+b,2)))\n", "def starting_mark(height):\n\n h1 = 1.52\n d1 = 9.45\n \n h2 = 1.83\n d2 = 10.67\n \n v = (d2 - d1) / (h2 - h1)\n \n return round(d2 - v * (h2 - height),2)", "def starting_mark(height):\n l = 3.93548387\n l1 = 3.46806452\n return round(height*l + l1,2)", "def starting_mark(height):\n return float(format(8.27 + (height-1.22)*3.58/0.91, '.2f'))", "def starting_mark(height):\n return round(3.470421640055+height*3.934119,2)\n", "def starting_mark(height):\n slope = (10.67-9.45)/(1.83-1.52)\n if height < 1.52:\n return round(9.45-(1.52-height)*slope, 2)\n elif height < 1.83:\n return round(10.67-(1.83-height)*slope, 2)\n else:\n return round(10.67+(height-1.83)*slope, 2)", "def starting_mark(height):\n slope = (10.67 - 9.45) / (1.83 - 1.52)\n intercept = 9.45 - 1.52 * slope\n return round(slope * height + intercept, 2)", "import math\ndef starting_mark(height):\n constant = (10.67 -9.45)/(1.83-1.52)\n return round((constant*height +10.67 -constant*1.83),2)", "def starting_mark(height):\n return round((3.934065934065934 * height) + 3.47043956043956, 2)", "def starting_mark(height):\n # 10.67 = 1.83*a + b\n # 9.45 = 1.52*a + b\n # ------------------ -\n # 1.22 = 0.31*a\n # a = 3.93548\n a = 1.22 / 0.31\n b = 9.45-1.52*a\n return round(a*height + b,2)", "def starting_mark(height):\n print (height)\n return round(height*3.9355+3.468,2)", "def starting_mark(height):\n return round((1.22 * height + 1.0751) / .31, 2)", "def starting_mark(height):\n a=(10.67-9.45)/(1.83-1.52)\n return round((9.45+a*(height-1.52)),2)#your code here", "def starting_mark(height):\n return round(height*3.935483870967742 + 3.468064516129032, 2)", "def starting_mark(height):\n return round(height*1.22/.31 + 3.468065,2)", "from decimal import Decimal\n\n\ndef starting_mark(height):\n\n# if height == 1.22:\n# return 8.27\n# elif height == 2.13:\n# return 11.85\n \n number = Decimal(\"0.03935483870967741935483870968\")\n start = Decimal(\"8.27\")\n height = Decimal(height)\n min_height = Decimal(\"1.22\")\n \n form = (height - min_height) * 100 * number + start\n form = form.quantize(Decimal(\"1.00\"))\n form = float(form)\n return form", "def starting_mark(height):\n x=3.935484\n y=3.468065\n \n return round(height*x+y,2)", "def starting_mark(height):\n m = (10.67 - 9.45) / (1.83 - 1.52)\n c = 10.67 - m * 1.83\n return round(m * height + c, 2)", "def starting_mark(h):\n return round(starting_mark.k*h+starting_mark.d, 2)\nstarting_mark.eg = [(1.52,9.45),(1.83,10.67)]\nstarting_mark.k = (starting_mark.eg[1][1]-starting_mark.eg[0][1])/(starting_mark.eg[1][0]-starting_mark.eg[0][0])\nstarting_mark.d = starting_mark.eg[0][1]-starting_mark.k*starting_mark.eg[0][0]", "def starting_mark(height):\n return round((height - 1.22) * 3.58 / 0.91 + 8.27, 2)", "def starting_mark(height):\n d = (10.67-9.45)/(1.83-1.52)\n return round(10.67 - d*(1.83-height), 2)\n", "def starting_mark(height):\n return round((9.45 + (height - 1.52) * (10.67 - 9.45)/(1.83 - 1.52)) * 100.0) / 100.0"] | {"fn_name": "starting_mark", "inputs": [[1.52], [1.83], [1.22], [2.13], [1.75]], "outputs": [[9.45], [10.67], [8.27], [11.85], [10.36]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 16,344 |
def starting_mark(height):
|
8de055cbd00c65589e319a85d5310490 | UNKNOWN | Complete the function that accepts a valid string and returns an integer.
Wait, that would be too easy! Every character of the string should be converted to the hex value of its ascii code, then the result should be the sum of the numbers in the hex strings (ignore letters).
## Examples
```
"Yo" ==> "59 6f" ==> 5 + 9 + 6 = 20
"Hello, World!" ==> 91
"Forty4Three" ==> 113
``` | ["def hex_hash(code):\n return sum(int(d) for c in code for d in hex(ord(c)) if d.isdigit())", "def hex_hash(s):\n return sum(sum(int(c) for c in hex(ord(c))[2:] if c in \"0123456789\") for c in s)", "def hex_hash(code):\n first = ''\n for i in code :\n first += hex(ord(i))[2:]\n second = ''\n for i in first :\n if i.isdigit() :\n second += i\n last = 0\n for i in second:\n last += int(i)\n return last", "def hex_hash(code):\n return sum(int(d) for c in code for d in f\"{ord(c):x}\" if d.isdecimal())\n", "def hex_hash(code):\n return sum(sum(int(d) for d in hex(ord(c)) if d.isdigit()) for c in code)", "def hex_hash(code):\n return sum( int(d) for d in ''.join(map(hex, map(ord, code))) if d.isdigit() )", "def hex_hash(code):\n return sum( int(d) for d in ''.join(hex(ord(c)) for c in code) if d.isdigit() )", "def hex_hash(code):\n r=0\n for c in code:\n for d in hex(ord(c))[2:]:\n if d.isdigit():\n r+=int(d)\n return r", "def hex_hash(code):\n res=''.join(list(map(hex, map(ord,code))))\n return sum(int(x) for x in res if x.isdigit())", "from re import sub\ndef hex_hash(code):\n return sum(sum(map(int,sub(\"[^0-9]\",\"\",hex(ord(c))))) for c in code)"] | {"fn_name": "hex_hash", "inputs": [["kcxnjsklsHskjHDkl7878hHJk"], [""], ["ThisIsATest!"], ["dhsajkbfyewquilb4y83q903ybr8q9apf7\\9ph79qw0-eq230br[wq87r0=18-[#20r370B 7Q0RFP23B79037902RF79WQ0[]]]"]], "outputs": [[218], [0], [120], [802]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,290 |
def hex_hash(code):
|
37a11955428191e3d3af4c61d2dde89b | UNKNOWN | Create a function that returns the average of an array of numbers ("scores"), rounded to the nearest whole number. You are not allowed to use any loops (including for, for/in, while, and do/while loops). | ["def average(array):\n return round(sum(array) / len(array))", "from statistics import mean\n\ndef average(array):\n return round(mean(array))", "from statistics import mean\ndef average(array):\n return int(round(mean(array), 0))", "from numpy import mean\ndef average(array):\n return round(mean(array))", "def average(array):\n print(array)\n return int(round(sum(array)/len(array)))", "from statistics import mean as m1\nfrom numpy import mean as m2, average as m3\n\n# Take your pick\ndef average(array):\n return round(sum(array) / len(array))\n return round(m1(array))\n return round(m2(array))\n return round(m3(array))", "import numpy\ndef average(array):\n return round(numpy.mean(array))", "import numpy\ndef average(array):\n return round(numpy.average(array))", "def average(scores):\n return round(sum(scores)/len(scores))", "def average(a):\n return round(sum(a) / len(a))"] | {"fn_name": "average", "inputs": [[[5, 78, 52, 900, 1]], [[5, 25, 50, 75]], [[2]], [[1, 1, 1, 1, 9999]], [[0]]], "outputs": [[207], [39], [2], [2001], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 932 |
def average(array):
|
62d466bee6315774356cccd70b2efde4 | UNKNOWN | ## Task
You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.
## Example
For `arr = [1, 1, 1]`, the output should be `3`.
## Input/Output
- `[input]` integer array `arr`
Constraints:
`3 ≤ inputArray.length ≤ 100,`
`-10000 ≤ inputArray[i] ≤ 10000.`
- `[output]` an integer
The minimal number of moves needed to obtain a strictly increasing sequence from inputArray.
It's guaranteed that for the given test cases the answer always fits signed 32-bit integer type. | ["from functools import reduce\n\narray_change = lambda arr: reduce(lambda a, u: (max(a[0] + 1, u), a[1] + max(0, a[0] - u + 1)), arr, (-10001, 0))[1]", "def array_change(arr):\n if not arr: return 0\n x, y = arr[0], 0\n for i in arr[1:]:\n x = max(x + 1, i)\n y += x - i\n return y", "def array_change(arr):\n m, s = 0, arr[0]\n for i in arr[1:]:\n if s >= i:\n s += 1\n m += s - i\n else:\n s = i\n return m\n", "def array_change(arr):\n count=0\n for i in range(len(arr)-1):\n if arr[i]>=arr[i+1]:\n count+=arr[i]-arr[i+1]+1\n arr[i+1]+=arr[i]-arr[i+1]+1\n return count", "def array_change(arr):\n count=0\n for i in range(len(arr)-1):\n if arr[i]==arr[i+1]:\n arr[i+1]+=1\n count+=1\n elif arr[i]>arr[i+1]:\n count+=arr[i]-arr[i+1]+1\n arr[i+1]+=arr[i]-arr[i+1]+1\n return count", "def array_change(arr):\n moves=0\n for i in range(len(arr)-1):\n if arr[i+1]<=arr[i]:\n diff=arr[i]-arr[i+1]+1\n arr[i+1]+=diff\n moves+=diff\n return moves", "def array_change(arr):\n res = 0\n for i, x in enumerate(arr[1:], start=1): \n inc = max(x, 1+max(arr[:i])) - x\n arr[i] += inc\n res += inc\n return res", "def array_change(a):\n c = 0\n for i in range(1,len(a)):\n if a[i]<=a[i-1]:\n c += (a[i-1]-a[i])+1\n a[i] = a[i-1]+1\n return c", "def array_change(arr):\n move = 0\n for i in range(1, len(arr)):\n if arr[i] <= arr[i - 1]:\n move += arr[i - 1] - arr[i] + 1\n arr[i] += arr[i - 1] - arr[i] + 1\n return move\n", "def array_change(arr):\n p, r = arr[0], 0\n for x in arr[1:]:\n if x <= p:\n r += p - x + 1\n x = p + 1\n p = x\n return r"] | {"fn_name": "array_change", "inputs": [[[1, 1, 1]], [[-1000, 0, -2, 0]], [[2, 1, 10, 1]], [[2, 3, 3, 5, 5, 5, 4, 12, 12, 10, 15]]], "outputs": [[3], [5], [12], [13]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,910 |
def array_change(arr):
|
ed4b6a2487bdbaf9c94083c02e2861bb | UNKNOWN | A hero is on his way to the castle to complete his mission. However, he's been told that the castle is surrounded with a couple of powerful dragons! each dragon takes 2 bullets to be defeated, our hero has no idea how many bullets he should carry.. Assuming he's gonna grab a specific given number of bullets and move forward to fight another specific given number of dragons, will he survive?
Return True if yes, False otherwise :) | ["def hero(bullets, dragons):\n return bullets >= dragons * 2", "def hero(bullets, dragons):\n '''\n Ascertains if hero can survive\n Parameters:\n bullets: (int) - number of bullets hero has\n dragons: (int) - number of dragons\n Returns:\n True (Survive) or False (Hero gets killed)\n '''\n if bullets >= 2*dragons:\n return True\n elif bullets < 2*dragons:\n return False\n", "def hero(bullets, dragons):\n return dragons <= bullets / 2", "def hero(bullets, dragons):\n return bullets >= 2*dragons", "def hero(bullets, dragons):\n return bullets / 2 >= dragons", "def hero(bullets, dragons):\n return dragons * 2 <= bullets", "hero = lambda b,d: 2*d<=b\n", "def hero(bullets, dragons):\n return (bullets / dragons) >= 2 if dragons > 0 else False", "def hero(bullets, dragons):\n return bullets / dragons >=2 if dragons else False\n", "def hero(bullets, dragons):\n return True if bullets / 2 >= dragons else False", "def hero(bullets, dragons):\n dead_dragons = bullets/2\n if dragons > dead_dragons:\n return False\n else:\n return True", "def hero(bullets: int, dragons: int) -> bool:\n \"\"\"\n Can the hero survive?\n It takes 2 bullets to kill a dragon\n Parameters:\n bullets (int): number of bullets\n dragons (int): number of dragons\n Returns:\n True (Lives) or False (Dies)\n \"\"\"\n return bullets >= (dragons * 2)", "hero = lambda _,__:__*2<=_", "def hero(bullets, dragons):\n while bullets >0:\n if bullets / dragons >= 2:\n return True\n break\n return False", "def hero(bullets, dragons):\n if bullets >= 2*dragons:\n return(True)\n pass\n else:\n return(False)\n pass", "def hero(bullets, dragons):\n survival = None\n if dragons == 0:\n survival = True\n elif bullets/dragons >= 2:\n survival = True\n else:\n survival = False\n return survival", "hero = lambda b,d: b/2-d>=0", "hero = lambda b,d: b-d*2>-1", "def hero(b, d):\n return b >= 2 * d", "def hero(bullets, dragons):\n if bullets/dragons >= 2:\n return True\n else:\n return False", "def hero(bullets, dragons):\n if dragons * 2 > bullets:\n return False\n else:\n return True", "def hero(bullets, dragons):\n if bullets >= dragons *2:\n return True \n else: \n\n return False", "def hero(bullets, dragons):\n return bullets - dragons >= dragons", "def hero(bullets, dragons):\n p = bullets >= 2*dragons\n return p", "def hero(bullets, dragons):\n return bullets >= dragons + dragons", "def hero(bullets, dragons):\n if dragons==0: return False\n if bullets/dragons>2 or bullets/dragons==2 or dragons==0 : return True\n else: return False", "def hero(bullets, dragons):\n try:\n return bullets / dragons >= 2\n except ZeroDivisionError:\n return True", "def hero(bullets, dragons):\n return bullets // 2 >= dragons", "def hero(bullets, dragons):\n return\n\ndef hero(bullets, dragons): \n return bullets / 2 >= dragons", "def hero(bullets, dragons): \n if int(bullets) / int(dragons) >= 2:\n return True\n else:\n return False ", "def hero(bullets, dragons):\n \n \n A =int(bullets)\n B =int(dragons)\n if A >= 2*B:\n \n return True \n \n else:\n \n return False", "def hero(bullets, dragons):\n if bullets > dragons:\n if bullets//dragons >=2:\n return True\n else:\n return False\n else:\n return False", "def hero(bullets, dragons):\n required = dragons * 2\n if required > bullets:\n return False\n else:\n return True\n", "def hero(bullets, dragons):\n for i in range(dragons):\n bullets -= 2\n return bullets >= 0", "def hero(bullets, dragons):\n shots = bullets // 2\n if shots >= dragons:\n return True\n else:\n return False", "def hero(bullets, dragons):\n result = False\n if bullets >= dragons * 2:\n return True \n \n return result\n \n \n", "def hero(bulets, dragons):\n if (bulets/2)>=dragons: \n return True \n else: \n return False\n\n", "def hero(bullets, dragons):\n \n try:\n \n devide = bullets // dragons\n \n except:\n pass\n \n if devide >= 2:\n \n return True\n \n else:\n \n return False\n\n\n\nhero(10, 5)", "def hero(b, d):\n if b-2*d>=0 and b%d>=0:\n return True\n else:\n return False", "def hero(bullets, dragons):\n if bullets == 0 or dragons == 0 :\n return False\n if (bullets/dragons) < 2:\n return False\n return True", "def hero(bullets, dragons):\n return bool( dragons * 2 - bullets <= 0)", "def hero(bullets, dragons):\n return bullets >= 2*dragons\n\nprint (hero(6,3)) ", "def hero(bullets, dragons):\n if bullets >= dragons * 2:\n a = True\n else:\n a = False\n return a", "def hero(bullets, dragons):\n x = bullets\n y = dragons\n if x/2 >= y:\n return True\n else:\n return False\n", "def hero(bullets, dragons):\n if dragons != 0:\n return bullets / dragons >= 2\n elif bullets != 0:\n return False\n return True", "bullets = [*range(0, 10)]\ndragons = [*range(0, 10)]\ndef hero(bullets, dragons):\n if bullets / dragons >= 2:\n return True\n else: return False", "def hero(bullets, dragons):\n return bool(bullets/2-dragons >= 0)", "def hero(bullets, dragons):\n return bullets>dragons*2-1 ", "def hero(bullets, dragons):\n if (bullets != 0 and bullets % dragons == 0) or (bullets != 0 and (bullets - 2 * dragons)) > 0:\n return True\n else:\n return False", "def hero(bullets, dragons):\n if bullets >= (dragons*2):\n survival = True\n else: \n survival = False\n return survival", "def hero(bullets, dragons):\n while True:\n bullets -= 2 \n dragons -= 1 \n if bullets >= 0 and dragons == 0:\n return True\n elif bullets < 0 or dragons < 0:\n return False", "def hero(bullets, dragons):\n survive = True #survive check\n temp_bullets = bullets / 2 #div bullets shott one dragon\n if temp_bullets >= dragons: #if avalible bullets >= dragons then hero win else loose\n survive = True\n else:\n survive = False\n return survive #return survive \n \n \n", "def hero(bullets, dragons):\n if (bullets / 2) > dragons :\n return True\n elif bullets == 0:\n return False\n else:\n return bullets % dragons == 0 and bullets / dragons == 2", "def hero(bullets, dragons):\n if dragons > 0:\n if bullets // dragons >= 2:\n return True\n \n return False", "def hero(bullets, dragons):\n if bullets > dragons and bullets >= dragons * 2:\n return True\n else:\n return False ", "def hero(bullets, dragons):\n x=bullets/dragons\n if x==2:\n return True\n else:\n if (bullets/2) > dragons:\n return True\n else:\n return False\n", "def hero(bullets, dragons):\n if bullets>dragons *2 -1:\n return (True)\n else:\n return (False)", "def hero(bullets, dragons):\n\n def teki(dragons):\n return 2*dragons\n\n if bullets > teki(dragons):\n return True\n else:\n if bullets == teki(dragons):\n return True\n else:\n return False", "def hero(bullets, dragons):\n x = bullets \n y = dragons\n if x >= (2 * y):\n return True\n else:\n return False", "def hero(bullets, dragons):\n dragons!=0\n if bullets/dragons < 2: \n result=False\n else :\n result=True\n return result;", "def hero(bullets, dragons):\n return dragons == 0 or bullets/(2*dragons) >= 1", "def hero(bullets, dragons):\n if dragons != 0:\n return (bullets / dragons) >= 2\n else:\n return False", "def hero(bullets, dragons):\n print(bullets, dragons)\n hm = bullets/2\n print(hm)\n if hm >= dragons:\n return True\n else:\n return False", "def hero(bullets, dragons):\n if bullets > 2*dragons or bullets == 2*dragons :\n return True\n else :\n return False", "def hero(bullets, dragons):\n alive = True\n if dragons*2 > bullets:\n alive = False\n else:\n alive = True\n return alive", "def hero(bullets, dragons):\n survive = True\n if bullets / 2 >= dragons:\n survive = True\n else:\n survive = False\n return survive", "def hero(bullets, dragons):\n try:\n return bullets // dragons >= 2\n except ZeroDivisionError:\n return True", "def hero(bullets, dragons):\n return bool(bullets//2 >= dragons)", "def hero(bullets, dragons):\n a = bullets/2\n while a >= dragons:\n return True\n else:\n return False", "def hero(bullets, dragons):\n if bullets >= dragons * 2:\n return True\n if bullets == None:\n return False\n else:\n return False", "def hero(bullets, dragons): #function\n if bullets >= dragons * 2: #number of bullets should be greater than or equal to twice the number of dragons\n return True\n else:\n return False", "def hero(bullets, dragons):\n res = bullets / dragons\n if res >= 2:\n return True\n else:\n return False", "def hero(bullets, dragons):\n print(('bullets are {} and dragons are {}'.format(bullets,dragons)))\n if bullets < 2:\n return False\n \n bulletsNeeded = dragons * 2\n \n if bullets - bulletsNeeded >= 0:\n return True\n else:\n return False\n", "def hero(b, d):\n if b/2 < d:\n return False\n elif b/2 >= d:\n return True", "def hero(bullets, dragons):\n return False if dragons == 0 else True if bullets / dragons >= 2 else False", "def hero(bullets, dragons):\n if bullets//dragons >= 2 and dragons != 0:\n return True\n else:\n return False", "def hero(bullets, dragons):\n kills= bullets/2\n print(kills, dragons)\n if dragons > kills: \n return False\n if dragons <= kills:\n return True", "def hero(bullets, dragons):\n if bullets >= dragons * 2 :\n return True\n if bullets <= dragons * 2 :\n return False", "def hero(bullets, dragons):\n if bullets/dragons >=2 and dragons!=0:\n return True\n else:\n return False\n if dragons==0:\n return True", "def hero(bullets, dragons):\n \n return dragons<1 or bullets//dragons>=2", "def hero(bullets, dragons):\n if dragons:\n return True if bullets / dragons >= 2.0 else False\n else:\n return True", "def hero(bullets, dragons):\n if bullets // 2 >= dragons: \n return True\n else:\n return False\n #pogchamp\n", "def hero(bullets = 0, dragons = 1):\n if bullets >= dragons*2:\n return True\n else:\n return False", "hero = lambda bul, drg: True if bul/drg >= 2 else False", "def hero(bullets, dragons):\n '''\n Dadas una cantidad de balas <bullets> y una cantidad de dragones <dragons>,\n devueve con True o False si esa cantidad de balas puede matar a esa cantidad de dragones.\n El numero necesario para matar un dragon son dos balas.\n '''\n if ( bullets >= 2 * dragons ):\n return True\n else:\n return False", "def hero(bullets,dragons) :\n x=int(dragons)*2\n if int(bullets)<int(x) :\n return False\n elif int(bullets)>=int(x) :\n return True\n", "def hero(bullets, dragons):\n x = True\n if dragons*2 <= bullets:\n return x\n else:\n return False", "def hero(bullets, dragons):\n\n if bullets >= dragons*2:\n return True\n else:\n return False\n return True", "def hero(bullets, dragons):\n if bullets == 0:\n return False\n if bullets < dragons*2:\n return False\n return True\n", "def hero(bullets, dragons):\n return False if dragons << 1 > bullets else True", "def hero(bullets, dragons):\n if dragons >= bullets:\n return False\n elif bullets >= dragons+dragons:\n return True\n else:\n return False", "def hero(bullets, dragons):\n return bullets // (dragons * 2) >= 1", "def hero(bullets, dragons):\n if bullets == 0:\n return False\n return bullets/dragons >= 2", "def hero(bullets, dragons):\n if(bullets/dragons >=2):\n b = True\n else:\n b = False\n \n return b", "def hero(bullets, dragons):\n f = dragons * 2\n return bullets >= f ", "def hero(bullets, dragons):\n return False if dragons == 0 or bullets / dragons < 2 else True", "def hero(bullets, dragons):\n #if there are twice as many bullets as dragons, or more;\n if bullets >= 2 * dragons :\n return True\n else :\n return False", "def hero(b, d):\n if d == 0 or b == 0: return False\n return d/(b)*2 <= 1", "def hero(bullets, dragons):\n if dragons == 0:\n return True\n return True if bullets // dragons >= 2 else False", "def hero(bullets, dragons):\n\n x = dragons * 2\n if x <= bullets:\n return True\n else:\n return False\n"] | {"fn_name": "hero", "inputs": [[10, 5], [7, 4], [4, 5], [100, 40], [1500, 751], [0, 1]], "outputs": [[true], [false], [false], [true], [false], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 13,556 |
def hero(bullets, dragons):
|
a439a038920828f065ddda58411c8458 | UNKNOWN | You are given two strings. In a single move, you can choose any of them, and delete the first (i.e. leftmost) character.
For Example:
* By applying a move to the string `"where"`, the result is the string `"here"`.
* By applying a move to the string `"a"`, the result is an empty string `""`.
Implement a function that calculates the minimum number of moves that should be performed to make the given strings equal.
## Notes
* Both strings consist of lowercase latin letters.
* If the string is already empty, you cannot perform any more delete operations. | ["def shift_left(a, b):\n r = len(a) + len(b)\n for i in range(-1, -min(len(a), len(b)) - 1, -1):\n if a[i] != b[i]:\n break\n r -= 2\n return r", "def shift_left(a, b):\n r = 0\n while a != b:\n if len(b) > len(a):\n b = b[1::] \n r += 1\n else:\n a = a[1::]\n r += 1\n \n return r", "def shift_left(a, b, n=0):\n if a == b:\n return n\n elif len(a)>len(b):\n return shift_left(a[1:], b, n + 1)\n else:\n return shift_left(a, b[1:], n + 1)\n \n", "def shift_left(a, b):\n return min(i+j for i in range(len(a)+1) for j in range(len(b)+1) if a[i:] == b[j:])", "import os\n\ndef shift_left(a, b):\n x = os.path.commonprefix([a[::-1], b[::-1]])\n return len(a) + len(b) - len(x) * 2", "def shift_left(a, b):\n while True:\n if a and b and a[-1] == b[-1]:\n a, b=a[:-1], b[:-1]\n continue\n return len(a)+len(b)\n", "def shift_left(a, b):\n n = 0\n while not b.endswith(a):\n n += 1\n a = a[1:]\n return n + (len(b) - len(a))", "def shift_left(a, b):\n m, n, i = len(a), len(b), -1\n while m > 0 and n > 0 and a[i] == b[i]: i, m, n = i-1, m-1, n-1\n return m + n\n", "def shift_left(a, b):\n return next((len(a) + len(b) - 2*len(b[i:]) for i in range(len(b)) if a.endswith(b[i:])), len(a) + len(b))", "def shift_left(a, b):\n for i in range(len(b)):\n if a.endswith(b[i:]):\n return len(a) + len(b) - 2*len(b[i:])\n return len(a) + len(b)"] | {"fn_name": "shift_left", "inputs": [["test", "west"], ["test", "yes"], ["b", "ab"], ["abacabadabacaba", "abacabadacaba"], ["aaabc", "bc"], ["dark", "d"], ["dadc", "dddc"], ["nogkvcdldfpvlbkpedsecl", "nogkvcdldfpvlbkpedsecl"]], "outputs": [[2], [7], [1], [18], [3], [5], [4], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,583 |
def shift_left(a, b):
|
2484c870eac9c61ed888b4d1cb608154 | UNKNOWN | You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
*Example*
```python
sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
``` | ["def sort_array(arr):\n odds = sorted((x for x in arr if x%2 != 0), reverse=True)\n return [x if x%2==0 else odds.pop() for x in arr]", "def sort_array(source_array):\n odds = iter(sorted(v for v in source_array if v % 2))\n return [next(odds) if i % 2 else i for i in source_array]", "def sort_array(source_array):\n\n odds = []\n answer = []\n \n for i in source_array:\n if i % 2 > 0:\n odds.append(i)\n answer.append(\"X\")\n \n else:\n answer.append(i)\n \n odds.sort()\n \n for i in odds:\n x = answer.index(\"X\")\n answer[x] = i\n return answer\n", "def sort_array(source_array):\n result = sorted([l for l in source_array if l % 2 == 1])\n for index, item in enumerate(source_array):\n if item % 2 == 0:\n result.insert(index, item)\n return result\n", "from collections import deque\n\ndef sort_array(array):\n odd = deque(sorted(x for x in array if x % 2))\n return [odd.popleft() if x % 2 else x for x in array]", "def sort_array(source_array):\n odd = sorted(list(filter(lambda x: x % 2, source_array)))\n l, c = [], 0\n for i in source_array:\n if i in odd:\n l.append(odd[c])\n c += 1\n else:\n l.append(i) \n return l", "def sort_array(source_array):\n\n return [] if len(source_array) == 0 else list(map(int,(','.join(['{}' if a%2 else str(a) for a in source_array])).format(*list(sorted(a for a in source_array if a%2 ==1))).split(',')))", "def sort_array(source_array):\n odd = []\n for i in source_array:\n if i % 2 == 1:\n odd.append(i)\n odd.sort()\n x=0\n for j in range(len(source_array)):\n if source_array[j]%2==1:\n source_array[j]=odd[x]\n x+=1\n \n return source_array\n\n\n", "def sort_array(source_array):\n # Return a sorted array.\n odds = iter(sorted(elem for elem in source_array if elem % 2 != 0))\n return [next(odds) if el % 2 != 0 else el for el in source_array]", "def sort_array(numbers):\n evens = []\n odds = []\n for a in numbers:\n if a % 2:\n odds.append(a)\n evens.append(None)\n else:\n evens.append(a)\n odds = iter(sorted(odds))\n return [next(odds) if b is None else b for b in evens]"] | {"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, 2, 8, 5, 4, 11]], [[2, 22, 1, 5, 4, 11, 37, 0]], [[1, 1, 5, 11, 2, 11, 111, 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, 5, 8, 7, 6, 9]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,398 |
def sort_array(source_array):
|
950672b8c05bf4a8a99d3fa828135c39 | UNKNOWN | # Pythagorean Triples
A Pythagorean triplet is a set of three numbers a, b, and c where `a^2 + b^2 = c^2`. In this Kata, you will be tasked with finding the Pythagorean triplets whose product is equal to `n`, the given argument to the function `pythagorean_triplet`.
## Your task
In this Kata, you will be tasked with finding the Pythagorean triplets whose product is equal to `n`, the given argument to the function, where `0 < n < 10000000`
## Examples
One such triple is `3, 4, 5`. For this challenge, you would be given the value `60` as the argument to your function, and then it would return the Pythagorean triplet in an array `[3, 4, 5]` which is returned in increasing order. `3^2 + 4^2 = 5^2` since `9 + 16 = 25` and then their product (`3 * 4 * 5`) is `60`.
More examples:
| **argument** | **returns** |
| ---------|---------|
| 60 | [3, 4, 5] |
| 780 | [5, 12, 13] |
| 2040 | [8, 15, 17] | | ["def pythagorean_triplet(n):\n for a in range(3, n):\n for b in range(a+1, n):\n c = (a*a + b*b)**0.5\n if a*b*c > n:\n break\n if c == int(c) and a*b*c == n:\n return [a, b, c]", "def getTriplets(n):\n divs = {y for x in range(1,int(n**.5)+1) for y in (x, n//x) if not n%x}\n for a in divs:\n for b in divs:\n if n/a/b in divs:\n yield sorted((a, b, n/(a*b)))\n\ndef pythagorean_triplet(n):\n return next( [a,b,c] for a,b,c in getTriplets(n) if a**2 + b**2 == c**2 )", "triples = [(3, 4, 5), (5, 12, 13), (8, 15, 17), (7, 24, 25), (20, 21, 29), (12, 35, 37),\n (9, 40, 41), (28, 45, 53), (11, 60, 61), (16, 63, 65), (33, 56, 65), (48, 55, 73),\n (13, 84, 85), (36, 77, 85), (39, 80, 89), (65, 72, 97), (20, 99, 101), (60, 91, 109),\n (15, 112, 113), (44, 117, 125), (88, 105, 137), (17, 144, 145), (24, 143, 145),\n (51, 140, 149), (85, 132, 157), (119, 120, 169), (52, 165, 173), (19, 180, 181),\n (57, 176, 185), (104, 153, 185), (95, 168, 193), (28, 195, 197), (84, 187, 205),\n (133, 156, 205), (21, 220, 221), (140, 171, 221), (60, 221, 229), (105, 208, 233),\n (120, 209, 241), (32, 255, 257), (23, 264, 265), (96, 247, 265), (69, 260, 269),\n (115, 252, 277), (160, 231, 281), (161, 240, 289), (68, 285, 293)]\n\ndef pythagorean_triplet(n):\n for a, b, c in triples:\n a0, b0, c0 = a, b, c\n \n while a * b * c < n:\n a += a0\n b += b0\n c += c0\n \n if a * b * c > n:\n continue\n else:\n return [a, b, c]", "from itertools import combinations\nfrom math import hypot\n\nlimit = 10000000\ncandidates = ((a,b,hypot(a,b)) for a,b in combinations(range(1, 1000), 2))\nD = {a*b*int(c):[a,b,int(c)] for a,b,c in candidates if c.is_integer() and a*b*c < limit}\npythagorean_triplet = D.__getitem__", "def triplet(n):\n for i in range(int(n**0.333), 1, -1):\n if n % i:\n continue\n c = n // i\n for j in range(int(c**0.5), i, -1):\n if c % j or j == c // j:\n continue\n yield (i, j, c // j)\n\ndef pythagorean_triplet(n):\n for a, b, c in triplet(n):\n if a**2 + b**2 == c**2:\n return [a, b, c]", "def pythagorean_triplet(n):\n for k in range(1, int(n ** (1 / 3))):\n if n % k ** 3: continue\n for p in range(1, int((n // k ** 3) ** .2) + 1):\n for q in range(1, p):\n a, b, c = p*p - q*q, 2*p*q, p*p + q*q\n if k**3 * a * b * c == n : return sorted([k*a, k*b, k*c])", "def pythagorean_triplet(n):\n for z in range(1, int(n**0.5) + 1): # z is hypotenuse\n y = n / z # y is a * b\n if y.is_integer():\n x = (z**2 + 2*y) ** 0.5 # (a + b)\n if x.is_integer():\n for a in range(1, int(x)):\n b = x - a\n if a*b == y:\n return sorted([a,b,z])", "def factors(n, limit):\n return [i for i in range(2, limit+1) if n % i == 0]\n\ndef pythagorean_triplet(n):\n for x in factors(n, int(n**(1/3))):\n nn = n // x\n for y in factors(nn, int(nn**(1/2))):\n z = nn // y\n if x*x + y*y == z*z :\n return [x, y, z]", "pythagorean_triplet=lambda n: [[d*round((n/k)**(1/3)) for d in v] for k,v in {60: [3, 4, 5], 780: [5, 12, 13], 2040: [8, 15, 17], 4200: [7, 24, 25], 14760: [9, 40, 41], 15540: [12, 35, 37], 40260: [11, 60, 61], 65520: [16, 63, 65], 66780: [28, 45, 53], 92820: [13, 84, 85], 12180: [20, 21, 29], 120120: [33, 56, 65], 192720: [48, 55, 73], 235620: [36, 77, 85], 277680: [39, 80, 89], 328860: [60, 63, 87], 453960: [65, 72, 97]}.items() if round((n // k)**(1/3))**3 == n / k][0]", "def pythagorean_triplet(n):\n from math import sqrt\n def divisors(n):\n divs = []\n for i in range(2, int(sqrt(n))+1):\n if n % i == 0:\n divs.append(i)\n divs.sort()\n return divs\n divs = divisors(n)\n for a in divs:\n for b in divs:\n c = n // (a * b)\n if a * a + b * b == c * c:\n return [a, b, c]"] | {"fn_name": "pythagorean_triplet", "inputs": [[60], [780], [2040], [4200], [12180], [120120], [192720], [328860], [907200], [1440600]], "outputs": [[[3, 4, 5]], [[5, 12, 13]], [[8, 15, 17]], [[7, 24, 25]], [[20, 21, 29]], [[33, 56, 65]], [[48, 55, 73]], [[60, 63, 87]], [[42, 144, 150]], [[49, 168, 175]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,289 |
def pythagorean_triplet(n):
|
cfb7deffd7e3bf3014ba3ab5acac6fec | UNKNOWN | Define n!! as
n!! = 1 \* 3 \* 5 \* ... \* n if n is odd,
n!! = 2 \* 4 \* 6 \* ... \* n if n is even.
Hence 8!! = 2 \* 4 \* 6 \* 8 = 384, there is no zero at the end.
30!! has 3 zeros at the end.
For a positive integer n, please count how many zeros are there at
the end of n!!.
Example:
count\_zeros\_n\_double\_fact(30) should return 3 | ["def count_zeros_n_double_fact(n): \n if n % 2 != 0:\n return 0\n k = 0\n while n >= 10:\n k += n // 10\n n //= 5\n return k", "def count_zeros_n_double_fact(n):\n return 0 if n%2 == 1 else (n // 6250) + (n // 1250) + (n // 250) + ( n // 50 ) + ( n // 10 ) ", "from functools import reduce\n\n\ndef count_zeros_n_double_fact(n): \n df = n % 2 or reduce(int.__mul__, range(2, n+1, 2), 1)\n return next(i for i, d in enumerate(f\"{df}\"[::-1]) if d != \"0\")", "from math import log\n\n# n//10 + n//50 + n//250 + n//1250 + ...\ndef count_zeros_n_double_fact(n):\n return 0 if n&1 else sum(n//2//5**x for x in range(1, int((log(n)-log(2))/log(5))+1))", "def count_zeros_n_double_fact(n): \n return 0 if n % 2 else sum(n // (10 * 5 ** x) for x in range(len(str(n)) + 1))", "def count_zeros_n_double_fact(n):\n if n % 2: return 0\n s, n = 0, n // 2\n while n >= 5:\n n //= 5\n s += n\n return s", "def count_zeros_n_double_fact(n): \n if (n % 2 == 1): \n return 0\n res = 0\n working = n // 2\n while (working > 0): \n res += working // 5\n working //= 5\n return res", "def count_zeros_n_double_fact(n): \n if n % 2 == 1:\n return 0\n return n // 10 + n // 50 + n // 250", "def count_zeros_n_double_fact(n): \n fact = 1\n while n > 2:\n fact *= n\n n -= 2\n return len(str(fact)) - len(str(fact).rstrip('0'))"] | {"fn_name": "count_zeros_n_double_fact", "inputs": [[8], [30], [487], [500]], "outputs": [[0], [3], [0], [62]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,453 |
def count_zeros_n_double_fact(n):
|
68f959091bab9095ff255e0fe43d19b0 | UNKNOWN | Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `0` will be considered even.
For example, `capitalize("abcdef") = ['AbCdEf', 'aBcDeF']`. See test cases for more examples.
The input will be a lowercase string with no spaces.
Good luck!
If you like this Kata, please try:
[Indexed capitalization](https://www.codewars.com/kata/59cfc09a86a6fdf6df0000f1)
[Even-odd disparity](https://www.codewars.com/kata/59c62f1bdcc40560a2000060) | ["def capitalize(s):\n s = ''.join(c if i%2 else c.upper() for i,c in enumerate(s))\n return [s, s.swapcase()]", "def capitalize(s):\n result = ['','']\n for i,c in enumerate(s):\n result[0] += c.lower() if i % 2 else c.upper()\n result[1] += c.upper() if i % 2 else c.lower()\n return result", "def capitalize(s):\n word = \"\"\n output = []\n for n in range(0, len(s)):\n if n%2==0:\n word = word+s[n].upper()\n else:\n word = word+s[n]\n output.append(word)\n output.append(word.swapcase())\n return output", "def capitalize(s):\n return [''.join(c if (k + i) % 2 else c.upper() for i, c in enumerate(s)) for k in [0, 1]]", "def capitalize(s):\n arr, arr1 = list(s), list(s)\n arr[::2], arr1[1::2] = s[::2].upper(), s[1::2].upper() \n return [''.join(arr), ''.join(arr1)]", "def capitalize(s):\n return [''.join(x if i % 2 else x.upper() for i, x in enumerate(s)), ''.join(x.upper() if i % 2 else x for i, x in enumerate(s))]", "def capitalize(s):\n index = 0\n string1 = \"\"\n string2 = \"\"\n for i in s:\n if index % 2 == 0:\n string1 += i.upper()\n string2 += i\n index += 1\n else:\n string1 += i\n string2 += i.upper()\n index += 1\n return [string1, string2]", "def capitalize(s):\n s1 = ''.join(s[i].upper() if i%2 == 0 else s[i] for i in range(0, len(s)))\n s2 = ''.join(s[i].upper() if i%2 != 0 else s[i] for i in range(0, len(s)))\n return [s1, s2]", "def capitalize(s):\n a=''\n for i,v in enumerate(s):\n a += v.upper() if i%2==0 else v\n return [a, a.swapcase()]", "def capitalize(s):\n alternate =\"\".join(x.lower() if c%2==1 else x.upper() for c,x in enumerate(s))\n return [alternate,alternate.swapcase()]", "from itertools import cycle\n\n\ndef capitalize(s):\n func = cycle((str.upper, str.lower))\n result = ''.join(next(func)(a) for a in s)\n return [result, result.swapcase()]\n", "capitalize=lambda s:[''.join(chr(ord(c)-i%2*32)for i,c in enumerate(s,n))for n in[1,0]]", "def capitalize(s):\n return [''.join([c,c.upper()][i%2] for i,c in enumerate(s,a)) for a in (1,0)]", "capitalize=lambda s,f=lambda s,p:''.join(e if i%2==p else e.upper()for i,e in enumerate(s)):[f(s,1),f(s,0)]", "def capitalize(s):\n lst1=[]\n for n in range(0,len(s)):\n if n%2==0:\n lst1.append(s[n].upper())\n else:\n lst1.append(s[n].lower())\n return [''.join(lst1),''.join(lst1).swapcase()]\n", "def capitalize(s):\n odd = []\n even = []\n\n for i in range(0, len(s)):\n if i % 2 == 0:\n odd.append(s[i].upper())\n else:\n odd.append(s[i])\n\n for i in range(0, len(s)):\n if not i % 2 == 0:\n even.append(s[i].upper())\n else:\n even.append(s[i])\n\n return [''.join(odd), ''.join(even)]", "def capitalize(s):\n even = \"\".join(w.upper() if i%2 else w.lower() for i,w in enumerate(s))\n odd = \"\".join(w.lower() if i%2 else w.upper() for i,w in enumerate(s))\n return [odd, even]", "def capitalize(s):\n s1, s2 = '', ''\n for i in range(len(s)): \n if i % 2 == 0: \n s1 += s[i].capitalize()\n s2 += s[i]\n else: \n s1 += s[i]\n s2 += s[i].capitalize()\n \n return [s1, s2]", "def capitalize(s):\n d = str(s)\n \n w = ''\n f = ''\n g = []\n\n for i in range(len(d)):\n if i % 2 == 0:\n w += d[i].upper()\n else:\n w += d[i]\n for i in range(len(d)):\n if i % 2 == 0:\n f += d[i].lower()\n else:\n f += d[i].upper()\n g.append(w)\n g.append(f)\n\n\n\n\n return g\n", "def capitalize(s):\n s.lower()\n z = s.__len__()\n count = 1\n i = 0\n new_one = ''\n new_two = ''\n while i < z:\n if (i +1) %2 == 0 and i > 0:\n new_one = new_one.ljust(count,str(s[i].upper()))\n new_two = new_two.ljust(count, str(s[i]))\n count =count + 1\n i = i + 1\n else:\n new_two = new_two.ljust(count, str(s[i].upper()))\n new_one = new_one.ljust(count, str(s[i]))\n count = count + 1\n i = i + 1\n answer = [new_two,new_one]\n return answer", "def capitalize(s):\n a1 = \"\"\n a2 = \"\"\n for i, v in enumerate(s, 1):\n if i % 2:\n a1 += v.upper()\n a2 += v.lower()\n else:\n a1 += v.lower()\n a2 += v.upper()\n return [a1, a2]", "def capitalize(s):\n i = 0\n ret = []\n for _ in range(2):\n alt = ''\n for e in s:\n alt += [e.upper(),e.lower()][i]\n i = not i\n ret.append(alt)\n i = [not i, i][len(alt)%2]\n return ret", "def capitalize(s):\n ret = [''] * 2\n for i in range(len(s)):\n ret[i % 2] += s[i].upper()\n ret[(i + 1) % 2] += s[i]\n return ret", "def capitalize(s):\n alt, out = [0, 1], [list(s), list(s)]\n for i in alt:\n for j in range(len(s)):\n if j % 2 == i:\n out[i][j] = out[i][j].upper()\n return [''.join([x for x in y]) for y in out]", "def capitalize(s):\n Even = ''\n Odd = ''\n Result = []\n \n for i in range(len(s)):\n if i % 2 == 0:\n Even += s[i].upper()\n else:\n Even += s[i] \n if i % 2 != 0:\n Odd += s[i].upper()\n else:\n Odd += s[i]\n\n \n\n Result.append(Even)\n Result.append(Odd)\n \n return Result;\n", "def capitalize(s):\n vars = []\n for num in range(2):\n buf = ''\n for ind in range(len(s)):\n if ind % 2 == num:\n buf += s[ind].upper()\n else:\n buf += s[ind]\n vars.append(buf)\n return vars", "def capitalize(s):\n return [''.join(s[i].upper() if i % 2 == 0 else s[i] for i in range(len(s))), ''.join(s[i].upper() if i % 2 != 0 else s[i] for i in range(len(s)))]", "capitalize=lambda Q:[''.join(V if 1 & F else V.upper() for F,V in enumerate(Q)),''.join(V.upper() if 1 & F else V for F,V in enumerate(Q))]", "def capitalize(s):\n odd = s[::2]\n even = s[1::2]\n if len(odd) != len(even):\n even= even+\" \"\n cap = ''\n for i in range(len(even)):\n cap += odd[i].upper() + even[i]\n cap2 = ''\n for i in range(len(even)):\n cap2 += odd[i] + even[i].upper()\n return [cap.strip(),cap2.strip()]", "def capitalize(s):\n list_a = list(s)\n temp_list1 = []\n temp_list2 = []\n counter = 0\n for i in list_a:\n if counter%2 == 0:\n temp_list1.append(chr(ord(list_a[counter])-32)) #capital letters are 32 below lowercase in table\n else:\n temp_list1.append(list_a[counter])\n counter += 1\n temp_str1 = ''.join(temp_list1) \n counter = 0\n for i in list_a:\n if counter%2 != 0:\n temp_list2.append(chr(ord(list_a[counter])-32)) #capital letters are 32 below lowercase in table\n else:\n temp_list2.append(list_a[counter])\n counter += 1\n temp_str2 = ''.join(temp_list2) \n return [temp_str1 , temp_str2] ", "def capitalize(s):\n even = \"\"\n odd = \"\"\n for ind,char in enumerate(s):\n if ind%2 == 0:\n even += char.upper()\n odd += char\n elif ind%2 != 0:\n odd += char.upper()\n even += char\n return [even, odd]", "def capitalize(s):\n list = []\n ret = \"\"\n i = True # capitalize\n for char in s:\n if i:\n ret += char.upper()\n else:\n ret += char.lower()\n if char != ' ':\n i = not i\n list.append(ret)\n ret2 = ret.swapcase()\n list.append(ret2)\n return list", "def capitalize(s):\n evens = ''\n odds = ''\n for i in range(0,len(s)):\n if i % 2 == 0:\n evens = evens + s[i].upper()\n else:\n evens = evens + s[i]\n for i in range(0,len(s)):\n if i % 2 == 0:\n odds = odds + s[i]\n else:\n odds = odds + s[i].upper()\n return([evens,odds])", "def capitalize(s):\n x=2\n z=2\n string=''\n string2=''\n \n for i,y in zip(s,s):\n if x%2==0:\n string=string + i.upper()\n x+=1\n else:\n string=string + i\n x+=1\n \n if z%2!=0:\n string2=string2 + i.upper()\n z+=1\n else:\n string2=string2 + i\n z+=1\n \n return [string,string2]\n \n", "def capitalize(s): \n abc = ''.join([k.capitalize() for k in[s[i-2:i] for i in range(2,len(s)+2,2)]]) \n return [abc,''.join([a.upper() if a == a.lower() else a.lower() for a in list(abc)])]\n", "def capitalize(s):\n return next([x, x.swapcase()] for x in [''.join(c if i%2 else c.upper() for i, c in enumerate(s))])", "def capitalize(s):\n return [''.join(ch.upper() if i % 2 == 0 else ch for (i, ch) in enumerate(s)), ''.join(ch.upper() if i % 2 == 1 else ch for (i, ch) in enumerate(s))]", "from itertools import cycle\n\ndef capitalize(s):\n fss = map(cycle, ((str.upper, str.lower), (str.lower, str.upper)))\n return [''.join(f(c) for f, c in zip(fs, s)) for fs in fss]", "def capitalize(s):\n st = \"\"\n st1 = \"\"\n for i in range(len(s)):\n if i % 2 == 0:\n st += s[i].upper()\n st1 += s[i].lower()\n else:\n st1 += s[i].upper()\n st += s[i].lower()\n return [st, st1]", "def capitalize(s):\n array = list(s)\n output1, output2 = [], []\n for i, letter in enumerate(array):\n if i % 2 == 0:\n output1.append(letter.upper())\n output2.append(letter.lower())\n else:\n output1.append(letter.lower())\n output2.append(letter.upper())\n output3 = ''.join(output1)\n output4 = ''.join(output2)\n return [output3, output4]", "def capitalize(s):\n s_lower = \"\".join(s.lower() if i%2==0 else s.upper() for i,s in enumerate(s))\n s_upper = \"\".join(s.upper() if i%2==0 else s.lower() for i,s in enumerate(s))\n return [s_upper]+[s_lower]", "def capitalize(s):\n a = \"\".join([char.upper() if not index%2 else char for index, char in enumerate(s)])\n b = \"\".join([char.upper() if index%2 else char for index, char in enumerate(s)])\n return [a, b]", "def capitalize(s):\n al = list(s)\n ab = list(s)\n l = []\n for i in range(0,len(al)):\n if i % 2 == 0:\n al[i] = al[i].upper()\n else:\n ab[i] = al[i].upper()\n l.append(''.join(al))\n l.append(''.join(ab))\n return l", "def capitalize(s):\n new = \"\"\n new1=\"\"\n out = []\n for i in range(len(s)):\n if i%2==0:\n new+=s[i].upper()\n else:\n new+=s[i]\n out.append(new)\n for i in range(len(s)):\n if i%2==0:\n new1+=s[i]\n else:\n new1+=s[i].upper()\n out.append(new1)\n return out\n", "def capitalize(s):\n first = []\n second = []\n\n for i in range(len(s)):\n first.append(s[i].upper() if i % 2 == 0 else s[i].lower())\n\n for j in range(len(s)):\n second.append(s[j].upper() if j % 2 != 0 else s[j].lower())\n\n return [''.join(first), ''.join(second)]", "def capitalize(s):\n ret = \"\"\n ter = \"\"\n i = True \n for char in s:\n if i:\n ret += char.upper()\n else:\n ret += char.lower()\n if char != ' ':\n i = not i\n i = True\n for char in s:\n if not i:\n ter += char.upper()\n else:\n ter += char.lower()\n if char != ' ':\n i = not i\n return [ret,ter]", "def capitalize(s):\n s1 = ''\n s2 = ''\n for i in range(0, len(s)):\n to_add = s[i]\n if i % 2 == 0:\n s1 = s1 + to_add.capitalize()\n s2 = s2 + to_add\n else:\n s2 = s2 + to_add.capitalize()\n s1 = s1 + to_add\n\n return [s1,s2]\n\n return [s1,s2]\n \n \n", "def capitalize(s):\n case_1 = ''\n case_2 = ''\n for i in range(len(s)):\n if i % 2 == 0:\n case_1 += s[i].upper()\n else:\n case_1 += s[i].lower()\n for i in range(len(s)):\n if i % 2 == 0:\n case_2 += s[i].lower()\n else:\n case_2 += s[i].upper()\n return [case_1, case_2]", "def capitalize(s):\n newString, secondString = \"\", \"\"\n for i, j in enumerate(s):\n if i % 2 == 0:\n newString += j.upper()\n else:\n newString += j\n for i, j in enumerate(s):\n if i % 2 == 0:\n secondString += j\n else:\n secondString += j.upper()\n return [newString, secondString]\n", "def capitalize(s):\n even_arr = ''\n \n for even in range(0, len(s)):\n if(even % 2 == 0):\n even_arr += s[even].upper()\n else:\n even_arr += s[even]\n \n return [even_arr, even_arr.swapcase()]\n", "def capitalize(s):\n return [''.join([v.upper() if i%2==0 else v for i,v in enumerate(s)]), ''.join([v.upper() if i%2==1 else v for i,v in enumerate(s)])]", "def capitalize(s):\n a1 = a2 = \"\"\n for i in range(len(s)):\n if i % 2 == 0:\n a1 += s[i].upper()\n a2 += s[i]\n else:\n a2 += s[i].upper()\n a1 += s[i]\n return [a1, a2]", "def capitalize(s):\n f1 = ''\n f2 = ''\n result = []\n \n for i,v in enumerate(s):\n if i == 0 or i % 2 == 0:\n f1+=v.upper()\n else:\n f1+=v.lower()\n result.append(f1)\n \n for j,v in enumerate(s):\n if j == 0 or j % 2 == 0:\n f2+=v.lower()\n else:\n f2+=v.upper()\n result.append(f2)\n\n return result", "def capitalize(s):\n evens = []\n g = 0\n \n for char in s:\n if g % 2 == 0: evens.append(char.title())\n else: evens.append(char)\n g+=1\n \n odds = [x.swapcase() for x in evens]\n return [\"\".join(evens), \"\".join(odds)]", "def capitalize(s):\n a=''\n b=''\n for i in range(len(s)):\n if i%2!=1:\n a=a+s[i].upper()\n b=b+s[i]\n else:\n a=a+s[i]\n b=b+s[i].upper()\n return [a,b]\n pass", "def capitalize(s):\n final1 = \"\"\n final2 = \"\"\n \n for x in range(len(s)): #1st string\n final1 += s[x].upper() if x%2==0 else s[x]\n \n for x in final1: #toggle 1st string to get the 2ns string\n final2 += x.lower() if x.isupper() else x.upper()\n \n return [final1,final2]", "def capitalize(s):\n str1 = ''\n str2 = ''\n for i,c in enumerate(s):\n if not i % 2:\n str1 += c.upper()\n str2 += c.lower()\n else:\n str2 += c.upper()\n str1 += c.lower()\n return [str1, str2]", "def capitalize(s):\n even = ''\n odd = ''\n count = 0\n for i in s:\n if count % 2 == 0:\n even += i.upper()\n odd += i\n else:\n even += i\n odd += i.upper()\n count += 1\n lst = []\n lst.append(even)\n lst.append(odd)\n return lst\n", "def capitalize(s):\n lst = [\"\",\"\"]\n for i in range(0,len(s)):\n if i % 2 == 0:\n lst[0] += s[i].upper()\n lst[1] += s[i]\n else:\n lst[1] += s[i].upper()\n lst[0] += s[i]\n return lst\n \n", "def capitalize(s):\n new1 = \"\"\n new2 = \"\"\n for i in range(len(s)):\n if i%2 == 0:\n new1 += s[i].upper()\n new2 += s[i]\n else:\n new1 += s[i]\n new2 += s[i].upper()\n return [new1, new2]", "def capitalize(s):\n a=\"\"\n big=True\n for i in s:\n if big==True:\n i=i.upper()\n big=False\n else:big=True\n a+=i\n b=\"\"\n big=False\n for i in s:\n if big==True:\n i=i.upper()\n big=False\n else:big=True\n b+=i\n return [a, b]", "def capitalize(s):\n x, y = \"\", \"\"\n for i, j in enumerate(s):\n if i % 2 == 0:\n x += j.upper()\n y += j.lower()\n else:\n y += j.upper()\n x += j.lower()\n return [x, y]", "def capitalize(s):\n l=[]\n x=\"\"\n for i in range(len(s)):\n if i%2==0:\n j=s[i].capitalize()\n x+=j\n else:\n x+=s[i]\n w=\"\"\n for i in range(len(s)):\n if not i%2==0:\n k=s[i].capitalize()\n w+=k\n else:\n w+=s[i]\n l.append(x)\n l.append(w)\n return l ", "def capitalize(s):\n odd,even = [], []\n for i,a in enumerate(s):\n if i%2==0:\n even.append(a.capitalize())\n odd.append(a)\n else:\n even.append(a)\n odd.append(a.capitalize())\n \n return [''.join(even)] + [''.join(odd)]", "def capitalize(s):\n cap1 = [s[i].upper() if not i % 2 else s[i] for i in range(len(s))]\n cap2 = [s[i].upper() if i % 2 else s[i] for i in range(len(s))]\n return [''.join(cap1), ''.join(cap2)]\n\n", "def capitalize(s):\n return [\"\".join([s[i].lower() if i%2 else s[i].upper() for i in range(len(s))]), \"\".join([s[i].upper() if i%2 else s[i].lower() for i in range(len(s))])]", "def capitalize(s):\n lst=[]\n print(s)\n a,b='',''\n for i in range( len(s) ):\n if i%2==0 or i==0:\n a=a+s[i].upper()\n else:\n a=a+s[i]\n for i in range( len(s) ):\n if i%2!=0 :\n b=b+s[i].upper()\n else:\n b=b+s[i] \n lst.append(a)\n lst.append(b)\n return lst", "def capitalize(s):\n \n l = list(s)\n s_1 = ''\n s_2 = ''\n \n #1st string in new list\n \n for i in range(len(l)):\n if i % 2 == 0:\n l[i] = l[i].capitalize()\n else:\n pass\n s_1 += l[i]\n \n return [s_1, s_1.swapcase()]", "def capitalize(s):\n s1 = ''.join(a.upper() if i % 2 == 0 else a for i,a in enumerate(s))\n s2 = ''.join(a.upper() if i % 2 != 0 else a for i,a in enumerate(s))\n return [s1,s2]", "def capitalize(s):\n my_string_1 = ''\n my_string_2 = ''\n i = 0\n for char in s:\n if i % 2 == 0:\n my_string_1 += s[i].upper()\n my_string_2 += s[i]\n i = i + 1 \n elif i % 2 != 0:\n my_string_1 += s[i]\n my_string_2 += s[i].upper()\n i = i + 1 \n\n arr = []\n arr.append(my_string_1)\n arr.append(my_string_2)\n return arr ", "def capitalize(s):\n s=list(s)\n even = [ ]\n for i in range(len(s)):\n if i%2==0:\n even.append(s[i].upper())\n else:\n even.append(s[i])\n even=\"\".join(even)\n \n odd = [ ]\n for i in range(len(s)):\n if i%2==0:\n odd.append(s[i])\n else:\n odd.append(s[i].upper())\n odd=\"\".join(odd)\n \n return [even,odd]\n \n", "def capitalize(s):\n i = 0\n s1 = ''\n s2 = ''\n while i < len(s):\n if i % 2 == 0:\n s1 += s[i].upper()\n s2 += s[i].lower()\n else:\n s1 += s[i].lower()\n s2 += s[i].upper()\n i += 1\n return [s1, s2]", "def capitalize(s):\n #given a string \n#capitalize the letters in the even positions\n#capitalize those that are in odd positions separately\n#0 is even\n# given a string of letters\n# when a letter occupy the even indexes\n# then capitalise\n even=[]\n odd=[]\n final=[]\n for i in range(len(s)):\n if i%2==0:\n a=s[i].capitalize()\n even.append(a)\n else:\n even.append(s[i])\n for i in range(len(s)):\n if i%2 != 0:\n b=s[i].capitalize()\n odd.append(b)\n else:\n odd.append(s[i])\n finaleven =''.join(even)\n finalodd =''.join(odd)\n final.append(finaleven)\n final.append(finalodd)\n return final\n\n\n", "def capitalize(s):\n x=\"\"\n for i in range(len(s)):\n if i%2==0 :\n x=x+s[i].upper()\n else:\n x=x+s[i].lower()\n y=\"\"\n for i in range(len(s)):\n if i%2==0 :\n y=y+s[i].lower()\n else:\n y=y+s[i].upper()\n return [x,y]\n \n \n", "def capitalize(s):\n #BDD\n #Given a sring\n #When capitalize letters with even indexes\n \n #ps\n #3lists \n #for loop thet will loop through the string\n #If statement\n even=[]\n odd=[]\n final=[]\n for i in range(len(s)):\n if i % 2 ==0:\n a = s[i].capitalize()\n even.append(a)\n else:\n even.append(s[i])\n for i in range(len(s)):\n if i % 2 != 0:\n b = s[i].capitalize()\n odd.append(b)\n else:\n odd.append(s[i])\n finaleven = ''.join(even)\n finalodd = ''.join(odd)\n final.append(finaleven)\n final.append(finalodd)\n return final\n", "def capitalize(s):\n res = ''.join([s[i] if i % 2 else s[i].upper() for i in range(len(s))])\n return [res, res.swapcase()]", "def capitalize(s):\n even = ''\n odd = ''\n for i, c in enumerate(s):\n if i % 2 == 0:\n even += c.upper()\n odd += c\n else:\n even += c\n odd += c.upper()\n \n return [even, odd]", "def capitalize(s):\n return [\"\".join([s[i].upper() if not (i + k) % 2 else s[i] for i in range(len(s))]) for k in [0, 1]]\n", "def capitalize(s):\n s = ''.join([s[i] if i%2 else s[i].upper() for i in range(len(s))])\n return [s,s.swapcase()]", "def capitalize(s):\n s = ''.join([s[i].lower() if i%2 else s[i].upper() for i in range(len(s))])\n return [s,s.swapcase()]", "def capitalize(s):\n a = ''.join([s[i].lower() if i%2 else s[i].upper() for i in range(len(s))])\n b = ''.join([s[i].upper() if i%2 else s[i].lower() for i in range(len(s))])\n return [a,b]", "def capitalize(s):\n return [''.join([(j, j.upper())[i%2==0] for i, j in enumerate(s)]), \n ''.join([(j, j.upper())[i%2==1] for i, j in enumerate(s)])]", "def capitalize(s):\n result = \"\"\n for index in range(len(s)):\n if not index % 2:\n result += s[index].upper()\n else:\n result += s[index].lower()\n arr = []\n arr.append(result)\n arr.append(result.swapcase())\n return arr\n \n", "def capitalize(s):\n x = []\n b = ''\n for i in range(len(s)):\n if i %2==0:\n c = s[i].upper()\n b += c\n else:\n c = s[i].lower()\n b += c\n x.append(b)\n d = b.swapcase()\n x.append(d)\n return x", "def capitalize(s):\n string_even, string_odd = [], []\n for i, n in enumerate(s):\n if i % 2 == 0:\n string_even.append(n.upper())\n else:\n string_even.append(n)\n\n for i, n in enumerate(s):\n if i % 2 != 0:\n string_odd.append(n.upper())\n else:\n string_odd.append(n)\n return [''.join(string_even), ''.join(string_odd)]\n\n\"\"\"\ndef capitalize(s):\n string_even = ''.join([c.upper() if not (i % 2) else c for i, c in enumerate(x)])\n string_odd = ''.join([c.upper() if i % 2 else c for i, c in enumerate(x)])\n return [string_even, string_odd]\n\"\"\" \n\n\n\n\n\n", "def capitalize(s):\n x = list(s)\n y = [x[n].upper() if n%2==0 else x[n] for n,i in enumerate(x) ]\n z = [x[n].upper() if n%2==1 else x[n] for n,i in enumerate(x) ]\n return [''.join(y),''.join(z)]", "def capitalize(s):\n o1 = ''\n o2 = ''\n uf = True\n for c in s:\n if uf:\n o1 += (c.upper())\n o2 += (c)\n uf = False\n else:\n o2 += (c.upper())\n o1 += (c)\n uf = True\n return [o1, o2]", "def capitalize(s):\n s = s.lower()\n even_str = ''\n for i in range(len(s)):\n if i % 2 == 0:\n even_str += s[i].upper()\n else:\n even_str += s[i]\n return [even_str, even_str.swapcase()]", "def capitalize(s):\n new_string = \"\"\n new_string1 = \"\"\n for i in range(len(s)): \n if i%2 == 0: \n new_string += s[i].upper() \n else: \n new_string += s[i]\n for j in range(len(s)):\n if j%2 != 0:\n new_string1 += s[j].upper()\n else:\n new_string1 += s[j]\n return [f\"{new_string}\", f\"{new_string1}\"]", "def capitalize(s):\n st = list(s)\n caps = []\n for i in range(1,len(st),2):\n st[i] = st[i].upper()\n caps.append(''.join(st))\n st = list(s)\n for i in range(0,len(st),2):\n st[i] = st[i].upper()\n caps.append(''.join(st))\n return caps[::-1]", "def capitalize(str):\n resArr = []\n def one(string):\n resStr = \"\"\n for index in range(len(string)):\n if index % 2 == False:\n resStr = resStr + string[index].upper()\n else:\n resStr = resStr + string[index].lower()\n return resStr\n def two(string):\n resStr = \"\"\n for index in range(len(string)):\n if index % 2 == False:\n resStr = resStr + string[index].lower()\n else:\n resStr = resStr + string[index].upper()\n return resStr\n resArr.append(one(str))\n resArr.append(two(str))\n return resArr\n \n", "def capitalize(s):\n p = len(s)\n newar = []\n o=\"\"\n e=\"\"\n for i in range(0,p):\n if i&1:\n e+=s[i].upper()\n o+=s[i]\n else:\n e+=s[i]\n o+=s[i].upper()\n newar.append(o)\n newar.append(e)\n return newar", "def capitalize(s):\n return [''.join([c if k % 2 else c.upper() for k, c in enumerate(s)]), ''.join([c.upper() if k % 2 else c for k, c in enumerate(s)])]", "def capitalize(s):\n x = \"\".join([i[1] if i[0]%2==0 else i[1].upper() for i in enumerate(s)])\n y = \"\".join([i[1].upper() if i[0]%2==0 else i[1] for i in enumerate(s)])\n return [y,x]", "def capitalize(s):\n result = []\n first = ''\n for c in range(len(s)):\n if c % 2 == 0:\n first += s[c].capitalize()\n else:\n first += s[c]\n second = ''\n for c in range(len(s)):\n if c % 2 == 0:\n second += s[c]\n else:\n second += s[c].capitalize()\n return [first, second]", "def capitalize(s):\n even = ''\n odd = ''\n bigArr = []\n for i in range(len(s)) :\n if(i % 2 == 0) :\n even += s[i].upper()\n odd += s[i].lower()\n else:\n even += s[i].lower()\n odd += s[i].upper()\n return [even, odd]", "def capitalize(s):\n return [''.join([char.lower() if i%2 == 1 else char.upper() for i, char in enumerate(s) ]), ''.join([char.lower() if i%2 == 0 else char.upper() for i, char in enumerate(s)])]", "def capitalize(s):\n t1=''\n t2=''\n for i,j in enumerate(s):\n if i%2==0:\n t1+=j.upper()\n t2+=j\n else:\n t1+=j\n t2+=j.upper()\n return [t1,t2]", "def capitalize(s):\n s1=\"\"\n s2=\"\"\n index=0\n k=0\n l=[]\n for i in s:\n if index%2==0:\n s1+=i.upper()\n else:\n s1+=i\n index+=1\n for j in s:\n if k%2!=0:\n s2+=j.upper()\n else:\n s2+=j\n k+=1\n l.append(s1)\n l.append(s2)\n return l\n \n \n", "def capitalize(s):\n first = \"\".join(v.upper() if i % 2 == 0 else v for i, v in enumerate(s))\n second = \"\".join(v.upper() if i % 2 != 0 else v for i, v in enumerate(s))\n return [first, second]"] | {"fn_name": "capitalize", "inputs": [["abcdef"], ["codewars"], ["abracadabra"], ["codewarriors"], ["indexinglessons"], ["codingisafunactivity"]], "outputs": [[["AbCdEf", "aBcDeF"]], [["CoDeWaRs", "cOdEwArS"]], [["AbRaCaDaBrA", "aBrAcAdAbRa"]], [["CoDeWaRrIoRs", "cOdEwArRiOrS"]], [["InDeXiNgLeSsOnS", "iNdExInGlEsSoNs"]], [["CoDiNgIsAfUnAcTiViTy", "cOdInGiSaFuNaCtIvItY"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 28,461 |
def capitalize(s):
|
cfe55c43e62586e7692691c5491acf0b | UNKNOWN | This is simple version of harder [Square Sums](/kata/square-sums).
# Square sums
Write function `square_sums_row` (or `squareSumsRow`/`SquareSumsRow` depending on language rules) that, given integer number `N` (in range `2..43`), returns array of integers `1..N` arranged in a way, so sum of each 2 consecutive numbers is a square.
Solution is valid if and only if following two criterias are met:
1. Each number in range `1..N` is used once and only once.
2. Sum of each 2 consecutive numbers is a perfect square.
### Example
For N=15 solution could look like this:
`[ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ]`
### Verification
1. All numbers are used once and only once. When sorted in ascending order array looks like this:
`[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]`
2. Sum of each 2 consecutive numbers is a perfect square:
```
16 16 16 16 16 16 16
/+\ /+\ /+\ /+\ /+\ /+\ /+\
[ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ]
\+/ \+/ \+/ \+/ \+/ \+/ \+/
9 25 9 25 9 25 9
9 = 3*3
16 = 4*4
25 = 5*5
```
If there is no solution, return `false` (or, `None` in scala). For example if `N=5`, then numbers `1,2,3,4,5` cannot be put into square sums row: `1+3=4`, `4+5=9`, but
`2` has no pairs and cannot link `[1,3]` and `[4,5]`
# Have fun!
Harder version of this Kata is [here](/kata/square-sums). | ["def square_sums_row(n):\n\n def dfs():\n if not inp: yield res\n for v in tuple(inp):\n if not res or not ((res[-1]+v)**.5 % 1):\n res.append(v)\n inp.discard(v)\n yield from dfs()\n inp.add(res.pop())\n\n inp, res = set(range(1,n+1)), []\n return next(dfs(), False)", "def square_sums_row(n):\n r=[]\n def dfs(r):\n if len(r)==n:return 1\n for i in range(1,n+1):\n if not len(r) or (i not in r and not(i+r[-1])**.5%1):\n r.append(i)\n if dfs(r):return 1\n r.pop()\n return 0\n return r if dfs(r) else 0", "# ==========================================================================================================================================\n# title : squares, v2: faster with dictionnary instead of graph\n# description :\n# author : JR\n# date : 28.04.20\n# version :\n# IDE : PyCharm\n# ==========================================================================================================================================\nimport math\n\n# code standard graphs (dirty-duct-copy networkx behavior)\nclass nx(dict):\n @staticmethod\n def empty_graph(nodes):\n return nx(nodes)\n\n @staticmethod\n def squares_graph(n=23):\n square_candidates = [(x+1)**2 for x in range(1, math.floor(math.sqrt(2*n-1)))]\n G = nx.empty_graph(list(range(1, n+1)))\n\n for s in square_candidates:\n true_indexes = [x for x in range(1, 1+math.floor((s-1) / 2)) if s-x <= n]\n for k in true_indexes:\n G.add_edge(k, s-k)\n\n return G\n\n @staticmethod\n def Graph(G):\n # here we will implement the by-copy\n return nx(G.copy())\n\n def __init__(self, nodes, edges=None):\n if edges is None:\n if isinstance(nodes, dict):\n # by-copy => this one should not really be used for our problem, but it is simpler at the beginning to be able to concentrate\n # on the central matter\n dict.__init__(self, {n: e.copy() for n,e in list(nodes.items())})\n else:\n dict.__init__(self, {n: set() for n in nodes})\n else:\n dict.__init__(self, {nodes[i]: edges[i] for i in range(len(nodes))})\n\n def add_edge(self, x, y):\n self[x] |= {y}\n self[y] |= {x}\n\n def remove_edge(self, x, y):\n self[x] -= {y}\n self[y] -= {x}\n\n def remove_node(self, n):\n edges = self[n].copy()\n for e in edges:\n self.remove_edge(n, e)\n\n del self[n]\n\n def display(self):\n import matplotlib.pyplot as plt\n import networkx as true_nx\n plt.clf()\n true_nx.draw(true_nx.Graph(G), labels={x: x for x in G.nodes})\n plt.show()\n\n @property\n def nodes(self):\n return list(self.keys())\n\n @property\n def degree(self):\n return {(n, len(e)) for n, e in list(self.items())}\n\n\ndef square_sums_row(n):\n return dfs_travel(n)\n\n\ndef dfs_travel(G=23, visit_ordered=None, N=None, display=False, verbose=False):\n if isinstance(G, int):\n G = nx.squares_graph(G)\n\n if N is None:\n N = len(G.nodes)\n\n if visit_ordered is None:\n visit_ordered = []\n\n if len(visit_ordered) == N:\n if verbose:\n print('SUCCESS')\n return visit_ordered\n\n impossible_nodes = [n for n, d in G.degree if d == 0]\n if len(impossible_nodes) > 0:\n return False\n ending_nodes = [n for n, d in G.degree if d == 1]\n\n if len(ending_nodes) > 2:\n return False\n\n if len(visit_ordered) == 0:\n\n # We do the best guess to visit nodes by random... starting by most certain ones\n if len(ending_nodes) > 0:\n if verbose:\n print('Guess zero')\n return dfs_travel(G, [ending_nodes[-1]], N, verbose=verbose) # if two, it will arrive at the second node !\n\n degrees = G.degree\n max_degree = max([y for x, y in degrees])\n for d in range(2, max_degree+1):\n for n in [nd for nd, deg in degrees if deg == d]:\n sol = dfs_travel(G, [n], verbose=verbose)\n if sol != False: # don't want the unsafe \"if sol\" with list\n if verbose:\n print('YESSS')\n return sol\n\n if verbose:\n print('Exhausted guesses')\n return False\n\n elif len(ending_nodes) == 2 and not visit_ordered[-1] in ending_nodes:\n return False\n\n G2 = nx.Graph(G) # copy the graph... will need to improve if >100 graphs are needed !\n\n last_idx = visit_ordered[-1]\n for current_idx in G2[last_idx]: #.keys():\n if verbose:\n print((last_idx, current_idx))\n visit_ordered.append(current_idx)\n if verbose:\n print(visit_ordered)\n G3 = nx.Graph(G2)\n G3.remove_node(last_idx)\n sol = dfs_travel(G3, visit_ordered, N, verbose=verbose)\n\n if sol != False:\n return visit_ordered\n\n visit_ordered.pop()\n if verbose:\n print(visit_ordered)\n print((len(visit_ordered) - N))\n return False\n", "def square_sums_row(n):\n def dfs():\n if not n: yield r\n for p in tuple(n):\n if not r or not ((r[-1]+p)**.5 % 1):\n r.append(p)\n n.discard(p)\n yield from dfs()\n n.add(r.pop())\n n, r = set(range(1,n+1)), []\n return next(dfs(), False)", "squares = {x**2 for x in range(10)}\n\ndef square_sums_row(n):\n def rec(x, L):\n if not L:\n return x and [x]\n for i,y in enumerate(L):\n if x==0 or x+y in squares:\n test = rec(y, L[:i]+L[i+1:])\n if test:\n return (x and [x] or []) + test\n return False\n return rec(0, list(range(1, n+1)))", "from math import sqrt\n\nclass Graph:\n def __init__(self, connections):\n self.n = len(connections)\n self.connections = connections\n self.adjacency_matrix = [[0] * (self.n) for _ in range(self.n)]\n\n for i, j in enumerate(self.connections):\n for k in j:\n self.adjacency_matrix[i][k - 1] = 1\n\n def hamilton(self):\n for i in range(self.n):\n visited = [False] * self.n\n path = []\n\n def _hamilton(curr):\n path.append(curr)\n if len(path) == self.n:\n return True\n\n visited[curr] = True\n for next in range(self.n):\n if self.adjacency_matrix[curr][next] == 1 and not visited[next]:\n if _hamilton(next):\n return True\n visited[curr] = False\n path.pop()\n return False\n\n if _hamilton(i):\n return [n + 1 for n in path]\n\n return False\n\ndef square_sums_row(n):\n connections = []\n temp = []\n for i in range(1, n + 1):\n for j in range(1, n + 1):\n if sqrt(i + j).is_integer():\n temp.append(j)\n connections.append([*temp])\n temp.clear()\n\n g = Graph(connections)\n return g.hamilton()\n", "ans = [0 for i in range(44)]\nhash1 = [False for i in range(44)]\n\ndef Dfs(num, cnt):\n\n if(num == cnt):\n return True\n\n for i in range(1, cnt + 1):\n if not hash1[i] and (not((i + ans[num])**0.5%1)):\n ans[num + 1] = i\n hash1[i] = True\n if Dfs(num + 1, cnt): return True\n hash1[i] = False\n return False\n\n\ndef square_sums_row(n):\n for i in range(1, n + 1):\n for j in range(1, n + 1):\n hash1[j] = False\n ans[1] = i\n hash1[i] = True\n if Dfs(1, n):\n return ans[1: n + 1]\n\n return False", "def square_sums_row(n):\n solutions = {\n 15: [9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8],\n 16: [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8],\n 17: [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17],\n 30: [18, 7, 29, 20, 16, 9, 27, 22, 14, 2, 23, 26, 10, 6, 30, 19, 17, 8, 28, 21, 4, 5, 11, 25, 24, 12, 13, 3, 1, 15],\n 31: [31, 18, 7, 29, 20, 16, 9, 27, 22, 14, 2, 23, 26, 10, 6, 30, 19, 17, 8, 28, 21, 4, 5, 11, 25, 24, 12, 13, 3, 1, 15],\n 32: [1, 8, 28, 21, 4, 32, 17, 19, 30, 6, 3, 13, 12, 24, 25, 11, 5, 31, 18, 7, 29, 20, 16, 9, 27, 22, 14, 2, 23, 26, 10, 15],\n 33: [2, 23, 26, 10, 6, 30, 19, 17, 8, 28, 21, 15, 1, 3, 13, 12, 24, 25, 11, 14, 22, 27, 9, 16, 33, 31, 18, 7, 29, 20, 5, 4, 32],\n 34: [1, 8, 17, 32, 4, 5, 11, 25, 24, 12, 13, 3, 33, 31, 18, 7, 29, 20, 16, 9, 27, 22, 14, 2, 23, 26, 10, 6, 19, 30, 34, 15, 21, 28],\n 35: [1, 3, 6, 19, 30, 34, 2, 7, 18, 31, 33, 16, 9, 27, 22, 14, 11, 25, 24, 12, 13, 23, 26, 10, 15, 21, 28, 8, 17, 32, 4, 5, 20, 29, 35],\n 36: [1, 3, 6, 10, 26, 23, 2, 7, 18, 31, 33, 16, 9, 27, 22, 14, 35, 29, 20, 5, 11, 25, 24, 12, 13, 36, 28, 8, 17, 19, 30, 34, 15, 21, 4, 32],\n 37: [1, 3, 13, 36, 28, 8, 17, 32, 4, 21, 15, 34, 30, 19, 6, 10, 26, 23, 2, 7, 18, 31, 33, 16, 9, 27, 22, 14, 35, 29, 20, 5, 11, 25, 24, 12, 37]}\n \n return solutions[n] if n in solutions else False", "def square_sums_row(n):\n stack = [ (set(range(1, n+1)), []) ]\n\n while stack:\n existing_nums, out = stack.pop()\n if len(out) == n:\n return out\n \n for num in existing_nums:\n if not out or not ((num+out[-1])**.5)%1:\n stack.append( (existing_nums-{num}, out+[num]) )\n\n return False"] | {"fn_name": "square_sums_row", "inputs": [[5], [24]], "outputs": [[false], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 9,910 |
def square_sums_row(n):
|
93644b0e6ecb335a6592e66322b5cbfb | UNKNOWN | A Madhav array has the following property:
```a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...```
Complete the function/method that returns `true` if the given array is a Madhav array, otherwise it returns `false`.
*Edge cases: An array of length* `0` *or* `1` *should not be considered a Madhav array as there is nothing to compare.* | ["def is_madhav_array(arr):\n nTerms = ((1+8*len(arr))**.5-1)/2\n return (len(arr) > 1 and not nTerms%1 and\n len({ sum(arr[int(i*(i+1)//2):int(i*(i+1)//2)+i+1]) for i in range(int(nTerms))}) == 1)", "def is_madhav_array(arr):\n p = 1\n c = 2\n while p < len(arr) and arr[0] == sum(arr[p:p + c]):\n p += c\n c += 1 \n return p == len(arr) > 1", "def is_madhav_array(arr):\n def check(a, n=1):\n return True if len(a) == n else sum(a[:n]) == sum(a[n:2*n+1]) and check(a[n:], n + 1)\n return False if len(arr) <= 1 else check(arr)\n", "def is_madhav_array(arr):\n if len(arr) < 3: return False\n i, n = 0, 1\n value = arr[0]\n while i + n <= len(arr):\n if sum(arr[i:i+n]) != value: return False\n i += n\n n += 1\n return i == len(arr)", "is_madhav_array=lambda a:(print(a),False if len(a)<3 or len(a)==5 or a[-1]+a[0]==7else len(set(sum(a[int(i*(i+1)/2):int((i+2)*(i+1)/2)]) for i in range(int(len(a)**.5)+1)))==1)[1]", "t = [i*(i-1)//2 for i in range(3,1000)]\ndef is_madhav_array(arr):\n if len(arr) not in t: return False\n sums = {arr[0], arr[1] + arr[2]}\n for i,j in zip(t, t[1:]):\n if j>len(arr): \n break\n sums.add(sum(arr[i:j]))\n return len(sums)==1", "def is_madhav_array(arr):\n print(arr)\n if len(arr) < 3:\n return False\n i = 1\n k = 2\n while i < len(arr):\n t = 0\n for j in range(k):\n if i > len(arr)-1:\n return False\n t += arr[i]\n i += 1\n \n if arr[0] != t:\n return False\n else:\n k += 1\n \n return True", "def is_madhav_array(arr):\n if len(arr)<2:\n return False\n x=1+8*len(arr)\n if int(x**0.5)**2!=x:\n return False\n y=(int(x**0.5)-1)//2\n s=arr[0]\n for i in range(2,y+1):\n j=i*(i-1)//2\n if sum(arr[j:j+i])!=s:\n return False\n return True", "def is_madhav_array(arr):\n if len(arr) <= 2:\n return False\n i, k = 0, 1\n while i + k <= len(arr):\n if arr[0] != sum(arr[i: i + k]):\n return False\n if i + k == len(arr):\n return True\n i += k\n k += 1\n return False", "def is_madhav_array(arr):\n r,x,c = [],1,len(arr)\n try:\n while arr:\n t = 0\n for i in range(x):\n t += arr.pop(0)\n r.append(t)\n x += 1\n return len(set(r)) == 1 and c>1\n except:\n return False"] | {"fn_name": "is_madhav_array", "inputs": [[[6, 2, 4, 2, 2, 2, 1, 5, 0, 0]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, -100]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, -2, -1]], [[-6, -3, -3, 8, -5, -4]], [[-6, -3, -3, 8, -10, -4]], [[3, 1, 2, 3, 0]], [[3, 3]], [[]], [[1]], [[5, 2, 4, 1, 0, 3]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, 0, -12, 13, -5, 4, 6]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, 0, -12, 13, -5, 4, 1]], [[2, 1, 1]], [[2, 1, 1, 4, -1, -1]]], "outputs": [[true], [false], [true], [false], [true], [false], [false], [false], [false], [false], [true], [false], [true], [true]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,607 |
def is_madhav_array(arr):
|
33fca673e0cb4421f8628e9bd4872455 | UNKNOWN | In your class, you have started lessons about [arithmetic progression](https://en.wikipedia.org/wiki/Arithmetic_progression). Since you are also a programmer, you have decided to write a function that will return the first `n` elements of the sequence with the given common difference `d` and first element `a`. Note that the difference may be zero!
The result should be a string of numbers, separated by comma and space.
## Example
```python
# first element: 1, difference: 2, how many: 5
arithmetic_sequence_elements(1, 2, 5) == "1, 3, 5, 7, 9"
```
~~~if:fortran
*NOTE: In Fortran, your returned string is* **not** *permitted to contain redundant leading/trailing whitespace.*
~~~ | ["def arithmetic_sequence_elements(a, r, n):\n return ', '.join(str(a + b * r) for b in range(n))\n", "def arithmetic_sequence_elements(a, r, n):\n return \", \".join((str(a+r*i) for i in range(n)))", "from itertools import count, islice\n\ndef arithmetic_sequence_elements(a, r, n):\n return ', '.join([str(x) for x in islice(count(a, r), n)])", "def arithmetic_sequence_elements(a, r, n):\n return ', '.join(str(a + r*x) for x in range(n))", "def arithmetic_sequence_elements(a, r, n):\n rng = list(range(a, a + (r * n), r)) if r != 0 else [a] * n\n return ', '.join(map(str,rng))", "def arithmetic_sequence_elements(a, r, n):\n z = str(a)\n for i in range(n - 1):\n a = a + r\n z = z + \", \" + str(a)\n\n return z", "def arithmetic_sequence_elements(a, r, n):\n def seq(a,r,n):\n while n>0:\n yield a\n n-=1\n a+=r\n return \", \".join(map(str,seq(a,r,n)))\n", "def arithmetic_sequence_elements(a, r, n):\n out = [str(a)]\n for i in range(n - 1):\n a += r\n out.append(str(a))\n \n return \", \".join(out)\n", "def arithmetic_sequence_elements(a, r, n):\n result = str(a)\n list_ = [a]\n for i in range(n-1):\n result += ', ' + str(list_[-1]+r)\n list_.append(list_[-1]+r)\n return result", "def arithmetic_sequence_elements(a, r, n):\n result = [str(a)]\n for i in range(1, n):\n a = a + r\n result.append(str(a))\n return \", \".join(result)"] | {"fn_name": "arithmetic_sequence_elements", "inputs": [[1, 2, 5], [1, 0, 5], [1, -3, 10], [100, -10, 10]], "outputs": [["1, 3, 5, 7, 9"], ["1, 1, 1, 1, 1"], ["1, -2, -5, -8, -11, -14, -17, -20, -23, -26"], ["100, 90, 80, 70, 60, 50, 40, 30, 20, 10"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,511 |
def arithmetic_sequence_elements(a, r, n):
|
6027f009a2f62a8118dad3f5ac166cbf | UNKNOWN | You will get an array of numbers.
Every preceding number is smaller than the one following it.
Some numbers will be missing, for instance:
```
[-3,-2,1,5] //missing numbers are: -1,0,2,3,4
```
Your task is to return an array of those missing numbers:
```
[-1,0,2,3,4]
``` | ["def find_missing_numbers(arr):\n if not arr:\n return []\n return sorted(set(range(arr[0] + 1, arr[-1])).difference(arr))\n", "def find_missing_numbers(arr):\n return [x for x in range(arr[0], arr[-1]+1) if x not in arr] if arr else []", "def find_missing_numbers(arr):\n return [n for n in range(arr[0], arr[-1]) if n not in arr] if arr else []", "def find_missing_numbers(arr):\n return [x for x in range(arr[0], arr[-1]) if x not in arr] if arr else []", "import itertools\n\n\ndef find_missing_numbers(arr):\n return list(itertools.chain.from_iterable(\n range(a+1, b)\n for a, b in zip(arr, arr[1:])\n ))", "def find_missing_numbers(arr):\n if not arr: return arr\n out,it = [],iter(arr)\n ref = next(it)\n for v in range(arr[0],arr[-1]):\n if v==ref: ref = next(it)\n else: out.append(v)\n return out", "def find_missing_numbers(arr):\n if len(arr) < 2:\n return []\n return sorted(set(list(range(min(arr), max(arr)))) - set(arr))", "def find_missing_numbers(arr):\n if len(arr):\n return [i for i in range(arr[0],arr[-1]) if i not in arr]\n else :\n return []", "def find_missing_numbers(arr):\n try:\n return [i for i in range(arr[0],arr[len(arr)-1]) if i not in arr]\n except IndexError:\n return []"] | {"fn_name": "find_missing_numbers", "inputs": [[[-3, -2, 1, 4]], [[-1, 0, 1, 2, 3, 4]], [[]], [[0]], [[-4, 4]]], "outputs": [[[-1, 0, 2, 3]], [[]], [[]], [[]], [[-3, -2, -1, 0, 1, 2, 3]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,344 |
def find_missing_numbers(arr):
|
3b8441afe2729ebb6fd6faebdd8e39d1 | UNKNOWN | Your task is to make two functions, ```max``` and ```min``` (`maximum` and `minimum` in PHP and Python) that take a(n) array/vector of integers ```list``` as input and outputs, respectively, the largest and lowest number in that array/vector.
#Examples
```python
maximun([4,6,2,1,9,63,-134,566]) returns 566
minimun([-52, 56, 30, 29, -54, 0, -110]) returns -110
maximun([5]) returns 5
minimun([42, 54, 65, 87, 0]) returns 0
```
#Notes
- You may consider that there will not be any empty arrays/vectors. | ["minimum = min\nmaximum = max", "minimum,maximum = min,max", "def minimum(arr):\n return min(arr)\n\ndef maximum(arr):\n return max(arr)", "\ndef minimum(arr):\n min = None\n for i in arr:\n if min == None:\n min = i\n elif i < min:\n min = i\n return min\n \ndef maximum(arr):\n max = None\n for i in arr:\n if max == None:\n max = i\n elif i > max:\n max = i\n return max", "def minimum(arr):\n min_ = arr[0]\n for e in arr[1:]:\n if e < min_:\n min_ = e\n return min_\n\ndef maximum(arr):\n max_ = arr[0]\n for e in arr[1:]:\n if e > max_:\n max_ = e\n return max_", "def minimum(arr):\n min = arr[0]\n for num in arr:\n if num < min:\n min = num\n return min\n\ndef maximum(arr):\n max = 0\n for num in arr:\n if num > max:\n max = num\n return max", "def minimum(arr):\n current_best = arr[0]\n for i in arr:\n if i < current_best:\n current_best = i\n return current_best\n\ndef maximum(arr):\n current_best = arr[0]\n for i in arr:\n if i > current_best:\n current_best = i\n return current_best", "def maximum(arr):\n maximum = arr[0]\n for i in arr:\n if i > maximum:\n maximum = i\n return maximum \n \n\ndef minimum(arr):\n minimum = arr[0]\n for i in arr:\n if i < minimum:\n minimum = i\n return minimum ", "def minimum(arr):\n #your code here...\n minarr = min(arr)\n return minarr\ndef maximum(arr):\n #...and here\n maxarr = max(arr)\n return maxarr", "def minimum(arr):\n Min = arr[0]\n for e in arr:\n if e < Min:\n Min = e\n return Min\n\ndef maximum(arr):\n Max = arr[0]\n for e in arr:\n if e > Max:\n Max = e\n return Max", "def minimum(arr):\n num = None\n for i in arr: \n if not num:\n num = i\n elif i < num:\n num = i\n return num\n\ndef maximum(arr):\n num = 0\n for i in arr:\n if i > num:\n num = i\n return num", "def minimum(arr):\n s= min(arr)\n return s\n \n \n\ndef maximum(arr):\n x=max(arr)\n return x", "def minimum(arr):\n #your code here...\n min_value = arr[0]\n for num in arr:\n if num < min_value:\n min_value = num\n return min_value\n\ndef maximum(arr):\n #...and here\n max_value = arr[0]\n for num in arr:\n if num > max_value:\n max_value = num\n return max_value\n", "def minimum(arr):\n m = arr[0]\n for i in arr:\n if m > i:\n m = i\n return m\n \n\ndef maximum(arr):\n t = arr[0]\n for i in arr:\n if i > t:\n t = i\n return t", "def minimum(arr):\n min = arr[0]\n while len(arr) > 1:\n if arr[1] < min:\n min = arr[1]\n arr.pop(0)\n else:\n arr.pop(1)\n return min\n\ndef maximum(arr):\n max = arr[0]\n while len(arr) > 1:\n if arr[1] > max:\n max = arr[1]\n arr.pop(0)\n else:\n arr.pop(1)\n return max\n", "def minimum(arr):\n return min(arr)\n\ndef maximum(arr):\n y = max(arr)\n return y", "def minimum(arr):\n lowest_num = 999999999999999\n for x in arr:\n if x < lowest_num:\n lowest_num = x\n return lowest_num \ndef maximum(arr):\n highest_num = 0\n for x in arr:\n if x > highest_num:\n highest_num = x\n return highest_num ", "def minimum(arr):\n for i in range(len(arr)-1,0,-1):\n if arr[i] < arr[i-1]:\n arr[i], arr[i-1] = arr[i-1], arr[i]\n return arr[0]\n\ndef maximum(arr):\n for i in range(len(arr)-1):\n if arr[i] > arr[i+1]:\n arr[i], arr[i+1] = arr[i+1], arr[i]\n return arr[len(arr)-1]", "def minimum(arr):\n return int(min(arr))\n\ndef maximum(arr):\n return int(max(arr))", "def minimum(arr):\n #your code here...\n y = 0\n for x in arr :\n if y == 0 : y=x\n elif x < y : y=x\n return y\ndef maximum(arr):\n #...and here\n y = 0\n for x in arr :\n if y == 0 : y=x\n elif x > y : y=x\n return y", "def minimum(arr):\n output = min(arr)\n return output\n\ndef maximum(arr):\n output= max(arr)\n return output", "def minimum(arr):\n a = 100000000000000000000000000000000000\n for i in range(len(arr)):\n if arr[i]<a:\n a = arr[i]\n return a\ndef maximum(arr):\n a = -1000000000000000000000000000000000000000000\n for i in range(len(arr)):\n if arr[i]>a:\n a = arr[i]\n return a", "def minimum(arr):\n #first we define the Minimum value 'Min' to be the first value in the array for comparison\n Min=arr[0]\n #Next we loop through the array to check if each value is smaller than the first. If it is, make that the new Min value\n for i in arr:\n if i<Min:\n Min=i\n return Min\n\ndef maximum(arr):\n #first we define the Maximum value 'Max' to be the first value in the array for comparison\n Max=arr[0]\n #Next we loop through the array to check if each value is bigger than the first. If it is, make that the new Max value\n for i in arr:\n if i>Max:\n Max=i\n return Max", "def minimum(arr):\n minimum = arr[0]\n for i in range(0, len(arr)):\n if arr[i] < minimum:\n minimum = arr[i]\n return minimum\n\ndef maximum(arr):\n maximum = arr[0]\n for i in range(0, len(arr)):\n if arr[i] > maximum:\n maximum = arr[i]\n return maximum", "def minimum(arr):\n \n for num in arr: return min(arr)\n\ndef maximum(arr):\n \n for num in arr: return max(arr)", "def minimum(arr):\n #your code here...\n smallest = None\n for i in arr:\n if smallest is None:\n smallest = i\n elif i < smallest:\n smallest = i\n return smallest\n \n \n \n\ndef maximum(arr):\n #...and here\n largest = 0\n for i in arr:\n if i > largest:\n largest = i\n else:\n largest = largest\n return largest", "def minimum(arr):\n min = arr[0]\n for i in arr:\n if i <= min:\n min = i\n return min\n\ndef maximum(arr):\n max = arr[0]\n for i in arr:\n if i >= max:\n max = i\n return max", "def minimum(arr):\n min = arr[0]\n for i in arr[1:]:\n if min > i:\n min = i\n return min\n\ndef maximum(arr):\n max = arr[0]\n for i in arr[1:]:\n if max < i:\n max = i\n return max", "def minimum(arr:[]):\n result = arr[0]\n for i in arr:\n if i < result:\n result = i\n\n return result\n\n\ndef maximum(arr:[]):\n result=arr[0]\n for i in arr:\n if i>result:\n result = i\n \n return result \n", "import statistics\ndef minimum(a):\n return min(a)\ndef maximum(a):\n return max(a)", "def minimum(arr):\n for minimum in arr:\n return min(arr)\ndef maximum(arr):\n for maximum in arr:\n return max(arr)", "def minimum(arr):\n min_value = min(arr)\n return min_value\n\ndef maximum(arr):\n max_value = max(arr)\n return max_value", "def minimum(arr):\n if not arr:\n return 0\n return min(arr)\n\ndef maximum(arr):\n if not arr:\n return 0\n return max(arr)", "def minimum(arr):\n #your code here...\n numbers = arr \n \n numbers.sort()\n \n minimum_number = numbers[0]\n \n return minimum_number\n \n\ndef maximum(arr):\n #...and here\n numbers = arr \n \n numbers.sort()\n \n max_number = numbers[-1]\n \n return max_number\n \n", "def minimum(arr):\n min=9999999999999999999\n for i in arr:\n if(min>i):\n min=i\n return min\n\ndef maximum(arr):\n max=-9999999999999999999\n for i in arr:\n if(max<i):\n max=i\n return max\n", "def minimum(arr):\n new=[]\n for num in arr:\n if new==[]:\n new=num\n if num<new:\n new=num\n else:\n pass\n return new\ndef maximum(arr):\n new=[]\n for num in arr:\n if new==[] or int(num)>new:\n new=num\n else:\n pass\n return new", "def minimum(arr):\n arr = sorted(list(arr))\n return arr[0]\n\ndef maximum(arr):\n arr = sorted(list(arr))\n return arr[-1]", "def minimum(arr):\n #your code here...\\\n x=list(map(int,arr))\n return min(sorted (x))\n\ndef maximum(arr):\n #...and here\n return max(arr)", "def minimum(arr):\n a = sorted(arr)\n return a[0]\n\ndef maximum(arr):\n a = sorted(arr)\n return a[-1]", "def minimum(arr):\n sorted_arr = sorted(arr)\n return sorted_arr[0]\n\ndef maximum(arr):\n sorted_arr = sorted(arr)\n return sorted_arr[-1]\n \n", "def minimum(arr):\n mi=100000\n for a in arr:\n if a<mi:\n mi=a\n return mi\ndef maximum(arr):\n ma=-1000000\n for b in arr:\n if b>ma:\n ma=b\n return ma", "def minimum(arr):\n min = float(\"inf\")\n for x in arr:\n if(x<min):\n min=x\n return min\n \n\ndef maximum(arr):\n max = float(\"-inf\")\n for x in arr:\n if(x>max):\n max=x\n return max", "def minimum(arr):\n if len(arr) > 0:\n result = arr[0]\n if len(arr) > 1:\n for i in range(1,len(arr)):\n if arr[i] < result:\n result = arr[i]\n else:\n result = 0\n return result\n\ndef maximum(arr):\n if len(arr) > 0:\n result = arr[0]\n if len(arr) > 1:\n for i in range(1,len(arr)):\n if arr[i] > result:\n result = arr[i]\n else:\n result = 0\n return result", "def minimum(arr):\n low = arr[0]\n for i in arr:\n if i < low:\n low = i\n return low\n\ndef maximum(arr):\n high= arr[0]\n for i in arr:\n if i > high:\n high = i\n return high", "def minimum(arr):\n small = min(arr)\n return small\ndef maximum(arr):\n large = max(arr)\n \n return large", "def minimum(arr):\n mini = arr[0]\n for num in arr:\n if num < mini: mini = num\n return mini\n\ndef maximum(arr):\n maxi = arr[0]\n for num in arr:\n if num > maxi: maxi = num\n return maxi", "def minimum(arr):\n min1 = min(arr)\n return min1\n\ndef maximum(arr):\n max1 = max(arr)\n return max1", "def minimum(arr):\n currentSmallest = arr[0]\n \n for x in range (1, len(arr)):\n if arr[x] < currentSmallest:\n currentSmallest = arr[x]\n \n return currentSmallest\n\ndef maximum(arr):\n currentLargest = arr[0]\n \n for x in range (1, len(arr)):\n if arr[x] > currentLargest:\n currentLargest = arr[x]\n \n return currentLargest", "def minimum(arr):\n minv = 10e7\n for i in range(len(arr)):\n if arr[i] < minv:\n minv = arr[i]\n return minv\n\ndef maximum(arr):\n maxv = -10e7\n for i in range(len(arr)):\n if arr[i] > maxv:\n maxv = arr[i]\n return maxv", "def minimum(arr):\n min = arr[0]\n for i in arr:\n if i < min:\n min = i\n return min\n \ndef maximum(arr):\n max = 0\n for i in arr:\n if i > max:\n max = i\n return max", "def minimum(arr):\n #your codre here...\n return min(arr)\ndef maximum(arr):\n #...and here\n return max(arr)", "def minimum(arr):\n min = float('inf')\n for num in arr:\n if num < min:\n min = num\n return min\n\ndef maximum(arr):\n max = float('-inf')\n for num in arr:\n if num > max:\n max = num\n return max", "def minimum(arr):\n min = 1000000000\n for i in arr:\n if i < min:\n min = i\n return min\n \n \n\ndef maximum(arr):\n max = -1000000000\n for i in arr:\n if i > max:\n max = i\n return max", "def minimum(arr):\n swapped=True\n while swapped:\n swapped=False\n for i in range(len(arr)-1):\n if arr[i]>arr[i+1]:\n arr[i],arr[i+1]=arr[i+1],arr[i]\n swapped=True\n return arr[0]\n\ndef maximum(arr):\n swapped=True\n while swapped:\n swapped=False\n for i in range(len(arr)-1):\n if arr[i]>arr[i+1]:\n arr[i],arr[i+1]=arr[i+1],arr[i]\n swapped=True\n return max(arr)\n #...and here\n", "def minimum(arr):\n answer = arr[0]\n for i in arr:\n if i < answer:\n answer = i\n return answer\n\ndef maximum(arr):\n answer = arr[0]\n for i in arr:\n if i > answer:\n answer = i\n return answer", "def minimum(arr):\n #your code here...\n val = arr[0]\n for i in arr:\n if i < val:\n val = i\n return val\ndef maximum(arr):\n #...and here\n val = arr[0]\n for i in arr:\n if i > val:\n val = i\n return val", "from functools import reduce\n\ndef minimum(arr):\n# return min(arr)\n return reduce(lambda x, y: x if x < y else y, arr)\n\ndef maximum(arr):\n# return max(arr)\n return reduce(lambda x, y: x if x > y else y, arr)", "def maximum(numbers):\n max_val = numbers[0]\n for i in range(len(numbers)):\n if numbers[i] > max_val:\n max_val = numbers[i]\n return max_val\n\ndef minimum(numbers):\n min_val = numbers[0]\n for i in range(len(numbers)):\n if numbers[i] < min_val:\n min_val = numbers[i]\n return min_val", "def minimum(arr):\n min = sorted(arr)\n return min[0]\n\ndef maximum(arr):\n max = sorted(arr)\n return max[len(max)-1]", "def minimum(arr):\n base = arr[0]\n if len(arr) == 1:\n return base\n else:\n for number in arr:\n if number < base:\n base = number\n return base\n\ndef maximum(arr):\n base = arr[0]\n if len(arr) == 1:\n return base\n else:\n for number in arr:\n if number > base:\n base = number\n return base", "def minimum(arr):\n arr.sort()\n return arr[0]\n\ndef maximum(arr):\n arr.sort()\n arr.reverse()\n return arr[0]", "def minimum(arr):\n smol = 1000\n for i in range (0, len(arr)):\n if arr[i] < smol:\n smol = arr[i]\n \n return smol\n\ndef maximum(arr):\n beeg = 0\n for i in range (0, len(arr)):\n if arr[i] > beeg:\n beeg = arr[i]\n \n return beeg"] | {"fn_name": "minimum", "inputs": [[[-52, 56, 30, 29, -54, 0, -110]], [[42, 54, 65, 87, 0]], [[1, 2, 3, 4, 5, 10]], [[-1, -2, -3, -4, -5, -10]], [[9]]], "outputs": [[-110], [0], [1], [-10], [9]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 15,055 |
def minimum(arr):
|
4cdeb702db2743f4ec1c952c22e512bc | UNKNOWN | **Steps**
1. Square the numbers that are greater than zero.
2. Multiply by 3 every third number.
3. Multiply by -1 every fifth number.
4. Return the sum of the sequence.
**Example**
`{ -2, -1, 0, 1, 2 }` returns `-6`
```
1. { -2, -1, 0, 1 * 1, 2 * 2 }
2. { -2, -1, 0 * 3, 1, 4 }
3. { -2, -1, 0, 1, -1 * 4 }
4. -6
```
P.S.: The sequence consists only of integers. And try not to use "for", "while" or "loop" statements. | ["def calc(a):\n return sum( x**(1 + (x>=0)) * (1 + 2*(not i%3)) * (-1)**(not i%5) for i,x in enumerate(a,1))", "def calc(a):\n for i, n in enumerate(a):\n if a[i] > 0: a[i] *= a[i]\n if i % 3 == 2: a[i] = a[i] * 3\n if i % 5 == 4: a[i] = a[i] * -1\n return sum(a)", "def calc(a):\n print(a)\n \n for i in range(len(a)):\n if a[i] > 0:\n a[i] *= a[i]\n \n for i in range(2,len(a),3):\n a[i] *= 3 \n \n for i in range(4,len(a),5):\n a[i] *= -1\n \n return sum(a)", "def calc(a):\n sum = 0\n for i in range(len(a)):\n value = a[i]\n if value > 0: value *= value\n if (i+1) % 3 == 0: value *= 3\n if (i+1) % 5 == 0: value = -value\n sum += value\n return sum", "def mod(e):\n i, n = e\n return (n**2 if n > 0 else n) * (3 if i % 3 == 0 else 1) * (-1 if i % 5 == 0 else 1)\n\ndef calc(lst):\n return sum(map(mod, enumerate(lst, 1)))\n \n# without loop, as asked \n##############################\n\n\n# there with a comprehension (so a for):\n#def calc(lst):\n# return sum((n**2 if n > 0 else n) * (3 if i % 3 == 0 else 1) * (-1 if i % 5 == 0 else 1) for i, n in enumerate(lst, 1))\n", "def calc(a):\n return sum([i * (i if i > 0 else 1) * (3 if k%3 == 2 else 1) * (-1 if k%5 == 4 else 1) for k, i in enumerate(a)])", "fifth = lambda i, x: x if i%5 else -x\nthird = lambda i, x: x if i%3 else 3*x\nsquare = lambda x : x if x<0 else x*x\n\ndef calc(a):\n return sum(fifth(i, third(i, square(x))) for i,x in enumerate(a, 1))", "from itertools import cycle\nfrom operator import mul\n\nmuls=(1,1,3,1,-1,3,1,1,3,-1,1,3,1,1,-3)\n\ndef calc(a):\n return sum(map(mul,map(lambda n:n*n if n>0 else n,a),cycle(muls)))", "from itertools import cycle\n\ndef calc(lst):\n return sum((a ** 2 if a > 0 else a) * b * c\n for a, b, c in zip(lst, cycle((1, 1, 3)), cycle((1, 1, 1, 1, -1))))", "def calc(a):\n return sum(i**(1,2)[i>0]*(1,3)[idx%3==2]*(1,-1)[idx%5==4] for idx,i in enumerate(a))"] | {"fn_name": "calc", "inputs": [[[0, 2, 1, -6, -3, 3]], [[0]], [[1, 1, 1, 1, 1]], [[1, 1, -9, 9, 16, -15, -45, -73, 26]], [[1, -1, 10, -9, 16, 15, 45, -73, -26]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [[-5, -5, -5, -5, -5, -5, -5]]], "outputs": [[31], [0], [5], [1665], [2584], [0], [-45]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,066 |
def calc(a):
|
82d41a1d23d1f5ad5480d33f054fc2c0 | UNKNOWN | # Task
In the city, a bus named Fibonacci runs on the road every day.
There are `n` stations on the route. The Bus runs from station1 to stationn.
At the departure station(station1), `k` passengers get on the bus.
At the second station(station2), a certain number of passengers get on and the same number get off. There are still `k` passengers on the bus.
From station3 to stationn-1, the number of boarding and alighting passengers follows the following rule:
- At stationi, the number of people getting on is the sum of the number of people getting on at the two previous stations(stationi-1 and stationi-2)
- The number of people getting off is equal to the number of people getting on at the previous station(stationi-1).
At stationn, all the passengers get off the bus.
Now, The numbers we know are: `k` passengers get on the bus at station1, `n` stations in total, `m` passengers get off the bus at stationn.
We want to know: How many passengers on the bus when the bus runs out stationx.
# Input
- `k`: The number of passengers get on the bus at station1.
- `1 <= k <= 100`
- `n`: The total number of stations(1-based).
- `6 <= n <= 30`
- `m`: The number of passengers get off the bus at stationn.
- `1 <= m <= 10^10`
- `x`: Stationx(1-based). The station we need to calculate.
- `3 <= m <= n-1`
- All inputs are valid integers.
# Output
An integer. The number of passengers on the bus when the bus runs out stationx. | ["def sim(k,n,p):\n r = [(k,k,0),(k,p,p)]\n for i in range(n-2):\n u,d = r[0][1]+r[1][1],r[1][1]\n r = [r[1],(r[1][0]+u-d,u,d)]\n return r[1][0]\n\ndef calc(k,n,m,x):\n z,o = sim(k,n-1,0), sim(k,n-1,1)\n return sim(k,x,(m-z)//(o-z))", "def fibLikeGen():\n a,b = (1,0), (0,1) # a: station i-1, b: station i\n while 1:\n yield a,b\n a,b = b, tuple(x+y for x,y in zip(a,b))\n\ngen = fibLikeGen()\nSUM_AT = [(), (1,0), (1,0)] # (k,l)\n \ndef getCoefs(n):\n while len(SUM_AT) <= n:\n a,b = next(gen)\n SUM_AT.append(tuple(x+y for x,y in zip(a,SUM_AT[-1])))\n return SUM_AT[n] \n\n\ndef calc(k,n,m,x):\n a,b = getCoefs(n-1)\n l = (m-a*k) // b\n a,b = getCoefs(x)\n return a*k + b*l", "def fib(n, a, b):\n for i in range(n):\n yield a\n a, b = b, a+b\n \ndef calc(k,n,m,x):\n if x <= 2:\n return k\n if x == 3:\n return 2 * k\n b = 2 + sum(fib(n-4-1, 1, 1))\n a = 1 + sum(fib(n-4-1, 1, 2))\n c = (m - b*k) // a\n b = 2 + sum(fib(x-4, 1, 1))\n a = 1 + sum(fib(x-4, 1, 2))\n return k*b + c*a", "fib = {3: 0, 4: 1, 5: 1}\nfor i in range(6, 31):\n fib[i] = fib[i - 2] + fib[i - 1]\n\ndef coefficients(n):\n y, z = 2, 0 # coefficients for number of passengers at station 3\n for i in range(4, n):\n y += fib[i - 1]\n z += fib[i]\n return y, z\n\ndef calc(k, n, m, x):\n y, z = coefficients(n)\n station2 = (m - y * k) // z\n y, z = coefficients(x + 1)\n return y * k + z * station2", "FIB = [0, 1]\nfor _ in range(1000): FIB.append(FIB[-2] + FIB[-1])\n\ndef calc(k, n, m, x):\n l = (m - (FIB[n-3] + 1) * k) // (FIB[n-2] - 1)\n return (FIB[x-2] + 1) * k + (FIB[x-1] - 1) * l", "from functools import reduce, lru_cache\n\n\ndef calc(k,n,m,x):\n n_of_eq_var = sum(fib(i) for i in range(1, n-4)) + 2\n got_on_2nd = int(\n (m - k * n_of_eq_var) / sum(fib(i) for i in range(1, n-3))\n )\n \n return reduce(\n lambda result, i: result+fib(i, k, got_on_2nd), range(1, x-1), k\n )\n\n\n@lru_cache(None)\ndef fib(n, fib_1=1, fib_2=1):\n for _ in range(n-2):\n fib_1, fib_2 = fib_2, fib_1+fib_2\n\n return fib_2 if n > 1 else fib_1", "def calc(k,n,m,x):\n \n f1=1\n f2=0\n fz2=0\n s=0\n t=0\n for i in range(1,n-3) :\n s+=f2\n a=f1\n f1=a+f2\n f2=a\n if i==x-3 : \n t =s \n fz2=f2\n \n A=(m-k*(s+2))/(s+f2)\n return A*(t+fz2)+k*(t+2)", "class Memoize:\n def __init__(self, fn):\n self.fn = fn\n self.memo = {}\n\n def __call__(self, *args):\n if args not in self.memo:\n self.memo[args] = self.fn(*args)\n return self.memo[args]\n\n@Memoize #makes things alot faster\ndef fib_spec(n): #that is the gain per station, so really we have to take the sum of all n's\n if n == 0:\n return (1, 0)\n elif n == 1:\n return (0, 1)\n else:\n k_1, s_1 = fib_spec(n-1)\n k_2, s_2 = fib_spec(n-2)\n return (k_1+k_2, s_1+s_2)\n\n\ndef calc(k,n,m,x):\n if x in (1,2):\n return k\n elif x == 3:\n return 2*k\n s_ = 0\n k_ = 1\n for i in range(n-3):\n tmp_k, tmp_s = fib_spec(i)\n s_ += tmp_s\n k_ += tmp_k\n if i == x-3:\n s_x, k_x = s_, k_\n s = (m-k*k_)//s_\n return k_x*k+s_x*s", "class Memoize:\n def __init__(self, fn):\n self.fn = fn\n self.memo = {}\n\n def __call__(self, *args):\n if args not in self.memo:\n self.memo[args] = self.fn(*args)\n return self.memo[args]\n\n@Memoize\ndef fib_spec(n): #that is the gain per station, so really we have to take the sum of all n's\n if n == 0:\n return (1, 0)\n elif n == 1:\n return (0, 1)\n else:\n k_1, s_1 = fib_spec(n-1)\n k_2, s_2 = fib_spec(n-2)\n return (k_1+k_2, s_1+s_2)\n\n\ndef fib(k, s, n):\n if n == 0:\n return k\n elif n == 1:\n return s\n else:\n return fib(k, s, n-1) + fib(k, s, n-2)\n\ndef calc(k,n,m,x):\n if x in (1,2):\n return k\n elif x == 3:\n return 2*k\n s_ = 0\n k_ = 1\n for i in range(n-3):\n tmp_k, tmp_s = fib_spec(i)\n s_ += tmp_s\n k_ += tmp_k\n s = (m-k*k_)//s_\n \n s_ = 0\n k_ = 1\n for i in range(x-2):\n tmp_k, tmp_s = fib_spec(i)\n s_ += tmp_s\n k_ += tmp_k\n return k_*k+s_*s\n\n", "def calc(k,n,m,x):\n # solve how many people get on board at station 2:\n on_list_x = [0, 1, 1, 2, 3] # num of times x people get on\n on_list_k = [k, 0, k, k, 2*k] # k people get on\n\n off_list_x = [0, 1, 1, 1, 2]\n off_list_k = [0, 0, 0, k, k]\n # total a*x + b*k at index n-1 == m\n while len(on_list_x) < n-1:\n on_list_x.append(on_list_x[-1] + on_list_x[-2])\n on_list_k.append(on_list_k[-1] + on_list_k[-2])\n off_list_x.append(off_list_x[-1] + off_list_x[-2])\n off_list_k.append(off_list_k[-1] + off_list_k[-2])\n num_x = sum(on_list_x) - sum(off_list_x)\n num_k = sum(on_list_k) - sum(off_list_k)\n x_val = (m - num_k) / num_x # people at station 2\n \n # now all numbers of boarding and leaving people can be calculated: \n passengers_station_x = (sum(on_list_x[:x]) - sum(off_list_x[:x]))*x_val + sum(on_list_k[:x]) - sum(off_list_k[:x])\n\n return int(passengers_station_x)"] | {"fn_name": "calc", "inputs": [[5, 7, 32, 4], [12, 23, 212532, 8]], "outputs": [[13], [252]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 5,530 |
def calc(k,n,m,x):
|
78fb1db3add939897902afa52093d6dd | UNKNOWN | ###Instructions
A time period starting from ```'hh:mm'``` lasting until ```'hh:mm'``` is stored in an array:
```
['08:14', '11:34']
```
A set of different time periods is then stored in a 2D Array like so, each in its own sub-array:
```
[['08:14','11:34'], ['08:16','08:18'], ['22:18','01:14'], ['09:30','10:32'], ['04:23','05:11'], ['11:48','13:48'], ['01:12','01:14'], ['01:13','08:15']]
```
Write a function that will take a 2D Array like the above as argument and return a 2D Array of the argument's sub-arrays sorted in ascending order.
Take note of the following:
* The first time period starts at the earliest time possible ```('00:00'+)```.
* The next time period is the one that starts the soonest **after** the prior time period finishes. If several time periods begin at the same hour, pick the first one showing up in the original array.
* The next time period can start the same time the last one finishes.
This:
```
[['08:14','11:34'], ['08:16','08:18'], ['13:48','01:14'], ['09:30','10:32'], ['04:23','05:11'], ['11:48','13:48'], ['01:12','01:14'], ['01:13','08:15']]
```
Should return:
```
[['01:12','01:14'], ['04:23','05:11'], ['08:14','11:34'], ['11:48','13:48'], ['13:48','01:14'], ['08:16','08:18'], ['09:30','10:32'], ['01:13','08:15']]
``` | ["def sort_time(arr):\n arr, s = sorted(arr, key=lambda t: t[0]), []\n while arr:\n nextTP = next((i for i,t in enumerate(arr) if not s or t[0] >= s[-1][1]), 0)\n s.append(arr.pop(nextTP))\n return s", "def sort_time(arr):\n arr = sorted(arr, key = lambda x: x[0])\n out = [[\"\", \"00:00\"]]\n \n while arr:\n i = next((i for i,t in enumerate(arr) if t[0] >= out[-1][1]), None)\n out.append(arr.pop(i if i else 0))\n\n return out[1:]", "def sort_time(arr):\n arr, prv, result = sorted(arr, key=lambda p: p[0]), \"00:00\", []\n while arr:\n nxt = next((p for p in arr if p[0] >= prv), arr[0])\n result.append(nxt)\n arr.remove(nxt)\n prv = nxt[1]\n return result\n\n\n\n\n# more compact but less readable:\n# while arr:\n# result.append(arr.pop(next((i for i, p in enumerate(arr) if p[0] >= prv), 0)))\n# prv = result[-1][1]\n", "\nmins=lambda time: (lambda res: int(res[0])*60+int(res[1]))(time.split(\":\")); dt=lambda a,b: (lambda diff: 1440+diff if diff<0 else diff)(mins(a)-mins(b)); sort_time=lambda arr,last=\"00:00\": [arr[0]] if len(arr)==1 else (lambda arr: [arr[0]]+sort_time(arr[1:],arr[0][1]))(sorted(arr,key=lambda a: dt(a[0],last)))", "from operator import itemgetter\n\ndef sort_time(arr):\n L = sorted(arr, key=itemgetter(0))\n result = [L.pop(0)]\n while L:\n result.append(L.pop(next((i for i in range(len(L)) if L[i][0] >= result[-1][1]), 0)))\n return result", "from datetime import datetime, timedelta\n\n\ndef delta(*span):\n start, end = [datetime.strptime(s, '%H:%M') for s in span]\n return (end + timedelta(days=1) if start > end else end) - start\n\ndef sort_time(arr):\n prev = '00:00'\n xs = list(arr)\n result = []\n while xs:\n i = min(enumerate(xs), key=lambda x: delta(prev, x[1][0]))[0]\n a, prev = xs.pop(i)\n result.append([a, prev])\n return result", "from datetime import datetime, timedelta\n\ndef _parse(s):\n return \n\ndef delta(*span):\n start, end = [datetime.strptime(s, '%H:%M') for s in span]\n return (end + timedelta(days=1) if start > end else end) - start\n\ndef sort_time(arr):\n prev = '00:00'\n xs = list(arr)\n result = []\n while xs:\n i = min(enumerate(xs), key=lambda x: delta(prev, x[1][0]))[0]\n [a, prev] = xs.pop(i)\n result.append([a, prev])\n return result", "def sort_time(arr):\n if len(arr) == 0:\n return []\n r_max = '23:59'\n r_min = '00:00'\n rr = arr[:]\n ret = []\n k = 0\n for i in range(len(arr)):\n for j in range(len(rr)):\n if r_min <= rr[j][0] < r_max:\n r_max = rr[j][0]\n k = j\n if r_max == r_min:\n break\n ret.append(rr[k]) \n r_min = rr[k][1]\n r_max = '23:59'\n rr.pop(k)\n k == 0\n if rr and max(rr)[0] < r_min:\n r_min = min(rr)[0]\n return ret", "def sort_time(arr):\n s=sorted(arr,key=lambda x:(x[0],arr.index(x)))\n r=[s.pop(0)]\n while(s):\n if r[-1][1]>s[-1][0]:\n r.append(s.pop(0))\n continue\n for i in range(len(s)):\n if r[-1][1]<=s[i][0]:\n r.append(s.pop(i))\n break\n return r", "def sort_time(arr):\n #def to_minutes(t):\n # hh,mm = t.split(':')\n # return int(hh)*60+int(mm)\n arr = arr[:]\n result = []\n next = min(arr)\n while True:\n result.append(next)\n arr.remove(next)\n if not arr:\n break\n next = None\n for t in arr:\n if result[-1][1]<=t[0]:\n if next is None or next[0]>t[0]:\n next = t\n if next is None:\n next = min(arr)\n \n \n return result\n"] | {"fn_name": "sort_time", "inputs": [[[["08:14", "11:34"], ["08:16", "08:18"], ["13:48", "01:14"], ["09:30", "10:32"], ["04:23", "05:11"], ["11:48", "13:48"], ["01:12", "01:14"], ["01:13", "08:15"]]], [[["00:00", "00:05"], ["16:37", "18:19"], ["12:07", "12:12"], ["00:30", "02:49"], ["12:12", "12:14"], ["12:14", "15:00"], ["15:00", "19:32"]]], [[["12:00", "10:01"], ["06:31", "14:23"], ["03:02", "07:58"], ["08:13", "10:05"], ["18:37", "04:22"], ["12:58", "14:28"], ["01:51", "14:40"], ["04:27", "01:00"], ["22:56", "23:33"], ["19:23", "07:00"], ["02:13", "16:14"], ["10:40", "02:36"], ["11:49", "00:10"]]], [[["07:05", "01:22"], ["07:40", "07:39"], ["17:35", "15:16"], ["21:33", "11:22"], ["02:58", "17:50"], ["18:43", "13:14"], ["18:15", "11:02"], ["12:42", "10:06"], ["00:26", "02:12"]]], [[["17:29", "06:34"], ["00:46", "15:02"], ["04:59", "22:28"], ["22:16", "21:53"], ["08:44", "00:57"]]], [[["13:40", "00:19"], ["11:09", "13:58"], ["06:50", "14:51"], ["00:15", "00:02"], ["19:18", "08:32"], ["03:19", "12:49"], ["18:16", "05:57"], ["14:27", "02:50"], ["01:11", "12:24"]]], [[["06:10", "04:38"], ["11:23", "08:13"], ["14:15", "01:21"], ["23:15", "23:27"], ["16:01", "12:16"], ["07:24", "19:36"], ["16:16", "03:07"]]], [[["07:41", "07:02"], ["02:47", "11:37"], ["16:04", "12:52"], ["03:55", "09:03"], ["00:16", "20:48"], ["02:44", "14:11"], ["23:12", "12:22"], ["22:29", "05:37"], ["18:22", "12:27"], ["17:44", "01:02"], ["03:15", "03:42"]]], [[["11:33", "18:09"], ["02:10", "08:51"], ["01:56", "18:22"], ["06:16", "21:38"], ["12:24", "19:01"], ["23:09", "20:42"], ["20:39", "09:01"], ["13:13", "06:13"], ["04:40", "12:01"]]], [[["08:15", "19:22"], ["08:35", "00:16"], ["19:37", "08:24"], ["18:33", "08:26"], ["20:17", "05:56"], ["23:45", "18:08"], ["02:52", "13:29"]]]], "outputs": [[[["01:12", "01:14"], ["04:23", "05:11"], ["08:14", "11:34"], ["11:48", "13:48"], ["13:48", "01:14"], ["08:16", "08:18"], ["09:30", "10:32"], ["01:13", "08:15"]]], [[["00:00", "00:05"], ["00:30", "02:49"], ["12:07", "12:12"], ["12:12", "12:14"], ["12:14", "15:00"], ["15:00", "19:32"], ["16:37", "18:19"]]], [[["01:51", "14:40"], ["18:37", "04:22"], ["04:27", "01:00"], ["02:13", "16:14"], ["19:23", "07:00"], ["08:13", "10:05"], ["10:40", "02:36"], ["03:02", "07:58"], ["11:49", "00:10"], ["06:31", "14:23"], ["22:56", "23:33"], ["12:00", "10:01"], ["12:58", "14:28"]]], [[["00:26", "02:12"], ["02:58", "17:50"], ["18:15", "11:02"], ["12:42", "10:06"], ["17:35", "15:16"], ["18:43", "13:14"], ["21:33", "11:22"], ["07:05", "01:22"], ["07:40", "07:39"]]], [[["00:46", "15:02"], ["17:29", "06:34"], ["08:44", "00:57"], ["04:59", "22:28"], ["22:16", "21:53"]]], [[["00:15", "00:02"], ["01:11", "12:24"], ["13:40", "00:19"], ["03:19", "12:49"], ["14:27", "02:50"], ["06:50", "14:51"], ["18:16", "05:57"], ["11:09", "13:58"], ["19:18", "08:32"]]], [[["06:10", "04:38"], ["07:24", "19:36"], ["23:15", "23:27"], ["11:23", "08:13"], ["14:15", "01:21"], ["16:01", "12:16"], ["16:16", "03:07"]]], [[["00:16", "20:48"], ["22:29", "05:37"], ["07:41", "07:02"], ["16:04", "12:52"], ["17:44", "01:02"], ["02:44", "14:11"], ["18:22", "12:27"], ["23:12", "12:22"], ["02:47", "11:37"], ["03:15", "03:42"], ["03:55", "09:03"]]], [[["01:56", "18:22"], ["20:39", "09:01"], ["11:33", "18:09"], ["23:09", "20:42"], ["02:10", "08:51"], ["12:24", "19:01"], ["04:40", "12:01"], ["13:13", "06:13"], ["06:16", "21:38"]]], [[["02:52", "13:29"], ["18:33", "08:26"], ["08:35", "00:16"], ["08:15", "19:22"], ["19:37", "08:24"], ["20:17", "05:56"], ["23:45", "18:08"]]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,906 |
def sort_time(arr):
|
8edd638804c2b16b33db6e3ebd27e994 | UNKNOWN | Calculate the number of items in a vector that appear at the same index in each vector, with the same value.
```python
vector_affinity([1, 2, 3, 4, 5], [1, 2, 2, 4, 3]) # => 0.6
vector_affinity([1, 2, 3], [1, 2, 3]) # => 1.0
```
Affinity value should be realized on a scale of 0.0 to 1.0, with 1.0 being absolutely identical. Two identical sets should always be evaulated as having an affinity or 1.0.
Hint: The last example test case holds a significant clue to calculating the affinity correctly. | ["def vector_affinity(a, b):\n longer = len(a) if len(a) > len(b) else len(b)\n return len([i for i, j in zip(a, b) if i == j]) / float(longer) if longer > 0 else 1.0", "def vector_affinity(a, b):\n return sum([1.0 for x, y in zip(a, b) if x == y]) / max(len(a), len(b)) if max(len(a), len(b)) else 1", "from itertools import zip_longest, starmap\nfrom statistics import mean\nfrom operator import eq\n\ndef vector_affinity(a, b):\n return not (a or b) or mean(starmap(eq, zip_longest(a, b, fillvalue='\u00af\\_(\u30c4)_/\u00af')))", "def vector_affinity( a, b ):\n sizeA = len(a)\n sizeB = len(b)\n\n if (sizeA + sizeB) == 0:\n return 1.0\n\n if sizeA >= sizeB:\n den = sizeA\n numIter = sizeB\n else:\n den = sizeB\n numIter = sizeA\n\n numMatch=0\n\n for i in range(numIter):\n if a[i]==b[i]:\n numMatch+=1\n\n affinity = numMatch/den\n\n return affinity\n#----end function\n", "def vector_affinity(a, b):\n return 1.0 if a == b else sum(1 for (m, n) in zip(a, b) if m == n) / max(len(a), len(b))", "def vector_affinity(*args):\n l1,l2 = list(map(len,args))\n return sum(x==y for x,y in zip(*args)) / (1.0 * (max(l1,l2))) if l1 or l2 else 1.0", "def vector_affinity(a, b):\n denom = max(len(a), len(b))\n return sum(l == r for l, r in zip(a, b)) / float(denom) if denom else 1\n", "def vector_affinity(a, b):\n return 1.0 if a == b else sum(1 for i, j in zip(a, b) if i == j) / float(max(len(a), len(b)))", "def vector_affinity(a, b):\n return 1.0 if a == b else sum(float(x == y) for x, y in zip(a, b)) / max(len(a), len(b))", "def vector_affinity(a, b):\n return sum([an==bn for an,bn in zip(a,b)])/float(max(len(a),len(b))) if len(a) or len(b) else 1"] | {"fn_name": "vector_affinity", "inputs": [[[1, 2, 3], [1, 2, 3, 4, 5]], [[1, 2, 3, 4], [1, 2, 3, 5]], [[1, 2, 3, 4, 5], []], [[1, 2, 3], [1, 2, 3]], [[6, 6, 6, 6, 6, 6], [6, null, null, 6, 6, null]], [[6], [6, 6, 6, 6, 6, 6]], [[], []], [[null], [null]]], "outputs": [[0.6], [0.75], [0.0], [1.0], [0.5], [0.16666666666666666], [1.0], [1.0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,771 |
def vector_affinity(a, b):
|
97b56116a4954c8701838260f5ed3807 | UNKNOWN | You probably know that the "mode" of a set of data is the data point that appears most frequently. Looking at the characters that make up the string `"sarsaparilla"` we can see that the letter `"a"` appears four times, more than any other letter, so the mode of `"sarsaparilla"` is `"a"`.
But do you know what happens when two or more data points occur the most? For example, what is the mode of the letters in `"tomato"`? Both `"t"` and `"o"` seem to be tied for appearing most frequently.
Turns out that a set of data can, in fact, have multiple modes, so `"tomato"` has two modes: `"t"` and `"o"`. It's important to note, though, that if *all* data appears the same number of times there is no mode. So `"cat"`, `"redder"`, and `[1, 2, 3, 4, 5]` do not have a mode.
Your job is to write a function `modes()` that will accept one argument `data` that is a sequence like a string or a list of numbers and return a sorted list containing the mode(s) of the input sequence. If data does not contain a mode you should return an empty list.
For example:
```python
>>> modes("tomato")
["o", "t"]
>>> modes([1, 3, 3, 7])
[3]
>>> modes(["redder"])
[]
```
You can trust that your input data will always be a sequence and will always contain orderable types (no inputs like `[1, 2, 2, "a", "b", "b"]`). | ["from collections import Counter\n\ndef modes(data):\n cnts = Counter(data)\n mx, mn = max(cnts.values()), min(cnts.values())\n return sorted([k for k in cnts if cnts[k] == mx and cnts[k] != mn])", "def modes(data):\n frequency = {}\n mode_list = []\n \n # adds or creates a counter for each character\n for d in data:\n if d in frequency:\n frequency[d] += 1\n else:\n frequency[d] = 1\n \n # adds modes from the dictionary to a list, and checks that there is a mode\n for f in frequency:\n if frequency[f] == max(frequency.values()) > min(frequency.values()):\n mode_list.append(f)\n \n return sorted(mode_list)", "def modes(data):\n d = {i : data.count(i) for i in set(data)}\n return [] if len(set(d.values())) == 1 else sorted([i for i in set(data) if d[i] == max(d.values())]) ", "from collections import Counter\n\ndef modes(data):\n c = Counter(data)\n m = max(c.values())\n if min(c.values()) == m:\n return []\n return [key for key in sorted(c) if c[key] == m]", "from collections import Counter\n\ndef modes(data):\n result = []\n counts = Counter(data)\n if len(set(counts.values())) > 1:\n result += sorted(k for k,v in list(counts.items()) if v == max(counts.values()))\n return result\n", "from collections import Counter\n\ndef modes(data):\n count = Counter(data)\n m = max(count.values()) if len(set(count.values())) > 1 else 0\n return sorted(item for item, number in count.items() if 0 < m == number)", "def modes(data):\n #making a dictionary with every symbol as key and numbers it's used in given data as value\n dict = {i: data.count(i) for i in data}\n\n #if there are at least two symbols used different number of times in data\n if max(dict.values()) != min(dict.values()): \n #we return sorted list with symbols used maximum times in data in it (list of modes)\n return sorted([key for key, value in dict.items() if value == max(dict.values())])\n \n return []", "def modes(data):\n most, l, length = 0, [], len(data)\n for x in set(data):\n res = data.count(x)\n if most < res:\n most = res\n l = []\n l.append(x)\n length = len(data)-most\n elif most == res:\n l.append(x)\n length -= most\n return sorted(l) if length else []", "def modes(data):\n d = {}\n for i in set(data):\n d[data.count(i)] = d.get(data.count(i), []) + [i]\n if len(d) == 1:\n return []\n else:\n return sorted(d[max(d.keys())])", "def modes(data):\n counts = {}\n for value in data:\n if value in counts:\n counts[value] += 1\n else:\n counts[value] = 1\n #return counts\n max_occurrence = max(counts.values())\n min_occurrence = min(counts.values())\n \n if max_occurrence == min_occurrence:\n return []\n result = []\n for key in counts.keys():\n if counts[key] == max_occurrence:\n result.append(key)\n return sorted(result)"] | {"fn_name": "modes", "inputs": [["tomato"], [[1, 3, 3, 7]], [["redder"]]], "outputs": [[["o", "t"]], [[3]], [[]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,140 |
def modes(data):
|
df4c2a2a1c9ee1eeb18b66b98a8a75ed | UNKNOWN | A grid is a perfect starting point for many games (Chess, battleships, Candy Crush!).
Making a digital chessboard I think is an interesting way of visualising how loops can work together.
Your task is to write a function that takes two integers `rows` and `columns` and returns a chessboard pattern as a two dimensional array.
So `chessBoard(6,4)` should return an array like this:
[
["O","X","O","X"],
["X","O","X","O"],
["O","X","O","X"],
["X","O","X","O"],
["O","X","O","X"],
["X","O","X","O"]
]
And `chessBoard(3,7)` should return this:
[
["O","X","O","X","O","X","O"],
["X","O","X","O","X","O","X"],
["O","X","O","X","O","X","O"]
]
The white spaces should be represented by an: `'O'`
and the black an: `'X'`
The first row should always start with a white space `'O'` | ["def chess_board(rows, columns):\n return [[\"OX\"[(row+col)%2] for col in range(columns)] for row in range(rows)]", "def chess_board(rows, columns):\n ans=[]\n for i in range(1,rows+1,1):\n l=[]\n for j in range(i,columns+i,1):\n if j%2!=0:\n l.append('O')\n else:\n l.append('X')\n ans.append(l)\n return ans", "chess_board = lambda rows, cols: [['X' if (y + x) % 2 else 'O' for x in range(cols)] for y in range(rows)] ", "chess_board=lambda r,c:[['OX'[i+j&1]for i in range(c)]for j in range(r)]", "def chess_board(rows, columns):\n board = []\n for row in range(rows):\n if row % 2:\n board.append([\"X\" if not column % 2 else \"O\" for column in range(columns)])\n else:\n board.append([\"O\" if not column % 2 else \"X\" for column in range(columns)])\n return board", "def chess_board(a, b):\n return [list(\"OXXO\"[i%2::2] * (b // 2 + 1))[:b] for i in range(a)]", "from itertools import cycle\n\ndef chess_board(rows, columns):\n result = []\n for i in range(rows):\n grida = cycle(['O', 'X'])\n gridb = cycle(['X', 'O'])\n result.append([next(gridb) if i % 2 else next(grida) for x in range(columns)])\n return result", "def chess_board(rows, columns):\n return [[\"OX\"[(row + column) % 2] for column in range(columns)] for row in range(rows)]", "def chess_board(rows, columns):\n line = [\"X\", \"O\"] * columns\n return [line[:columns] if r % 2 else line[1:columns+1] for r in range(rows)]", "chess_board = lambda r, c: [[\"OX\"[(i+j)%2] for j in range(c)] for i in range(r)]"] | {"fn_name": "chess_board", "inputs": [[1, 1], [1, 2], [2, 1], [2, 2], [6, 6]], "outputs": [[[["O"]]], [[["O", "X"]]], [[["O"], ["X"]]], [[["O", "X"], ["X", "O"]]], [[["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"], ["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"], ["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"]]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,663 |
def chess_board(rows, columns):
|
44e1d424bd3f7e925f093440c49c8085 | UNKNOWN | Integral numbers can be even or odd.
Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`.
Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Recursively. :]
Even numbers are just not odd.
# Task
Given a finite list of integral ( not necessarily non-negative ) numbers, determine the number that is _odder than the rest_.
If there is no single such number, no number is odder than the rest; return `Nothing`, `null` or a similar empty value.
# Examples
```python
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => None
```
# Hint
Do you _really_ want one? Point or tap here. | ["def oddest(numbers):\n most_odd = 0 # The current most odd number in the list\n max_oddity = -1 # The current greatest oddity rate, starts at -1 so that even an even number can be the unique most odd\n is_unique = True # If the current most odd number is really the most, so if there is no unique oddest number, it will return None\n for num in numbers: # Loop through all the numbers\n oddity = 0 # The oddity rate starts at 0\n print(num)\n insider = num # The coefficient of the number 2, so in 2n + 1, the insider is n\n while insider % 2 == 1: # While that coefficient is odd\n if insider == -1:\n oddity = 1 + max([abs(n) for n in numbers]) # Since the oddity rate of a number is NEVER greater than the absolute value of the number, this garantees that the current number is the most odd one\n break\n else:\n oddity += 1 # Add the oddity rate of the total number\n insider = (insider-1)/2 # So if in 2n + 1, n is odd, represent it as 2(2m + 1) + 1, and set the value to m\n if oddity > max_oddity: # If the current number's oddity rate is greater than the current max oddity,\n is_unique = True # Set it to unique\n max_oddity = oddity # Set the max oddity to the current oddity\n most_odd = num # Set the most odd number to the current number\n elif oddity == max_oddity:# Otherwise, if it's the same rate\n is_unique = False # It's not unique\n if is_unique and max_oddity >= 0: # If the current most odd number is REALLY the most odd number and the list isn't empty\n return most_odd # Return it\n return None # Otherwise, return None", "def oddest(xs):\n os = list(map(oddness, xs))\n max_o = max(os, default=None)\n return xs[os.index(max_o)] if os.count(max_o) == 1 else None\n\ndef oddness(x):\n return float('inf') if x == -1 else ~x & -~x", "from collections import defaultdict\n\ndef oddity(n):\n if n == -1:\n return float('inf')\n odd = 0\n while n % 2:\n odd += 1\n n //= 2\n return odd\n\ndef oddest(a):\n result = defaultdict(list)\n for n in a:\n result[oddity(n)].append(n)\n try:\n x, = result[max(result)]\n return x\n except ValueError:\n pass", "from heapq import nlargest\nfrom functools import cmp_to_key\n\ndef oddity(n1, n2):\n while True:\n n1, m1 = divmod(n1, 2)\n n2, m2 = divmod(n2, 2)\n if m1 != m2 or m1 == 0 == m2 or n1 == n2:\n break\n return -1 if m1 < m2 else m1 > m2\n \ndef oddest(arr):\n res = nlargest(2, arr, key = cmp_to_key(oddity))\n if res and (len(res) == 1 or oddity(res[0], res[1])):\n return res[0]", "def oddest(a):\n d, o = {}, a.count(-1)\n for i, j in enumerate(a):\n n = j\n while n != 0 and n & 1 and n != -1:\n n = (abs(n) // 2 + int(n < 0)) * [1, -1][n < 0]\n d[i] = d.get(i, -1) + 1\n m = max(d, key=lambda x: d[x],default=0) \n return a[0] if len(a)==1 else -1 if o==1 else a[m] if d and list(d.values()).count(d[m])==1 and o<2 else None", "from collections import defaultdict\n\ndef odd(x):\n if x == -1: return 10 # Infinite recursive, that's the oddest you can get\n if not x&1: return 0\n return 1 + odd((x-1)>>1)\n\ndef oddest(a):\n if not a: return\n D = defaultdict(list)\n for x in a: D[odd(x)].append(x)\n L = D[max(D)]\n if len(L) == 1: return L[0]", "def oddest(a):\n f = lambda x: 1e6 if x == -1 else x % 2 and 1 + f(x // 2) or 0\n a = [(x, f(x)) for x in a]\n n = max((y for x, y in a), default=-1)\n a = [x for x, y in a if y == n]\n if len(a) == 1: return a[0]", "def oddest(a):\n if all(n % 2 == 0 for n in a):\n return a[0] if len(a) == 1 else None\n if -1 in a:\n return -1 if a.count(-1) == 1 else None\n a = [(x, x) for x in a if x % 2 != 0]\n while True:\n if len(a) == 0:\n return None\n if len(a) == 1:\n return a[0][0]\n a = list(filter(lambda n: n[1] % 2 != 0, ((n[0], (n[1] - 1) // 2 if n[1] != -1 else 1) for n in a)))", "d={}\ndef odd(n):\n if n==-1:return 10**1000\n r=0\n while n%2:\n r+=1\n n=(n-1)//2\n return r\n \ndef oddest(a):\n if not a:return\n o=[*map(odd,a)]\n if o.count(max(o))>1:return\n return max(a,key=odd)", "from collections import Counter\nfrom math import inf\n\ndef oddest(arr):\n c = Counter(map(oddness, arr))\n return max(arr, key=oddness) if c and c[max(c)] == 1 else None\n \ndef oddness(n):\n if n == -1:\n return inf\n m, is_odd = divmod(n, 2)\n cnt = 0\n while is_odd:\n m, is_odd = divmod(m, 2)\n cnt += 1\n return cnt"] | {"fn_name": "oddest", "inputs": [[[1, 2]], [[1, 3]], [[1, 5]], [[]], [[0]], [[0, 1]], [[1, 3, 5, 7]], [[2, 4]], [[-1]], [[-1, -1]], [[-1, 0, 1]], [[-3, 3]], [[-5, 3]]], "outputs": [[1], [3], [null], [null], [0], [1], [7], [null], [-1], [null], [-1], [3], [null]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,881 |
def oddest(a):
|
ff75fcd3d0a9312c4a3dc63a545ac277 | UNKNOWN | # Introduction
The Condi (Consecutive Digraphs) cipher was introduced by G4EGG (Wilfred Higginson) in 2011. The cipher preserves word divisions, and is simple to describe and encode, but it's surprisingly difficult to crack.
# Encoding Algorithm
The encoding steps are:
- Start with an `initial key`, e.g. `cryptogram`
- Form a `key`, remove the key duplicated letters except for the first occurrence
- Append to it, in alphabetical order all letters which do not occur in the `key`.
The example produces: `cryptogambdefhijklnqsuvwxz`
- Number the `key alphabet` starting with 1.
```python
1 2 3 4 5 6 7 8 9 10 11 12 13
c r y p t o g a m b d e f
14 15 16 17 18 19 20 21 22 23 24 25 26
h i j k l n q s u v w x z
```
- One of the inputs to encoding algorithm is an `initial shift`, say `10`
- Encode the first letter of your `message` by moving 10 places to the right from the letter's position in the key alphabet. If the first letter were say `o` then the letter 10 places to the right in the `key alphabet` is `j`, so `o` would be encoded as `j`. If you move past the end of the key alphabet you wrap back to the beginning. For example if the first letter were `s` then counting 10 places would bring you around to `t`.
- Use the position of the previous plaintext letter as the number of places to move to encode the next plaintext number. If you have just encoded an `o` (position 6) , and you now want to encode say `n`, then you move 6 places to the right from `n` which brings you to `x`.
- Keep repeating the previous step until all letters are encoded.
Decoding is the reverse of encoding - you move to the left instead of to the right.
# Task
Create two functions - `encode`/`Encode` and `decode`/`Decode` which implement Condi cipher encoding and decoding.
# Inputs
- `message` - a string to encode/decode
- `key` - a key consists of only lower case letters
- `initShift` - a non-negative integer representing the initial shift
# Notes
- Don't forget to remove the duplicated letters from the `key` except for the first occurrence
- Characters which do not exist in the `key alphabet` should be coppied to the output string exactly like they appear in the `message` string
- Check the test cases for samples | ["#from string import ascii_lowercase as LOWER\nLOWER = \"abcdefghijklmnopqrstuvwxyz\"\n\ndef encode(message, key, shift, encode=True):\n key = sorted(LOWER, key=f\"{key}{LOWER}\".index)\n result = []\n for char in message:\n if char in key:\n i = key.index(char)\n char = key[(i + shift) % 26]\n shift = i + 1 if encode else -(key.index(char) + 1)\n result.append(char)\n return \"\".join(result)\n \ndef decode(message, key, shift): \n return encode(message, key, -shift, encode=False)", "from string import ascii_lowercase\n\ndef encode_decode(message, key, shift, func):\n keys = ''.join(dict.fromkeys(key)) + ''.join(c for c in ascii_lowercase if c not in key)\n for c in message:\n if c.islower():\n c, shift = func(keys, c, shift)\n yield c\n\ndef encode(message, key, shift):\n return ''.join(encode_decode(\n message, key, shift,\n lambda k, c, s: (k[(k.find(c) + s) % 26], k.find(c) + 1)),\n )\n \ndef decode(message, key, shift):\n return ''.join(encode_decode(\n message, key, shift,\n lambda k, c, s: (k[(k.find(c) - s) % 26], k.find(k[(k.find(c) - s) % 26]) + 1)),\n )", "from string import ascii_lowercase\n\n\ndef form_key(key):\n working_key = \"\"\n for letter in key + ascii_lowercase:\n if letter not in working_key:\n working_key += letter\n return working_key\n\n\ndef encode(msg, key, init_shift):\n encode_key = form_key(key)\n shift = init_shift\n encoded_msg = \"\"\n for letter in msg:\n if letter not in encode_key:\n encoded_msg += letter\n else:\n encoded_msg += encode_key[(encode_key.index(letter) + shift) % 26]\n shift = encode_key.index(letter) + 1\n return encoded_msg\n\n\ndef decode(msg, key, init_shift):\n decode_key = form_key(key)\n shift = init_shift\n decoded_msg = \"\"\n for letter in msg:\n if letter not in decode_key:\n decoded_msg += letter\n else:\n decoded_msg += decode_key[(decode_key.index(letter) - shift) % 26]\n shift = decode_key.index(decoded_msg[-1]) + 1\n return decoded_msg", "def condi_helper(message, init_key, shift, mode):\n key = sorted(set(init_key), key=init_key.index)\n key += sorted(set('abcdefghijklmnopqrstuvwxyz') - set(init_key))\n \n result=[]\n for char in message:\n if char in key:\n idx = key.index(char)\n new = (idx + mode * shift) % 26\n result.append(key[new])\n if mode == 1:\n shift = idx + 1\n else:\n shift = new + 1\n else:\n result.append(char)\n \n return ''.join(result)\n\nencode = lambda msg, key, sh: condi_helper(msg, key, sh, 1)\ndecode = lambda msg, key, sh: condi_helper(msg, key, sh, -1)", "from string import ascii_lowercase as low\n\ndef encode(message, key, initShift): return shifter(message, key, initShift, 1)\ndef decode(message, key, initShift): return shifter(message, key, initShift, -1)\n\ndef shifter(msg, k, shift, dir):\n\n def moveChar(c):\n shifted = alphaStr[(keyAlpha[c] + dir + shift[0]*dir) % 26 ]\n shift[0] = keyAlpha[(c if dir == 1 else shifted)]\n return shifted\n \n def cleanKey(k):\n s, sk = \"\", set()\n for c in k:\n if c not in sk: s += c\n sk.add(c)\n return s,sk\n\n shift = [shift-1]\n k, sk = cleanKey(k)\n alphaStr = k + ''.join(c for c in low if c not in sk)\n keyAlpha = {l:i for i,l in enumerate(alphaStr)}\n \n return ''.join(c if c not in keyAlpha else moveChar(c) for c in msg)", "import string\n\ndef xcode(message, key, initShift, is_encode):\n seen, ret, shift = set(), \"\", initShift\n alphabet = [c for c in key.lower() + string.ascii_lowercase if c.isalpha() and not (c in seen or seen.add(c))]\n for letter in list(message):\n if letter.isalpha():\n new_index = (alphabet.index(letter) + (shift if is_encode else -shift)) % 26\n shift = (alphabet.index(letter) if is_encode else new_index) + 1\n letter = alphabet[new_index]\n ret += letter\n return ret\n\ndef encode(message, key, initShift):\n return xcode(message, key, initShift, True)\n\ndef decode(message, key, initShift):\n return xcode(message, key, initShift, False)", "from string import ascii_lowercase as AL\n\ndef encode(s, key, n):\n a = \"\".join(dict.fromkeys(key + AL))\n d = {x: i for i, x in enumerate(a, 1)}\n r = []\n for x in s:\n if x in d:\n r.append(a[(d[x] + n - 1) % len(a)])\n n = d[x]\n else:\n r.append(x)\n return \"\".join(r)\n \ndef decode(s, key, n): \n a = \"\".join(dict.fromkeys(key + AL))\n d = {x: i for i, x in enumerate(a, 1)}\n r = []\n for x in s:\n if x in d:\n r.append(a[(d[x] - n - 1) % len(a)])\n n = d[r[-1]]\n else:\n r.append(x)\n return \"\".join(r)", "def encode(message, key, shift): return cipher(message, key, shift, 1)\n\ndef decode(message, key, shift): return cipher(message, key, -shift, 0)\n\ndef cipher(message, key, shift, mode):\n key = tuple(dict.fromkeys(key.lower() + 'abcdefghijklmnopqrstuvwxyz'))\n res = ''\n for char in message:\n if char in key:\n i = key.index(char)\n char = key[(i + shift) % 26]\n shift = i + 1 if mode else -key.index(char) - 1\n res += char\n return res", "def encode(string, key, initShift):\n key = tuple(dict.fromkeys(key.lower() + 'abcdefghijklmnopqrstuvwxyz'))\n shift = (initShift - 1) % 26\n res = ''\n for c in string:\n if c in key:\n i = key.index(c)\n c = key[(i + shift + 1) % 26]\n shift = i\n res += c\n return res\n\n\ndef decode(string, key, initShift):\n key = tuple(dict.fromkeys(key.lower() + 'abcdefghijklmnopqrstuvwxyz'))\n shift = (initShift - 1) % 26\n res = ''\n for i, c in enumerate(string):\n if c in key:\n res += key[(key.index(c) - shift - 1) % 26]\n shift = key.index(res[i])\n else:\n res += c\n return res", "def get_key(d, value):\n for k, v in d.items():\n if v == value:\n return k\n\ndef encode(message, key, initShift):\n new_key = ''\n for i in key:\n if i not in new_key:\n new_key += i\n\n alf = 'abcdefghijklmnopqrstuvwxyz'\n for i in alf:\n if not i in new_key:\n new_key += i\n\n alphabet = {x: y for x, y in zip(range(1, 27), new_key)}\n result = ''\n for i in message:\n if i.isalpha() == False:\n result += i\n continue\n i = get_key(alphabet, i)\n if (i + initShift) <= 26:\n result += alphabet.get(i + initShift)\n initShift = i\n else:\n result += alphabet.get((i + initShift) - 26)\n initShift = i\n return result\n\n\ndef decode(message, key, initShift):\n new_key = ''\n for i in key:\n if i not in new_key:\n new_key += i\n\n alf = 'abcdefghijklmnopqrstuvwxyz'\n for i in alf:\n if not i in new_key:\n new_key += i\n\n alphabet = {x: y for x, y in zip(range(1, 27), new_key)}\n result = ''\n for i in message:\n if i.isalpha() == False:\n result += i\n continue\n i = get_key(alphabet, i)\n if (i - initShift) > 0:\n result += alphabet.get(i - initShift)\n initShift = i - initShift\n elif (i - initShift + 26) == 0:\n result += alphabet.get(26)\n initShift = 26\n else:\n result += alphabet.get((i - initShift) + 26)\n initShift = (i - initShift) + 26\n return result"] | {"fn_name": "encode", "inputs": [["on", "cryptogram", 10]], "outputs": [["jx"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 7,967 |
def encode(message, key, shift, encode=True):
|
f4d528f23a1b781a75f97dbbf3372056 | UNKNOWN | There were and still are many problem in CW about palindrome numbers and palindrome strings. We suposse that you know which kind of numbers they are. If not, you may search about them using your favourite search engine.
In this kata you will be given a positive integer, ```val``` and you have to create the function ```next_pal()```(```nextPal``` Javascript) that will output the smallest palindrome number higher than ```val```.
Let's see:
```python
For Python
next_pal(11) == 22
next_pal(188) == 191
next_pal(191) == 202
next_pal(2541) == 2552
```
You will be receiving values higher than 10, all valid.
Enjoy it!! | ["def palindrome(n):\n s = str(n)\n return s[::-1] == s\n\ndef next_pal(val):\n val += 1\n while not palindrome(val):\n val += 1\n return val", "def next_pal(val):\n int_to_digits = lambda n: [int(d) for d in str(n)]\n digits_to_int = lambda a: int(\"\".join(map(str, a)))\n \n digits = int_to_digits(val)\n half, odd = len(digits) // 2, len(digits) % 2\n build = lambda start: digits_to_int(start + start[::-1][-half:])\n\n base_start = digits[:half + odd]\n possible = build(base_start)\n if possible > val:\n return possible\n return build(int_to_digits(digits_to_int(base_start) + 1))\n", "def next_pal(val):\n val += 1\n while str(val) != str(val)[::-1]:\n val += 1\n return val", "def is_palindrome(n):\n return str(n)[::-1] == str(n)\n\ndef next_pal(val):\n for i in range(val + 1, 10*val):\n if is_palindrome(i): return i\n", "def next_pal(val):\n n = val+1\n while n != int(str(n)[::-1]):\n n += 1\n return n \n \n \n", "from itertools import count,dropwhile\n\ndef next_pal(val): return next(dropwhile(isNotPal, count(val+1)))\ndef isNotPal(n): return n!=int(str(n)[::-1])", "def next_pal(val):\n val += 1\n while f\"{val}\" != f\"{val}\"[::-1]:\n val += 1\n return val", "def next_pal(val):\n ret = val + 1\n while str(ret) != str(ret)[::-1]:\n ret += 1\n return ret", "import itertools\n\ndef next_pal(val):\n for n in itertools.count(val + 1):\n s = str(n)\n if s == s[::-1]:\n return n"] | {"fn_name": "next_pal", "inputs": [[11], [188], [191], [2541]], "outputs": [[22], [191], [202], [2552]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,579 |
def next_pal(val):
|
d11de4e9081ba86cd2d38f580051d1d3 | UNKNOWN | Implement `String#ipv4_address?`, which should return true if given object is an IPv4 address - four numbers (0-255) separated by dots.
It should only accept addresses in canonical representation, so no leading `0`s, spaces etc. | ["from re import compile, match\n\nREGEX = compile(r'((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){4}$')\n\n\ndef ipv4_address(address):\n # refactored thanks to @leonoverweel on CodeWars\n return bool(match(REGEX, address + '.'))\n", "import socket\ndef ipv4_address(address):\n try: # No need to do work that's already been done\n socket.inet_pton(socket.AF_INET,address)\n return True\n except socket.error: # Better to ask forgiveness than permission\n return False", "def ipv4_address(address):\n return address.count(\".\")==3 and all([str.isdigit(s) and s==str(int(s)) and int(s)>=0 and int(s)<256 for s in address.split(\".\")])", "def ipv4_address(address):\n addr = address.split('.')\n if len(addr) != 4:\n return False\n for e in addr:\n try:\n a = int(e)\n if a > 255 or a < 0:\n return False\n if str(a) != e:\n return False\n except:\n return False\n return True", "ipv4_address = lambda address: bool(__import__('re').match('(([1-9]?\\d|1\\d\\d|2[0-4]\\d|25[0-5])(\\.(?!$)|$)){4}\\Z',address))", "import re\n\n\ndef ipv4_address(address):\n return bool(re.match('((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])[.]){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\Z', address))", "from ipaddress import ip_address\n\n\ndef ipv4_address(address: str) -> bool:\n try:\n return len(str(ip_address(address))) == len(address)\n except ValueError:\n return False\n", "from re import match\ndef ipv4_address(address):\n return bool(match(r'^(([1-9]?\\d|1\\d{2}|2([0-4]\\d|5[0-5]))(\\.(?!$)|$)){4}\\Z', address))", "import re\n\ndef ipv4_address(address):\n return (\n bool(re.match(r'\\d+(\\.\\d+){3}\\Z', address))\n and all(0 <= int(x) <= 255 and (x == '0' or not x.startswith('0')) for x in re.findall(r'\\d+', address))\n )", "import re\n\ndef ipv4_address(address):\n byte_reg = r'(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])'\n ipv4_regex = r'\\A({0}[.]){{3}}{0}\\Z'.format(byte_reg)\n return bool(re.match(ipv4_regex, address))"] | {"fn_name": "ipv4_address", "inputs": [[""], ["127.0.0.1"], ["0.0.0.0"], ["255.255.255.255"], ["10.20.30.40"], ["10.256.30.40"], ["10.20.030.40"], ["127.0.1"], ["127.0.0.0.1"], ["..255.255"], ["127.0.0.1\n"], ["\n127.0.0.1"], [" 127.0.0.1"], ["127.0.0.1 "], [" 127.0.0.1 "], ["127.0.0.1."], [".127.0.0.1"], ["127..0.1"]], "outputs": [[false], [true], [true], [true], [true], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,138 |
def ipv4_address(address):
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.